diff
stringlengths 262
553k
| is_single_chunk
bool 2
classes | is_single_function
bool 1
class | buggy_function
stringlengths 20
391k
| fixed_function
stringlengths 0
392k
|
---|---|---|---|---|
diff --git a/src/biz/bokhorst/xprivacy/RState.java b/src/biz/bokhorst/xprivacy/RState.java
index 8c2cedbc..403e302b 100644
--- a/src/biz/bokhorst/xprivacy/RState.java
+++ b/src/biz/bokhorst/xprivacy/RState.java
@@ -1,87 +1,87 @@
package biz.bokhorst.xprivacy;
import java.util.ArrayList;
import java.util.List;
public class RState {
public int mUid;
public String mRestrictionName;
public String mMethodName;
public boolean restricted;
public boolean asked;
public boolean partial = false;
public RState(int uid, String restrictionName, String methodName) {
mUid = uid;
mRestrictionName = restrictionName;
mMethodName = methodName;
// Get if on demand
boolean onDemand = PrivacyManager.getSettingBool(0, PrivacyManager.cSettingOnDemand, true, false);
if (onDemand)
onDemand = PrivacyManager.getSettingBool(-uid, PrivacyManager.cSettingOnDemand, false, false);
boolean allRestricted = true;
boolean someRestricted = false;
- boolean asked = false;
+ asked = false;
if (methodName == null) {
if (restrictionName == null) {
// Examine the category state
asked = true;
for (String rRestrictionName : PrivacyManager.getRestrictions()) {
PRestriction query = PrivacyManager.getRestrictionEx(uid, rRestrictionName, null);
allRestricted = (allRestricted && query.restricted);
someRestricted = (someRestricted || query.restricted);
if (!query.asked)
asked = false;
}
} else {
// Examine the category/method states
PRestriction query = PrivacyManager.getRestrictionEx(uid, restrictionName, null);
someRestricted = query.restricted;
for (PRestriction restriction : PrivacyManager.getRestrictionList(uid, restrictionName)) {
allRestricted = (allRestricted && restriction.restricted);
someRestricted = (someRestricted || restriction.restricted);
}
asked = query.asked;
}
} else {
// Examine the method state
PRestriction query = PrivacyManager.getRestrictionEx(uid, restrictionName, methodName);
allRestricted = query.restricted;
someRestricted = false;
asked = query.asked;
}
restricted = (allRestricted || someRestricted);
partial = (!allRestricted && someRestricted);
asked = (!onDemand || asked);
}
public void toggleRestriction() {
if (mMethodName == null) {
// Get restrictions to change
List<String> listRestriction;
if (mRestrictionName == null)
listRestriction = PrivacyManager.getRestrictions();
else {
listRestriction = new ArrayList<String>();
listRestriction.add(mRestrictionName);
}
// Change restriction
if (restricted)
PrivacyManager.deleteRestrictions(mUid, mRestrictionName);
else
for (String restrictionName : listRestriction)
PrivacyManager.setRestriction(mUid, restrictionName, null, true, false);
} else
PrivacyManager.setRestriction(mUid, mRestrictionName, mMethodName, !restricted, false);
}
public void toggleAsked() {
asked = !asked;
PrivacyManager.setRestriction(mUid, mRestrictionName, mMethodName, restricted, asked);
}
}
| true | true | public RState(int uid, String restrictionName, String methodName) {
mUid = uid;
mRestrictionName = restrictionName;
mMethodName = methodName;
// Get if on demand
boolean onDemand = PrivacyManager.getSettingBool(0, PrivacyManager.cSettingOnDemand, true, false);
if (onDemand)
onDemand = PrivacyManager.getSettingBool(-uid, PrivacyManager.cSettingOnDemand, false, false);
boolean allRestricted = true;
boolean someRestricted = false;
boolean asked = false;
if (methodName == null) {
if (restrictionName == null) {
// Examine the category state
asked = true;
for (String rRestrictionName : PrivacyManager.getRestrictions()) {
PRestriction query = PrivacyManager.getRestrictionEx(uid, rRestrictionName, null);
allRestricted = (allRestricted && query.restricted);
someRestricted = (someRestricted || query.restricted);
if (!query.asked)
asked = false;
}
} else {
// Examine the category/method states
PRestriction query = PrivacyManager.getRestrictionEx(uid, restrictionName, null);
someRestricted = query.restricted;
for (PRestriction restriction : PrivacyManager.getRestrictionList(uid, restrictionName)) {
allRestricted = (allRestricted && restriction.restricted);
someRestricted = (someRestricted || restriction.restricted);
}
asked = query.asked;
}
} else {
// Examine the method state
PRestriction query = PrivacyManager.getRestrictionEx(uid, restrictionName, methodName);
allRestricted = query.restricted;
someRestricted = false;
asked = query.asked;
}
restricted = (allRestricted || someRestricted);
partial = (!allRestricted && someRestricted);
asked = (!onDemand || asked);
}
| public RState(int uid, String restrictionName, String methodName) {
mUid = uid;
mRestrictionName = restrictionName;
mMethodName = methodName;
// Get if on demand
boolean onDemand = PrivacyManager.getSettingBool(0, PrivacyManager.cSettingOnDemand, true, false);
if (onDemand)
onDemand = PrivacyManager.getSettingBool(-uid, PrivacyManager.cSettingOnDemand, false, false);
boolean allRestricted = true;
boolean someRestricted = false;
asked = false;
if (methodName == null) {
if (restrictionName == null) {
// Examine the category state
asked = true;
for (String rRestrictionName : PrivacyManager.getRestrictions()) {
PRestriction query = PrivacyManager.getRestrictionEx(uid, rRestrictionName, null);
allRestricted = (allRestricted && query.restricted);
someRestricted = (someRestricted || query.restricted);
if (!query.asked)
asked = false;
}
} else {
// Examine the category/method states
PRestriction query = PrivacyManager.getRestrictionEx(uid, restrictionName, null);
someRestricted = query.restricted;
for (PRestriction restriction : PrivacyManager.getRestrictionList(uid, restrictionName)) {
allRestricted = (allRestricted && restriction.restricted);
someRestricted = (someRestricted || restriction.restricted);
}
asked = query.asked;
}
} else {
// Examine the method state
PRestriction query = PrivacyManager.getRestrictionEx(uid, restrictionName, methodName);
allRestricted = query.restricted;
someRestricted = false;
asked = query.asked;
}
restricted = (allRestricted || someRestricted);
partial = (!allRestricted && someRestricted);
asked = (!onDemand || asked);
}
|
diff --git a/howl/src/java/org/apache/hadoop/hive/howl/data/type/HowlTypeInfo.java b/howl/src/java/org/apache/hadoop/hive/howl/data/type/HowlTypeInfo.java
index 8b841fce..a5fc0bbf 100644
--- a/howl/src/java/org/apache/hadoop/hive/howl/data/type/HowlTypeInfo.java
+++ b/howl/src/java/org/apache/hadoop/hive/howl/data/type/HowlTypeInfo.java
@@ -1,189 +1,194 @@
/*
* 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.hive.howl.data.type;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector.Category;
import org.apache.hadoop.hive.serde2.typeinfo.ListTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.MapTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.PrimitiveTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.StructTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoUtils;
public class HowlTypeInfo implements Serializable {
private static final long serialVersionUID = 1L;
HowlType type;
private TypeInfo baseTypeInfo = null;
// populated if the base type is a struct
List<HowlTypeInfo> structFields = null;
// populated if base type is a list
HowlTypeInfo listType = null;
// populated if the base type is a map
HowlTypeInfo mapKeyType = null;
HowlTypeInfo mapValueType = null;
@SuppressWarnings("unused")
private HowlTypeInfo(){
// preventing empty ctor from being callable
}
/**
* Instantiates a HowlTypeInfo from a string representation of the underlying type.
* @param type The base type representation
*/
HowlTypeInfo(String type) {
this(TypeInfoUtils.getTypeInfoFromTypeString(type));
}
/**
* Instantiating a HowlTypeInfo overlaying a underlying TypeInfo
* @param typeInfo the base TypeInfo
*/
HowlTypeInfo(TypeInfo typeInfo){
this.baseTypeInfo = typeInfo;
deepTraverseAndSetup();
}
private void deepTraverseAndSetup() {
if (baseTypeInfo.getCategory() == Category.MAP){
mapKeyType = new HowlTypeInfo(((MapTypeInfo)baseTypeInfo).getMapKeyTypeInfo());
mapValueType = new HowlTypeInfo(((MapTypeInfo)baseTypeInfo).getMapValueTypeInfo());
+ type = HowlType.MAP;
}else if (baseTypeInfo.getCategory() == Category.LIST){
listType = new HowlTypeInfo(((ListTypeInfo)baseTypeInfo).getListElementTypeInfo());
+ type = HowlType.ARRAY;
}else if (baseTypeInfo.getCategory() == Category.STRUCT){
structFields = new ArrayList<HowlTypeInfo>();
for(TypeInfo ti : ((StructTypeInfo)baseTypeInfo).getAllStructFieldTypeInfos()){
structFields.add(new HowlTypeInfo(ti));
}
+ type = HowlType.STRUCT;
} else if(baseTypeInfo.getCategory() == Category.PRIMITIVE) {
switch(((PrimitiveTypeInfo)baseTypeInfo).getPrimitiveCategory()) {
case BOOLEAN:
type = HowlType.BOOLEAN;
break;
case BYTE:
type = HowlType.TINYINT;
break;
case DOUBLE:
type = HowlType.DOUBLE;
break;
case FLOAT:
type = HowlType.FLOAT;
break;
case INT:
type = HowlType.INT;
break;
case LONG:
type = HowlType.BIGINT;
break;
case SHORT:
type = HowlType.SMALLINT;
break;
case STRING:
type = HowlType.STRING;
break;
default:
throw new
TypeNotPresentException(((PrimitiveTypeInfo)baseTypeInfo).getTypeName(), null);
}
+ } else{
+ throw new TypeNotPresentException(baseTypeInfo.getTypeName(),null);
}
}
// TODO : throw exception if null? do we want null or exception semantics?
// (Currently going with null semantics)
/**
* Get the underlying map key type (if the underlying TypeInfo is a map type)
*/
public HowlTypeInfo getMapKeyTypeInfo(){
return mapKeyType;
}
/**
* Get the underlying map value type (if the underlying TypeInfo is a map type)
*/
public HowlTypeInfo getMapValueTypeInfo(){
return mapValueType;
}
/**
* Get the underlying list element type (if the underlying TypeInfo is a list type)
*/
public HowlTypeInfo getListElementTypeInfo(){
return listType;
}
/**
* Get the underlying struct element types (if the underlying TypeInfo is a struct type)
*/
public List<HowlTypeInfo> getAllStructFieldTypeInfos(){
return structFields;
}
@Override
public int hashCode(){
return baseTypeInfo.hashCode();
// true, we have other fields here, but all other fields base themselves off parsing
// the base TypeInfo. Also, for equal HowlTypeInfos, the hashCode() must be the same
}
@Override
public boolean equals(Object other){
if (other == null){
return false;
// no need to check if we're null too, because we disallow empty ctor,
// and baseTypeInfo *will* be set on instantiations. if baseTypeInfo is
// not set because of some future modification without this being changed,
// it's good to throw that exception
}
return baseTypeInfo.equals(((HowlTypeInfo)other).baseTypeInfo);
}
/**
* @return the type
*/
public HowlType getType() {
return type;
}
/**
* @return the string representation of the type
*/
public String getTypeString(){
return baseTypeInfo.getTypeName();
}
/**
* package scope function - returns the underlying TypeInfo
* @return the underlying TypeInfo
*/
TypeInfo getTypeInfo(){
return baseTypeInfo;
}
}
| false | true | private void deepTraverseAndSetup() {
if (baseTypeInfo.getCategory() == Category.MAP){
mapKeyType = new HowlTypeInfo(((MapTypeInfo)baseTypeInfo).getMapKeyTypeInfo());
mapValueType = new HowlTypeInfo(((MapTypeInfo)baseTypeInfo).getMapValueTypeInfo());
}else if (baseTypeInfo.getCategory() == Category.LIST){
listType = new HowlTypeInfo(((ListTypeInfo)baseTypeInfo).getListElementTypeInfo());
}else if (baseTypeInfo.getCategory() == Category.STRUCT){
structFields = new ArrayList<HowlTypeInfo>();
for(TypeInfo ti : ((StructTypeInfo)baseTypeInfo).getAllStructFieldTypeInfos()){
structFields.add(new HowlTypeInfo(ti));
}
} else if(baseTypeInfo.getCategory() == Category.PRIMITIVE) {
switch(((PrimitiveTypeInfo)baseTypeInfo).getPrimitiveCategory()) {
case BOOLEAN:
type = HowlType.BOOLEAN;
break;
case BYTE:
type = HowlType.TINYINT;
break;
case DOUBLE:
type = HowlType.DOUBLE;
break;
case FLOAT:
type = HowlType.FLOAT;
break;
case INT:
type = HowlType.INT;
break;
case LONG:
type = HowlType.BIGINT;
break;
case SHORT:
type = HowlType.SMALLINT;
break;
case STRING:
type = HowlType.STRING;
break;
default:
throw new
TypeNotPresentException(((PrimitiveTypeInfo)baseTypeInfo).getTypeName(), null);
}
}
}
| private void deepTraverseAndSetup() {
if (baseTypeInfo.getCategory() == Category.MAP){
mapKeyType = new HowlTypeInfo(((MapTypeInfo)baseTypeInfo).getMapKeyTypeInfo());
mapValueType = new HowlTypeInfo(((MapTypeInfo)baseTypeInfo).getMapValueTypeInfo());
type = HowlType.MAP;
}else if (baseTypeInfo.getCategory() == Category.LIST){
listType = new HowlTypeInfo(((ListTypeInfo)baseTypeInfo).getListElementTypeInfo());
type = HowlType.ARRAY;
}else if (baseTypeInfo.getCategory() == Category.STRUCT){
structFields = new ArrayList<HowlTypeInfo>();
for(TypeInfo ti : ((StructTypeInfo)baseTypeInfo).getAllStructFieldTypeInfos()){
structFields.add(new HowlTypeInfo(ti));
}
type = HowlType.STRUCT;
} else if(baseTypeInfo.getCategory() == Category.PRIMITIVE) {
switch(((PrimitiveTypeInfo)baseTypeInfo).getPrimitiveCategory()) {
case BOOLEAN:
type = HowlType.BOOLEAN;
break;
case BYTE:
type = HowlType.TINYINT;
break;
case DOUBLE:
type = HowlType.DOUBLE;
break;
case FLOAT:
type = HowlType.FLOAT;
break;
case INT:
type = HowlType.INT;
break;
case LONG:
type = HowlType.BIGINT;
break;
case SHORT:
type = HowlType.SMALLINT;
break;
case STRING:
type = HowlType.STRING;
break;
default:
throw new
TypeNotPresentException(((PrimitiveTypeInfo)baseTypeInfo).getTypeName(), null);
}
} else{
throw new TypeNotPresentException(baseTypeInfo.getTypeName(),null);
}
}
|
diff --git a/wikAPIdia-sr/src/main/java/org/wikapidia/sr/ensemble/EnsembleMetric.java b/wikAPIdia-sr/src/main/java/org/wikapidia/sr/ensemble/EnsembleMetric.java
index c33a2fb2..dee65944 100644
--- a/wikAPIdia-sr/src/main/java/org/wikapidia/sr/ensemble/EnsembleMetric.java
+++ b/wikAPIdia-sr/src/main/java/org/wikapidia/sr/ensemble/EnsembleMetric.java
@@ -1,269 +1,268 @@
package org.wikapidia.sr.ensemble;
import com.typesafe.config.Config;
import gnu.trove.map.TIntDoubleMap;
import gnu.trove.set.TIntSet;
import org.wikapidia.conf.Configuration;
import org.wikapidia.conf.ConfigurationException;
import org.wikapidia.conf.Configurator;
import org.wikapidia.core.WikapidiaException;
import org.wikapidia.core.dao.DaoException;
import org.wikapidia.core.dao.LocalPageDao;
import org.wikapidia.core.lang.Language;
import org.wikapidia.core.lang.LanguageSet;
import org.wikapidia.core.lang.LocalId;
import org.wikapidia.core.lang.LocalString;
import org.wikapidia.core.model.LocalPage;
import org.wikapidia.sr.*;
import org.wikapidia.sr.disambig.Disambiguator;
import org.wikapidia.sr.normalize.Normalizer;
import org.wikapidia.sr.utils.Dataset;
import org.wikapidia.sr.utils.KnownSim;
import org.wikapidia.utils.Function;
import org.wikapidia.utils.ParallelForEach;
import java.io.*;
import java.util.*;
/**
* @author Matt Lesicko
*/
public class EnsembleMetric extends BaseLocalSRMetric{
private final double missingScore = 0.0;
private List<LocalSRMetric> metrics;
Ensemble ensemble;
public EnsembleMetric(List<LocalSRMetric> metrics, Ensemble ensemble, Disambiguator disambiguator, LocalPageDao pageHelper){
this.metrics=metrics;
this.ensemble=ensemble;
this.disambiguator=disambiguator;
this.pageHelper=pageHelper;
}
@Override
public String getName() {
return "Ensemble";
}
@Override
public SRResult similarity(LocalPage page1, LocalPage page2, boolean explanations) throws DaoException {
List<SRResult> scores = new ArrayList<SRResult>();
for (LocalSRMetric metric : metrics){
scores.add(metric.similarity(page1,page2,explanations));
}
return ensemble.predictSimilarity(scores);
}
@Override
public SRResult similarity(String phrase1, String phrase2, Language language, boolean explanations) throws DaoException {
List<SRResult> scores = new ArrayList<SRResult>();
for (LocalSRMetric metric : metrics){
scores.add(metric.similarity(phrase1,phrase2,language,explanations));
}
return ensemble.predictSimilarity(scores);
}
@Override
public SRResultList mostSimilar(LocalPage page, int maxResults) throws DaoException {
return mostSimilar(page,maxResults,null);
}
@Override
public SRResultList mostSimilar(LocalPage page, int maxResults, TIntSet validIds) throws DaoException {
List<SRResultList> scores = new ArrayList<SRResultList>();
for (LocalSRMetric metric : metrics){
scores.add(metric.mostSimilar(page,maxResults,validIds));
}
return ensemble.predictMostSimilar(scores,maxResults);
}
@Override
public SRResultList mostSimilar(LocalString phrase, int maxResults) throws DaoException{
return mostSimilar(phrase,maxResults,null);
}
@Override
public SRResultList mostSimilar(LocalString phrase, int maxResults, TIntSet validIds) throws DaoException {
List<SRResultList> scores = new ArrayList<SRResultList>();
for (LocalSRMetric metric : metrics){
scores.add(metric.mostSimilar(phrase,maxResults,validIds));
}
return ensemble.predictMostSimilar(scores,maxResults);
}
@Override
public void trainSimilarity(Dataset dataset) {
List<EnsembleSim> ensembleSims = new ArrayList<EnsembleSim>();
for (KnownSim ks : dataset.getData()){
List<Double> scores = new ArrayList<Double>();
for (LocalSRMetric metric : metrics){
double score;
try {
score = metric.similarity(ks.phrase1,ks.phrase2,ks.language,false).getScore();
}
catch (DaoException e){
score = Double.NaN;
}
if (!Double.isNaN(score)&&!Double.isInfinite(score)){
scores.add(score);
} else {
scores.add(missingScore);
}
}
ensembleSims.add(new EnsembleSim(scores,ks));
}
ensemble.trainSimilarity(ensembleSims);
}
@Override
public void trainDefaultSimilarity(Dataset dataset) {
List<EnsembleSim> ensembleSims = new ArrayList<EnsembleSim>();
for (KnownSim ks : dataset.getData()){
List<Double> scores = new ArrayList<Double>();
for (LocalSRMetric metric : metrics){
try {
scores.add(metric.similarity(ks.phrase1,ks.phrase2,ks.language,false).getScore());
}
catch (DaoException e){
scores.add(missingScore);
}
}
ensembleSims.add(new EnsembleSim(scores,ks));
}
ensemble.trainSimilarity(ensembleSims);
}
@Override
public void trainMostSimilar(Dataset dataset, final int numResults, final TIntSet validIds){
for (LocalSRMetric metric : metrics){
metric.trainMostSimilar(dataset,numResults,validIds);
}
List<EnsembleSim> ensembleSims = ParallelForEach.loop(dataset.getData(), new Function<KnownSim,EnsembleSim>() {
public EnsembleSim call(KnownSim ks) throws DaoException{
List<Double> scores = new ArrayList<Double>();
List<LocalString> localStrings = new ArrayList<LocalString>();
localStrings.add(new LocalString(ks.language, ks.phrase1));
localStrings.add(new LocalString(ks.language, ks.phrase2));
List<LocalId> ids = disambiguator.disambiguate(localStrings, null);
LocalPage page = pageHelper.getById(ks.language,ids.get(0).getId());
if (page!=null){
for (LocalSRMetric metric : metrics){
try {
SRResultList dsl = metric.mostSimilar(page, numResults, validIds);
if (dsl!=null&&dsl.getIndexForId(ids.get(1).getId())>1){
scores.add(dsl.getScore(dsl.getIndexForId(ids.get(1).getId())));
}
else {
scores.add(missingScore);
}
} catch (DaoException e){scores.add(missingScore);} //In event of metric failure
}
return new EnsembleSim(scores,ks);
}
return null;
}
},1);
ensemble.trainMostSimilar(ensembleSims);
}
@Override
public void write(String path) throws IOException{
ensemble.write(path);
}
@Override
public void read(String path) throws IOException{
ensemble.read(path);
}
@Override
public void trainDefaultMostSimilar(Dataset dataset, int numResults, TIntSet validIds){
//TODO: implement me
}
@Override
public TIntDoubleMap getVector(int id, Language language) throws DaoException {
//TODO: implement me
throw new UnsupportedOperationException();
}
@Override
public void writeCosimilarity(String path, LanguageSet languages, int maxHits) throws IOException, DaoException, WikapidiaException {
//TODO: implement me
throw new UnsupportedOperationException();
}
@Override
public void readCosimilarity(String path, LanguageSet languages) throws IOException {
//TODO: implement me
throw new UnsupportedOperationException();
}
public static class Provider extends org.wikapidia.conf.Provider<LocalSRMetric>{
public Provider(Configurator configurator, Configuration config) throws ConfigurationException {
super(configurator, config);
}
@Override
public Class getType() {
return LocalSRMetric.class;
}
@Override
public String getPath() {
return "sr.metric.local";
}
@Override
public LocalSRMetric get(String name, Config config) throws ConfigurationException{
if (!config.getString("type").equals("Ensemble")) {
return null;
}
- List<String> langCodes = getConfig().get().getStringList("languages");
+ LanguageSet langs = getConfigurator().get(LanguageSet.class);
if (config.hasPath("metrics")){
EnsembleMetric sr;
List<LocalSRMetric> metrics = new ArrayList<LocalSRMetric>();
for (String metric : config.getStringList("metrics")){
metrics.add(getConfigurator().get(LocalSRMetric.class,metric));
}
Ensemble ensemble;
if (config.getString("ensemble").equals("linear")){
ensemble = new LinearEnsemble(metrics.size());
} else if (config.getString("ensemble").equals("even")){
ensemble = new EvenEnsemble();
} else {
throw new ConfigurationException("I don't know how to do that ensemble.");
}
Disambiguator disambiguator = getConfigurator().get(Disambiguator.class,config.getString("disambiguator"));
LocalPageDao pagehelper = getConfigurator().get(LocalPageDao.class,config.getString("pageDao"));
sr = new EnsembleMetric(metrics,ensemble,disambiguator,pagehelper);
try {
sr.read(getConfigurator().getConf().get().getString("sr.metric.path")+sr.getName());
} catch (IOException e){
System.out.println(e.getMessage());
e.printStackTrace();
}
//Set up normalizers
sr.setDefaultSimilarityNormalizer(getConfigurator().get(Normalizer.class,config.getString("similaritynormalizer")));
sr.setDefaultMostSimilarNormalizer(getConfigurator().get(Normalizer.class,config.getString("similaritynormalizer")));
- for (String langCode : langCodes){
- Language language = Language.getByLangCode(langCode);
+ for (Language language : langs){
sr.setSimilarityNormalizer(getConfigurator().get(Normalizer.class, config.getString("similaritynormalizer")), language);
sr.setMostSimilarNormalizer(getConfigurator().get(Normalizer.class, config.getString("similaritynormalizer")), language);
}
return sr;
}
else {
throw new ConfigurationException("Ensemble metric has no base metrics to use.");
}
}
}
}
| false | true | public LocalSRMetric get(String name, Config config) throws ConfigurationException{
if (!config.getString("type").equals("Ensemble")) {
return null;
}
List<String> langCodes = getConfig().get().getStringList("languages");
if (config.hasPath("metrics")){
EnsembleMetric sr;
List<LocalSRMetric> metrics = new ArrayList<LocalSRMetric>();
for (String metric : config.getStringList("metrics")){
metrics.add(getConfigurator().get(LocalSRMetric.class,metric));
}
Ensemble ensemble;
if (config.getString("ensemble").equals("linear")){
ensemble = new LinearEnsemble(metrics.size());
} else if (config.getString("ensemble").equals("even")){
ensemble = new EvenEnsemble();
} else {
throw new ConfigurationException("I don't know how to do that ensemble.");
}
Disambiguator disambiguator = getConfigurator().get(Disambiguator.class,config.getString("disambiguator"));
LocalPageDao pagehelper = getConfigurator().get(LocalPageDao.class,config.getString("pageDao"));
sr = new EnsembleMetric(metrics,ensemble,disambiguator,pagehelper);
try {
sr.read(getConfigurator().getConf().get().getString("sr.metric.path")+sr.getName());
} catch (IOException e){
System.out.println(e.getMessage());
e.printStackTrace();
}
//Set up normalizers
sr.setDefaultSimilarityNormalizer(getConfigurator().get(Normalizer.class,config.getString("similaritynormalizer")));
sr.setDefaultMostSimilarNormalizer(getConfigurator().get(Normalizer.class,config.getString("similaritynormalizer")));
for (String langCode : langCodes){
Language language = Language.getByLangCode(langCode);
sr.setSimilarityNormalizer(getConfigurator().get(Normalizer.class, config.getString("similaritynormalizer")), language);
sr.setMostSimilarNormalizer(getConfigurator().get(Normalizer.class, config.getString("similaritynormalizer")), language);
}
return sr;
}
else {
throw new ConfigurationException("Ensemble metric has no base metrics to use.");
}
}
| public LocalSRMetric get(String name, Config config) throws ConfigurationException{
if (!config.getString("type").equals("Ensemble")) {
return null;
}
LanguageSet langs = getConfigurator().get(LanguageSet.class);
if (config.hasPath("metrics")){
EnsembleMetric sr;
List<LocalSRMetric> metrics = new ArrayList<LocalSRMetric>();
for (String metric : config.getStringList("metrics")){
metrics.add(getConfigurator().get(LocalSRMetric.class,metric));
}
Ensemble ensemble;
if (config.getString("ensemble").equals("linear")){
ensemble = new LinearEnsemble(metrics.size());
} else if (config.getString("ensemble").equals("even")){
ensemble = new EvenEnsemble();
} else {
throw new ConfigurationException("I don't know how to do that ensemble.");
}
Disambiguator disambiguator = getConfigurator().get(Disambiguator.class,config.getString("disambiguator"));
LocalPageDao pagehelper = getConfigurator().get(LocalPageDao.class,config.getString("pageDao"));
sr = new EnsembleMetric(metrics,ensemble,disambiguator,pagehelper);
try {
sr.read(getConfigurator().getConf().get().getString("sr.metric.path")+sr.getName());
} catch (IOException e){
System.out.println(e.getMessage());
e.printStackTrace();
}
//Set up normalizers
sr.setDefaultSimilarityNormalizer(getConfigurator().get(Normalizer.class,config.getString("similaritynormalizer")));
sr.setDefaultMostSimilarNormalizer(getConfigurator().get(Normalizer.class,config.getString("similaritynormalizer")));
for (Language language : langs){
sr.setSimilarityNormalizer(getConfigurator().get(Normalizer.class, config.getString("similaritynormalizer")), language);
sr.setMostSimilarNormalizer(getConfigurator().get(Normalizer.class, config.getString("similaritynormalizer")), language);
}
return sr;
}
else {
throw new ConfigurationException("Ensemble metric has no base metrics to use.");
}
}
|
diff --git a/cyklotron-ui/src/main/java/net/cyklotron/cms/modules/views/documents/ProposeDocument.java b/cyklotron-ui/src/main/java/net/cyklotron/cms/modules/views/documents/ProposeDocument.java
index c86e96274..0b3fa1fda 100644
--- a/cyklotron-ui/src/main/java/net/cyklotron/cms/modules/views/documents/ProposeDocument.java
+++ b/cyklotron-ui/src/main/java/net/cyklotron/cms/modules/views/documents/ProposeDocument.java
@@ -1,282 +1,277 @@
package net.cyklotron.cms.modules.views.documents;
import java.util.Arrays;
import java.util.List;
import org.jcontainer.dna.Logger;
import org.objectledge.authentication.AuthenticationContext;
import org.objectledge.context.Context;
import org.objectledge.coral.security.Permission;
import org.objectledge.coral.security.Subject;
import org.objectledge.coral.session.CoralSession;
import org.objectledge.coral.store.Resource;
import org.objectledge.html.HTMLService;
import org.objectledge.parameters.Parameters;
import org.objectledge.parameters.RequestParameters;
import org.objectledge.pipeline.ProcessingException;
import org.objectledge.table.TableStateManager;
import org.objectledge.templating.TemplatingContext;
import org.objectledge.web.mvc.finders.MVCFinder;
import net.cyklotron.cms.CmsData;
import net.cyklotron.cms.CmsDataFactory;
import net.cyklotron.cms.category.CategoryService;
import net.cyklotron.cms.documents.DocumentNodeResource;
import net.cyklotron.cms.documents.DocumentNodeResourceImpl;
import net.cyklotron.cms.preferences.PreferencesService;
import net.cyklotron.cms.related.RelatedService;
import net.cyklotron.cms.site.SiteResource;
import net.cyklotron.cms.skins.SkinService;
import net.cyklotron.cms.structure.NavigationNodeResourceImpl;
import net.cyklotron.cms.structure.StructureService;
import net.cyklotron.cms.structure.internal.ProposedDocumentData;
import net.cyklotron.cms.style.StyleService;
/**
* Stateful screen for propose document application.
*
* @author <a href="mailto:[email protected]">Pawe� Potempski</a>
* @version $Id: ProposeDocument.java,v 1.12 2008-11-04 17:14:48 rafal Exp $
*/
public class ProposeDocument
extends BaseSkinableDocumentScreen
{
private final CategoryService categoryService;
private final RelatedService relatedService;
private final HTMLService htmlService;
public ProposeDocument(org.objectledge.context.Context context, Logger logger,
PreferencesService preferencesService, CmsDataFactory cmsDataFactory,
StructureService structureService, StyleService styleService, SkinService skinService,
MVCFinder mvcFinder, TableStateManager tableStateManager, CategoryService categoryService,
RelatedService relatedService, HTMLService htmlService)
{
super(context, logger, preferencesService, cmsDataFactory, structureService, styleService,
skinService, mvcFinder, tableStateManager);
this.categoryService = categoryService;
this.relatedService = relatedService;
this.htmlService = htmlService;
}
public String getState()
throws ProcessingException
{
// this method is called multiple times during rendering, so it makes sense to cache the evaluated state
String state = (String) context.getAttribute(getClass().getName()+".state");
if(state == null)
{
Parameters parameters = RequestParameters.getRequestParameters(context);
AuthenticationContext authContext = context.getAttribute(AuthenticationContext.class);
state = parameters.get("state",null);
if(state == null)
{
CmsData cmsData = cmsDataFactory.getCmsData(context);
Parameters screenConfig = cmsData.getEmbeddedScreenConfig();
boolean editingEnabled = screenConfig.getBoolean("editing_enabled", false);
if(editingEnabled)
{
if(authContext.isUserAuthenticated())
{
state = "MyDocuments";
}
else
{
state = "Anonymous";
}
}
else
{
state = "AddDocument";
}
}
context.setAttribute(getClass().getName()+".state", state);
}
return state;
}
@Override
public boolean requiresAuthenticatedUser(Context context)
throws Exception
{
String state = getState();
if("EditDocument".equals(state))
{
return true;
}
if("MyDocuments".equals(state))
{
return true;
}
return false;
}
@Override
public boolean checkAccessRights(Context context)
throws ProcessingException
{
TemplatingContext templatingContext = context.getAttribute(TemplatingContext.class);
String result = (String)templatingContext.get("result");
if("exception".equals(result))
{
return true;
}
String state = getState();
if("Anonymous".equals(state))
{
return true;
}
if("MyDocuments".equals(state))
{
// no particular permission needed to see the stuff you sumbitted, provided you are
// authenticated
return true;
}
try
{
Parameters requestParameters = context.getAttribute(RequestParameters.class);
CoralSession coralSession = context.getAttribute(CoralSession.class);
Subject userSubject = coralSession.getUserSubject();
if("AddDocument".equals(state))
{
- long id = requestParameters.getLong("parent_node_id", -1);
- Resource node;
- if(id != -1)
- {
- node = NavigationNodeResourceImpl.getNavigationNodeResource(coralSession, id);
- }
- else
- {
- node = cmsDataFactory.getCmsData(context).getHomePage();
- }
Permission submitPermission = coralSession.getSecurity().getUniquePermission(
- "cms.structure.submit");
- return userSubject.hasPermission(node, submitPermission);
+ "cms.structure.submit");
+ CmsData cmsData = cmsDataFactory.getCmsData(context);
+ Parameters screenConfig = cmsData.getEmbeddedScreenConfig();
+ long parentId = screenConfig.getLong("parent_id", -1L);
+ Resource parent = parentId != -1L ? NavigationNodeResourceImpl
+ .getNavigationNodeResource(coralSession, parentId) : cmsData.getNode();
+ return userSubject.hasPermission(parent, submitPermission);
}
if("EditDocument".equals(state))
{
long id = requestParameters.getLong("node_id", -1);
Resource node = NavigationNodeResourceImpl.getNavigationNodeResource(coralSession,
id);
Permission modifyPermission = coralSession.getSecurity().getUniquePermission(
"cms.structure.modify");
Permission modifyOwnPermission = coralSession.getSecurity().getUniquePermission(
"cms.structure.modify_own");
if(userSubject.hasPermission(node, modifyPermission))
{
return true;
}
if(node.getOwner().equals(userSubject)
&& userSubject.hasPermission(node, modifyOwnPermission))
{
return true;
}
return false;
}
}
catch(Exception e)
{
throw new ProcessingException(e);
}
throw new ProcessingException("invalid state " + state);
}
/**
* Welcome view for the anonymous user.
* <p>
* Allows the user to log in, or proceed to submit a document anonymously.
* </p>
*/
public void prepareAnonymous(Context context)
{
}
/**
* Submitted documents list for an authenticated user.
*/
public void prepareMyDocuments(Context context) throws ProcessingException
{
try
{
CmsData cmsData = cmsDataFactory.getCmsData(context);
CoralSession coralSession = context.getAttribute(CoralSession.class);
String query = "FIND RESOURCE FROM documents.document_node WHERE created_by = "
+ coralSession.getUserSubject().getIdString() + " AND site = "
+ cmsData.getSite().getIdString();
List<Resource> myDocuments = coralSession.getQuery().executeQuery(query).getList(1);
TemplatingContext templatingContext = context.getAttribute(TemplatingContext.class);
templatingContext.put("myDocuments", myDocuments);
}
catch(Exception e)
{
throw new ProcessingException("internal errror", e);
}
}
/**
* Propse a new document, either anonymously or as an authenitcated user.
*
* @param context
* @throws ProcessingException
*/
public void prepareAddDocument(Context context)
throws ProcessingException
{
Parameters parameters = RequestParameters.getRequestParameters(context);
CoralSession coralSession = (CoralSession)context.getAttribute(CoralSession.class);
TemplatingContext templatingContext = TemplatingContext.getTemplatingContext(context);
SiteResource site = getSite();
try
{
// refill parameters in case we are coming back failed validation
Parameters screenConfig = getScreenConfig();
ProposedDocumentData data = new ProposedDocumentData(screenConfig);
data.fromParameters(parameters, coralSession);
data.toTemplatingContext(templatingContext);
prepareCategories(context, true);
// resolve parent node in case template needs it for security check
CmsData cmsData = cmsDataFactory.getCmsData(context);
long parentId = screenConfig.getLong("parent_id", -1L);
Resource parentNode = parentId != -1L ? NavigationNodeResourceImpl
.getNavigationNodeResource(coralSession, parentId) : cmsData.getNode();
templatingContext.put("parent_node", parentNode);
}
catch(Exception e)
{
screenError(getNode(), context, "Screen Error ", e);
}
}
/**
* Edit a previously submitted document.
*
* @param context
* @throws ProcessingException
*/
public void prepareEditDocument(Context context) throws ProcessingException
{
Parameters parameters = RequestParameters.getRequestParameters(context);
CoralSession coralSession = (CoralSession)context.getAttribute(CoralSession.class);
TemplatingContext templatingContext = TemplatingContext.getTemplatingContext(context);
try
{
long docId = parameters.getLong("doc_id");
DocumentNodeResource node = DocumentNodeResourceImpl.getDocumentNodeResource(coralSession, docId);
templatingContext.put("doc", node);
ProposedDocumentData data = new ProposedDocumentData(getScreenConfig());
data.fromNode(node, categoryService, relatedService, htmlService, coralSession);
data.toTemplatingContext(templatingContext);
prepareCategories(context, true);
}
catch(Exception e)
{
screenError(getNode(), context, "Internal Error", e);
}
}
public void prepareResult(Context context)
throws ProcessingException
{
// does nothing
}
}
| false | true | public boolean checkAccessRights(Context context)
throws ProcessingException
{
TemplatingContext templatingContext = context.getAttribute(TemplatingContext.class);
String result = (String)templatingContext.get("result");
if("exception".equals(result))
{
return true;
}
String state = getState();
if("Anonymous".equals(state))
{
return true;
}
if("MyDocuments".equals(state))
{
// no particular permission needed to see the stuff you sumbitted, provided you are
// authenticated
return true;
}
try
{
Parameters requestParameters = context.getAttribute(RequestParameters.class);
CoralSession coralSession = context.getAttribute(CoralSession.class);
Subject userSubject = coralSession.getUserSubject();
if("AddDocument".equals(state))
{
long id = requestParameters.getLong("parent_node_id", -1);
Resource node;
if(id != -1)
{
node = NavigationNodeResourceImpl.getNavigationNodeResource(coralSession, id);
}
else
{
node = cmsDataFactory.getCmsData(context).getHomePage();
}
Permission submitPermission = coralSession.getSecurity().getUniquePermission(
"cms.structure.submit");
return userSubject.hasPermission(node, submitPermission);
}
if("EditDocument".equals(state))
{
long id = requestParameters.getLong("node_id", -1);
Resource node = NavigationNodeResourceImpl.getNavigationNodeResource(coralSession,
id);
Permission modifyPermission = coralSession.getSecurity().getUniquePermission(
"cms.structure.modify");
Permission modifyOwnPermission = coralSession.getSecurity().getUniquePermission(
"cms.structure.modify_own");
if(userSubject.hasPermission(node, modifyPermission))
{
return true;
}
if(node.getOwner().equals(userSubject)
&& userSubject.hasPermission(node, modifyOwnPermission))
{
return true;
}
return false;
}
}
catch(Exception e)
{
throw new ProcessingException(e);
}
throw new ProcessingException("invalid state " + state);
}
| public boolean checkAccessRights(Context context)
throws ProcessingException
{
TemplatingContext templatingContext = context.getAttribute(TemplatingContext.class);
String result = (String)templatingContext.get("result");
if("exception".equals(result))
{
return true;
}
String state = getState();
if("Anonymous".equals(state))
{
return true;
}
if("MyDocuments".equals(state))
{
// no particular permission needed to see the stuff you sumbitted, provided you are
// authenticated
return true;
}
try
{
Parameters requestParameters = context.getAttribute(RequestParameters.class);
CoralSession coralSession = context.getAttribute(CoralSession.class);
Subject userSubject = coralSession.getUserSubject();
if("AddDocument".equals(state))
{
Permission submitPermission = coralSession.getSecurity().getUniquePermission(
"cms.structure.submit");
CmsData cmsData = cmsDataFactory.getCmsData(context);
Parameters screenConfig = cmsData.getEmbeddedScreenConfig();
long parentId = screenConfig.getLong("parent_id", -1L);
Resource parent = parentId != -1L ? NavigationNodeResourceImpl
.getNavigationNodeResource(coralSession, parentId) : cmsData.getNode();
return userSubject.hasPermission(parent, submitPermission);
}
if("EditDocument".equals(state))
{
long id = requestParameters.getLong("node_id", -1);
Resource node = NavigationNodeResourceImpl.getNavigationNodeResource(coralSession,
id);
Permission modifyPermission = coralSession.getSecurity().getUniquePermission(
"cms.structure.modify");
Permission modifyOwnPermission = coralSession.getSecurity().getUniquePermission(
"cms.structure.modify_own");
if(userSubject.hasPermission(node, modifyPermission))
{
return true;
}
if(node.getOwner().equals(userSubject)
&& userSubject.hasPermission(node, modifyOwnPermission))
{
return true;
}
return false;
}
}
catch(Exception e)
{
throw new ProcessingException(e);
}
throw new ProcessingException("invalid state " + state);
}
|
diff --git a/BitMusic/bitmusic/hmi/popup/ratesong/RateSongPopUpView.java b/BitMusic/bitmusic/hmi/popup/ratesong/RateSongPopUpView.java
index 08c70a5..0172013 100644
--- a/BitMusic/bitmusic/hmi/popup/ratesong/RateSongPopUpView.java
+++ b/BitMusic/bitmusic/hmi/popup/ratesong/RateSongPopUpView.java
@@ -1,299 +1,299 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package bitmusic.hmi.popup.ratesong;
import bitmusic.hmi.mainwindow.WindowComponent;
import bitmusic.hmi.patterns.AbstractView;
import bitmusic.hmi.patterns.Observable;
import bitmusic.music.data.Grade;
import bitmusic.music.data.Song;
import java.awt.Dimension;
import java.util.HashMap;
import javax.swing.ButtonGroup;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
/**
*
* @author unkedeuxke
*/
public final class RateSongPopUpView extends AbstractView<RateSongPopUpController> {
private final String type = "POPUP";
private int parentTabId;
private final JLabel rateSongLabel = new JLabel("Noter un morceau");
private final JButton validateButton = new JButton("Valider");
private final JButton cancelButton = new JButton("Annuler");
private ButtonGroup groupRadio = new ButtonGroup();
private JRadioButton songRater0 = new JRadioButton("0", false);
private JRadioButton songRater1 = new JRadioButton("1", false);
private JRadioButton songRater2 = new JRadioButton("2", false);
private JRadioButton songRater3 = new JRadioButton("3", false);
private JRadioButton songRater4 = new JRadioButton("4", false);
private JRadioButton songRater5 = new JRadioButton("5", false);
/**
*
* @param parentTabId
*/
public RateSongPopUpView(int parentTabId) {
super();
this.parentTabId = parentTabId;
}
/**
*
*/
@Override
public void initPanel() {
System.out.println("--- RateSongPopUpView.initPanel()");
final Dimension d = new Dimension(80, 20);
this.rateSongLabel.setSize(d);
this.validateButton.setSize(d);
this.validateButton.addActionListener(this.getController().new ValiderListener());
this.cancelButton.setSize(d);
this.cancelButton.addActionListener(this.getController().new CancelListener());
Song song = this.getController().getModel().getSong();
- String currentUserId = WindowComponent.getInstance().getApiProfile().getCurrentUser().getLogin(); //devrait être un userId !!! Issue à Profile
+ String currentUserId = WindowComponent.getInstance().getApiProfile().getCurrentUser().getUserId();
int rate = -1;
HashMap<String,Grade> mapGrade = song.getGrades();
if (mapGrade != null) {
Grade grade = mapGrade.get(currentUserId);
if (grade != null) {
rate = grade.getGrade();
System.out.println("note = " + rate);
}
}
if (rate==0)
songRater0.setSelected(true);
if (rate==1)
songRater1.setSelected(true);
else if (rate==2)
songRater2.setSelected(true);
else if (rate==3)
songRater3.setSelected(true);
else if (rate==4)
songRater4.setSelected(true);
else if (rate==5)
songRater5.setSelected(true);
//Sinon on n'a pas encore noté la musique on n'affiche rien
// ajout dans un group radio pour faire en sorte de ne pouvoir cliquer que sur un bouton radio
this.groupRadio.add(songRater0);
this.groupRadio.add(songRater1);
this.groupRadio.add(songRater2);
this.groupRadio.add(songRater3);
this.groupRadio.add(songRater4);
this.groupRadio.add(songRater5);
GroupLayout layout = new GroupLayout(this.getPanel());
this.getPanel().setLayout(layout);
layout.setAutoCreateGaps(true);
layout.setAutoCreateContainerGaps(true);
layout.setHorizontalGroup(
layout.createSequentialGroup()
.addComponent(this.rateSongLabel)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(this.songRater0)
)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(this.songRater1)
)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(this.songRater2)
)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(this.songRater3)
)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(this.songRater4)
)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(this.songRater5)
)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(this.validateButton)
)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(this.cancelButton)
)
);
layout.setVerticalGroup(
layout.createSequentialGroup()
.addComponent(this.rateSongLabel)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(this.songRater0)
.addComponent(this.songRater1)
.addComponent(this.songRater2)
.addComponent(this.songRater3)
.addComponent(this.songRater4)
.addComponent(this.songRater5)
)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(this.validateButton)
.addComponent(this.cancelButton)
)
);
// TODO : étoiles de notation manquantes
}
/**
*
* @return
*/
@Override
public String getType() {
return type;
}
/**
*
* @param obj
* @param str
*/
@Override
public void update(Observable obj, String str) {
System.out.println("----- RateSongPopUpView.update() -> " + str);
}
/**
*
* @return
*/
public ButtonGroup getGroupRadio() {
return groupRadio;
}
/**
*
* @param groupRadio
*/
public void setGroupRadio(ButtonGroup groupRadio) {
this.groupRadio = groupRadio;
}
/**
*
* @return
*/
public JRadioButton getSongRater0() {
return songRater0;
}
/**
*
* @param songRater0
*/
public void setSongRater0(JRadioButton songRater0) {
this.songRater0 = songRater0;
}
/**
*
* @return
*/
public JRadioButton getSongRater1() {
return songRater1;
}
/**
*
* @param songRater1
*/
public void setSongRater1(JRadioButton songRater1) {
this.songRater1 = songRater1;
}
/**
*
* @return
*/
public JRadioButton getSongRater2() {
return songRater2;
}
/**
*
* @param songRater2
*/
public void setSongRater2(JRadioButton songRater2) {
this.songRater2 = songRater2;
}
/**
*
* @return
*/
public JRadioButton getSongRater3() {
return songRater3;
}
/**
*
* @param songRater3
*/
public void setSongRater3(JRadioButton songRater3) {
this.songRater3 = songRater3;
}
/**
*
* @return
*/
public JRadioButton getSongRater4() {
return songRater4;
}
/**
*
* @param songRater4
*/
public void setSongRater4(JRadioButton songRater4) {
this.songRater4 = songRater4;
}
/**
*
* @return
*/
public JRadioButton getSongRater5() {
return songRater5;
}
/**
*
* @param songRater5
*/
public void setSongRater5(JRadioButton songRater5) {
this.songRater5 = songRater5;
}
/**
*
* @return
*/
public int getParentTabId() {
return parentTabId;
}
}
| true | true | public void initPanel() {
System.out.println("--- RateSongPopUpView.initPanel()");
final Dimension d = new Dimension(80, 20);
this.rateSongLabel.setSize(d);
this.validateButton.setSize(d);
this.validateButton.addActionListener(this.getController().new ValiderListener());
this.cancelButton.setSize(d);
this.cancelButton.addActionListener(this.getController().new CancelListener());
Song song = this.getController().getModel().getSong();
String currentUserId = WindowComponent.getInstance().getApiProfile().getCurrentUser().getLogin(); //devrait être un userId !!! Issue à Profile
int rate = -1;
HashMap<String,Grade> mapGrade = song.getGrades();
if (mapGrade != null) {
Grade grade = mapGrade.get(currentUserId);
if (grade != null) {
rate = grade.getGrade();
System.out.println("note = " + rate);
}
}
if (rate==0)
songRater0.setSelected(true);
if (rate==1)
songRater1.setSelected(true);
else if (rate==2)
songRater2.setSelected(true);
else if (rate==3)
songRater3.setSelected(true);
else if (rate==4)
songRater4.setSelected(true);
else if (rate==5)
songRater5.setSelected(true);
//Sinon on n'a pas encore noté la musique on n'affiche rien
// ajout dans un group radio pour faire en sorte de ne pouvoir cliquer que sur un bouton radio
this.groupRadio.add(songRater0);
this.groupRadio.add(songRater1);
this.groupRadio.add(songRater2);
this.groupRadio.add(songRater3);
this.groupRadio.add(songRater4);
this.groupRadio.add(songRater5);
GroupLayout layout = new GroupLayout(this.getPanel());
this.getPanel().setLayout(layout);
layout.setAutoCreateGaps(true);
layout.setAutoCreateContainerGaps(true);
layout.setHorizontalGroup(
layout.createSequentialGroup()
.addComponent(this.rateSongLabel)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(this.songRater0)
)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(this.songRater1)
)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(this.songRater2)
)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(this.songRater3)
)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(this.songRater4)
)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(this.songRater5)
)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(this.validateButton)
)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(this.cancelButton)
)
);
layout.setVerticalGroup(
layout.createSequentialGroup()
.addComponent(this.rateSongLabel)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(this.songRater0)
.addComponent(this.songRater1)
.addComponent(this.songRater2)
.addComponent(this.songRater3)
.addComponent(this.songRater4)
.addComponent(this.songRater5)
)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(this.validateButton)
.addComponent(this.cancelButton)
)
);
// TODO : étoiles de notation manquantes
}
| public void initPanel() {
System.out.println("--- RateSongPopUpView.initPanel()");
final Dimension d = new Dimension(80, 20);
this.rateSongLabel.setSize(d);
this.validateButton.setSize(d);
this.validateButton.addActionListener(this.getController().new ValiderListener());
this.cancelButton.setSize(d);
this.cancelButton.addActionListener(this.getController().new CancelListener());
Song song = this.getController().getModel().getSong();
String currentUserId = WindowComponent.getInstance().getApiProfile().getCurrentUser().getUserId();
int rate = -1;
HashMap<String,Grade> mapGrade = song.getGrades();
if (mapGrade != null) {
Grade grade = mapGrade.get(currentUserId);
if (grade != null) {
rate = grade.getGrade();
System.out.println("note = " + rate);
}
}
if (rate==0)
songRater0.setSelected(true);
if (rate==1)
songRater1.setSelected(true);
else if (rate==2)
songRater2.setSelected(true);
else if (rate==3)
songRater3.setSelected(true);
else if (rate==4)
songRater4.setSelected(true);
else if (rate==5)
songRater5.setSelected(true);
//Sinon on n'a pas encore noté la musique on n'affiche rien
// ajout dans un group radio pour faire en sorte de ne pouvoir cliquer que sur un bouton radio
this.groupRadio.add(songRater0);
this.groupRadio.add(songRater1);
this.groupRadio.add(songRater2);
this.groupRadio.add(songRater3);
this.groupRadio.add(songRater4);
this.groupRadio.add(songRater5);
GroupLayout layout = new GroupLayout(this.getPanel());
this.getPanel().setLayout(layout);
layout.setAutoCreateGaps(true);
layout.setAutoCreateContainerGaps(true);
layout.setHorizontalGroup(
layout.createSequentialGroup()
.addComponent(this.rateSongLabel)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(this.songRater0)
)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(this.songRater1)
)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(this.songRater2)
)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(this.songRater3)
)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(this.songRater4)
)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(this.songRater5)
)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(this.validateButton)
)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(this.cancelButton)
)
);
layout.setVerticalGroup(
layout.createSequentialGroup()
.addComponent(this.rateSongLabel)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(this.songRater0)
.addComponent(this.songRater1)
.addComponent(this.songRater2)
.addComponent(this.songRater3)
.addComponent(this.songRater4)
.addComponent(this.songRater5)
)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(this.validateButton)
.addComponent(this.cancelButton)
)
);
// TODO : étoiles de notation manquantes
}
|
diff --git a/jingle/extension/source/org/jivesoftware/smackx/jingle/mediaimpl/jmf/AudioReceiver.java b/jingle/extension/source/org/jivesoftware/smackx/jingle/mediaimpl/jmf/AudioReceiver.java
index de718d7d..22a301db 100644
--- a/jingle/extension/source/org/jivesoftware/smackx/jingle/mediaimpl/jmf/AudioReceiver.java
+++ b/jingle/extension/source/org/jivesoftware/smackx/jingle/mediaimpl/jmf/AudioReceiver.java
@@ -1,154 +1,154 @@
/**
* $RCSfile$
* $Revision: $
* $Date: 08/11/2006
* <p/>
* Copyright 2003-2006 Jive Software.
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* 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.jivesoftware.smackx.jingle.mediaimpl.jmf;
import org.jivesoftware.smackx.jingle.media.JingleMediaSession;
import javax.media.*;
import javax.media.protocol.DataSource;
import javax.media.rtp.*;
import javax.media.rtp.event.*;
/**
* This class implements receive methods and listeners to be used in AudioChannel
*
* @author Thiago Camargo
*/
public class AudioReceiver implements ReceiveStreamListener, SessionListener,
ControllerListener {
boolean dataReceived = false;
Object dataSync;
JingleMediaSession jingleMediaSession;
public AudioReceiver(final Object dataSync, final JingleMediaSession jingleMediaSession) {
this.dataSync = dataSync;
this.jingleMediaSession = jingleMediaSession;
}
/**
* JingleSessionListener.
*/
public synchronized void update(SessionEvent evt) {
if (evt instanceof NewParticipantEvent) {
Participant p = ((NewParticipantEvent) evt).getParticipant();
System.err.println(" - A new participant had just joined: " + p.getCNAME());
}
}
/**
* ReceiveStreamListener
*/
public synchronized void update(ReceiveStreamEvent evt) {
Participant participant = evt.getParticipant(); // could be null.
ReceiveStream stream = evt.getReceiveStream(); // could be null.
if (evt instanceof RemotePayloadChangeEvent) {
System.err.println(" - Received an RTP PayloadChangeEvent.");
System.err.println("Sorry, cannot handle payload change.");
}
else if (evt instanceof NewReceiveStreamEvent) {
try {
stream = evt.getReceiveStream();
DataSource ds = stream.getDataSource();
// Find out the formats.
RTPControl ctl = (RTPControl) ds.getControl("javax.jmf.rtp.RTPControl");
- jingleMediaSession.mediaReceived(participant!=null?participant.getCNAME():"");
if (ctl != null) {
System.err.println(" - Recevied new RTP stream: " + ctl.getFormat());
}
else
System.err.println(" - Recevied new RTP stream");
if (participant == null)
System.err.println(" The sender of this stream had yet to be identified.");
else {
System.err.println(" The stream comes from: " + participant.getCNAME());
}
// create a player by passing datasource to the Media Manager
Player p = javax.media.Manager.createPlayer(ds);
if (p == null)
return;
p.addControllerListener(this);
p.realize();
+ jingleMediaSession.mediaReceived(participant != null ? participant.getCNAME() : "");
// Notify intialize() that a new stream had arrived.
synchronized (dataSync) {
dataReceived = true;
dataSync.notifyAll();
}
}
catch (Exception e) {
System.err.println("NewReceiveStreamEvent exception " + e.getMessage());
return;
}
}
else if (evt instanceof StreamMappedEvent) {
if (stream != null && stream.getDataSource() != null) {
DataSource ds = stream.getDataSource();
// Find out the formats.
RTPControl ctl = (RTPControl) ds.getControl("javax.jmf.rtp.RTPControl");
System.err.println(" - The previously unidentified stream ");
if (ctl != null)
System.err.println(" " + ctl.getFormat());
System.err.println(" had now been identified as sent by: " + participant.getCNAME());
}
}
else if (evt instanceof ByeEvent) {
System.err.println(" - Got \"bye\" from: " + participant.getCNAME());
}
}
/**
* ControllerListener for the Players.
*/
public synchronized void controllerUpdate(ControllerEvent ce) {
Player p = (Player) ce.getSourceController();
if (p == null)
return;
// Get this when the internal players are realized.
if (ce instanceof RealizeCompleteEvent) {
p.start();
}
if (ce instanceof ControllerErrorEvent) {
p.removeControllerListener(this);
System.err.println("Receiver internal error: " + ce);
}
}
}
| false | true | public synchronized void update(ReceiveStreamEvent evt) {
Participant participant = evt.getParticipant(); // could be null.
ReceiveStream stream = evt.getReceiveStream(); // could be null.
if (evt instanceof RemotePayloadChangeEvent) {
System.err.println(" - Received an RTP PayloadChangeEvent.");
System.err.println("Sorry, cannot handle payload change.");
}
else if (evt instanceof NewReceiveStreamEvent) {
try {
stream = evt.getReceiveStream();
DataSource ds = stream.getDataSource();
// Find out the formats.
RTPControl ctl = (RTPControl) ds.getControl("javax.jmf.rtp.RTPControl");
jingleMediaSession.mediaReceived(participant!=null?participant.getCNAME():"");
if (ctl != null) {
System.err.println(" - Recevied new RTP stream: " + ctl.getFormat());
}
else
System.err.println(" - Recevied new RTP stream");
if (participant == null)
System.err.println(" The sender of this stream had yet to be identified.");
else {
System.err.println(" The stream comes from: " + participant.getCNAME());
}
// create a player by passing datasource to the Media Manager
Player p = javax.media.Manager.createPlayer(ds);
if (p == null)
return;
p.addControllerListener(this);
p.realize();
// Notify intialize() that a new stream had arrived.
synchronized (dataSync) {
dataReceived = true;
dataSync.notifyAll();
}
}
catch (Exception e) {
System.err.println("NewReceiveStreamEvent exception " + e.getMessage());
return;
}
}
else if (evt instanceof StreamMappedEvent) {
if (stream != null && stream.getDataSource() != null) {
DataSource ds = stream.getDataSource();
// Find out the formats.
RTPControl ctl = (RTPControl) ds.getControl("javax.jmf.rtp.RTPControl");
System.err.println(" - The previously unidentified stream ");
if (ctl != null)
System.err.println(" " + ctl.getFormat());
System.err.println(" had now been identified as sent by: " + participant.getCNAME());
}
}
else if (evt instanceof ByeEvent) {
System.err.println(" - Got \"bye\" from: " + participant.getCNAME());
}
}
| public synchronized void update(ReceiveStreamEvent evt) {
Participant participant = evt.getParticipant(); // could be null.
ReceiveStream stream = evt.getReceiveStream(); // could be null.
if (evt instanceof RemotePayloadChangeEvent) {
System.err.println(" - Received an RTP PayloadChangeEvent.");
System.err.println("Sorry, cannot handle payload change.");
}
else if (evt instanceof NewReceiveStreamEvent) {
try {
stream = evt.getReceiveStream();
DataSource ds = stream.getDataSource();
// Find out the formats.
RTPControl ctl = (RTPControl) ds.getControl("javax.jmf.rtp.RTPControl");
if (ctl != null) {
System.err.println(" - Recevied new RTP stream: " + ctl.getFormat());
}
else
System.err.println(" - Recevied new RTP stream");
if (participant == null)
System.err.println(" The sender of this stream had yet to be identified.");
else {
System.err.println(" The stream comes from: " + participant.getCNAME());
}
// create a player by passing datasource to the Media Manager
Player p = javax.media.Manager.createPlayer(ds);
if (p == null)
return;
p.addControllerListener(this);
p.realize();
jingleMediaSession.mediaReceived(participant != null ? participant.getCNAME() : "");
// Notify intialize() that a new stream had arrived.
synchronized (dataSync) {
dataReceived = true;
dataSync.notifyAll();
}
}
catch (Exception e) {
System.err.println("NewReceiveStreamEvent exception " + e.getMessage());
return;
}
}
else if (evt instanceof StreamMappedEvent) {
if (stream != null && stream.getDataSource() != null) {
DataSource ds = stream.getDataSource();
// Find out the formats.
RTPControl ctl = (RTPControl) ds.getControl("javax.jmf.rtp.RTPControl");
System.err.println(" - The previously unidentified stream ");
if (ctl != null)
System.err.println(" " + ctl.getFormat());
System.err.println(" had now been identified as sent by: " + participant.getCNAME());
}
}
else if (evt instanceof ByeEvent) {
System.err.println(" - Got \"bye\" from: " + participant.getCNAME());
}
}
|
diff --git a/src/com/midlandroid/apps/android/laptimer/TimerHistory.java b/src/com/midlandroid/apps/android/laptimer/TimerHistory.java
index d7796e8..937bec4 100644
--- a/src/com/midlandroid/apps/android/laptimer/TimerHistory.java
+++ b/src/com/midlandroid/apps/android/laptimer/TimerHistory.java
@@ -1,138 +1,138 @@
package com.midlandroid.apps.android.laptimer;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import com.midlandroid.apps.android.laptimer.util.OpenDatabaseHelper;
import com.midlandroid.apps.android.laptimer.util.SimpleFileAccess;
import com.midlandroid.apps.android.laptimer.util.TextUtil;
import com.midlandroid.apps.android.laptimer.util.TimerHistoryDbResult;
import android.app.Activity;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class TimerHistory extends Activity {
private ListView historyList;
private List<TimerHistoryDbResult> timerHistory;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.timer_history);
historyList = (ListView) findViewById(R.id.history_list);
historyList.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
// TODO replace this with a pop-up window displaying the contents of the history
- Toast.makeText(getApplicationContext(), "View item coming soon.", Toast.LENGTH_LONG).show();
+ Toast.makeText(getApplicationContext(), "View item coming soon.", Toast.LENGTH_SHORT).show();
}
});
historyList.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View view, int pos, long id) {
// TODO replace this with a pop-up window displaying the contents of the history
- Toast.makeText(getApplicationContext(), "Manage item coming soon.", Toast.LENGTH_LONG).show();
+ Toast.makeText(getApplicationContext(), "Manage item coming soon.", Toast.LENGTH_SHORT).show();
// long click was handled
return true;
}
});
OpenDatabaseHelper dbHelper = new OpenDatabaseHelper(this);
timerHistory = dbHelper.selectAll();
dbHelper.close();
_populateListWithTimerHistory();
}
////////////////////////////////////
// Options Menu
////////////////////////////////////
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.history_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.mi_write_all_to_sdcard:
_writeAllHistoryToSdCard();
return true;
}
return false;
}
////////////////////////////////////
// Private Methods
////////////////////////////////////
private void _writeAllHistoryToSdCard() {
//SimpleFileAccess fileAccess = new SimpleFileAccess();
// Create the number formatter that will be used later
NumberFormat numFormat = NumberFormat.getInstance();
numFormat.setMinimumIntegerDigits(2);
numFormat.setMaximumIntegerDigits(2);
numFormat.setParseIntegerOnly(true);
// Local reference to the timer history list
List<TimerHistoryDbResult> tmpHistory = timerHistory;
for (TimerHistoryDbResult result : tmpHistory) {
new SimpleFileAccess().showOutFileAlertPromptAndWriteTo(this,
//"/sdcard/laptimer/"+DateFormat.format("yyyyMMdd-kkmmss",new Date().getTime())+"/laptimer_"+DateFormat.format("yyyyMMdd-kkmmss",result.getStartedAt()) + ".txt",
"/sdcard/laptimer_"+DateFormat.format("yyyyMMdd-kkmmss",result.getStartedAt()) + ".txt",
"Started on: "+TextUtil.formatDateToString(result.getStartedAt()) + "\n" +
"Duration: "+TextUtil.formatDateToString(result.getDuration(), numFormat) + "\n\n" +
"History:\n" + result.getHistory());
}
}
/**
* Using the values returned by querying for
* saved timer histories, build the history list.
*/
private void _populateListWithTimerHistory() {
// Create the number formatter that will be used later
NumberFormat numFormat = NumberFormat.getInstance();
numFormat.setMinimumIntegerDigits(2);
numFormat.setMaximumIntegerDigits(2);
numFormat.setParseIntegerOnly(true);
// Local reference to the timer history list
List<TimerHistoryDbResult> tmpHistory = timerHistory;
// Get the values from each element in the results list
List<String> listItems = new ArrayList<String>();
for (TimerHistoryDbResult result : tmpHistory) {
listItems.add(new String(
TextUtil.formatDateToString(result.getStartedAt()) + "\n" +
"Duration: " + TextUtil.formatDateToString(result.getDuration(), numFormat)));
}
// Add the values to the list
historyList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listItems.toArray(new String[0])));
}
}
| false | true | public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.timer_history);
historyList = (ListView) findViewById(R.id.history_list);
historyList.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
// TODO replace this with a pop-up window displaying the contents of the history
Toast.makeText(getApplicationContext(), "View item coming soon.", Toast.LENGTH_LONG).show();
}
});
historyList.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View view, int pos, long id) {
// TODO replace this with a pop-up window displaying the contents of the history
Toast.makeText(getApplicationContext(), "Manage item coming soon.", Toast.LENGTH_LONG).show();
// long click was handled
return true;
}
});
OpenDatabaseHelper dbHelper = new OpenDatabaseHelper(this);
timerHistory = dbHelper.selectAll();
dbHelper.close();
_populateListWithTimerHistory();
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.timer_history);
historyList = (ListView) findViewById(R.id.history_list);
historyList.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
// TODO replace this with a pop-up window displaying the contents of the history
Toast.makeText(getApplicationContext(), "View item coming soon.", Toast.LENGTH_SHORT).show();
}
});
historyList.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View view, int pos, long id) {
// TODO replace this with a pop-up window displaying the contents of the history
Toast.makeText(getApplicationContext(), "Manage item coming soon.", Toast.LENGTH_SHORT).show();
// long click was handled
return true;
}
});
OpenDatabaseHelper dbHelper = new OpenDatabaseHelper(this);
timerHistory = dbHelper.selectAll();
dbHelper.close();
_populateListWithTimerHistory();
}
|
diff --git a/src/com/simple/calculator/MainActivity.java b/src/com/simple/calculator/MainActivity.java
index 03f6247..f44b7cf 100644
--- a/src/com/simple/calculator/MainActivity.java
+++ b/src/com/simple/calculator/MainActivity.java
@@ -1,344 +1,346 @@
package com.simple.calculator;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
/**
* Project Simple Calculator : Main Activity
* This class is main activity class for Simple Calculator project
* In this class is portrait mode for calculator interface found in activity_main.xml
* This is only interface class and all calculations are done in different class
* Class tries to be smart about what inputs are valid and what are not and that way prevent user errors
*/
public ArrayList<String> calculate = new ArrayList<String>(); //This ArrayList holds calculation
public String buffer = null; //This String is buffer for adding numbers to the calculate Sting ArrayList
public String ans = "0"; //This Sting holds last answer that is calculated and it has default value of 0
/*
* Here is interface TextView
*/
TextView screen;
/*
* Hear is few static variables for some important chars
*/
public static String POTENS = "²";
public static String SQROOT = "√";
public static String OBRACKET = "(";
public static String CBRACKET = ")";
public static String DIVISION = "÷";
public static String MULTIPLY = "x";
public static String PLUS = "+";
public static String MINUS = "-";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
screen = (TextView) findViewById(R.id.view);
}
public void updScreen(){
/**
* updScreen() is method for updating TextView called screen for giving user feedback
* screen shows calculation that is entered
*/
if (this.calculate.size() == 0){
// Set number 0 for screen if no calculation has been given
this.screen.setText("0");
return;
}
// Idea is show user everything that has been set for ArrayList calculate by getting all Strings and adding them into one and setting that string text for TextView screen
String tmp = "";
for (String s : this.calculate) tmp = tmp + s;
this.screen.setText(tmp);
}
public void don(View v){
/**
* don() is method used as button listener for number buttons
*/
if (this.buffer == null){
if (calculate.size() == 0){
// if calculate size is 0 and ans is pushed then ans value is set to buffer and calculate
if ("ans".equals((String) v.getTag())){
buffer = ans;
calculate.add(buffer);
}
// if calculate size is 0 and number button is pushed then that number is set to buffer and calculate
else{
buffer = (String) v.getTag();
calculate.add(this.buffer);
}
}
// if calculate size is one or more and last symbol is potens it is replaced by number
else if (calculate.get(this.calculate.size()-1).equals(POTENS) && calculate.size() != 0){
calculate.remove(calculate.size()-1);
buffer = calculate.get(calculate.size()-1);
buffer = buffer + ( (String) v.getTag());
calculate.set(calculate.size()-1, buffer);
}
// if calculate size is one or more and last symbol is closing bracket nothing will be done
else if (calculate.get(this.calculate.size()-1).equals(CBRACKET)) return;
// if calculate size is one or more and last symbol isn't potens or closing bracket then number of tag is added to calculator
else {
if ("ans".equals((String) v.getTag())){
buffer = ans;
calculate.add(buffer);
}
else {
this.buffer = (String) v.getTag();
this.calculate.add(this.buffer);
}
}
}
else {
// if point or ans is given then nothing will be done
if ( ((String) v.getTag()).equals(".") && buffer.contains(".")) return;
if ( ((String) v.getTag()).equals("ans")) return;
// In other case number is add to buffer and calulate is updated
this.buffer = this.buffer + ( (String) v.getTag() );
this.calculate.set(this.calculate.size()-1, this.buffer);
}
this.updScreen();
}
public void doact(View v){
/**
* doact() is used button listener for actions/symbol (like +, - or x) buttons like
*/
// symbol is get from component tag witch is found from View
if (calculate.size() == 0){
// if calculate size is 0 then ans is added to calculate and after that symbol is add to calculate
calculate.add(ans);
this.calculate.add((String) v.getTag());
}
else if (this.buffer != null){
// if buffer isn't empty symbol is added to calculate and buffer is emptied
this.calculate.add((String) v.getTag());
buffer = null;
this.updScreen();
return;
}
else {
String tmp = this.calculate.get(this.calculate.size()-1);
// if buffer is empty and if last symbol in calculate is potens or closing bracket then symbol is added to calculate
if (tmp.equals(POTENS) || tmp.equals(CBRACKET)){
calculate.add((String) v.getTag());
}
// if buffer is empty and last symbol is square root nothing will be done
else if (tmp.equals(SQROOT)) return;
// if buffer is empty and last symbol isn't potens, square root or closing bracket then symbol is added to calculate in way that it replaces last symbol
else {
this.calculate.set(calculate.size()-1, (String) v.getTag());
}
}
this.updScreen();
}
public void clear(View v){
/**
* clear() is button listener method for clear button and it clear buffer and calculate ArrayList
*/
this.calculate = new ArrayList<String>();
this.buffer = null;
this.updScreen();
}
public void erase(View v){
/**
* erase() is button listener method for erasing one char or number from TextView screen
*/
// if calculate size is 0 then nothing will be done
if (calculate.size() == 0) return;
if (buffer != null){
// If buffer isn't empty and buffer is longer than 1 char
// Then last char from buffer is removed and change is updated to calculate
if (buffer.length() != 1){
buffer = buffer.substring(0, buffer.length()-1);
calculate.set(calculate.size()-1, buffer);
}
// In other case (buffer isn't empty and buffer has only 1 char) buffer is emptied and last string (number) is removed from calculate
else {
calculate.remove(calculate.size()-1);
buffer = null;
}
}
else {
String tmp = this.calculate.get(this.calculate.size()-1);
// if buffer is empty and last symbol is square root then square root is removed
if (tmp.equals(SQROOT)){
calculate.remove(calculate.size()-1);
}
// if buffer is empty and last symbol is opening bracket then opening bracket is removed
else if (tmp.equals(OBRACKET)){
calculate.remove(calculate.size()-1);
}
// In other case last symbol is removed and if next to last string is number string then it will be set to buffer
else {
calculate.remove(calculate.size()-1);
tmp = this.calculate.get(this.calculate.size()-1);
if (tmp.equals(POTENS)) ;
else if (tmp.equals(CBRACKET)) ;
else buffer = tmp;
}
}
this.updScreen();
}
public void calc(View v){
/**
* calc() is button listener for "=" symbol and does the calculating. calc() calls Calculate.java with does calculating in this application
*/
//if calculate size is 1 then nothing will be done
if (this.calculate.size() == 0) return;
String tmp = this.calculate.get(this.calculate.size()-1);
//if last symbol in calculate is of the following [ +, -, x, ÷, √, ( ] then last symbol will be removed from calculate because it would cause error
if (tmp.equals(SQROOT) || tmp.equals(MULTIPLY) || tmp.equals(MINUS) || tmp.equals(PLUS) || tmp.equals(DIVISION) || tmp.equals(OBRACKET)){
// if only symbol in calculate is "(" then calculate will be initialized and nothing else will be done
if (this.calculate.size() == 1 && tmp.equals(OBRACKET)){
this.calculate = new ArrayList<String>();
this.updScreen();
return;
}
else if (tmp.equals(OBRACKET)){
// if last symbol is "(" and calculate is longer than 1 then last two symbol are removed from calculate
this.calculate.remove(this.calculate.size()-1);
this.calculate.remove(this.calculate.size()-1);
}
else{
// in other cases last symbol will be removed
this.calculate.remove(this.calculate.size()-1);
}
}
int open = 0;
for (int i = 0; i < this.calculate.size(); i++){
// This for loop has two purposes:
// 1. count how many open brackets are in calculate
// 2. change "x" symbols to "*" symbols
if (this.calculate.get(i).equals(OBRACKET)) open++;
else if (this.calculate.get(i).equals(CBRACKET)) open--;
else if (this.calculate.get(i).equals(MULTIPLY)) this.calculate.set(i, "*");
}
while (open > 0){
// This while loop will close all open brackets
this.calculate.add(CBRACKET);
open--;
}
this.updScreen();
try {
// Try Catch is used to ensure that if some illegal calculate is give for Calculate.java then application don't crash and gives user error message
// First in this try calculate we call Calculate.java and give calculate for it
new Calculate(this.calculate);
// Then answer from calculation is saved to ans
this.ans = Calculate.getResult();
// Then ans will be simplified if possible by using double and integer variables
double test = Double.parseDouble(this.ans);
if (test%1==0){
- this.ans = this.ans.substring(0, this.ans.length()-2);
+ //this.ans = this.ans.substring(0, this.ans.length()-2);
+ Double a = Double.parseDouble(this.ans);
+ this.ans = String.valueOf(a.intValue());
}
// Last ans will be set for screen
String lastText = (String) this.screen.getText();
this.screen.setText(lastText + "=\n"+this.ans);
}
catch(java.lang.Exception e) {
// if there is error or exception in try bloc and error message will be given for user
this.screen.setText("ERROR");
//System.out.print(e.toString());
this.ans = "0";
}
// Buffer is emptied and if calculate is initialize
this.calculate = new ArrayList<String>();
this.buffer = null;
}
public void brac(View v){
/**
* brac() is button listener method for brackets button and tries to be smart for adding brackets
*/
//if calculate size is 0 then "(" will be added
if (calculate.size() == 0){
calculate.add(OBRACKET);
}
else {
int open = 0; //if calculate size is not 0 then we count "(" and ")" in calculate
int close = 0;
for (String st: calculate){ //bracket count is done with for loop
if (st.equals(OBRACKET)) open ++;
else if (st.equals(CBRACKET)) close++;
}
String tmp = calculate.get(calculate.size()-1);
if (buffer == null && tmp.compareTo(POTENS) != 0){ //if buffer is empty and last symbol is not potens symbol then:
if (close < open && tmp.equals(CBRACKET)) calculate.add(CBRACKET); // -if there are open brackets and last symbol is closing bracket then closing bracket will be added
else if (close == open && tmp.equals(CBRACKET)) return; // -if there are no open brackets and last symbol is closing bracket then nothing will be done
else calculate.add(OBRACKET); // -in all other cases we will add opening bracket
}
else if (tmp.equals(POTENS) && close < open) calculate.add(CBRACKET);
else if (buffer != null && close < open){ //if buffer isn't empty and there are open brackets then buffer will be emptied and closing bracket
buffer = null;
calculate.add(CBRACKET);
}
}
this.updScreen();
}
public void tosecond(View v){
/**
* tosecond() is button listener method for potency button
*/
if (this.buffer == null ){ //if buffer is empty and if last symbol is closing bracket then potens will be added
if (calculate.size() == 0) return;
if (calculate.get(calculate.size()-1).equals(CBRACKET)){
calculate.add(POTENS);
}
else return;
}
else { //if buffer isn't empty then buffer is emptied and potens symbol will be added
buffer = null;
calculate.add(POTENS);
}
this.updScreen();
}
public void squeroot(View v){
/**
* squeroot() is button listener for square root button
*/
if (this.buffer != null) return; //if buffer isn't null then nothing will be done
if (calculate.size() != 0){
if (calculate.get(calculate.size()-1).equals(POTENS)) return;
else if (calculate.get(calculate.size()-1).equals(SQROOT)){
calculate.add(OBRACKET);
calculate.add(SQROOT);
}
else calculate.add(SQROOT);
}
else calculate.add(SQROOT); //if last symbol is not potens then square root will be added
this.updScreen();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.menuAbout:
Intent about = new Intent(MainActivity.this, AboutActivity.class);
MainActivity.this.startActivity(about);
return true;
case R.id.menuEquation:
Intent equation = new Intent(MainActivity.this, EquationActivity.class);
MainActivity.this.startActivity(equation);
return true;
default:
return false;
}
}
}
| true | true | public void calc(View v){
/**
* calc() is button listener for "=" symbol and does the calculating. calc() calls Calculate.java with does calculating in this application
*/
//if calculate size is 1 then nothing will be done
if (this.calculate.size() == 0) return;
String tmp = this.calculate.get(this.calculate.size()-1);
//if last symbol in calculate is of the following [ +, -, x, ÷, √, ( ] then last symbol will be removed from calculate because it would cause error
if (tmp.equals(SQROOT) || tmp.equals(MULTIPLY) || tmp.equals(MINUS) || tmp.equals(PLUS) || tmp.equals(DIVISION) || tmp.equals(OBRACKET)){
// if only symbol in calculate is "(" then calculate will be initialized and nothing else will be done
if (this.calculate.size() == 1 && tmp.equals(OBRACKET)){
this.calculate = new ArrayList<String>();
this.updScreen();
return;
}
else if (tmp.equals(OBRACKET)){
// if last symbol is "(" and calculate is longer than 1 then last two symbol are removed from calculate
this.calculate.remove(this.calculate.size()-1);
this.calculate.remove(this.calculate.size()-1);
}
else{
// in other cases last symbol will be removed
this.calculate.remove(this.calculate.size()-1);
}
}
int open = 0;
for (int i = 0; i < this.calculate.size(); i++){
// This for loop has two purposes:
// 1. count how many open brackets are in calculate
// 2. change "x" symbols to "*" symbols
if (this.calculate.get(i).equals(OBRACKET)) open++;
else if (this.calculate.get(i).equals(CBRACKET)) open--;
else if (this.calculate.get(i).equals(MULTIPLY)) this.calculate.set(i, "*");
}
while (open > 0){
// This while loop will close all open brackets
this.calculate.add(CBRACKET);
open--;
}
this.updScreen();
try {
// Try Catch is used to ensure that if some illegal calculate is give for Calculate.java then application don't crash and gives user error message
// First in this try calculate we call Calculate.java and give calculate for it
new Calculate(this.calculate);
// Then answer from calculation is saved to ans
this.ans = Calculate.getResult();
// Then ans will be simplified if possible by using double and integer variables
double test = Double.parseDouble(this.ans);
if (test%1==0){
this.ans = this.ans.substring(0, this.ans.length()-2);
}
// Last ans will be set for screen
String lastText = (String) this.screen.getText();
this.screen.setText(lastText + "=\n"+this.ans);
}
catch(java.lang.Exception e) {
// if there is error or exception in try bloc and error message will be given for user
this.screen.setText("ERROR");
//System.out.print(e.toString());
this.ans = "0";
}
// Buffer is emptied and if calculate is initialize
this.calculate = new ArrayList<String>();
this.buffer = null;
}
| public void calc(View v){
/**
* calc() is button listener for "=" symbol and does the calculating. calc() calls Calculate.java with does calculating in this application
*/
//if calculate size is 1 then nothing will be done
if (this.calculate.size() == 0) return;
String tmp = this.calculate.get(this.calculate.size()-1);
//if last symbol in calculate is of the following [ +, -, x, ÷, √, ( ] then last symbol will be removed from calculate because it would cause error
if (tmp.equals(SQROOT) || tmp.equals(MULTIPLY) || tmp.equals(MINUS) || tmp.equals(PLUS) || tmp.equals(DIVISION) || tmp.equals(OBRACKET)){
// if only symbol in calculate is "(" then calculate will be initialized and nothing else will be done
if (this.calculate.size() == 1 && tmp.equals(OBRACKET)){
this.calculate = new ArrayList<String>();
this.updScreen();
return;
}
else if (tmp.equals(OBRACKET)){
// if last symbol is "(" and calculate is longer than 1 then last two symbol are removed from calculate
this.calculate.remove(this.calculate.size()-1);
this.calculate.remove(this.calculate.size()-1);
}
else{
// in other cases last symbol will be removed
this.calculate.remove(this.calculate.size()-1);
}
}
int open = 0;
for (int i = 0; i < this.calculate.size(); i++){
// This for loop has two purposes:
// 1. count how many open brackets are in calculate
// 2. change "x" symbols to "*" symbols
if (this.calculate.get(i).equals(OBRACKET)) open++;
else if (this.calculate.get(i).equals(CBRACKET)) open--;
else if (this.calculate.get(i).equals(MULTIPLY)) this.calculate.set(i, "*");
}
while (open > 0){
// This while loop will close all open brackets
this.calculate.add(CBRACKET);
open--;
}
this.updScreen();
try {
// Try Catch is used to ensure that if some illegal calculate is give for Calculate.java then application don't crash and gives user error message
// First in this try calculate we call Calculate.java and give calculate for it
new Calculate(this.calculate);
// Then answer from calculation is saved to ans
this.ans = Calculate.getResult();
// Then ans will be simplified if possible by using double and integer variables
double test = Double.parseDouble(this.ans);
if (test%1==0){
//this.ans = this.ans.substring(0, this.ans.length()-2);
Double a = Double.parseDouble(this.ans);
this.ans = String.valueOf(a.intValue());
}
// Last ans will be set for screen
String lastText = (String) this.screen.getText();
this.screen.setText(lastText + "=\n"+this.ans);
}
catch(java.lang.Exception e) {
// if there is error or exception in try bloc and error message will be given for user
this.screen.setText("ERROR");
//System.out.print(e.toString());
this.ans = "0";
}
// Buffer is emptied and if calculate is initialize
this.calculate = new ArrayList<String>();
this.buffer = null;
}
|
diff --git a/bundles/org.eclipse.ecf.salvo.ui/src/org/eclipse/ecf/salvo/ui/tools/DateUtils.java b/bundles/org.eclipse.ecf.salvo.ui/src/org/eclipse/ecf/salvo/ui/tools/DateUtils.java
index f600bde..6b25892 100644
--- a/bundles/org.eclipse.ecf.salvo.ui/src/org/eclipse/ecf/salvo/ui/tools/DateUtils.java
+++ b/bundles/org.eclipse.ecf.salvo.ui/src/org/eclipse/ecf/salvo/ui/tools/DateUtils.java
@@ -1,64 +1,69 @@
/*******************************************************************************
* Copyright (c) 2011 University Of Moratuwa
*
* 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:
* Isuru Udana - UI Integration in the Workbench
*******************************************************************************/
package org.eclipse.ecf.salvo.ui.tools;
import org.eclipse.ecf.protocol.nntp.model.IArticle;
import java.text.DateFormat;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* This class provides utilities to format article dates
*
*/
public class DateUtils {
private static DateUtils INSTANCE;
/**
* @return an instance of DateUtil
*/
public static DateUtils instance(){
if (INSTANCE==null){
INSTANCE=new DateUtils();
}
return INSTANCE;
}
/**
* Makes a pleasant readable date like "today 12:15" or "12:15"
*
* @param article
* @param date RFC822 Date
* @return a pleasant readable date
*/
public String getNiceDate(IArticle article, Date date) {
if (date != null) {
Date now = new Date();
Format formatter = new SimpleDateFormat("dd/MM/yy");
String today = formatter.format(now);
String articleDate = formatter.format(date);
String formattedDate = DateFormat.getInstance().format(date);
if (today.equals(articleDate)) {
- return "Today " + formattedDate.split(" ")[1] +" "+ formattedDate.split(" ")[2];
+ String[] fD = formattedDate.split(" ");
+ if (fD.length == 2) {
+ return "Today " + fD[1];
+ } else if (fD.length == 3) {
+ return "Today " + fD[1] + " " + fD[2];
+ }
}
return formattedDate;
}
return article.getDate();
}
}
| true | true | public String getNiceDate(IArticle article, Date date) {
if (date != null) {
Date now = new Date();
Format formatter = new SimpleDateFormat("dd/MM/yy");
String today = formatter.format(now);
String articleDate = formatter.format(date);
String formattedDate = DateFormat.getInstance().format(date);
if (today.equals(articleDate)) {
return "Today " + formattedDate.split(" ")[1] +" "+ formattedDate.split(" ")[2];
}
return formattedDate;
}
return article.getDate();
}
| public String getNiceDate(IArticle article, Date date) {
if (date != null) {
Date now = new Date();
Format formatter = new SimpleDateFormat("dd/MM/yy");
String today = formatter.format(now);
String articleDate = formatter.format(date);
String formattedDate = DateFormat.getInstance().format(date);
if (today.equals(articleDate)) {
String[] fD = formattedDate.split(" ");
if (fD.length == 2) {
return "Today " + fD[1];
} else if (fD.length == 3) {
return "Today " + fD[1] + " " + fD[2];
}
}
return formattedDate;
}
return article.getDate();
}
|
diff --git a/application/app/controllers/user/ResetPasswordController.java b/application/app/controllers/user/ResetPasswordController.java
index 01933c57..a6abe026 100644
--- a/application/app/controllers/user/ResetPasswordController.java
+++ b/application/app/controllers/user/ResetPasswordController.java
@@ -1,246 +1,246 @@
package controllers.user;
import com.avaje.ebean.Ebean;
import controllers.EController;
import controllers.util.PasswordHasher;
import models.EMessages;
import models.data.Link;
import models.dbentities.ClassGroup;
import models.dbentities.UserModel;
import models.mail.EMail;
import models.mail.ForgotPwdMail;
import models.mail.StudentTeacherEmailReset;
import models.user.Independent;
import play.data.Form;
import play.data.validation.Constraints.Required;
import play.mvc.Result;
import views.html.commons.noaccess;
import views.html.forgotPwd;
import views.html.login.resetPwd;
import javax.mail.MessagingException;
import java.math.BigInteger;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.util.ArrayList;
import java.util.List;
public class ResetPasswordController extends EController {
private static SecureRandom secureRandom = new SecureRandom();
/**
* This method is called when a user hits the 'Forgot Password' button.
*
* @return forgot_pwd page
*/
public static Result forgotPwd() {
List<Link> breadcrumbs = new ArrayList<>();
breadcrumbs.add(new Link("Home", "/"));
breadcrumbs.add(new Link(EMessages.get("forgot_pwd.forgot_pwd"), "/forgotPwd"));
return ok(forgotPwd.render(EMessages.get("forgot_pwd.forgot_pwd"),
breadcrumbs,
form(ForgotPwd.class)
));
}
/**
* This method sends an email when the user requests a new password.
* @return page after user tried to request a new pwd
* @throws InvalidKeySpecException
* @throws NoSuchAlgorithmException
*/
public static Result forgotPwdSendMail() throws InvalidKeySpecException, NoSuchAlgorithmException {
List<Link> breadcrumbs = new ArrayList<>();
breadcrumbs.add(new Link("Home", "/"));
breadcrumbs.add(new Link(EMessages.get("forgot_pwd.forgot_pwd"), "/forgotPwd"));
Form<ForgotPwd> form = form(ForgotPwd.class).bindFromRequest();
if (form.hasErrors()) {
flash("error", EMessages.get(EMessages.get("error.text")));
return badRequest(forgotPwd.render((EMessages.get("forgot_pwd.forgot_pwd")), breadcrumbs, form));
}
String id = form.get().id;
UserModel userModel = Ebean.find(UserModel.class).where().eq("id", id).findUnique();
if (userModel == null) {
- flash("error", EMessages.get("error.text"));
+ flash("error", EMessages.get("error.invalid_id"));
return badRequest(forgotPwd.render(EMessages.get("forgot_pwd.forgot_pwd"), breadcrumbs, form));
}
// There are two cases, the user has an email or the user does not has a email
if (!userModel.email.isEmpty()) {
// Case 1
//check if provided email is the same as stored in the database associated with the ID
if (!userModel.email.equals(form.get().email)) {
flash("error", EMessages.get("error.text"));
return badRequest(forgotPwd.render(EMessages.get("forgot_pwd.forgot_pwd"), breadcrumbs, form));
}
// Put reset token into database
userModel.reset_token = new BigInteger(130, secureRandom).toString(32);
Ebean.save(userModel);
String baseUrl = request().host() + "/reset_password?token=" + userModel.reset_token;
// Prepare email
EMail mail = new ForgotPwdMail(userModel.email, userModel.id, baseUrl);
try {
mail.send();
flash("success", EMessages.get("forgot_pwd.mail"));
return ok(forgotPwd.render(EMessages.get("forgot_pwd.forgot_pwd"), breadcrumbs, form));
} catch (MessagingException e) {
flash("error", EMessages.get("forgot_pwd.notsent"));
return badRequest(forgotPwd.render(EMessages.get("forgot_pwd.forgot_pwd"), breadcrumbs, form));
}
} else if (userModel.email.isEmpty()) {
// Case 2
Independent indep = new Independent(userModel);
ClassGroup g = indep.getCurrentClass();
// check if there is a classgroup.
if(g == null){
flash("error", EMessages.get("forgot_pwd.no_classgroup"));
return ok(forgotPwd.render(EMessages.get("forgot_pwd.forgot_pwd"), breadcrumbs, form));
}
if(g.getTeacher() == null){
flash("error",EMessages.get("forgot_pwd.no_teacher"));
return ok(forgotPwd.render(EMessages.get("forgot_pwd.forgot_pwd"), breadcrumbs, form));
}
String teacherEmail = g.getTeacher().getData().email;
//TODO: should point to location where teacher can change passwords for a student
EMail mail = new StudentTeacherEmailReset(teacherEmail, userModel.id, "");
try {
mail.send();
flash("success", EMessages.get("forgot_pwd.mail"));
return ok(forgotPwd.render(EMessages.get("forgot_pwd.forgot_pwd"), breadcrumbs, form));
} catch (MessagingException e) {
flash("error", EMessages.get("forgot_pwd.notsent"));
return badRequest(forgotPwd.render(EMessages.get("forgot_pwd.forgot_pwd"), breadcrumbs, form));
}
} else {
flash("error", EMessages.get("error.text"));
return badRequest(forgotPwd.render(EMessages.get("forgot_pwd.forgot_pwd"), breadcrumbs, form));
}
}
/**
* The method is called when the user clicks in the email on the provided link.
* The purpose of this method is to generate a new time-based token to verify the
* form validity and the provide a new view for the users to enter his new password.
*
* @param token the generated token <url>?token=TOKEN
* @return if the provided token is valid, this method will return a view for the user to set his new password.
*/
public static Result receivePasswordResetToken(String token) {
List<Link> breadcrumbs = new ArrayList<>();
breadcrumbs.add(new Link(EMessages.get("app.home"), "/"));
breadcrumbs.add(new Link(EMessages.get("app.signUp"), "/signup"));
UserModel userModel = Ebean.find(UserModel.class).where().eq("reset_token", token).findUnique();
if (userModel == null) {
return ok(noaccess.render(breadcrumbs));
} else {
Form<ResetPasswordVerify> reset_form = form(ResetPasswordVerify.class);
// old token that is being re-used?
// generate new token to send back to the client to make sure that we don't get a random request.
// it's import that time is included in this token.
String secure_token = new BigInteger(130, secureRandom).toString(32);
Long unixTime = System.currentTimeMillis() / 1000L;
secure_token = secure_token + unixTime.toString();
userModel.reset_token = secure_token;
// Save new token.
userModel.save();
return ok(resetPwd.render(EMessages.get("forgot_pwd.forgot_pwd"),
breadcrumbs,
reset_form,
secure_token
));
}
}
/**
* This method is called when the users filled in his new password.
* The purpose of this method is to calculate the new hash value of the password and store it into the database
*
* @return page after try to reset pwd
* @throws Exception
*/
public static Result resetPassword() throws Exception {
List<Link> breadcrumbs = new ArrayList<>();
breadcrumbs.add(new Link(EMessages.get("app.home"), "/"));
breadcrumbs.add(new Link(EMessages.get("app.signUp"), "/signup"));
Form<ResetPasswordVerify> form = form(ResetPasswordVerify.class).bindFromRequest();
String id = form.get().bebras_id;
String reset_token = form.get().reset_token;
UserModel userModel = Ebean.find(UserModel.class).where().eq("id", id).findUnique();
// We perform some checks on the server side (view can be skipped).
if (userModel == null || userModel.reset_token.isEmpty() || !form.get().r_password.equals(form.get().controle_passwd)) {
return ok(noaccess.render(breadcrumbs));
}
String reset_token_database = userModel.reset_token;
Long time_check = Long.parseLong(reset_token_database.substring(26, reset_token_database.length()));
Long system_time_check = (System.currentTimeMillis() / 1000L);
// 1 min time to fill in new password
if (reset_token.equals(reset_token_database) && (system_time_check - time_check) < 60) {
PasswordHasher.SaltAndPassword sp = PasswordHasher.generateSP(form.get().r_password.toCharArray());
String passwordHEX = sp.password;
String saltHEX = sp.salt;
userModel.password = passwordHEX;
userModel.hash = saltHEX;
userModel.reset_token = "";
userModel.save();
flash("success", EMessages.get("forgot_pwd.reset_success"));
return ok(resetPwd.render(EMessages.get("forgot_pwd.forgot_pwd"),
breadcrumbs,
form,
reset_token
));
} else {
flash("error", EMessages.get("forgot_pwd.reset_fail"));
return ok(resetPwd.render(EMessages.get("forgot_pwd.forgot_pwd"),
breadcrumbs,
form,
reset_token
));
}
}
/**
* Inline class that contains public fields for play forms.
*/
public static class ForgotPwd {
@Required
public String id;
public String email;
}
/**
* Inline class that contains public fields for play forms.
*/
public static class ResetPasswordVerify {
public String bebras_id;
public String r_password;
public String controle_passwd;
public String reset_token;
}
}
| true | true | public static Result forgotPwdSendMail() throws InvalidKeySpecException, NoSuchAlgorithmException {
List<Link> breadcrumbs = new ArrayList<>();
breadcrumbs.add(new Link("Home", "/"));
breadcrumbs.add(new Link(EMessages.get("forgot_pwd.forgot_pwd"), "/forgotPwd"));
Form<ForgotPwd> form = form(ForgotPwd.class).bindFromRequest();
if (form.hasErrors()) {
flash("error", EMessages.get(EMessages.get("error.text")));
return badRequest(forgotPwd.render((EMessages.get("forgot_pwd.forgot_pwd")), breadcrumbs, form));
}
String id = form.get().id;
UserModel userModel = Ebean.find(UserModel.class).where().eq("id", id).findUnique();
if (userModel == null) {
flash("error", EMessages.get("error.text"));
return badRequest(forgotPwd.render(EMessages.get("forgot_pwd.forgot_pwd"), breadcrumbs, form));
}
// There are two cases, the user has an email or the user does not has a email
if (!userModel.email.isEmpty()) {
// Case 1
//check if provided email is the same as stored in the database associated with the ID
if (!userModel.email.equals(form.get().email)) {
flash("error", EMessages.get("error.text"));
return badRequest(forgotPwd.render(EMessages.get("forgot_pwd.forgot_pwd"), breadcrumbs, form));
}
// Put reset token into database
userModel.reset_token = new BigInteger(130, secureRandom).toString(32);
Ebean.save(userModel);
String baseUrl = request().host() + "/reset_password?token=" + userModel.reset_token;
// Prepare email
EMail mail = new ForgotPwdMail(userModel.email, userModel.id, baseUrl);
try {
mail.send();
flash("success", EMessages.get("forgot_pwd.mail"));
return ok(forgotPwd.render(EMessages.get("forgot_pwd.forgot_pwd"), breadcrumbs, form));
} catch (MessagingException e) {
flash("error", EMessages.get("forgot_pwd.notsent"));
return badRequest(forgotPwd.render(EMessages.get("forgot_pwd.forgot_pwd"), breadcrumbs, form));
}
} else if (userModel.email.isEmpty()) {
// Case 2
Independent indep = new Independent(userModel);
ClassGroup g = indep.getCurrentClass();
// check if there is a classgroup.
if(g == null){
flash("error", EMessages.get("forgot_pwd.no_classgroup"));
return ok(forgotPwd.render(EMessages.get("forgot_pwd.forgot_pwd"), breadcrumbs, form));
}
if(g.getTeacher() == null){
flash("error",EMessages.get("forgot_pwd.no_teacher"));
return ok(forgotPwd.render(EMessages.get("forgot_pwd.forgot_pwd"), breadcrumbs, form));
}
String teacherEmail = g.getTeacher().getData().email;
//TODO: should point to location where teacher can change passwords for a student
EMail mail = new StudentTeacherEmailReset(teacherEmail, userModel.id, "");
try {
mail.send();
flash("success", EMessages.get("forgot_pwd.mail"));
return ok(forgotPwd.render(EMessages.get("forgot_pwd.forgot_pwd"), breadcrumbs, form));
} catch (MessagingException e) {
flash("error", EMessages.get("forgot_pwd.notsent"));
return badRequest(forgotPwd.render(EMessages.get("forgot_pwd.forgot_pwd"), breadcrumbs, form));
}
} else {
flash("error", EMessages.get("error.text"));
return badRequest(forgotPwd.render(EMessages.get("forgot_pwd.forgot_pwd"), breadcrumbs, form));
}
}
| public static Result forgotPwdSendMail() throws InvalidKeySpecException, NoSuchAlgorithmException {
List<Link> breadcrumbs = new ArrayList<>();
breadcrumbs.add(new Link("Home", "/"));
breadcrumbs.add(new Link(EMessages.get("forgot_pwd.forgot_pwd"), "/forgotPwd"));
Form<ForgotPwd> form = form(ForgotPwd.class).bindFromRequest();
if (form.hasErrors()) {
flash("error", EMessages.get(EMessages.get("error.text")));
return badRequest(forgotPwd.render((EMessages.get("forgot_pwd.forgot_pwd")), breadcrumbs, form));
}
String id = form.get().id;
UserModel userModel = Ebean.find(UserModel.class).where().eq("id", id).findUnique();
if (userModel == null) {
flash("error", EMessages.get("error.invalid_id"));
return badRequest(forgotPwd.render(EMessages.get("forgot_pwd.forgot_pwd"), breadcrumbs, form));
}
// There are two cases, the user has an email or the user does not has a email
if (!userModel.email.isEmpty()) {
// Case 1
//check if provided email is the same as stored in the database associated with the ID
if (!userModel.email.equals(form.get().email)) {
flash("error", EMessages.get("error.text"));
return badRequest(forgotPwd.render(EMessages.get("forgot_pwd.forgot_pwd"), breadcrumbs, form));
}
// Put reset token into database
userModel.reset_token = new BigInteger(130, secureRandom).toString(32);
Ebean.save(userModel);
String baseUrl = request().host() + "/reset_password?token=" + userModel.reset_token;
// Prepare email
EMail mail = new ForgotPwdMail(userModel.email, userModel.id, baseUrl);
try {
mail.send();
flash("success", EMessages.get("forgot_pwd.mail"));
return ok(forgotPwd.render(EMessages.get("forgot_pwd.forgot_pwd"), breadcrumbs, form));
} catch (MessagingException e) {
flash("error", EMessages.get("forgot_pwd.notsent"));
return badRequest(forgotPwd.render(EMessages.get("forgot_pwd.forgot_pwd"), breadcrumbs, form));
}
} else if (userModel.email.isEmpty()) {
// Case 2
Independent indep = new Independent(userModel);
ClassGroup g = indep.getCurrentClass();
// check if there is a classgroup.
if(g == null){
flash("error", EMessages.get("forgot_pwd.no_classgroup"));
return ok(forgotPwd.render(EMessages.get("forgot_pwd.forgot_pwd"), breadcrumbs, form));
}
if(g.getTeacher() == null){
flash("error",EMessages.get("forgot_pwd.no_teacher"));
return ok(forgotPwd.render(EMessages.get("forgot_pwd.forgot_pwd"), breadcrumbs, form));
}
String teacherEmail = g.getTeacher().getData().email;
//TODO: should point to location where teacher can change passwords for a student
EMail mail = new StudentTeacherEmailReset(teacherEmail, userModel.id, "");
try {
mail.send();
flash("success", EMessages.get("forgot_pwd.mail"));
return ok(forgotPwd.render(EMessages.get("forgot_pwd.forgot_pwd"), breadcrumbs, form));
} catch (MessagingException e) {
flash("error", EMessages.get("forgot_pwd.notsent"));
return badRequest(forgotPwd.render(EMessages.get("forgot_pwd.forgot_pwd"), breadcrumbs, form));
}
} else {
flash("error", EMessages.get("error.text"));
return badRequest(forgotPwd.render(EMessages.get("forgot_pwd.forgot_pwd"), breadcrumbs, form));
}
}
|
diff --git a/core/src/processing/core/PApplet.java b/core/src/processing/core/PApplet.java
index 58f6f3b41..2eb3e3dd6 100755
--- a/core/src/processing/core/PApplet.java
+++ b/core/src/processing/core/PApplet.java
@@ -1,15598 +1,15599 @@
/* -*- 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;
/**
* 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 boolean, byte, char, color, int, float, String, Object
* @see PApplet#println(byte)
* @see PApplet#join(String[], char)
*/
static public void print(byte what) {
System.out.print(what);
System.out.flush();
}
static public void print(boolean what) {
System.out.print(what);
System.out.flush();
}
static public void print(char what) {
System.out.print(what);
System.out.flush();
}
static public void print(int what) {
System.out.print(what);
System.out.flush();
}
static public void print(long what) {
System.out.print(what);
System.out.flush();
}
static public void print(float what) {
System.out.print(what);
System.out.flush();
}
static public void print(double what) {
System.out.print(what);
System.out.flush();
}
static public void print(String what) {
System.out.print(what);
System.out.flush();
}
static public void print(Object what) {
if (what == null) {
// special case since this does fuggly things on > 1.1
System.out.print("null");
} else {
System.out.println(what.toString());
}
}
//
/**
* ( begin auto-generated from println.xml )
*
* Writes to the text area of the Processing environment's console. This is
* often helpful for looking at the data a program is producing. Each call
* to this function creates a new line of output. Individual elements can
* be separated with quotes ("") and joined with the string concatenation
* operator (+). See <b>print()</b> for more about what to expect in the output.
* <br/><br/> <b>println()</b> on an array (by itself) will write the
* contents of the array to the console. This is often helpful for looking
* at the data a program is producing. A new line is put between each
* element of the array. This function can only print one dimensional
* arrays. For arrays with higher dimensions, the result will be closer to
* that of <b>print()</b>.
*
* ( end auto-generated )
* @webref output:text_area
* @usage IDE
* @see PApplet#print(byte)
*/
static public void println() {
System.out.println();
}
//
/**
* @param what boolean, byte, char, color, int, float, String, Object
*/
static public void println(byte what) {
System.out.println(what);
System.out.flush();
}
static public void println(boolean what) {
System.out.println(what);
System.out.flush();
}
static public void println(char what) {
System.out.println(what);
System.out.flush();
}
static public void println(int what) {
System.out.println(what);
System.out.flush();
}
static public void println(long what) {
System.out.println(what);
System.out.flush();
}
static public void println(float what) {
System.out.println(what);
System.out.flush();
}
static public void println(double what) {
System.out.println(what);
System.out.flush();
}
static public void println(String what) {
System.out.println(what);
System.out.flush();
}
static public void println(Object what) {
if (what == null) {
// special case since this does fuggly things on > 1.1
System.out.println("null");
} else {
String name = what.getClass().getName();
if (name.charAt(0) == '[') {
switch (name.charAt(1)) {
case '[':
// don't even mess with multi-dimensional arrays (case '[')
// or anything else that's not int, float, boolean, char
System.out.println(what);
break;
case 'L':
// print a 1D array of objects as individual elements
Object poo[] = (Object[]) what;
for (int i = 0; i < poo.length; i++) {
if (poo[i] instanceof String) {
System.out.println("[" + i + "] \"" + poo[i] + "\"");
} else {
System.out.println("[" + i + "] " + poo[i]);
}
}
break;
case 'Z': // boolean
boolean zz[] = (boolean[]) what;
for (int i = 0; i < zz.length; i++) {
System.out.println("[" + i + "] " + zz[i]);
}
break;
case 'B': // byte
byte bb[] = (byte[]) what;
for (int i = 0; i < bb.length; i++) {
System.out.println("[" + i + "] " + bb[i]);
}
break;
case 'C': // char
char cc[] = (char[]) what;
for (int i = 0; i < cc.length; i++) {
System.out.println("[" + i + "] '" + cc[i] + "'");
}
break;
case 'I': // int
int ii[] = (int[]) what;
for (int i = 0; i < ii.length; i++) {
System.out.println("[" + i + "] " + ii[i]);
}
break;
case 'J': // int
long jj[] = (long[]) what;
for (int i = 0; i < jj.length; i++) {
System.out.println("[" + i + "] " + jj[i]);
}
break;
case 'F': // float
float ff[] = (float[]) what;
for (int i = 0; i < ff.length; i++) {
System.out.println("[" + i + "] " + ff[i]);
}
break;
case 'D': // double
double dd[] = (double[]) what;
for (int i = 0; i < dd.length; i++) {
System.out.println("[" + i + "] " + dd[i]);
}
break;
default:
System.out.println(what);
}
} else { // not an array
System.out.println(what);
}
}
}
static public void debug(String msg) {
if (DEBUG) println(msg);
}
//
/*
// not very useful, because it only works for public (and protected?)
// fields of a class, not local variables to methods
public void printvar(String name) {
try {
Field field = getClass().getDeclaredField(name);
println(name + " = " + field.get(this));
} catch (Exception e) {
e.printStackTrace();
}
}
*/
//////////////////////////////////////////////////////////////
// MATH
// lots of convenience methods for math with floats.
// doubles are overkill for processing applets, and casting
// things all the time is annoying, thus the functions below.
/**
* ( begin auto-generated from abs.xml )
*
* Calculates the absolute value (magnitude) of a number. The absolute
* value of a number is always positive.
*
* ( end auto-generated )
* @webref math:calculation
* @param n number to compute
*/
static public final float abs(float n) {
return (n < 0) ? -n : n;
}
static public final int abs(int n) {
return (n < 0) ? -n : n;
}
/**
* ( begin auto-generated from sq.xml )
*
* Squares a number (multiplies a number by itself). The result is always a
* positive number, as multiplying two negative numbers always yields a
* positive result. For example, -1 * -1 = 1.
*
* ( end auto-generated )
* @webref math:calculation
* @param n number to square
* @see PApplet#sqrt(float)
*/
static public final float sq(float n) {
return n*n;
}
/**
* ( begin auto-generated from sqrt.xml )
*
* Calculates the square root of a number. The square root of a number is
* always positive, even though there may be a valid negative root. The
* square root <b>s</b> of number <b>a</b> is such that <b>s*s = a</b>. It
* is the opposite of squaring.
*
* ( end auto-generated )
* @webref math:calculation
* @param n non-negative number
* @see PApplet#pow(float, float)
* @see PApplet#sq(float)
*/
static public final float sqrt(float n) {
return (float)Math.sqrt(n);
}
/**
* ( begin auto-generated from log.xml )
*
* Calculates the natural logarithm (the base-<i>e</i> logarithm) of a
* number. This function expects the values greater than 0.0.
*
* ( end auto-generated )
* @webref math:calculation
* @param n number greater than 0.0
*/
static public final float log(float n) {
return (float)Math.log(n);
}
/**
* ( begin auto-generated from exp.xml )
*
* Returns Euler's number <i>e</i> (2.71828...) raised to the power of the
* <b>value</b> parameter.
*
* ( end auto-generated )
* @webref math:calculation
* @param n exponent to raise
*/
static public final float exp(float n) {
return (float)Math.exp(n);
}
/**
* ( begin auto-generated from pow.xml )
*
* Facilitates exponential expressions. The <b>pow()</b> function is an
* efficient way of multiplying numbers by themselves (or their reciprocal)
* in large quantities. For example, <b>pow(3, 5)</b> is equivalent to the
* expression 3*3*3*3*3 and <b>pow(3, -5)</b> is equivalent to 1 / 3*3*3*3*3.
*
* ( end auto-generated )
* @webref math:calculation
* @param n base of the exponential expression
* @param e power by which to raise the base
* @see PApplet#sqrt(float)
*/
static public final float pow(float n, float e) {
return (float)Math.pow(n, e);
}
/**
* ( begin auto-generated from max.xml )
*
* Determines the largest value in a sequence of numbers.
*
* ( end auto-generated )
* @webref math:calculation
* @param a first number to compare
* @param b second number to compare
* @see PApplet#min(float, float, float)
*/
static public final int max(int a, int b) {
return (a > b) ? a : b;
}
static public final float max(float a, float b) {
return (a > b) ? a : b;
}
/*
static public final double max(double a, double b) {
return (a > b) ? a : b;
}
*/
/**
* @param c third number to compare
*/
static public final int max(int a, int b, int c) {
return (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c);
}
static public final float max(float a, float b, float c) {
return (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c);
}
/**
* @param list array of numbers to compare
*/
static public final int max(int[] list) {
if (list.length == 0) {
throw new ArrayIndexOutOfBoundsException(ERROR_MIN_MAX);
}
int max = list[0];
for (int i = 1; i < list.length; i++) {
if (list[i] > max) max = list[i];
}
return max;
}
static public final float max(float[] list) {
if (list.length == 0) {
throw new ArrayIndexOutOfBoundsException(ERROR_MIN_MAX);
}
float max = list[0];
for (int i = 1; i < list.length; i++) {
if (list[i] > max) max = list[i];
}
return max;
}
/**
* Find the maximum value in an array.
* Throws an ArrayIndexOutOfBoundsException if the array is length 0.
* @param list the source array
* @return The maximum value
*/
/*
static public final double max(double[] list) {
if (list.length == 0) {
throw new ArrayIndexOutOfBoundsException(ERROR_MIN_MAX);
}
double max = list[0];
for (int i = 1; i < list.length; i++) {
if (list[i] > max) max = list[i];
}
return max;
}
*/
static public final int min(int a, int b) {
return (a < b) ? a : b;
}
static public final float min(float a, float b) {
return (a < b) ? a : b;
}
/*
static public final double min(double a, double b) {
return (a < b) ? a : b;
}
*/
static public final int min(int a, int b, int c) {
return (a < b) ? ((a < c) ? a : c) : ((b < c) ? b : c);
}
/**
* ( begin auto-generated from min.xml )
*
* Determines the smallest value in a sequence of numbers.
*
* ( end auto-generated )
* @webref math:calculation
* @param a first number
* @param b second number
* @param c third number
* @see PApplet#max(float, float, float)
*/
static public final float min(float a, float b, float c) {
return (a < b) ? ((a < c) ? a : c) : ((b < c) ? b : c);
}
/*
static public final double min(double a, double b, double c) {
return (a < b) ? ((a < c) ? a : c) : ((b < c) ? b : c);
}
*/
/**
* @param list array of numbers to compare
*/
static public final int min(int[] list) {
if (list.length == 0) {
throw new ArrayIndexOutOfBoundsException(ERROR_MIN_MAX);
}
int min = list[0];
for (int i = 1; i < list.length; i++) {
if (list[i] < min) min = list[i];
}
return min;
}
static public final float min(float[] list) {
if (list.length == 0) {
throw new ArrayIndexOutOfBoundsException(ERROR_MIN_MAX);
}
float min = list[0];
for (int i = 1; i < list.length; i++) {
if (list[i] < min) min = list[i];
}
return min;
}
/**
* Find the minimum value in an array.
* Throws an ArrayIndexOutOfBoundsException if the array is length 0.
* @param list the source array
* @return The minimum value
*/
/*
static public final double min(double[] list) {
if (list.length == 0) {
throw new ArrayIndexOutOfBoundsException(ERROR_MIN_MAX);
}
double min = list[0];
for (int i = 1; i < list.length; i++) {
if (list[i] < min) min = list[i];
}
return min;
}
*/
static public final int constrain(int amt, int low, int high) {
return (amt < low) ? low : ((amt > high) ? high : amt);
}
/**
* ( begin auto-generated from constrain.xml )
*
* Constrains a value to not exceed a maximum and minimum value.
*
* ( end auto-generated )
* @webref math:calculation
* @param amt the value to constrain
* @param low minimum limit
* @param high maximum limit
* @see PApplet#max(float, float, float)
* @see PApplet#min(float, float, float)
*/
static public final float constrain(float amt, float low, float high) {
return (amt < low) ? low : ((amt > high) ? high : amt);
}
/**
* ( begin auto-generated from sin.xml )
*
* Calculates the sine of an angle. This function expects the values of the
* <b>angle</b> parameter to be provided in radians (values from 0 to
* 6.28). Values are returned in the range -1 to 1.
*
* ( end auto-generated )
* @webref math:trigonometry
* @param angle an angle in radians
* @see PApplet#cos(float)
* @see PApplet#tan(float)
* @see PApplet#radians(float)
*/
static public final float sin(float angle) {
return (float)Math.sin(angle);
}
/**
* ( begin auto-generated from cos.xml )
*
* Calculates the cosine of an angle. This function expects the values of
* the <b>angle</b> parameter to be provided in radians (values from 0 to
* PI*2). Values are returned in the range -1 to 1.
*
* ( end auto-generated )
* @webref math:trigonometry
* @param angle an angle in radians
* @see PApplet#sin(float)
* @see PApplet#tan(float)
* @see PApplet#radians(float)
*/
static public final float cos(float angle) {
return (float)Math.cos(angle);
}
/**
* ( begin auto-generated from tan.xml )
*
* Calculates the ratio of the sine and cosine of an angle. This function
* expects the values of the <b>angle</b> parameter to be provided in
* radians (values from 0 to PI*2). Values are returned in the range
* <b>infinity</b> to <b>-infinity</b>.
*
* ( end auto-generated )
* @webref math:trigonometry
* @param angle an angle in radians
* @see PApplet#cos(float)
* @see PApplet#sin(float)
* @see PApplet#radians(float)
*/
static public final float tan(float angle) {
return (float)Math.tan(angle);
}
/**
* ( begin auto-generated from asin.xml )
*
* The inverse of <b>sin()</b>, returns the arc sine of a value. This
* function expects the values in the range of -1 to 1 and values are
* returned in the range <b>-PI/2</b> to <b>PI/2</b>.
*
* ( end auto-generated )
* @webref math:trigonometry
* @param value the value whose arc sine is to be returned
* @see PApplet#sin(float)
* @see PApplet#acos(float)
* @see PApplet#atan(float)
*/
static public final float asin(float value) {
return (float)Math.asin(value);
}
/**
* ( begin auto-generated from acos.xml )
*
* The inverse of <b>cos()</b>, returns the arc cosine of a value. This
* function expects the values in the range of -1 to 1 and values are
* returned in the range <b>0</b> to <b>PI (3.1415927)</b>.
*
* ( end auto-generated )
* @webref math:trigonometry
* @param value the value whose arc cosine is to be returned
* @see PApplet#cos(float)
* @see PApplet#asin(float)
* @see PApplet#atan(float)
*/
static public final float acos(float value) {
return (float)Math.acos(value);
}
/**
* ( begin auto-generated from atan.xml )
*
* The inverse of <b>tan()</b>, returns the arc tangent of a value. This
* function expects the values in the range of -Infinity to Infinity
* (exclusive) and values are returned in the range <b>-PI/2</b> to <b>PI/2 </b>.
*
* ( end auto-generated )
* @webref math:trigonometry
* @param value -Infinity to Infinity (exclusive)
* @see PApplet#tan(float)
* @see PApplet#asin(float)
* @see PApplet#acos(float)
*/
static public final float atan(float value) {
return (float)Math.atan(value);
}
/**
* ( begin auto-generated from atan2.xml )
*
* Calculates the angle (in radians) from a specified point to the
* coordinate origin as measured from the positive x-axis. Values are
* returned as a <b>float</b> in the range from <b>PI</b> to <b>-PI</b>.
* The <b>atan2()</b> function is most often used for orienting geometry to
* the position of the cursor. Note: The y-coordinate of the point is the
* first parameter and the x-coordinate is the second due the the structure
* of calculating the tangent.
*
* ( end auto-generated )
* @webref math:trigonometry
* @param y y-coordinate of the point
* @param x x-coordinate of the point
* @see PApplet#tan(float)
*/
static public final float atan2(float y, float x) {
return (float)Math.atan2(y, x);
}
/**
* ( begin auto-generated from degrees.xml )
*
* Converts a radian measurement to its corresponding value in degrees.
* Radians and degrees are two ways of measuring the same thing. There are
* 360 degrees in a circle and 2*PI radians in a circle. For example,
* 90° = 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).
*/
protected PImage loadImageTGA(String filename) throws IOException {
InputStream is = createInput(filename);
if (is == null) return null;
byte header[] = new byte[18];
int offset = 0;
do {
int count = is.read(header, offset, header.length - offset);
if (count == -1) return null;
offset += count;
} while (offset < 18);
/*
header[2] image type code
2 (0x02) - Uncompressed, RGB images.
3 (0x03) - Uncompressed, black and white images.
10 (0x0A) - Runlength encoded RGB images.
11 (0x0B) - Compressed, black and white images. (grayscale?)
header[16] is the bit depth (8, 24, 32)
header[17] image descriptor (packed bits)
0x20 is 32 = origin upper-left
0x28 is 32 + 8 = origin upper-left + 32 bits
7 6 5 4 3 2 1 0
128 64 32 16 8 4 2 1
*/
int format = 0;
if (((header[2] == 3) || (header[2] == 11)) && // B&W, plus RLE or not
(header[16] == 8) && // 8 bits
((header[17] == 0x8) || (header[17] == 0x28))) { // origin, 32 bit
format = ALPHA;
} else if (((header[2] == 2) || (header[2] == 10)) && // RGB, RLE or not
(header[16] == 24) && // 24 bits
((header[17] == 0x20) || (header[17] == 0))) { // origin
format = RGB;
} else if (((header[2] == 2) || (header[2] == 10)) &&
(header[16] == 32) &&
((header[17] == 0x8) || (header[17] == 0x28))) { // origin, 32
format = ARGB;
}
if (format == 0) {
System.err.println("Unknown .tga file format for " + filename);
//" (" + header[2] + " " +
//(header[16] & 0xff) + " " +
//hex(header[17], 2) + ")");
return null;
}
int w = ((header[13] & 0xff) << 8) + (header[12] & 0xff);
int h = ((header[15] & 0xff) << 8) + (header[14] & 0xff);
PImage outgoing = createImage(w, h, format);
// where "reversed" means upper-left corner (normal for most of
// the modernized world, but "reversed" for the tga spec)
//boolean reversed = (header[17] & 0x20) != 0;
// https://github.com/processing/processing/issues/1682
boolean reversed = (header[17] & 0x20) == 0;
if ((header[2] == 2) || (header[2] == 3)) { // not RLE encoded
if (reversed) {
int index = (h-1) * w;
switch (format) {
case ALPHA:
for (int y = h-1; y >= 0; y--) {
for (int x = 0; x < w; x++) {
outgoing.pixels[index + x] = is.read();
}
index -= w;
}
break;
case RGB:
for (int y = h-1; y >= 0; y--) {
for (int x = 0; x < w; x++) {
outgoing.pixels[index + x] =
is.read() | (is.read() << 8) | (is.read() << 16) |
0xff000000;
}
index -= w;
}
break;
case ARGB:
for (int y = h-1; y >= 0; y--) {
for (int x = 0; x < w; x++) {
outgoing.pixels[index + x] =
is.read() | (is.read() << 8) | (is.read() << 16) |
(is.read() << 24);
}
index -= w;
}
}
} else { // not reversed
int count = w * h;
switch (format) {
case ALPHA:
for (int i = 0; i < count; i++) {
outgoing.pixels[i] = is.read();
}
break;
case RGB:
for (int i = 0; i < count; i++) {
outgoing.pixels[i] =
is.read() | (is.read() << 8) | (is.read() << 16) |
0xff000000;
}
break;
case ARGB:
for (int i = 0; i < count; i++) {
outgoing.pixels[i] =
is.read() | (is.read() << 8) | (is.read() << 16) |
(is.read() << 24);
}
break;
}
}
} else { // header[2] is 10 or 11
int index = 0;
int px[] = outgoing.pixels;
while (index < px.length) {
int num = is.read();
boolean isRLE = (num & 0x80) != 0;
if (isRLE) {
num -= 127; // (num & 0x7F) + 1
int pixel = 0;
switch (format) {
case ALPHA:
pixel = is.read();
break;
case RGB:
pixel = 0xFF000000 |
is.read() | (is.read() << 8) | (is.read() << 16);
//(is.read() << 16) | (is.read() << 8) | is.read();
break;
case ARGB:
pixel = is.read() |
(is.read() << 8) | (is.read() << 16) | (is.read() << 24);
break;
}
for (int i = 0; i < num; i++) {
px[index++] = pixel;
if (index == px.length) break;
}
} else { // write up to 127 bytes as uncompressed
num += 1;
switch (format) {
case ALPHA:
for (int i = 0; i < num; i++) {
px[index++] = is.read();
}
break;
case RGB:
for (int i = 0; i < num; i++) {
px[index++] = 0xFF000000 |
is.read() | (is.read() << 8) | (is.read() << 16);
//(is.read() << 16) | (is.read() << 8) | is.read();
}
break;
case ARGB:
for (int i = 0; i < num; i++) {
px[index++] = is.read() | //(is.read() << 24) |
(is.read() << 8) | (is.read() << 16) | (is.read() << 24);
//(is.read() << 16) | (is.read() << 8) | is.read();
}
break;
}
}
}
if (!reversed) {
int[] temp = new int[w];
for (int y = 0; y < h/2; y++) {
int z = (h-1) - y;
System.arraycopy(px, y*w, temp, 0, w);
System.arraycopy(px, z*w, px, y*w, w);
System.arraycopy(temp, 0, px, z*w, w);
}
}
}
return outgoing;
}
//////////////////////////////////////////////////////////////
// DATA I/O
// /**
// * @webref input:files
// * @brief Creates a new XML object
// * @param name the name to be given to the root element of the new XML object
// * @return an XML object, or null
// * @see XML
// * @see PApplet#loadXML(String)
// * @see PApplet#parseXML(String)
// * @see PApplet#saveXML(XML, String)
// */
// public XML createXML(String name) {
// try {
// return new XML(name);
// } catch (Exception e) {
// e.printStackTrace();
// return null;
// }
// }
/**
* @webref input:files
* @param filename name of a file in the data folder or a URL.
* @see XML
* @see PApplet#parseXML(String)
* @see PApplet#saveXML(XML, String)
* @see PApplet#loadBytes(String)
* @see PApplet#loadStrings(String)
* @see PApplet#loadTable(String)
*/
public XML loadXML(String filename) {
return loadXML(filename, null);
}
// version that uses 'options' though there are currently no supported options
/**
* @nowebref
*/
public XML loadXML(String filename, String options) {
try {
return new XML(createReader(filename), options);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* @webref input:files
* @brief Converts String content to an XML object
* @param data the content to be parsed as XML
* @return an XML object, or null
* @see XML
* @see PApplet#loadXML(String)
* @see PApplet#saveXML(XML, String)
*/
public XML parseXML(String xmlString) {
return parseXML(xmlString, null);
}
public XML parseXML(String xmlString, String options) {
try {
return XML.parse(xmlString, options);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* @webref output:files
* @param xml the XML object to save to disk
* @param filename name of the file to write to
* @see XML
* @see PApplet#loadXML(String)
* @see PApplet#parseXML(String)
*/
public boolean saveXML(XML xml, String filename) {
return saveXML(xml, filename, null);
}
public boolean saveXML(XML xml, String filename, String options) {
return xml.save(saveFile(filename), options);
}
public JSONObject parseJSONObject(String input) {
return new JSONObject(new StringReader(input));
}
/**
* @webref 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));
}
/**
* Return a full path to an item in the data folder.
* <p>
* This is only available with applications, not applets or Android.
* On Windows and Linux, this is simply the data folder, which is located
* in the same directory as the EXE file and lib folders. On Mac OS X, this
* is a path to the data folder buried inside Contents/Resources/Java.
* For the latter point, that also means that the data folder should not be
* considered writable. Use sketchPath() for now, or inputPath() and
* outputPath() once they're available in the 2.0 release.
* <p>
* dataPath() is not supported with applets because applets have their data
* folder wrapped into the JAR file. To read data from the data folder that
* works with an applet, you should use other methods such as createInput(),
* createReader(), or loadStrings().
*/
public String dataPath(String where) {
return dataFile(where).getAbsolutePath();
}
/**
* Return a full path to an item in the data folder as a File object.
* See the dataPath() method for more information.
*/
public File dataFile(String where) {
// isAbsolute() could throw an access exception, but so will writing
// to the local disk using the sketch path, so this is safe here.
File why = new File(where);
if (why.isAbsolute()) return why;
String jarPath =
getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
if (jarPath.contains("Contents/Resources/Java/")) {
// The path will be URL encoded (%20 for spaces) coming from above
// http://code.google.com/p/processing/issues/detail?id=1073
File containingFolder = new File(urlDecode(jarPath)).getParentFile();
File dataFolder = new File(containingFolder, "data");
return new File(dataFolder, where);
}
// Windows, Linux, or when not using a Mac OS X .app file
return new File(sketchPath + File.separator + "data" + File.separator + where);
}
/**
* On Windows and Linux, this is simply the data folder. On Mac OS X, this is
* the path to the data folder buried inside Contents/Resources/Java
*/
// public File inputFile(String where) {
// }
// public String inputPath(String where) {
// }
/**
* Takes a path and creates any in-between folders if they don't
* already exist. Useful when trying to save to a subfolder that
* may not actually exist.
*/
static public void createPath(String path) {
createPath(new File(path));
}
static public void createPath(File file) {
try {
String parent = file.getParent();
if (parent != null) {
File unit = new File(parent);
if (!unit.exists()) unit.mkdirs();
}
} catch (SecurityException se) {
System.err.println("You don't have permissions to create " +
file.getAbsolutePath());
}
}
static public String getExtension(String filename) {
String extension;
String lower = filename.toLowerCase();
int dot = filename.lastIndexOf('.');
if (dot == -1) {
extension = "unknown"; // no extension found
}
extension = lower.substring(dot + 1);
// check for, and strip any parameters on the url, i.e.
// filename.jpg?blah=blah&something=that
int question = extension.indexOf('?');
if (question != -1) {
extension = extension.substring(0, question);
}
return extension;
}
//////////////////////////////////////////////////////////////
// URL ENCODING
static public String urlEncode(String str) {
try {
return URLEncoder.encode(str, "UTF-8");
} catch (UnsupportedEncodingException e) { // oh c'mon
return null;
}
}
static public String urlDecode(String str) {
try {
return URLDecoder.decode(str, "UTF-8");
} catch (UnsupportedEncodingException e) { // safe per the JDK source
return null;
}
}
//////////////////////////////////////////////////////////////
// SORT
/**
* ( begin auto-generated from sort.xml )
*
* Sorts an array of numbers from smallest to largest and puts an array of
* words in alphabetical order. The original array is not modified, a
* re-ordered array is returned. The <b>count</b> parameter states the
* number of elements to sort. For example if there are 12 elements in an
* array and if count is the value 5, only the first five elements on the
* array will be sorted. <!--As of release 0126, the alphabetical ordering
* is case insensitive.-->
*
* ( end auto-generated )
* @webref data:array_functions
* @param list array to sort
* @see PApplet#reverse(boolean[])
*/
static public byte[] sort(byte list[]) {
return sort(list, list.length);
}
/**
* @param count number of elements to sort, starting from 0
*/
static public byte[] sort(byte[] list, int count) {
byte[] outgoing = new byte[list.length];
System.arraycopy(list, 0, outgoing, 0, list.length);
Arrays.sort(outgoing, 0, count);
return outgoing;
}
static public char[] sort(char list[]) {
return sort(list, list.length);
}
static public char[] sort(char[] list, int count) {
char[] outgoing = new char[list.length];
System.arraycopy(list, 0, outgoing, 0, list.length);
Arrays.sort(outgoing, 0, count);
return outgoing;
}
static public int[] sort(int list[]) {
return sort(list, list.length);
}
static public int[] sort(int[] list, int count) {
int[] outgoing = new int[list.length];
System.arraycopy(list, 0, outgoing, 0, list.length);
Arrays.sort(outgoing, 0, count);
return outgoing;
}
static public float[] sort(float list[]) {
return sort(list, list.length);
}
static public float[] sort(float[] list, int count) {
float[] outgoing = new float[list.length];
System.arraycopy(list, 0, outgoing, 0, list.length);
Arrays.sort(outgoing, 0, count);
return outgoing;
}
static public String[] sort(String list[]) {
return sort(list, list.length);
}
static public String[] sort(String[] list, int count) {
String[] outgoing = new String[list.length];
System.arraycopy(list, 0, outgoing, 0, list.length);
Arrays.sort(outgoing, 0, count);
return outgoing;
}
//////////////////////////////////////////////////////////////
// ARRAY UTILITIES
/**
* ( begin auto-generated from arrayCopy.xml )
*
* Copies an array (or part of an array) to another array. The <b>src</b>
* array is copied to the <b>dst</b> array, beginning at the position
* specified by <b>srcPos</b> and into the position specified by
* <b>dstPos</b>. The number of elements to copy is determined by
* <b>length</b>. The simplified version with two arguments copies an
* entire array to another of the same size. It is equivalent to
* "arrayCopy(src, 0, dst, 0, src.length)". This function is far more
* efficient for copying array data than iterating through a <b>for</b> and
* copying each element.
*
* ( end auto-generated )
* @webref data:array_functions
* @param src the source array
* @param srcPosition starting position in the source array
* @param dst the destination array of the same data type as the source array
* @param dstPosition starting position in the destination array
* @param length number of array elements to be copied
* @see PApplet#concat(boolean[], boolean[])
*/
static public void arrayCopy(Object src, int srcPosition,
Object dst, int dstPosition,
int length) {
System.arraycopy(src, srcPosition, dst, dstPosition, length);
}
/**
* Convenience method for arraycopy().
* Identical to <CODE>arraycopy(src, 0, dst, 0, length);</CODE>
*/
static public void arrayCopy(Object src, Object dst, int length) {
System.arraycopy(src, 0, dst, 0, length);
}
/**
* Shortcut to copy the entire contents of
* the source into the destination array.
* Identical to <CODE>arraycopy(src, 0, dst, 0, src.length);</CODE>
*/
static public void arrayCopy(Object src, Object dst) {
System.arraycopy(src, 0, dst, 0, Array.getLength(src));
}
//
/**
* @deprecated Use arrayCopy() instead.
*/
static public void arraycopy(Object src, int srcPosition,
Object dst, int dstPosition,
int length) {
System.arraycopy(src, srcPosition, dst, dstPosition, length);
}
/**
* @deprecated Use arrayCopy() instead.
*/
static public void arraycopy(Object src, Object dst, int length) {
System.arraycopy(src, 0, dst, 0, length);
}
/**
* @deprecated Use arrayCopy() instead.
*/
static public void arraycopy(Object src, Object dst) {
System.arraycopy(src, 0, dst, 0, Array.getLength(src));
}
/**
* ( begin auto-generated from expand.xml )
*
* Increases the size of an array. By default, this function doubles the
* size of the array, but the optional <b>newSize</b> parameter provides
* precise control over the increase in size.
* <br/> <br/>
* When using an array of objects, the data returned from the function must
* be cast to the object array's data type. For example: <em>SomeClass[]
* items = (SomeClass[]) expand(originalArray)</em>.
*
* ( end auto-generated )
*
* @webref data:array_functions
* @param list the array to expand
* @see PApplet#shorten(boolean[])
*/
static public boolean[] expand(boolean list[]) {
return expand(list, list.length << 1);
}
/**
* @param newSize new size for the array
*/
static public boolean[] expand(boolean list[], int newSize) {
boolean temp[] = new boolean[newSize];
System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length));
return temp;
}
static public byte[] expand(byte list[]) {
return expand(list, list.length << 1);
}
static public byte[] expand(byte list[], int newSize) {
byte temp[] = new byte[newSize];
System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length));
return temp;
}
static public char[] expand(char list[]) {
return expand(list, list.length << 1);
}
static public char[] expand(char list[], int newSize) {
char temp[] = new char[newSize];
System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length));
return temp;
}
static public int[] expand(int list[]) {
return expand(list, list.length << 1);
}
static public int[] expand(int list[], int newSize) {
int temp[] = new int[newSize];
System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length));
return temp;
}
static public long[] expand(long list[]) {
return expand(list, list.length << 1);
}
static public long[] expand(long list[], int newSize) {
long temp[] = new long[newSize];
System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length));
return temp;
}
static public float[] expand(float list[]) {
return expand(list, list.length << 1);
}
static public float[] expand(float list[], int newSize) {
float temp[] = new float[newSize];
System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length));
return temp;
}
static public double[] expand(double list[]) {
return expand(list, list.length << 1);
}
static public double[] expand(double list[], int newSize) {
double temp[] = new double[newSize];
System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length));
return temp;
}
static public String[] expand(String list[]) {
return expand(list, list.length << 1);
}
static public String[] expand(String list[], int newSize) {
String temp[] = new String[newSize];
// in case the new size is smaller than list.length
System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length));
return temp;
}
/**
* @nowebref
*/
static public Object expand(Object array) {
return expand(array, Array.getLength(array) << 1);
}
static public Object expand(Object list, int newSize) {
Class<?> type = list.getClass().getComponentType();
Object temp = Array.newInstance(type, newSize);
System.arraycopy(list, 0, temp, 0,
Math.min(Array.getLength(list), newSize));
return temp;
}
// contract() has been removed in revision 0124, use subset() instead.
// (expand() is also functionally equivalent)
/**
* ( begin auto-generated from append.xml )
*
* Expands an array by one element and adds data to the new position. The
* datatype of the <b>element</b> parameter must be the same as the
* datatype of the array.
* <br/> <br/>
* When using an array of objects, the data returned from the function must
* be cast to the object array's data type. For example: <em>SomeClass[]
* items = (SomeClass[]) append(originalArray, element)</em>.
*
* ( end auto-generated )
*
* @webref data:array_functions
* @param array array to append
* @param value new data for the array
* @see PApplet#shorten(boolean[])
* @see PApplet#expand(boolean[])
*/
static public byte[] append(byte array[], byte value) {
array = expand(array, array.length + 1);
array[array.length-1] = value;
return array;
}
static public char[] append(char array[], char value) {
array = expand(array, array.length + 1);
array[array.length-1] = value;
return array;
}
static public int[] append(int array[], int value) {
array = expand(array, array.length + 1);
array[array.length-1] = value;
return array;
}
static public float[] append(float array[], float value) {
array = expand(array, array.length + 1);
array[array.length-1] = value;
return array;
}
static public String[] append(String array[], String value) {
array = expand(array, array.length + 1);
array[array.length-1] = value;
return array;
}
static public Object append(Object array, Object value) {
int length = Array.getLength(array);
array = expand(array, length + 1);
Array.set(array, length, value);
return array;
}
/**
* ( begin auto-generated from shorten.xml )
*
* Decreases an array by one element and returns the shortened array.
* <br/> <br/>
* When using an array of objects, the data returned from the function must
* be cast to the object array's data type. For example: <em>SomeClass[]
* items = (SomeClass[]) shorten(originalArray)</em>.
*
* ( end auto-generated )
*
* @webref data:array_functions
* @param list array to shorten
* @see PApplet#append(byte[], byte)
* @see PApplet#expand(boolean[])
*/
static public boolean[] shorten(boolean list[]) {
return subset(list, 0, list.length-1);
}
static public byte[] shorten(byte list[]) {
return subset(list, 0, list.length-1);
}
static public char[] shorten(char list[]) {
return subset(list, 0, list.length-1);
}
static public int[] shorten(int list[]) {
return subset(list, 0, list.length-1);
}
static public float[] shorten(float list[]) {
return subset(list, 0, list.length-1);
}
static public String[] shorten(String list[]) {
return subset(list, 0, list.length-1);
}
static public Object shorten(Object list) {
int length = Array.getLength(list);
return subset(list, 0, length - 1);
}
/**
* ( begin auto-generated from splice.xml )
*
* Inserts a value or array of values into an existing array. The first two
* parameters must be of the same datatype. The <b>array</b> parameter
* defines the array which will be modified and the second parameter
* defines the data which will be inserted.
* <br/> <br/>
* When using an array of objects, the data returned from the function must
* be cast to the object array's data type. For example: <em>SomeClass[]
* items = (SomeClass[]) splice(array1, array2, index)</em>.
*
* ( end auto-generated )
* @webref data:array_functions
* @param list array to splice into
* @param value value to be spliced in
* @param index position in the array from which to insert data
* @see PApplet#concat(boolean[], boolean[])
* @see PApplet#subset(boolean[], int, int)
*/
static final public boolean[] splice(boolean list[],
boolean value, int index) {
boolean outgoing[] = new boolean[list.length + 1];
System.arraycopy(list, 0, outgoing, 0, index);
outgoing[index] = value;
System.arraycopy(list, index, outgoing, index + 1,
list.length - index);
return outgoing;
}
static final public boolean[] splice(boolean list[],
boolean value[], int index) {
boolean outgoing[] = new boolean[list.length + value.length];
System.arraycopy(list, 0, outgoing, 0, index);
System.arraycopy(value, 0, outgoing, index, value.length);
System.arraycopy(list, index, outgoing, index + value.length,
list.length - index);
return outgoing;
}
static final public byte[] splice(byte list[],
byte value, int index) {
byte outgoing[] = new byte[list.length + 1];
System.arraycopy(list, 0, outgoing, 0, index);
outgoing[index] = value;
System.arraycopy(list, index, outgoing, index + 1,
list.length - index);
return outgoing;
}
static final public byte[] splice(byte list[],
byte value[], int index) {
byte outgoing[] = new byte[list.length + value.length];
System.arraycopy(list, 0, outgoing, 0, index);
System.arraycopy(value, 0, outgoing, index, value.length);
System.arraycopy(list, index, outgoing, index + value.length,
list.length - index);
return outgoing;
}
static final public char[] splice(char list[],
char value, int index) {
char outgoing[] = new char[list.length + 1];
System.arraycopy(list, 0, outgoing, 0, index);
outgoing[index] = value;
System.arraycopy(list, index, outgoing, index + 1,
list.length - index);
return outgoing;
}
static final public char[] splice(char list[],
char value[], int index) {
char outgoing[] = new char[list.length + value.length];
System.arraycopy(list, 0, outgoing, 0, index);
System.arraycopy(value, 0, outgoing, index, value.length);
System.arraycopy(list, index, outgoing, index + value.length,
list.length - index);
return outgoing;
}
static final public int[] splice(int list[],
int value, int index) {
int outgoing[] = new int[list.length + 1];
System.arraycopy(list, 0, outgoing, 0, index);
outgoing[index] = value;
System.arraycopy(list, index, outgoing, index + 1,
list.length - index);
return outgoing;
}
static final public int[] splice(int list[],
int value[], int index) {
int outgoing[] = new int[list.length + value.length];
System.arraycopy(list, 0, outgoing, 0, index);
System.arraycopy(value, 0, outgoing, index, value.length);
System.arraycopy(list, index, outgoing, index + value.length,
list.length - index);
return outgoing;
}
static final public float[] splice(float list[],
float value, int index) {
float outgoing[] = new float[list.length + 1];
System.arraycopy(list, 0, outgoing, 0, index);
outgoing[index] = value;
System.arraycopy(list, index, outgoing, index + 1,
list.length - index);
return outgoing;
}
static final public float[] splice(float list[],
float value[], int index) {
float outgoing[] = new float[list.length + value.length];
System.arraycopy(list, 0, outgoing, 0, index);
System.arraycopy(value, 0, outgoing, index, value.length);
System.arraycopy(list, index, outgoing, index + value.length,
list.length - index);
return outgoing;
}
static final public String[] splice(String list[],
String value, int index) {
String outgoing[] = new String[list.length + 1];
System.arraycopy(list, 0, outgoing, 0, index);
outgoing[index] = value;
System.arraycopy(list, index, outgoing, index + 1,
list.length - index);
return outgoing;
}
static final public String[] splice(String list[],
String value[], int index) {
String outgoing[] = new String[list.length + value.length];
System.arraycopy(list, 0, outgoing, 0, index);
System.arraycopy(value, 0, outgoing, index, value.length);
System.arraycopy(list, index, outgoing, index + value.length,
list.length - index);
return outgoing;
}
static final public Object splice(Object list, Object value, int index) {
Object[] outgoing = null;
int length = Array.getLength(list);
// check whether item being spliced in is an array
if (value.getClass().getName().charAt(0) == '[') {
int vlength = Array.getLength(value);
outgoing = new Object[length + vlength];
System.arraycopy(list, 0, outgoing, 0, index);
System.arraycopy(value, 0, outgoing, index, vlength);
System.arraycopy(list, index, outgoing, index + vlength, length - index);
} else {
outgoing = new Object[length + 1];
System.arraycopy(list, 0, outgoing, 0, index);
Array.set(outgoing, index, value);
System.arraycopy(list, index, outgoing, index + 1, length - index);
}
return outgoing;
}
static public boolean[] subset(boolean list[], int start) {
return subset(list, start, list.length - start);
}
/**
* ( begin auto-generated from subset.xml )
*
* Extracts an array of elements from an existing array. The <b>array</b>
* parameter defines the array from which the elements will be copied and
* the <b>offset</b> and <b>length</b> parameters determine which elements
* to extract. If no <b>length</b> is given, elements will be extracted
* from the <b>offset</b> to the end of the array. When specifying the
* <b>offset</b> remember the first array element is 0. This function does
* not change the source array.
* <br/> <br/>
* When using an array of objects, the data returned from the function must
* be cast to the object array's data type. For example: <em>SomeClass[]
* items = (SomeClass[]) subset(originalArray, 0, 4)</em>.
*
* ( end auto-generated )
* @webref data:array_functions
* @param list array to extract from
* @param start position to begin
* @param count number of values to extract
* @see PApplet#splice(boolean[], boolean, int)
*/
static public boolean[] subset(boolean list[], int start, int count) {
boolean output[] = new boolean[count];
System.arraycopy(list, start, output, 0, count);
return output;
}
static public byte[] subset(byte list[], int start) {
return subset(list, start, list.length - start);
}
static public byte[] subset(byte list[], int start, int count) {
byte output[] = new byte[count];
System.arraycopy(list, start, output, 0, count);
return output;
}
static public char[] subset(char list[], int start) {
return subset(list, start, list.length - start);
}
static public char[] subset(char list[], int start, int count) {
char output[] = new char[count];
System.arraycopy(list, start, output, 0, count);
return output;
}
static public int[] subset(int list[], int start) {
return subset(list, start, list.length - start);
}
static public int[] subset(int list[], int start, int count) {
int output[] = new int[count];
System.arraycopy(list, start, output, 0, count);
return output;
}
static public float[] subset(float list[], int start) {
return subset(list, start, list.length - start);
}
static public float[] subset(float list[], int start, int count) {
float output[] = new float[count];
System.arraycopy(list, start, output, 0, count);
return output;
}
static public String[] subset(String list[], int start) {
return subset(list, start, list.length - start);
}
static public String[] subset(String list[], int start, int count) {
String output[] = new String[count];
System.arraycopy(list, start, output, 0, count);
return output;
}
static public Object subset(Object list, int start) {
int length = Array.getLength(list);
return subset(list, start, length - start);
}
static public Object subset(Object list, int start, int count) {
Class<?> type = list.getClass().getComponentType();
Object outgoing = Array.newInstance(type, count);
System.arraycopy(list, start, outgoing, 0, count);
return outgoing;
}
/**
* ( begin auto-generated from concat.xml )
*
* Concatenates two arrays. For example, concatenating the array { 1, 2, 3
* } and the array { 4, 5, 6 } yields { 1, 2, 3, 4, 5, 6 }. Both parameters
* must be arrays of the same datatype.
* <br/> <br/>
* When using an array of objects, the data returned from the function must
* be cast to the object array's data type. For example: <em>SomeClass[]
* items = (SomeClass[]) concat(array1, array2)</em>.
*
* ( end auto-generated )
* @webref data:array_functions
* @param a first array to concatenate
* @param b second array to concatenate
* @see PApplet#splice(boolean[], boolean, int)
* @see PApplet#arrayCopy(Object, int, Object, int, int)
*/
static public boolean[] concat(boolean a[], boolean b[]) {
boolean c[] = new boolean[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
static public byte[] concat(byte a[], byte b[]) {
byte c[] = new byte[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
static public char[] concat(char a[], char b[]) {
char c[] = new char[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
static public int[] concat(int a[], int b[]) {
int c[] = new int[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
static public float[] concat(float a[], float b[]) {
float c[] = new float[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
static public String[] concat(String a[], String b[]) {
String c[] = new String[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
static public Object concat(Object a, Object b) {
Class<?> type = a.getClass().getComponentType();
int alength = Array.getLength(a);
int blength = Array.getLength(b);
Object outgoing = Array.newInstance(type, alength + blength);
System.arraycopy(a, 0, outgoing, 0, alength);
System.arraycopy(b, 0, outgoing, alength, blength);
return outgoing;
}
//
/**
* ( begin auto-generated from reverse.xml )
*
* Reverses the order of an array.
*
* ( end auto-generated )
* @webref data:array_functions
* @param list booleans[], bytes[], chars[], ints[], floats[], or Strings[]
* @see PApplet#sort(String[], int)
*/
static public boolean[] reverse(boolean list[]) {
boolean outgoing[] = new boolean[list.length];
int length1 = list.length - 1;
for (int i = 0; i < list.length; i++) {
outgoing[i] = list[length1 - i];
}
return outgoing;
}
static public byte[] reverse(byte list[]) {
byte outgoing[] = new byte[list.length];
int length1 = list.length - 1;
for (int i = 0; i < list.length; i++) {
outgoing[i] = list[length1 - i];
}
return outgoing;
}
static public char[] reverse(char list[]) {
char outgoing[] = new char[list.length];
int length1 = list.length - 1;
for (int i = 0; i < list.length; i++) {
outgoing[i] = list[length1 - i];
}
return outgoing;
}
static public int[] reverse(int list[]) {
int outgoing[] = new int[list.length];
int length1 = list.length - 1;
for (int i = 0; i < list.length; i++) {
outgoing[i] = list[length1 - i];
}
return outgoing;
}
static public float[] reverse(float list[]) {
float outgoing[] = new float[list.length];
int length1 = list.length - 1;
for (int i = 0; i < list.length; i++) {
outgoing[i] = list[length1 - i];
}
return outgoing;
}
static public String[] reverse(String list[]) {
String outgoing[] = new String[list.length];
int length1 = list.length - 1;
for (int i = 0; i < list.length; i++) {
outgoing[i] = list[length1 - i];
}
return outgoing;
}
static public Object reverse(Object list) {
Class<?> type = list.getClass().getComponentType();
int length = Array.getLength(list);
Object outgoing = Array.newInstance(type, length);
for (int i = 0; i < length; i++) {
Array.set(outgoing, i, Array.get(list, (length - 1) - i));
}
return outgoing;
}
//////////////////////////////////////////////////////////////
// STRINGS
/**
* ( begin auto-generated from trim.xml )
*
* Removes whitespace characters from the beginning and end of a String. In
* addition to standard whitespace characters such as space, carriage
* return, and tab, this function also removes the Unicode "nbsp" character.
*
* ( end auto-generated )
* @webref data:string_functions
* @param str any string
* @see PApplet#split(String, String)
* @see PApplet#join(String[], char)
*/
static public String trim(String str) {
return str.replace('\u00A0', ' ').trim();
}
/**
* @param array a String array
*/
static public String[] trim(String[] array) {
String[] outgoing = new String[array.length];
for (int i = 0; i < array.length; i++) {
if (array[i] != null) {
outgoing[i] = array[i].replace('\u00A0', ' ').trim();
}
}
return outgoing;
}
/**
* ( begin auto-generated from join.xml )
*
* Combines an array of Strings into one String, each separated by the
* character(s) used for the <b>separator</b> parameter. To join arrays of
* ints or floats, it's necessary to first convert them to strings using
* <b>nf()</b> or <b>nfs()</b>.
*
* ( end auto-generated )
* @webref data:string_functions
* @param list array of Strings
* @param separator char or String to be placed between each item
* @see PApplet#split(String, String)
* @see PApplet#trim(String)
* @see PApplet#nf(float, int, int)
* @see PApplet#nfs(float, int, int)
*/
static public String join(String[] list, char separator) {
return join(list, String.valueOf(separator));
}
static public String join(String[] list, String separator) {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < list.length; i++) {
if (i != 0) buffer.append(separator);
buffer.append(list[i]);
}
return buffer.toString();
}
static public String[] splitTokens(String value) {
return splitTokens(value, WHITESPACE);
}
/**
* ( begin auto-generated from splitTokens.xml )
*
* The splitTokens() function splits a String at one or many character
* "tokens." The <b>tokens</b> parameter specifies the character or
* characters to be used as a boundary.
* <br/> <br/>
* If no <b>tokens</b> character is specified, any whitespace character is
* used to split. Whitespace characters include tab (\\t), line feed (\\n),
* carriage return (\\r), form feed (\\f), and space. To convert a String
* to an array of integers or floats, use the datatype conversion functions
* <b>int()</b> and <b>float()</b> to convert the array of Strings.
*
* ( end auto-generated )
* @webref data:string_functions
* @param value the String to be split
* @param delim list of individual characters that will be used as separators
* @see PApplet#split(String, String)
* @see PApplet#join(String[], String)
* @see PApplet#trim(String)
*/
static public String[] splitTokens(String value, String delim) {
StringTokenizer toker = new StringTokenizer(value, delim);
String pieces[] = new String[toker.countTokens()];
int index = 0;
while (toker.hasMoreTokens()) {
pieces[index++] = toker.nextToken();
}
return pieces;
}
/**
* ( begin auto-generated from split.xml )
*
* The split() function breaks a string into pieces using a character or
* string as the divider. The <b>delim</b> parameter specifies the
* character or characters that mark the boundaries between each piece. A
* String[] array is returned that contains each of the pieces.
* <br/> <br/>
* If the result is a set of numbers, you can convert the String[] array to
* to a float[] or int[] array using the datatype conversion functions
* <b>int()</b> and <b>float()</b> (see example above).
* <br/> <br/>
* The <b>splitTokens()</b> function works in a similar fashion, except
* that it splits using a range of characters instead of a specific
* character or sequence.
* <!-- /><br />
* This function uses regular expressions to determine how the <b>delim</b>
* parameter divides the <b>str</b> parameter. Therefore, if you use
* characters such parentheses and brackets that are used with regular
* expressions as a part of the <b>delim</b> parameter, you'll need to put
* two blackslashes (\\\\) in front of the character (see example above).
* You can read more about <a
* href="http://en.wikipedia.org/wiki/Regular_expression">regular
* expressions</a> and <a
* href="http://en.wikipedia.org/wiki/Escape_character">escape
* characters</a> on Wikipedia.
* -->
*
* ( end auto-generated )
* @webref data:string_functions
* @usage web_application
* @param value the String to be split
* @param delim the character or String used to separate the data
*/
static public String[] split(String value, char delim) {
// do this so that the exception occurs inside the user's
// program, rather than appearing to be a bug inside split()
if (value == null) return null;
//return split(what, String.valueOf(delim)); // huh
char chars[] = value.toCharArray();
int splitCount = 0; //1;
for (int i = 0; i < chars.length; i++) {
if (chars[i] == delim) splitCount++;
}
// make sure that there is something in the input string
//if (chars.length > 0) {
// if the last char is a delimeter, get rid of it..
//if (chars[chars.length-1] == delim) splitCount--;
// on second thought, i don't agree with this, will disable
//}
if (splitCount == 0) {
String splits[] = new String[1];
splits[0] = new String(value);
return splits;
}
//int pieceCount = splitCount + 1;
String splits[] = new String[splitCount + 1];
int splitIndex = 0;
int startIndex = 0;
for (int i = 0; i < chars.length; i++) {
if (chars[i] == delim) {
splits[splitIndex++] =
new String(chars, startIndex, i-startIndex);
startIndex = i + 1;
}
}
//if (startIndex != chars.length) {
splits[splitIndex] =
new String(chars, startIndex, chars.length-startIndex);
//}
return splits;
}
static public String[] split(String value, String delim) {
ArrayList<String> items = new ArrayList<String>();
int index;
int offset = 0;
while ((index = value.indexOf(delim, offset)) != -1) {
items.add(value.substring(offset, index));
offset = index + delim.length();
}
items.add(value.substring(offset));
String[] outgoing = new String[items.size()];
items.toArray(outgoing);
return outgoing;
}
static protected HashMap<String, Pattern> matchPatterns;
static Pattern matchPattern(String regexp) {
Pattern p = null;
if (matchPatterns == null) {
matchPatterns = new HashMap<String, Pattern>();
} else {
p = matchPatterns.get(regexp);
}
if (p == null) {
if (matchPatterns.size() == 10) {
// Just clear out the match patterns here if more than 10 are being
// used. It's not terribly efficient, but changes that you have >10
// different match patterns are very slim, unless you're doing
// something really tricky (like custom match() methods), in which
// case match() won't be efficient anyway. (And you should just be
// using your own Java code.) The alternative is using a queue here,
// but that's a silly amount of work for negligible benefit.
matchPatterns.clear();
}
p = Pattern.compile(regexp, Pattern.MULTILINE | Pattern.DOTALL);
matchPatterns.put(regexp, p);
}
return p;
}
/**
* ( begin auto-generated from match.xml )
*
* The match() function is used to apply a regular expression to a piece of
* text, and return matching groups (elements found inside parentheses) as
* a String array. No match will return null. If no groups are specified in
* the regexp, but the sequence matches, an array of length one (with the
* matched text as the first element of the array) will be returned.<br />
* <br />
* To use the function, first check to see if the result is null. If the
* result is null, then the sequence did not match. If the sequence did
* match, an array is returned.
* If there are groups (specified by sets of parentheses) in the regexp,
* then the contents of each will be returned in the array.
* Element [0] of a regexp match returns the entire matching string, and
* the match groups start at element [1] (the first group is [1], the
* second [2], and so on).<br />
* <br />
* The syntax can be found in the reference for Java's <a
* href="http://download.oracle.com/javase/6/docs/api/">Pattern</a> class.
* For regular expression syntax, read the <a
* href="http://download.oracle.com/javase/tutorial/essential/regex/">Java
* Tutorial</a> on the topic.
*
* ( end auto-generated )
* @webref data:string_functions
* @param str the String to be searched
* @param regexp the regexp to be used for matching
* @see PApplet#matchAll(String, String)
* @see PApplet#split(String, String)
* @see PApplet#splitTokens(String, String)
* @see PApplet#join(String[], String)
* @see PApplet#trim(String)
*/
static public String[] match(String str, String regexp) {
Pattern p = matchPattern(regexp);
Matcher m = p.matcher(str);
if (m.find()) {
int count = m.groupCount() + 1;
String[] groups = new String[count];
for (int i = 0; i < count; i++) {
groups[i] = m.group(i);
}
return groups;
}
return null;
}
/**
* ( begin auto-generated from matchAll.xml )
*
* This function is used to apply a regular expression to a piece of text,
* and return a list of matching groups (elements found inside parentheses)
* as a two-dimensional String array. No matches will return null. If no
* groups are specified in the regexp, but the sequence matches, a two
* dimensional array is still returned, but the second dimension is only of
* length one.<br />
* <br />
* To use the function, first check to see if the result is null. If the
* result is null, then the sequence did not match at all. If the sequence
* did match, a 2D array is returned. If there are groups (specified by
* sets of parentheses) in the regexp, then the contents of each will be
* returned in the array.
* Assuming, a loop with counter variable i, element [i][0] of a regexp
* match returns the entire matching string, and the match groups start at
* element [i][1] (the first group is [i][1], the second [i][2], and so
* on).<br />
* <br />
* The syntax can be found in the reference for Java's <a
* href="http://download.oracle.com/javase/6/docs/api/">Pattern</a> class.
* For regular expression syntax, read the <a
* href="http://download.oracle.com/javase/tutorial/essential/regex/">Java
* Tutorial</a> on the topic.
*
* ( end auto-generated )
* @webref data:string_functions
* @param str the String to be searched
* @param regexp the regexp to be used for matching
* @see PApplet#match(String, String)
* @see PApplet#split(String, String)
* @see PApplet#splitTokens(String, String)
* @see PApplet#join(String[], String)
* @see PApplet#trim(String)
*/
static public String[][] matchAll(String str, String regexp) {
Pattern p = matchPattern(regexp);
Matcher m = p.matcher(str);
ArrayList<String[]> results = new ArrayList<String[]>();
int count = m.groupCount() + 1;
while (m.find()) {
String[] groups = new String[count];
for (int i = 0; i < count; i++) {
groups[i] = m.group(i);
}
results.add(groups);
}
if (results.isEmpty()) {
return null;
}
String[][] matches = new String[results.size()][count];
for (int i = 0; i < matches.length; i++) {
matches[i] = results.get(i);
}
return matches;
}
//////////////////////////////////////////////////////////////
// CASTING FUNCTIONS, INSERTED BY PREPROC
/**
* Convert a char to a boolean. 'T', 't', and '1' will become the
* boolean value true, while 'F', 'f', or '0' will become false.
*/
/*
static final public boolean parseBoolean(char what) {
return ((what == 't') || (what == 'T') || (what == '1'));
}
*/
/**
* <p>Convert an integer to a boolean. Because of how Java handles upgrading
* numbers, this will also cover byte and char (as they will upgrade to
* an int without any sort of explicit cast).</p>
* <p>The preprocessor will convert boolean(what) to parseBoolean(what).</p>
* @return false if 0, true if any other number
*/
static final public boolean parseBoolean(int what) {
return (what != 0);
}
/*
// removed because this makes no useful sense
static final public boolean parseBoolean(float what) {
return (what != 0);
}
*/
/**
* Convert the string "true" or "false" to a boolean.
* @return true if 'what' is "true" or "TRUE", false otherwise
*/
static final public boolean parseBoolean(String what) {
return new Boolean(what).booleanValue();
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
/*
// removed, no need to introduce strange syntax from other languages
static final public boolean[] parseBoolean(char what[]) {
boolean outgoing[] = new boolean[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] =
((what[i] == 't') || (what[i] == 'T') || (what[i] == '1'));
}
return outgoing;
}
*/
/**
* Convert a byte array to a boolean array. Each element will be
* evaluated identical to the integer case, where a byte equal
* to zero will return false, and any other value will return true.
* @return array of boolean elements
*/
/*
static final public boolean[] parseBoolean(byte what[]) {
boolean outgoing[] = new boolean[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = (what[i] != 0);
}
return outgoing;
}
*/
/**
* Convert an int array to a boolean array. An int equal
* to zero will return false, and any other value will return true.
* @return array of boolean elements
*/
static final public boolean[] parseBoolean(int what[]) {
boolean outgoing[] = new boolean[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = (what[i] != 0);
}
return outgoing;
}
/*
// removed, not necessary... if necessary, convert to int array first
static final public boolean[] parseBoolean(float what[]) {
boolean outgoing[] = new boolean[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = (what[i] != 0);
}
return outgoing;
}
*/
static final public boolean[] parseBoolean(String what[]) {
boolean outgoing[] = new boolean[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = new Boolean(what[i]).booleanValue();
}
return outgoing;
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
static final public byte parseByte(boolean what) {
return what ? (byte)1 : 0;
}
static final public byte parseByte(char what) {
return (byte) what;
}
static final public byte parseByte(int what) {
return (byte) what;
}
static final public byte parseByte(float what) {
return (byte) what;
}
/*
// nixed, no precedent
static final public byte[] parseByte(String what) { // note: array[]
return what.getBytes();
}
*/
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
static final public byte[] parseByte(boolean what[]) {
byte outgoing[] = new byte[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = what[i] ? (byte)1 : 0;
}
return outgoing;
}
static final public byte[] parseByte(char what[]) {
byte outgoing[] = new byte[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = (byte) what[i];
}
return outgoing;
}
static final public byte[] parseByte(int what[]) {
byte outgoing[] = new byte[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = (byte) what[i];
}
return outgoing;
}
static final public byte[] parseByte(float what[]) {
byte outgoing[] = new byte[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = (byte) what[i];
}
return outgoing;
}
/*
static final public byte[][] parseByte(String what[]) { // note: array[][]
byte outgoing[][] = new byte[what.length][];
for (int i = 0; i < what.length; i++) {
outgoing[i] = what[i].getBytes();
}
return outgoing;
}
*/
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
/*
static final public char parseChar(boolean what) { // 0/1 or T/F ?
return what ? 't' : 'f';
}
*/
static final public char parseChar(byte what) {
return (char) (what & 0xff);
}
static final public char parseChar(int what) {
return (char) what;
}
/*
static final public char parseChar(float what) { // nonsensical
return (char) what;
}
static final public char[] parseChar(String what) { // note: array[]
return what.toCharArray();
}
*/
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
/*
static final public char[] parseChar(boolean what[]) { // 0/1 or T/F ?
char outgoing[] = new char[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = what[i] ? 't' : 'f';
}
return outgoing;
}
*/
static final public char[] parseChar(byte what[]) {
char outgoing[] = new char[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = (char) (what[i] & 0xff);
}
return outgoing;
}
static final public char[] parseChar(int what[]) {
char outgoing[] = new char[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = (char) what[i];
}
return outgoing;
}
/*
static final public char[] parseChar(float what[]) { // nonsensical
char outgoing[] = new char[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = (char) what[i];
}
return outgoing;
}
static final public char[][] parseChar(String what[]) { // note: array[][]
char outgoing[][] = new char[what.length][];
for (int i = 0; i < what.length; i++) {
outgoing[i] = what[i].toCharArray();
}
return outgoing;
}
*/
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
static final public int parseInt(boolean what) {
return what ? 1 : 0;
}
/**
* Note that parseInt() will un-sign a signed byte value.
*/
static final public int parseInt(byte what) {
return what & 0xff;
}
/**
* Note that parseInt('5') is unlike String in the sense that it
* won't return 5, but the ascii value. This is because ((int) someChar)
* returns the ascii value, and parseInt() is just longhand for the cast.
*/
static final public int parseInt(char what) {
return what;
}
/**
* Same as floor(), or an (int) cast.
*/
static final public int parseInt(float what) {
return (int) what;
}
/**
* Parse a String into an int value. Returns 0 if the value is bad.
*/
static final public int parseInt(String what) {
return parseInt(what, 0);
}
/**
* Parse a String to an int, and provide an alternate value that
* should be used when the number is invalid.
*/
static final public int parseInt(String what, int otherwise) {
try {
int offset = what.indexOf('.');
if (offset == -1) {
return Integer.parseInt(what);
} else {
return Integer.parseInt(what.substring(0, offset));
}
} catch (NumberFormatException e) { }
return otherwise;
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
static final public int[] parseInt(boolean what[]) {
int list[] = new int[what.length];
for (int i = 0; i < what.length; i++) {
list[i] = what[i] ? 1 : 0;
}
return list;
}
static final public int[] parseInt(byte what[]) { // note this unsigns
int list[] = new int[what.length];
for (int i = 0; i < what.length; i++) {
list[i] = (what[i] & 0xff);
}
return list;
}
static final public int[] parseInt(char what[]) {
int list[] = new int[what.length];
for (int i = 0; i < what.length; i++) {
list[i] = what[i];
}
return list;
}
static public int[] parseInt(float what[]) {
int inties[] = new int[what.length];
for (int i = 0; i < what.length; i++) {
inties[i] = (int)what[i];
}
return inties;
}
/**
* Make an array of int elements from an array of String objects.
* If the String can't be parsed as a number, it will be set to zero.
*
* String s[] = { "1", "300", "44" };
* int numbers[] = parseInt(s);
*
* numbers will contain { 1, 300, 44 }
*/
static public int[] parseInt(String what[]) {
return parseInt(what, 0);
}
/**
* Make an array of int elements from an array of String objects.
* If the String can't be parsed as a number, its entry in the
* array will be set to the value of the "missing" parameter.
*
* String s[] = { "1", "300", "apple", "44" };
* int numbers[] = parseInt(s, 9999);
*
* numbers will contain { 1, 300, 9999, 44 }
*/
static public int[] parseInt(String what[], int missing) {
int output[] = new int[what.length];
for (int i = 0; i < what.length; i++) {
try {
output[i] = Integer.parseInt(what[i]);
} catch (NumberFormatException e) {
output[i] = missing;
}
}
return output;
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
/*
static final public float parseFloat(boolean what) {
return what ? 1 : 0;
}
*/
/**
* Convert an int to a float value. Also handles bytes because of
* Java's rules for upgrading values.
*/
static final public float parseFloat(int what) { // also handles byte
return what;
}
static final public float parseFloat(String what) {
return parseFloat(what, Float.NaN);
}
static final public float parseFloat(String what, float otherwise) {
try {
return new Float(what).floatValue();
} catch (NumberFormatException e) { }
return otherwise;
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
/*
static final public float[] parseFloat(boolean what[]) {
float floaties[] = new float[what.length];
for (int i = 0; i < what.length; i++) {
floaties[i] = what[i] ? 1 : 0;
}
return floaties;
}
static final public float[] parseFloat(char what[]) {
float floaties[] = new float[what.length];
for (int i = 0; i < what.length; i++) {
floaties[i] = (char) what[i];
}
return floaties;
}
*/
static final public float[] parseByte(byte what[]) {
float floaties[] = new float[what.length];
for (int i = 0; i < what.length; i++) {
floaties[i] = what[i];
}
return floaties;
}
static final public float[] parseFloat(int what[]) {
float floaties[] = new float[what.length];
for (int i = 0; i < what.length; i++) {
floaties[i] = what[i];
}
return floaties;
}
static final public float[] parseFloat(String what[]) {
return parseFloat(what, Float.NaN);
}
static final public float[] parseFloat(String what[], float missing) {
float output[] = new float[what.length];
for (int i = 0; i < what.length; i++) {
try {
output[i] = new Float(what[i]).floatValue();
} catch (NumberFormatException e) {
output[i] = missing;
}
}
return output;
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
static final public String str(boolean x) {
return String.valueOf(x);
}
static final public String str(byte x) {
return String.valueOf(x);
}
static final public String str(char x) {
return String.valueOf(x);
}
static final public String str(int x) {
return String.valueOf(x);
}
static final public String str(float x) {
return String.valueOf(x);
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
static final public String[] str(boolean x[]) {
String s[] = new String[x.length];
for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]);
return s;
}
static final public String[] str(byte x[]) {
String s[] = new String[x.length];
for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]);
return s;
}
static final public String[] str(char x[]) {
String s[] = new String[x.length];
for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]);
return s;
}
static final public String[] str(int x[]) {
String s[] = new String[x.length];
for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]);
return s;
}
static final public String[] str(float x[]) {
String s[] = new String[x.length];
for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]);
return s;
}
//////////////////////////////////////////////////////////////
// INT NUMBER FORMATTING
/**
* Integer number formatter.
*/
static private NumberFormat int_nf;
static private int int_nf_digits;
static private boolean int_nf_commas;
static public String[] nf(int num[], int digits) {
String formatted[] = new String[num.length];
for (int i = 0; i < formatted.length; i++) {
formatted[i] = nf(num[i], digits);
}
return formatted;
}
/**
* ( begin auto-generated from nf.xml )
*
* Utility function for formatting numbers into strings. There are two
* versions, one for formatting floats and one for formatting ints. The
* values for the <b>digits</b>, <b>left</b>, and <b>right</b> parameters
* should always be positive integers.<br /><br />As shown in the above
* example, <b>nf()</b> is used to add zeros to the left and/or right of a
* number. This is typically for aligning a list of numbers. To
* <em>remove</em> digits from a floating-point number, use the
* <b>int()</b>, <b>ceil()</b>, <b>floor()</b>, or <b>round()</b>
* functions.
*
* ( end auto-generated )
* @webref data:string_functions
* @param num the number(s) to format
* @param digits number of digits to pad with zero
* @see PApplet#nfs(float, int, int)
* @see PApplet#nfp(float, int, int)
* @see PApplet#nfc(float, int)
* @see PApplet#int(float)
*/
static public String nf(int num, int digits) {
if ((int_nf != null) &&
(int_nf_digits == digits) &&
!int_nf_commas) {
return int_nf.format(num);
}
int_nf = NumberFormat.getInstance();
int_nf.setGroupingUsed(false); // no commas
int_nf_commas = false;
int_nf.setMinimumIntegerDigits(digits);
int_nf_digits = digits;
return int_nf.format(num);
}
/**
* ( begin auto-generated from nfc.xml )
*
* Utility function for formatting numbers into strings and placing
* appropriate commas to mark units of 1000. There are two versions, one
* for formatting ints and one for formatting an array of ints. The value
* for the <b>digits</b> parameter should always be a positive integer.
* <br/> <br/>
* For a non-US locale, this will insert periods instead of commas, or
* whatever is apprioriate for that region.
*
* ( end auto-generated )
* @webref data:string_functions
* @param num the number(s) to format
* @see PApplet#nf(float, int, int)
* @see PApplet#nfp(float, int, int)
* @see PApplet#nfc(float, int)
*/
static public String[] nfc(int num[]) {
String formatted[] = new String[num.length];
for (int i = 0; i < formatted.length; i++) {
formatted[i] = nfc(num[i]);
}
return formatted;
}
/**
* nfc() or "number format with commas". This is an unfortunate misnomer
* because in locales where a comma is not the separator for numbers, it
* won't actually be outputting a comma, it'll use whatever makes sense for
* the locale.
*/
static public String nfc(int num) {
if ((int_nf != null) &&
(int_nf_digits == 0) &&
int_nf_commas) {
return int_nf.format(num);
}
int_nf = NumberFormat.getInstance();
int_nf.setGroupingUsed(true);
int_nf_commas = true;
int_nf.setMinimumIntegerDigits(0);
int_nf_digits = 0;
return int_nf.format(num);
}
/**
* number format signed (or space)
* Formats a number but leaves a blank space in the front
* when it's positive so that it can be properly aligned with
* numbers that have a negative sign in front of them.
*/
/**
* ( begin auto-generated from nfs.xml )
*
* Utility function for formatting numbers into strings. Similar to
* <b>nf()</b> but leaves a blank space in front of positive numbers so
* they align with negative numbers in spite of the minus symbol. There are
* two versions, one for formatting floats and one for formatting ints. The
* values for the <b>digits</b>, <b>left</b>, and <b>right</b> parameters
* should always be positive integers.
*
* ( end auto-generated )
* @webref data:string_functions
* @param num the number(s) to format
* @param digits number of digits to pad with zeroes
* @see PApplet#nf(float, int, int)
* @see PApplet#nfp(float, int, int)
* @see PApplet#nfc(float, int)
*/
static public String nfs(int num, int digits) {
return (num < 0) ? nf(num, digits) : (' ' + nf(num, digits));
}
static public String[] nfs(int num[], int digits) {
String formatted[] = new String[num.length];
for (int i = 0; i < formatted.length; i++) {
formatted[i] = nfs(num[i], digits);
}
return formatted;
}
//
/**
* number format positive (or plus)
* Formats a number, always placing a - or + sign
* in the front when it's negative or positive.
*/
/**
* ( begin auto-generated from nfp.xml )
*
* Utility function for formatting numbers into strings. Similar to
* <b>nf()</b> but puts a "+" in front of positive numbers and a "-" in
* front of negative numbers. There are two versions, one for formatting
* floats and one for formatting ints. The values for the <b>digits</b>,
* <b>left</b>, and <b>right</b> parameters should always be positive integers.
*
* ( end auto-generated )
* @webref data:string_functions
* @param num the number(s) to format
* @param digits number of digits to pad with zeroes
* @see PApplet#nf(float, int, int)
* @see PApplet#nfs(float, int, int)
* @see PApplet#nfc(float, int)
*/
static public String nfp(int num, int digits) {
return (num < 0) ? nf(num, digits) : ('+' + nf(num, digits));
}
static public String[] nfp(int num[], int digits) {
String formatted[] = new String[num.length];
for (int i = 0; i < formatted.length; i++) {
formatted[i] = nfp(num[i], digits);
}
return formatted;
}
//////////////////////////////////////////////////////////////
// FLOAT NUMBER FORMATTING
static private NumberFormat float_nf;
static private int float_nf_left, float_nf_right;
static private boolean float_nf_commas;
static public String[] nf(float num[], int left, int right) {
String formatted[] = new String[num.length];
for (int i = 0; i < formatted.length; i++) {
formatted[i] = nf(num[i], left, right);
}
return formatted;
}
/**
* @param num[] the number(s) to format
* @param left number of digits to the left of the decimal point
* @param right number of digits to the right of the decimal point
*/
static public String nf(float num, int left, int right) {
if ((float_nf != null) &&
(float_nf_left == left) &&
(float_nf_right == right) &&
!float_nf_commas) {
return float_nf.format(num);
}
float_nf = NumberFormat.getInstance();
float_nf.setGroupingUsed(false);
float_nf_commas = false;
if (left != 0) float_nf.setMinimumIntegerDigits(left);
if (right != 0) {
float_nf.setMinimumFractionDigits(right);
float_nf.setMaximumFractionDigits(right);
}
float_nf_left = left;
float_nf_right = right;
return float_nf.format(num);
}
/**
* @param num[] the number(s) to format
* @param right number of digits to the right of the decimal point
*/
static public String[] nfc(float num[], int right) {
String formatted[] = new String[num.length];
for (int i = 0; i < formatted.length; i++) {
formatted[i] = nfc(num[i], right);
}
return formatted;
}
static public String nfc(float num, int right) {
if ((float_nf != null) &&
(float_nf_left == 0) &&
(float_nf_right == right) &&
float_nf_commas) {
return float_nf.format(num);
}
float_nf = NumberFormat.getInstance();
float_nf.setGroupingUsed(true);
float_nf_commas = true;
if (right != 0) {
float_nf.setMinimumFractionDigits(right);
float_nf.setMaximumFractionDigits(right);
}
float_nf_left = 0;
float_nf_right = right;
return float_nf.format(num);
}
/**
* @param num[] the number(s) to format
* @param left the number of digits to the left of the decimal point
* @param right the number of digits to the right of the decimal point
*/
static public String[] nfs(float num[], int left, int right) {
String formatted[] = new String[num.length];
for (int i = 0; i < formatted.length; i++) {
formatted[i] = nfs(num[i], left, right);
}
return formatted;
}
static public String nfs(float num, int left, int right) {
return (num < 0) ? nf(num, left, right) : (' ' + nf(num, left, right));
}
/**
* @param left the number of digits to the left of the decimal point
* @param right the number of digits to the right of the decimal point
*/
static public String[] nfp(float num[], int left, int right) {
String formatted[] = new String[num.length];
for (int i = 0; i < formatted.length; i++) {
formatted[i] = nfp(num[i], left, right);
}
return formatted;
}
static public String nfp(float num, int left, int right) {
return (num < 0) ? nf(num, left, right) : ('+' + nf(num, left, right));
}
//////////////////////////////////////////////////////////////
// HEX/BINARY CONVERSION
/**
* ( begin auto-generated from hex.xml )
*
* Converts a byte, char, int, or color to a String containing the
* equivalent hexadecimal notation. For example color(0, 102, 153) will
* convert to the String "FF006699". This function can help make your geeky
* debugging sessions much happier.
* <br/> <br/>
* Note that the maximum number of digits is 8, because an int value can
* only represent up to 32 bits. Specifying more than eight digits will
* simply shorten the string to eight anyway.
*
* ( end auto-generated )
* @webref data:conversion
* @param value the value to convert
* @see PApplet#unhex(String)
* @see PApplet#binary(byte)
* @see PApplet#unbinary(String)
*/
static final public String hex(byte value) {
return hex(value, 2);
}
static final public String hex(char value) {
return hex(value, 4);
}
static final public String hex(int value) {
return hex(value, 8);
}
/**
* @param digits the number of digits (maximum 8)
*/
static final public String hex(int value, int digits) {
String stuff = Integer.toHexString(value).toUpperCase();
if (digits > 8) {
digits = 8;
}
int length = stuff.length();
if (length > digits) {
return stuff.substring(length - digits);
} else if (length < digits) {
return "00000000".substring(8 - (digits-length)) + stuff;
}
return stuff;
}
/**
* ( begin auto-generated from unhex.xml )
*
* Converts a String representation of a hexadecimal number to its
* equivalent integer value.
*
* ( end auto-generated )
*
* @webref data:conversion
* @param value String to convert to an integer
* @see PApplet#hex(int, int)
* @see PApplet#binary(byte)
* @see PApplet#unbinary(String)
*/
static final public int unhex(String value) {
// has to parse as a Long so that it'll work for numbers bigger than 2^31
return (int) (Long.parseLong(value, 16));
}
//
/**
* Returns a String that contains the binary value of a byte.
* The returned value will always have 8 digits.
*/
static final public String binary(byte value) {
return binary(value, 8);
}
/**
* Returns a String that contains the binary value of a char.
* The returned value will always have 16 digits because chars
* are two bytes long.
*/
static final public String binary(char value) {
return binary(value, 16);
}
/**
* Returns a String that contains the binary value of an int. The length
* depends on the size of the number itself. If you want a specific number
* of digits use binary(int what, int digits) to specify how many.
*/
static final public String binary(int value) {
return binary(value, 32);
}
/*
* Returns a String that contains the binary value of an int.
* The digits parameter determines how many digits will be used.
*/
/**
* ( begin auto-generated from binary.xml )
*
* Converts a byte, char, int, or color to a String containing the
* equivalent binary notation. For example color(0, 102, 153, 255) will
* convert to the String "11111111000000000110011010011001". This function
* can help make your geeky debugging sessions much happier.
* <br/> <br/>
* Note that the maximum number of digits is 32, because an int value can
* only represent up to 32 bits. Specifying more than 32 digits will simply
* shorten the string to 32 anyway.
*
* ( end auto-generated )
* @webref data:conversion
* @param value value to convert
* @param digits number of digits to return
* @see PApplet#unbinary(String)
* @see PApplet#hex(int,int)
* @see PApplet#unhex(String)
*/
static final public String binary(int value, int digits) {
String stuff = Integer.toBinaryString(value);
if (digits > 32) {
digits = 32;
}
int length = stuff.length();
if (length > digits) {
return stuff.substring(length - digits);
} else if (length < digits) {
int offset = 32 - (digits-length);
return "00000000000000000000000000000000".substring(offset) + stuff;
}
return stuff;
}
/**
* ( begin auto-generated from unbinary.xml )
*
* Converts a String representation of a binary number to its equivalent
* integer value. For example, unbinary("00001000") will return 8.
*
* ( end auto-generated )
* @webref data:conversion
* @param value String to convert to an integer
* @see PApplet#binary(byte)
* @see PApplet#hex(int,int)
* @see PApplet#unhex(String)
*/
static final public int unbinary(String value) {
return Integer.parseInt(value, 2);
}
//////////////////////////////////////////////////////////////
// COLOR FUNCTIONS
// moved here so that they can work without
// the graphics actually being instantiated (outside setup)
/**
* ( begin auto-generated from color.xml )
*
* Creates colors for storing in variables of the <b>color</b> datatype.
* The parameters are interpreted as RGB or HSB values depending on the
* current <b>colorMode()</b>. The default mode is RGB values from 0 to 255
* and therefore, the function call <b>color(255, 204, 0)</b> will return a
* bright yellow color. More about how colors are stored can be found in
* the reference for the <a href="color_datatype.html">color</a> datatype.
*
* ( end auto-generated )
* @webref color:creating_reading
* @param gray number specifying value between white and black
* @see PApplet#colorMode(int)
*/
public final int color(int gray) {
if (g == null) {
if (gray > 255) gray = 255; else if (gray < 0) gray = 0;
return 0xff000000 | (gray << 16) | (gray << 8) | gray;
}
return g.color(gray);
}
/**
* @nowebref
* @param fgray number specifying value between white and black
*/
public final int color(float fgray) {
if (g == null) {
int gray = (int) fgray;
if (gray > 255) gray = 255; else if (gray < 0) gray = 0;
return 0xff000000 | (gray << 16) | (gray << 8) | gray;
}
return g.color(fgray);
}
/**
* As of 0116 this also takes color(#FF8800, alpha)
* @param alpha relative to current color range
*/
public final int color(int gray, int alpha) {
if (g == null) {
if (alpha > 255) alpha = 255; else if (alpha < 0) alpha = 0;
if (gray > 255) {
// then assume this is actually a #FF8800
return (alpha << 24) | (gray & 0xFFFFFF);
} else {
//if (gray > 255) gray = 255; else if (gray < 0) gray = 0;
return (alpha << 24) | (gray << 16) | (gray << 8) | gray;
}
}
return g.color(gray, alpha);
}
/**
* @nowebref
*/
public final int color(float fgray, float falpha) {
if (g == null) {
int gray = (int) fgray;
int alpha = (int) falpha;
if (gray > 255) gray = 255; else if (gray < 0) gray = 0;
if (alpha > 255) alpha = 255; else if (alpha < 0) alpha = 0;
return 0xff000000 | (gray << 16) | (gray << 8) | gray;
}
return g.color(fgray, falpha);
}
/**
* @param v1 red or hue values relative to the current color range
* @param v2 green or saturation values relative to the current color range
* @param v3 blue or brightness values relative to the current color range
*/
public final int color(int v1, int v2, int v3) {
if (g == null) {
if (v1 > 255) v1 = 255; else if (v1 < 0) v1 = 0;
if (v2 > 255) v2 = 255; else if (v2 < 0) v2 = 0;
if (v3 > 255) v3 = 255; else if (v3 < 0) v3 = 0;
return 0xff000000 | (v1 << 16) | (v2 << 8) | v3;
}
return g.color(v1, v2, v3);
}
public final int color(int v1, int v2, int v3, int alpha) {
if (g == null) {
if (alpha > 255) alpha = 255; else if (alpha < 0) alpha = 0;
if (v1 > 255) v1 = 255; else if (v1 < 0) v1 = 0;
if (v2 > 255) v2 = 255; else if (v2 < 0) v2 = 0;
if (v3 > 255) v3 = 255; else if (v3 < 0) v3 = 0;
return (alpha << 24) | (v1 << 16) | (v2 << 8) | v3;
}
return g.color(v1, v2, v3, alpha);
}
public final int color(float v1, float v2, float v3) {
if (g == null) {
if (v1 > 255) v1 = 255; else if (v1 < 0) v1 = 0;
if (v2 > 255) v2 = 255; else if (v2 < 0) v2 = 0;
if (v3 > 255) v3 = 255; else if (v3 < 0) v3 = 0;
return 0xff000000 | ((int)v1 << 16) | ((int)v2 << 8) | (int)v3;
}
return g.color(v1, v2, v3);
}
public final int color(float v1, float v2, float v3, float alpha) {
if (g == null) {
if (alpha > 255) alpha = 255; else if (alpha < 0) alpha = 0;
if (v1 > 255) v1 = 255; else if (v1 < 0) v1 = 0;
if (v2 > 255) v2 = 255; else if (v2 < 0) v2 = 0;
if (v3 > 255) v3 = 255; else if (v3 < 0) v3 = 0;
return ((int)alpha << 24) | ((int)v1 << 16) | ((int)v2 << 8) | (int)v3;
}
return g.color(v1, v2, v3, alpha);
}
static public int blendColor(int c1, int c2, int mode) {
return PImage.blendColor(c1, c2, mode);
}
//////////////////////////////////////////////////////////////
// MAIN
/**
* Set this sketch to communicate its state back to the PDE.
* <p/>
* This uses the stderr stream to write positions of the window
* (so that it will be saved by the PDE for the next run) and
* notify on quit. See more notes in the Worker class.
*/
public void setupExternalMessages() {
frame.addComponentListener(new ComponentAdapter() {
@Override
public void componentMoved(ComponentEvent e) {
Point where = ((Frame) e.getSource()).getLocation();
System.err.println(PApplet.EXTERNAL_MOVE + " " +
where.x + " " + where.y);
System.err.flush(); // doesn't seem to help or hurt
}
});
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
// System.err.println(PApplet.EXTERNAL_QUIT);
// System.err.flush(); // important
// System.exit(0);
exit(); // don't quit, need to just shut everything down (0133)
}
});
}
/**
* Set up a listener that will fire proper component resize events
* in cases where frame.setResizable(true) is called.
*/
public void setupFrameResizeListener() {
frame.addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
// Ignore bad resize events fired during setup to fix
// http://dev.processing.org/bugs/show_bug.cgi?id=341
// This should also fix the blank screen on Linux bug
// http://dev.processing.org/bugs/show_bug.cgi?id=282
if (frame.isResizable()) {
// might be multiple resize calls before visible (i.e. first
// when pack() is called, then when it's resized for use).
// ignore them because it's not the user resizing things.
Frame farm = (Frame) e.getComponent();
if (farm.isVisible()) {
Insets insets = farm.getInsets();
Dimension windowSize = farm.getSize();
// 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);
}
}
}
}
});
}
// /**
// * 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).
- ((JFrame)frame).getContentPane().setBackground(new Color(0xCC, 0xCC, 0xCC));
+ 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);
+ ((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);
+ ((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);
}
}
| false | true | public PImage loadImage(String filename, String extension) { //, Object params) {
if (extension == null) {
String lower = filename.toLowerCase();
int dot = filename.lastIndexOf('.');
if (dot == -1) {
extension = "unknown"; // no extension found
}
extension = lower.substring(dot + 1);
// check for, and strip any parameters on the url, i.e.
// filename.jpg?blah=blah&something=that
int question = extension.indexOf('?');
if (question != -1) {
extension = extension.substring(0, question);
}
}
// just in case. them users will try anything!
extension = extension.toLowerCase();
if (extension.equals("tga")) {
try {
PImage image = loadImageTGA(filename);
// if (params != null) {
// image.setParams(g, params);
// }
return image;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
if (extension.equals("tif") || extension.equals("tiff")) {
byte bytes[] = loadBytes(filename);
PImage image = (bytes == null) ? null : PImage.loadTIFF(bytes);
// if (params != null) {
// image.setParams(g, params);
// }
return image;
}
// For jpeg, gif, and png, load them using createImage(),
// because the javax.imageio code was found to be much slower.
// http://dev.processing.org/bugs/show_bug.cgi?id=392
try {
if (extension.equals("jpg") || extension.equals("jpeg") ||
extension.equals("gif") || extension.equals("png") ||
extension.equals("unknown")) {
byte bytes[] = loadBytes(filename);
if (bytes == null) {
return null;
} else {
Image awtImage = Toolkit.getDefaultToolkit().createImage(bytes);
PImage image = loadImageMT(awtImage);
if (image.width == -1) {
System.err.println("The file " + filename +
" contains bad image data, or may not be an image.");
}
// if it's a .gif image, test to see if it has transparency
if (extension.equals("gif") || extension.equals("png")) {
image.checkAlpha();
}
// if (params != null) {
// image.setParams(g, params);
// }
return image;
}
}
} catch (Exception e) {
// show error, but move on to the stuff below, see if it'll work
e.printStackTrace();
}
if (loadImageFormats == null) {
loadImageFormats = ImageIO.getReaderFormatNames();
}
if (loadImageFormats != null) {
for (int i = 0; i < loadImageFormats.length; i++) {
if (extension.equals(loadImageFormats[i])) {
return loadImageIO(filename);
// PImage image = loadImageIO(filename);
// if (params != null) {
// image.setParams(g, params);
// }
// return image;
}
}
}
// failed, could not load image after all those attempts
System.err.println("Could not find a method to load " + filename);
return null;
}
public PImage requestImage(String filename) {
// return requestImage(filename, null, null);
return requestImage(filename, null);
}
/**
* ( begin auto-generated from requestImage.xml )
*
* This function load images on a separate thread so that your sketch does
* not freeze while images load during <b>setup()</b>. While the image is
* loading, its width and height will be 0. If an error occurs while
* loading the image, its width and height will be set to -1. You'll know
* when the image has loaded properly because its width and height will be
* greater than 0. Asynchronous image loading (particularly when
* downloading from a server) can dramatically improve performance.<br />
* <br/> <b>extension</b> parameter is used to determine the image type in
* cases where the image filename does not end with a proper extension.
* Specify the extension as the second parameter to <b>requestImage()</b>.
*
* ( end auto-generated )
*
* @webref image:loading_displaying
* @param filename name of the file to load, can be .gif, .jpg, .tga, or a handful of other image types depending on your platform
* @param extension the type of image to load, for example "png", "gif", "jpg"
* @see PImage
* @see PApplet#loadImage(String, String)
*/
public PImage requestImage(String filename, String extension) {
PImage vessel = createImage(0, 0, ARGB);
AsyncImageLoader ail =
new AsyncImageLoader(filename, extension, vessel);
ail.start();
return vessel;
}
// /**
// * @nowebref
// */
// public PImage requestImage(String filename, String extension, Object params) {
// PImage vessel = createImage(0, 0, ARGB, params);
// AsyncImageLoader ail =
// new AsyncImageLoader(filename, extension, vessel);
// ail.start();
// return vessel;
// }
/**
* By trial and error, four image loading threads seem to work best when
* loading images from online. This is consistent with the number of open
* connections that web browsers will maintain. The variable is made public
* (however no accessor has been added since it's esoteric) if you really
* want to have control over the value used. For instance, when loading local
* files, it might be better to only have a single thread (or two) loading
* images so that you're disk isn't simply jumping around.
*/
public int requestImageMax = 4;
volatile int requestImageCount;
class AsyncImageLoader extends Thread {
String filename;
String extension;
PImage vessel;
public AsyncImageLoader(String filename, String extension, PImage vessel) {
this.filename = filename;
this.extension = extension;
this.vessel = vessel;
}
@Override
public void run() {
while (requestImageCount == requestImageMax) {
try {
Thread.sleep(10);
} catch (InterruptedException e) { }
}
requestImageCount++;
PImage actual = loadImage(filename, extension);
// An error message should have already printed
if (actual == null) {
vessel.width = -1;
vessel.height = -1;
} else {
vessel.width = actual.width;
vessel.height = actual.height;
vessel.format = actual.format;
vessel.pixels = actual.pixels;
}
requestImageCount--;
}
}
/**
* Load an AWT image synchronously by setting up a MediaTracker for
* a single image, and blocking until it has loaded.
*/
protected PImage loadImageMT(Image awtImage) {
MediaTracker tracker = new MediaTracker(this);
tracker.addImage(awtImage, 0);
try {
tracker.waitForAll();
} catch (InterruptedException e) {
//e.printStackTrace(); // non-fatal, right?
}
PImage image = new PImage(awtImage);
image.parent = this;
return image;
}
/**
* Use Java 1.4 ImageIO methods to load an image.
*/
protected PImage loadImageIO(String filename) {
InputStream stream = createInput(filename);
if (stream == null) {
System.err.println("The image " + filename + " could not be found.");
return null;
}
try {
BufferedImage bi = ImageIO.read(stream);
PImage outgoing = new PImage(bi.getWidth(), bi.getHeight());
outgoing.parent = this;
bi.getRGB(0, 0, outgoing.width, outgoing.height,
outgoing.pixels, 0, outgoing.width);
// check the alpha for this image
// was gonna call getType() on the image to see if RGB or ARGB,
// but it's not actually useful, since gif images will come through
// as TYPE_BYTE_INDEXED, which means it'll still have to check for
// the transparency. also, would have to iterate through all the other
// types and guess whether alpha was in there, so.. just gonna stick
// with the old method.
outgoing.checkAlpha();
// return the image
return outgoing;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* Targa image loader for RLE-compressed TGA files.
* <p>
* Rewritten for 0115 to read/write RLE-encoded targa images.
* For 0125, non-RLE encoded images are now supported, along with
* images whose y-order is reversed (which is standard for TGA files).
*/
protected PImage loadImageTGA(String filename) throws IOException {
InputStream is = createInput(filename);
if (is == null) return null;
byte header[] = new byte[18];
int offset = 0;
do {
int count = is.read(header, offset, header.length - offset);
if (count == -1) return null;
offset += count;
} while (offset < 18);
/*
header[2] image type code
2 (0x02) - Uncompressed, RGB images.
3 (0x03) - Uncompressed, black and white images.
10 (0x0A) - Runlength encoded RGB images.
11 (0x0B) - Compressed, black and white images. (grayscale?)
header[16] is the bit depth (8, 24, 32)
header[17] image descriptor (packed bits)
0x20 is 32 = origin upper-left
0x28 is 32 + 8 = origin upper-left + 32 bits
7 6 5 4 3 2 1 0
128 64 32 16 8 4 2 1
*/
int format = 0;
if (((header[2] == 3) || (header[2] == 11)) && // B&W, plus RLE or not
(header[16] == 8) && // 8 bits
((header[17] == 0x8) || (header[17] == 0x28))) { // origin, 32 bit
format = ALPHA;
} else if (((header[2] == 2) || (header[2] == 10)) && // RGB, RLE or not
(header[16] == 24) && // 24 bits
((header[17] == 0x20) || (header[17] == 0))) { // origin
format = RGB;
} else if (((header[2] == 2) || (header[2] == 10)) &&
(header[16] == 32) &&
((header[17] == 0x8) || (header[17] == 0x28))) { // origin, 32
format = ARGB;
}
if (format == 0) {
System.err.println("Unknown .tga file format for " + filename);
//" (" + header[2] + " " +
//(header[16] & 0xff) + " " +
//hex(header[17], 2) + ")");
return null;
}
int w = ((header[13] & 0xff) << 8) + (header[12] & 0xff);
int h = ((header[15] & 0xff) << 8) + (header[14] & 0xff);
PImage outgoing = createImage(w, h, format);
// where "reversed" means upper-left corner (normal for most of
// the modernized world, but "reversed" for the tga spec)
//boolean reversed = (header[17] & 0x20) != 0;
// https://github.com/processing/processing/issues/1682
boolean reversed = (header[17] & 0x20) == 0;
if ((header[2] == 2) || (header[2] == 3)) { // not RLE encoded
if (reversed) {
int index = (h-1) * w;
switch (format) {
case ALPHA:
for (int y = h-1; y >= 0; y--) {
for (int x = 0; x < w; x++) {
outgoing.pixels[index + x] = is.read();
}
index -= w;
}
break;
case RGB:
for (int y = h-1; y >= 0; y--) {
for (int x = 0; x < w; x++) {
outgoing.pixels[index + x] =
is.read() | (is.read() << 8) | (is.read() << 16) |
0xff000000;
}
index -= w;
}
break;
case ARGB:
for (int y = h-1; y >= 0; y--) {
for (int x = 0; x < w; x++) {
outgoing.pixels[index + x] =
is.read() | (is.read() << 8) | (is.read() << 16) |
(is.read() << 24);
}
index -= w;
}
}
} else { // not reversed
int count = w * h;
switch (format) {
case ALPHA:
for (int i = 0; i < count; i++) {
outgoing.pixels[i] = is.read();
}
break;
case RGB:
for (int i = 0; i < count; i++) {
outgoing.pixels[i] =
is.read() | (is.read() << 8) | (is.read() << 16) |
0xff000000;
}
break;
case ARGB:
for (int i = 0; i < count; i++) {
outgoing.pixels[i] =
is.read() | (is.read() << 8) | (is.read() << 16) |
(is.read() << 24);
}
break;
}
}
} else { // header[2] is 10 or 11
int index = 0;
int px[] = outgoing.pixels;
while (index < px.length) {
int num = is.read();
boolean isRLE = (num & 0x80) != 0;
if (isRLE) {
num -= 127; // (num & 0x7F) + 1
int pixel = 0;
switch (format) {
case ALPHA:
pixel = is.read();
break;
case RGB:
pixel = 0xFF000000 |
is.read() | (is.read() << 8) | (is.read() << 16);
//(is.read() << 16) | (is.read() << 8) | is.read();
break;
case ARGB:
pixel = is.read() |
(is.read() << 8) | (is.read() << 16) | (is.read() << 24);
break;
}
for (int i = 0; i < num; i++) {
px[index++] = pixel;
if (index == px.length) break;
}
} else { // write up to 127 bytes as uncompressed
num += 1;
switch (format) {
case ALPHA:
for (int i = 0; i < num; i++) {
px[index++] = is.read();
}
break;
case RGB:
for (int i = 0; i < num; i++) {
px[index++] = 0xFF000000 |
is.read() | (is.read() << 8) | (is.read() << 16);
//(is.read() << 16) | (is.read() << 8) | is.read();
}
break;
case ARGB:
for (int i = 0; i < num; i++) {
px[index++] = is.read() | //(is.read() << 24) |
(is.read() << 8) | (is.read() << 16) | (is.read() << 24);
//(is.read() << 16) | (is.read() << 8) | is.read();
}
break;
}
}
}
if (!reversed) {
int[] temp = new int[w];
for (int y = 0; y < h/2; y++) {
int z = (h-1) - y;
System.arraycopy(px, y*w, temp, 0, w);
System.arraycopy(px, z*w, px, y*w, w);
System.arraycopy(temp, 0, px, z*w, w);
}
}
}
return outgoing;
}
//////////////////////////////////////////////////////////////
// DATA I/O
// /**
// * @webref input:files
// * @brief Creates a new XML object
// * @param name the name to be given to the root element of the new XML object
// * @return an XML object, or null
// * @see XML
// * @see PApplet#loadXML(String)
// * @see PApplet#parseXML(String)
// * @see PApplet#saveXML(XML, String)
// */
// public XML createXML(String name) {
// try {
// return new XML(name);
// } catch (Exception e) {
// e.printStackTrace();
// return null;
// }
// }
/**
* @webref input:files
* @param filename name of a file in the data folder or a URL.
* @see XML
* @see PApplet#parseXML(String)
* @see PApplet#saveXML(XML, String)
* @see PApplet#loadBytes(String)
* @see PApplet#loadStrings(String)
* @see PApplet#loadTable(String)
*/
public XML loadXML(String filename) {
return loadXML(filename, null);
}
// version that uses 'options' though there are currently no supported options
/**
* @nowebref
*/
public XML loadXML(String filename, String options) {
try {
return new XML(createReader(filename), options);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* @webref input:files
* @brief Converts String content to an XML object
* @param data the content to be parsed as XML
* @return an XML object, or null
* @see XML
* @see PApplet#loadXML(String)
* @see PApplet#saveXML(XML, String)
*/
public XML parseXML(String xmlString) {
return parseXML(xmlString, null);
}
public XML parseXML(String xmlString, String options) {
try {
return XML.parse(xmlString, options);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* @webref output:files
* @param xml the XML object to save to disk
* @param filename name of the file to write to
* @see XML
* @see PApplet#loadXML(String)
* @see PApplet#parseXML(String)
*/
public boolean saveXML(XML xml, String filename) {
return saveXML(xml, filename, null);
}
public boolean saveXML(XML xml, String filename, String options) {
return xml.save(saveFile(filename), options);
}
public JSONObject parseJSONObject(String input) {
return new JSONObject(new StringReader(input));
}
/**
* @webref 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));
}
/**
* Return a full path to an item in the data folder.
* <p>
* This is only available with applications, not applets or Android.
* On Windows and Linux, this is simply the data folder, which is located
* in the same directory as the EXE file and lib folders. On Mac OS X, this
* is a path to the data folder buried inside Contents/Resources/Java.
* For the latter point, that also means that the data folder should not be
* considered writable. Use sketchPath() for now, or inputPath() and
* outputPath() once they're available in the 2.0 release.
* <p>
* dataPath() is not supported with applets because applets have their data
* folder wrapped into the JAR file. To read data from the data folder that
* works with an applet, you should use other methods such as createInput(),
* createReader(), or loadStrings().
*/
public String dataPath(String where) {
return dataFile(where).getAbsolutePath();
}
/**
* Return a full path to an item in the data folder as a File object.
* See the dataPath() method for more information.
*/
public File dataFile(String where) {
// isAbsolute() could throw an access exception, but so will writing
// to the local disk using the sketch path, so this is safe here.
File why = new File(where);
if (why.isAbsolute()) return why;
String jarPath =
getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
if (jarPath.contains("Contents/Resources/Java/")) {
// The path will be URL encoded (%20 for spaces) coming from above
// http://code.google.com/p/processing/issues/detail?id=1073
File containingFolder = new File(urlDecode(jarPath)).getParentFile();
File dataFolder = new File(containingFolder, "data");
return new File(dataFolder, where);
}
// Windows, Linux, or when not using a Mac OS X .app file
return new File(sketchPath + File.separator + "data" + File.separator + where);
}
/**
* On Windows and Linux, this is simply the data folder. On Mac OS X, this is
* the path to the data folder buried inside Contents/Resources/Java
*/
// public File inputFile(String where) {
// }
// public String inputPath(String where) {
// }
/**
* Takes a path and creates any in-between folders if they don't
* already exist. Useful when trying to save to a subfolder that
* may not actually exist.
*/
static public void createPath(String path) {
createPath(new File(path));
}
static public void createPath(File file) {
try {
String parent = file.getParent();
if (parent != null) {
File unit = new File(parent);
if (!unit.exists()) unit.mkdirs();
}
} catch (SecurityException se) {
System.err.println("You don't have permissions to create " +
file.getAbsolutePath());
}
}
static public String getExtension(String filename) {
String extension;
String lower = filename.toLowerCase();
int dot = filename.lastIndexOf('.');
if (dot == -1) {
extension = "unknown"; // no extension found
}
extension = lower.substring(dot + 1);
// check for, and strip any parameters on the url, i.e.
// filename.jpg?blah=blah&something=that
int question = extension.indexOf('?');
if (question != -1) {
extension = extension.substring(0, question);
}
return extension;
}
//////////////////////////////////////////////////////////////
// URL ENCODING
static public String urlEncode(String str) {
try {
return URLEncoder.encode(str, "UTF-8");
} catch (UnsupportedEncodingException e) { // oh c'mon
return null;
}
}
static public String urlDecode(String str) {
try {
return URLDecoder.decode(str, "UTF-8");
} catch (UnsupportedEncodingException e) { // safe per the JDK source
return null;
}
}
//////////////////////////////////////////////////////////////
// SORT
/**
* ( begin auto-generated from sort.xml )
*
* Sorts an array of numbers from smallest to largest and puts an array of
* words in alphabetical order. The original array is not modified, a
* re-ordered array is returned. The <b>count</b> parameter states the
* number of elements to sort. For example if there are 12 elements in an
* array and if count is the value 5, only the first five elements on the
* array will be sorted. <!--As of release 0126, the alphabetical ordering
* is case insensitive.-->
*
* ( end auto-generated )
* @webref data:array_functions
* @param list array to sort
* @see PApplet#reverse(boolean[])
*/
static public byte[] sort(byte list[]) {
return sort(list, list.length);
}
/**
* @param count number of elements to sort, starting from 0
*/
static public byte[] sort(byte[] list, int count) {
byte[] outgoing = new byte[list.length];
System.arraycopy(list, 0, outgoing, 0, list.length);
Arrays.sort(outgoing, 0, count);
return outgoing;
}
static public char[] sort(char list[]) {
return sort(list, list.length);
}
static public char[] sort(char[] list, int count) {
char[] outgoing = new char[list.length];
System.arraycopy(list, 0, outgoing, 0, list.length);
Arrays.sort(outgoing, 0, count);
return outgoing;
}
static public int[] sort(int list[]) {
return sort(list, list.length);
}
static public int[] sort(int[] list, int count) {
int[] outgoing = new int[list.length];
System.arraycopy(list, 0, outgoing, 0, list.length);
Arrays.sort(outgoing, 0, count);
return outgoing;
}
static public float[] sort(float list[]) {
return sort(list, list.length);
}
static public float[] sort(float[] list, int count) {
float[] outgoing = new float[list.length];
System.arraycopy(list, 0, outgoing, 0, list.length);
Arrays.sort(outgoing, 0, count);
return outgoing;
}
static public String[] sort(String list[]) {
return sort(list, list.length);
}
static public String[] sort(String[] list, int count) {
String[] outgoing = new String[list.length];
System.arraycopy(list, 0, outgoing, 0, list.length);
Arrays.sort(outgoing, 0, count);
return outgoing;
}
//////////////////////////////////////////////////////////////
// ARRAY UTILITIES
/**
* ( begin auto-generated from arrayCopy.xml )
*
* Copies an array (or part of an array) to another array. The <b>src</b>
* array is copied to the <b>dst</b> array, beginning at the position
* specified by <b>srcPos</b> and into the position specified by
* <b>dstPos</b>. The number of elements to copy is determined by
* <b>length</b>. The simplified version with two arguments copies an
* entire array to another of the same size. It is equivalent to
* "arrayCopy(src, 0, dst, 0, src.length)". This function is far more
* efficient for copying array data than iterating through a <b>for</b> and
* copying each element.
*
* ( end auto-generated )
* @webref data:array_functions
* @param src the source array
* @param srcPosition starting position in the source array
* @param dst the destination array of the same data type as the source array
* @param dstPosition starting position in the destination array
* @param length number of array elements to be copied
* @see PApplet#concat(boolean[], boolean[])
*/
static public void arrayCopy(Object src, int srcPosition,
Object dst, int dstPosition,
int length) {
System.arraycopy(src, srcPosition, dst, dstPosition, length);
}
/**
* Convenience method for arraycopy().
* Identical to <CODE>arraycopy(src, 0, dst, 0, length);</CODE>
*/
static public void arrayCopy(Object src, Object dst, int length) {
System.arraycopy(src, 0, dst, 0, length);
}
/**
* Shortcut to copy the entire contents of
* the source into the destination array.
* Identical to <CODE>arraycopy(src, 0, dst, 0, src.length);</CODE>
*/
static public void arrayCopy(Object src, Object dst) {
System.arraycopy(src, 0, dst, 0, Array.getLength(src));
}
//
/**
* @deprecated Use arrayCopy() instead.
*/
static public void arraycopy(Object src, int srcPosition,
Object dst, int dstPosition,
int length) {
System.arraycopy(src, srcPosition, dst, dstPosition, length);
}
/**
* @deprecated Use arrayCopy() instead.
*/
static public void arraycopy(Object src, Object dst, int length) {
System.arraycopy(src, 0, dst, 0, length);
}
/**
* @deprecated Use arrayCopy() instead.
*/
static public void arraycopy(Object src, Object dst) {
System.arraycopy(src, 0, dst, 0, Array.getLength(src));
}
/**
* ( begin auto-generated from expand.xml )
*
* Increases the size of an array. By default, this function doubles the
* size of the array, but the optional <b>newSize</b> parameter provides
* precise control over the increase in size.
* <br/> <br/>
* When using an array of objects, the data returned from the function must
* be cast to the object array's data type. For example: <em>SomeClass[]
* items = (SomeClass[]) expand(originalArray)</em>.
*
* ( end auto-generated )
*
* @webref data:array_functions
* @param list the array to expand
* @see PApplet#shorten(boolean[])
*/
static public boolean[] expand(boolean list[]) {
return expand(list, list.length << 1);
}
/**
* @param newSize new size for the array
*/
static public boolean[] expand(boolean list[], int newSize) {
boolean temp[] = new boolean[newSize];
System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length));
return temp;
}
static public byte[] expand(byte list[]) {
return expand(list, list.length << 1);
}
static public byte[] expand(byte list[], int newSize) {
byte temp[] = new byte[newSize];
System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length));
return temp;
}
static public char[] expand(char list[]) {
return expand(list, list.length << 1);
}
static public char[] expand(char list[], int newSize) {
char temp[] = new char[newSize];
System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length));
return temp;
}
static public int[] expand(int list[]) {
return expand(list, list.length << 1);
}
static public int[] expand(int list[], int newSize) {
int temp[] = new int[newSize];
System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length));
return temp;
}
static public long[] expand(long list[]) {
return expand(list, list.length << 1);
}
static public long[] expand(long list[], int newSize) {
long temp[] = new long[newSize];
System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length));
return temp;
}
static public float[] expand(float list[]) {
return expand(list, list.length << 1);
}
static public float[] expand(float list[], int newSize) {
float temp[] = new float[newSize];
System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length));
return temp;
}
static public double[] expand(double list[]) {
return expand(list, list.length << 1);
}
static public double[] expand(double list[], int newSize) {
double temp[] = new double[newSize];
System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length));
return temp;
}
static public String[] expand(String list[]) {
return expand(list, list.length << 1);
}
static public String[] expand(String list[], int newSize) {
String temp[] = new String[newSize];
// in case the new size is smaller than list.length
System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length));
return temp;
}
/**
* @nowebref
*/
static public Object expand(Object array) {
return expand(array, Array.getLength(array) << 1);
}
static public Object expand(Object list, int newSize) {
Class<?> type = list.getClass().getComponentType();
Object temp = Array.newInstance(type, newSize);
System.arraycopy(list, 0, temp, 0,
Math.min(Array.getLength(list), newSize));
return temp;
}
// contract() has been removed in revision 0124, use subset() instead.
// (expand() is also functionally equivalent)
/**
* ( begin auto-generated from append.xml )
*
* Expands an array by one element and adds data to the new position. The
* datatype of the <b>element</b> parameter must be the same as the
* datatype of the array.
* <br/> <br/>
* When using an array of objects, the data returned from the function must
* be cast to the object array's data type. For example: <em>SomeClass[]
* items = (SomeClass[]) append(originalArray, element)</em>.
*
* ( end auto-generated )
*
* @webref data:array_functions
* @param array array to append
* @param value new data for the array
* @see PApplet#shorten(boolean[])
* @see PApplet#expand(boolean[])
*/
static public byte[] append(byte array[], byte value) {
array = expand(array, array.length + 1);
array[array.length-1] = value;
return array;
}
static public char[] append(char array[], char value) {
array = expand(array, array.length + 1);
array[array.length-1] = value;
return array;
}
static public int[] append(int array[], int value) {
array = expand(array, array.length + 1);
array[array.length-1] = value;
return array;
}
static public float[] append(float array[], float value) {
array = expand(array, array.length + 1);
array[array.length-1] = value;
return array;
}
static public String[] append(String array[], String value) {
array = expand(array, array.length + 1);
array[array.length-1] = value;
return array;
}
static public Object append(Object array, Object value) {
int length = Array.getLength(array);
array = expand(array, length + 1);
Array.set(array, length, value);
return array;
}
/**
* ( begin auto-generated from shorten.xml )
*
* Decreases an array by one element and returns the shortened array.
* <br/> <br/>
* When using an array of objects, the data returned from the function must
* be cast to the object array's data type. For example: <em>SomeClass[]
* items = (SomeClass[]) shorten(originalArray)</em>.
*
* ( end auto-generated )
*
* @webref data:array_functions
* @param list array to shorten
* @see PApplet#append(byte[], byte)
* @see PApplet#expand(boolean[])
*/
static public boolean[] shorten(boolean list[]) {
return subset(list, 0, list.length-1);
}
static public byte[] shorten(byte list[]) {
return subset(list, 0, list.length-1);
}
static public char[] shorten(char list[]) {
return subset(list, 0, list.length-1);
}
static public int[] shorten(int list[]) {
return subset(list, 0, list.length-1);
}
static public float[] shorten(float list[]) {
return subset(list, 0, list.length-1);
}
static public String[] shorten(String list[]) {
return subset(list, 0, list.length-1);
}
static public Object shorten(Object list) {
int length = Array.getLength(list);
return subset(list, 0, length - 1);
}
/**
* ( begin auto-generated from splice.xml )
*
* Inserts a value or array of values into an existing array. The first two
* parameters must be of the same datatype. The <b>array</b> parameter
* defines the array which will be modified and the second parameter
* defines the data which will be inserted.
* <br/> <br/>
* When using an array of objects, the data returned from the function must
* be cast to the object array's data type. For example: <em>SomeClass[]
* items = (SomeClass[]) splice(array1, array2, index)</em>.
*
* ( end auto-generated )
* @webref data:array_functions
* @param list array to splice into
* @param value value to be spliced in
* @param index position in the array from which to insert data
* @see PApplet#concat(boolean[], boolean[])
* @see PApplet#subset(boolean[], int, int)
*/
static final public boolean[] splice(boolean list[],
boolean value, int index) {
boolean outgoing[] = new boolean[list.length + 1];
System.arraycopy(list, 0, outgoing, 0, index);
outgoing[index] = value;
System.arraycopy(list, index, outgoing, index + 1,
list.length - index);
return outgoing;
}
static final public boolean[] splice(boolean list[],
boolean value[], int index) {
boolean outgoing[] = new boolean[list.length + value.length];
System.arraycopy(list, 0, outgoing, 0, index);
System.arraycopy(value, 0, outgoing, index, value.length);
System.arraycopy(list, index, outgoing, index + value.length,
list.length - index);
return outgoing;
}
static final public byte[] splice(byte list[],
byte value, int index) {
byte outgoing[] = new byte[list.length + 1];
System.arraycopy(list, 0, outgoing, 0, index);
outgoing[index] = value;
System.arraycopy(list, index, outgoing, index + 1,
list.length - index);
return outgoing;
}
static final public byte[] splice(byte list[],
byte value[], int index) {
byte outgoing[] = new byte[list.length + value.length];
System.arraycopy(list, 0, outgoing, 0, index);
System.arraycopy(value, 0, outgoing, index, value.length);
System.arraycopy(list, index, outgoing, index + value.length,
list.length - index);
return outgoing;
}
static final public char[] splice(char list[],
char value, int index) {
char outgoing[] = new char[list.length + 1];
System.arraycopy(list, 0, outgoing, 0, index);
outgoing[index] = value;
System.arraycopy(list, index, outgoing, index + 1,
list.length - index);
return outgoing;
}
static final public char[] splice(char list[],
char value[], int index) {
char outgoing[] = new char[list.length + value.length];
System.arraycopy(list, 0, outgoing, 0, index);
System.arraycopy(value, 0, outgoing, index, value.length);
System.arraycopy(list, index, outgoing, index + value.length,
list.length - index);
return outgoing;
}
static final public int[] splice(int list[],
int value, int index) {
int outgoing[] = new int[list.length + 1];
System.arraycopy(list, 0, outgoing, 0, index);
outgoing[index] = value;
System.arraycopy(list, index, outgoing, index + 1,
list.length - index);
return outgoing;
}
static final public int[] splice(int list[],
int value[], int index) {
int outgoing[] = new int[list.length + value.length];
System.arraycopy(list, 0, outgoing, 0, index);
System.arraycopy(value, 0, outgoing, index, value.length);
System.arraycopy(list, index, outgoing, index + value.length,
list.length - index);
return outgoing;
}
static final public float[] splice(float list[],
float value, int index) {
float outgoing[] = new float[list.length + 1];
System.arraycopy(list, 0, outgoing, 0, index);
outgoing[index] = value;
System.arraycopy(list, index, outgoing, index + 1,
list.length - index);
return outgoing;
}
static final public float[] splice(float list[],
float value[], int index) {
float outgoing[] = new float[list.length + value.length];
System.arraycopy(list, 0, outgoing, 0, index);
System.arraycopy(value, 0, outgoing, index, value.length);
System.arraycopy(list, index, outgoing, index + value.length,
list.length - index);
return outgoing;
}
static final public String[] splice(String list[],
String value, int index) {
String outgoing[] = new String[list.length + 1];
System.arraycopy(list, 0, outgoing, 0, index);
outgoing[index] = value;
System.arraycopy(list, index, outgoing, index + 1,
list.length - index);
return outgoing;
}
static final public String[] splice(String list[],
String value[], int index) {
String outgoing[] = new String[list.length + value.length];
System.arraycopy(list, 0, outgoing, 0, index);
System.arraycopy(value, 0, outgoing, index, value.length);
System.arraycopy(list, index, outgoing, index + value.length,
list.length - index);
return outgoing;
}
static final public Object splice(Object list, Object value, int index) {
Object[] outgoing = null;
int length = Array.getLength(list);
// check whether item being spliced in is an array
if (value.getClass().getName().charAt(0) == '[') {
int vlength = Array.getLength(value);
outgoing = new Object[length + vlength];
System.arraycopy(list, 0, outgoing, 0, index);
System.arraycopy(value, 0, outgoing, index, vlength);
System.arraycopy(list, index, outgoing, index + vlength, length - index);
} else {
outgoing = new Object[length + 1];
System.arraycopy(list, 0, outgoing, 0, index);
Array.set(outgoing, index, value);
System.arraycopy(list, index, outgoing, index + 1, length - index);
}
return outgoing;
}
static public boolean[] subset(boolean list[], int start) {
return subset(list, start, list.length - start);
}
/**
* ( begin auto-generated from subset.xml )
*
* Extracts an array of elements from an existing array. The <b>array</b>
* parameter defines the array from which the elements will be copied and
* the <b>offset</b> and <b>length</b> parameters determine which elements
* to extract. If no <b>length</b> is given, elements will be extracted
* from the <b>offset</b> to the end of the array. When specifying the
* <b>offset</b> remember the first array element is 0. This function does
* not change the source array.
* <br/> <br/>
* When using an array of objects, the data returned from the function must
* be cast to the object array's data type. For example: <em>SomeClass[]
* items = (SomeClass[]) subset(originalArray, 0, 4)</em>.
*
* ( end auto-generated )
* @webref data:array_functions
* @param list array to extract from
* @param start position to begin
* @param count number of values to extract
* @see PApplet#splice(boolean[], boolean, int)
*/
static public boolean[] subset(boolean list[], int start, int count) {
boolean output[] = new boolean[count];
System.arraycopy(list, start, output, 0, count);
return output;
}
static public byte[] subset(byte list[], int start) {
return subset(list, start, list.length - start);
}
static public byte[] subset(byte list[], int start, int count) {
byte output[] = new byte[count];
System.arraycopy(list, start, output, 0, count);
return output;
}
static public char[] subset(char list[], int start) {
return subset(list, start, list.length - start);
}
static public char[] subset(char list[], int start, int count) {
char output[] = new char[count];
System.arraycopy(list, start, output, 0, count);
return output;
}
static public int[] subset(int list[], int start) {
return subset(list, start, list.length - start);
}
static public int[] subset(int list[], int start, int count) {
int output[] = new int[count];
System.arraycopy(list, start, output, 0, count);
return output;
}
static public float[] subset(float list[], int start) {
return subset(list, start, list.length - start);
}
static public float[] subset(float list[], int start, int count) {
float output[] = new float[count];
System.arraycopy(list, start, output, 0, count);
return output;
}
static public String[] subset(String list[], int start) {
return subset(list, start, list.length - start);
}
static public String[] subset(String list[], int start, int count) {
String output[] = new String[count];
System.arraycopy(list, start, output, 0, count);
return output;
}
static public Object subset(Object list, int start) {
int length = Array.getLength(list);
return subset(list, start, length - start);
}
static public Object subset(Object list, int start, int count) {
Class<?> type = list.getClass().getComponentType();
Object outgoing = Array.newInstance(type, count);
System.arraycopy(list, start, outgoing, 0, count);
return outgoing;
}
/**
* ( begin auto-generated from concat.xml )
*
* Concatenates two arrays. For example, concatenating the array { 1, 2, 3
* } and the array { 4, 5, 6 } yields { 1, 2, 3, 4, 5, 6 }. Both parameters
* must be arrays of the same datatype.
* <br/> <br/>
* When using an array of objects, the data returned from the function must
* be cast to the object array's data type. For example: <em>SomeClass[]
* items = (SomeClass[]) concat(array1, array2)</em>.
*
* ( end auto-generated )
* @webref data:array_functions
* @param a first array to concatenate
* @param b second array to concatenate
* @see PApplet#splice(boolean[], boolean, int)
* @see PApplet#arrayCopy(Object, int, Object, int, int)
*/
static public boolean[] concat(boolean a[], boolean b[]) {
boolean c[] = new boolean[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
static public byte[] concat(byte a[], byte b[]) {
byte c[] = new byte[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
static public char[] concat(char a[], char b[]) {
char c[] = new char[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
static public int[] concat(int a[], int b[]) {
int c[] = new int[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
static public float[] concat(float a[], float b[]) {
float c[] = new float[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
static public String[] concat(String a[], String b[]) {
String c[] = new String[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
static public Object concat(Object a, Object b) {
Class<?> type = a.getClass().getComponentType();
int alength = Array.getLength(a);
int blength = Array.getLength(b);
Object outgoing = Array.newInstance(type, alength + blength);
System.arraycopy(a, 0, outgoing, 0, alength);
System.arraycopy(b, 0, outgoing, alength, blength);
return outgoing;
}
//
/**
* ( begin auto-generated from reverse.xml )
*
* Reverses the order of an array.
*
* ( end auto-generated )
* @webref data:array_functions
* @param list booleans[], bytes[], chars[], ints[], floats[], or Strings[]
* @see PApplet#sort(String[], int)
*/
static public boolean[] reverse(boolean list[]) {
boolean outgoing[] = new boolean[list.length];
int length1 = list.length - 1;
for (int i = 0; i < list.length; i++) {
outgoing[i] = list[length1 - i];
}
return outgoing;
}
static public byte[] reverse(byte list[]) {
byte outgoing[] = new byte[list.length];
int length1 = list.length - 1;
for (int i = 0; i < list.length; i++) {
outgoing[i] = list[length1 - i];
}
return outgoing;
}
static public char[] reverse(char list[]) {
char outgoing[] = new char[list.length];
int length1 = list.length - 1;
for (int i = 0; i < list.length; i++) {
outgoing[i] = list[length1 - i];
}
return outgoing;
}
static public int[] reverse(int list[]) {
int outgoing[] = new int[list.length];
int length1 = list.length - 1;
for (int i = 0; i < list.length; i++) {
outgoing[i] = list[length1 - i];
}
return outgoing;
}
static public float[] reverse(float list[]) {
float outgoing[] = new float[list.length];
int length1 = list.length - 1;
for (int i = 0; i < list.length; i++) {
outgoing[i] = list[length1 - i];
}
return outgoing;
}
static public String[] reverse(String list[]) {
String outgoing[] = new String[list.length];
int length1 = list.length - 1;
for (int i = 0; i < list.length; i++) {
outgoing[i] = list[length1 - i];
}
return outgoing;
}
static public Object reverse(Object list) {
Class<?> type = list.getClass().getComponentType();
int length = Array.getLength(list);
Object outgoing = Array.newInstance(type, length);
for (int i = 0; i < length; i++) {
Array.set(outgoing, i, Array.get(list, (length - 1) - i));
}
return outgoing;
}
//////////////////////////////////////////////////////////////
// STRINGS
/**
* ( begin auto-generated from trim.xml )
*
* Removes whitespace characters from the beginning and end of a String. In
* addition to standard whitespace characters such as space, carriage
* return, and tab, this function also removes the Unicode "nbsp" character.
*
* ( end auto-generated )
* @webref data:string_functions
* @param str any string
* @see PApplet#split(String, String)
* @see PApplet#join(String[], char)
*/
static public String trim(String str) {
return str.replace('\u00A0', ' ').trim();
}
/**
* @param array a String array
*/
static public String[] trim(String[] array) {
String[] outgoing = new String[array.length];
for (int i = 0; i < array.length; i++) {
if (array[i] != null) {
outgoing[i] = array[i].replace('\u00A0', ' ').trim();
}
}
return outgoing;
}
/**
* ( begin auto-generated from join.xml )
*
* Combines an array of Strings into one String, each separated by the
* character(s) used for the <b>separator</b> parameter. To join arrays of
* ints or floats, it's necessary to first convert them to strings using
* <b>nf()</b> or <b>nfs()</b>.
*
* ( end auto-generated )
* @webref data:string_functions
* @param list array of Strings
* @param separator char or String to be placed between each item
* @see PApplet#split(String, String)
* @see PApplet#trim(String)
* @see PApplet#nf(float, int, int)
* @see PApplet#nfs(float, int, int)
*/
static public String join(String[] list, char separator) {
return join(list, String.valueOf(separator));
}
static public String join(String[] list, String separator) {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < list.length; i++) {
if (i != 0) buffer.append(separator);
buffer.append(list[i]);
}
return buffer.toString();
}
static public String[] splitTokens(String value) {
return splitTokens(value, WHITESPACE);
}
/**
* ( begin auto-generated from splitTokens.xml )
*
* The splitTokens() function splits a String at one or many character
* "tokens." The <b>tokens</b> parameter specifies the character or
* characters to be used as a boundary.
* <br/> <br/>
* If no <b>tokens</b> character is specified, any whitespace character is
* used to split. Whitespace characters include tab (\\t), line feed (\\n),
* carriage return (\\r), form feed (\\f), and space. To convert a String
* to an array of integers or floats, use the datatype conversion functions
* <b>int()</b> and <b>float()</b> to convert the array of Strings.
*
* ( end auto-generated )
* @webref data:string_functions
* @param value the String to be split
* @param delim list of individual characters that will be used as separators
* @see PApplet#split(String, String)
* @see PApplet#join(String[], String)
* @see PApplet#trim(String)
*/
static public String[] splitTokens(String value, String delim) {
StringTokenizer toker = new StringTokenizer(value, delim);
String pieces[] = new String[toker.countTokens()];
int index = 0;
while (toker.hasMoreTokens()) {
pieces[index++] = toker.nextToken();
}
return pieces;
}
/**
* ( begin auto-generated from split.xml )
*
* The split() function breaks a string into pieces using a character or
* string as the divider. The <b>delim</b> parameter specifies the
* character or characters that mark the boundaries between each piece. A
* String[] array is returned that contains each of the pieces.
* <br/> <br/>
* If the result is a set of numbers, you can convert the String[] array to
* to a float[] or int[] array using the datatype conversion functions
* <b>int()</b> and <b>float()</b> (see example above).
* <br/> <br/>
* The <b>splitTokens()</b> function works in a similar fashion, except
* that it splits using a range of characters instead of a specific
* character or sequence.
* <!-- /><br />
* This function uses regular expressions to determine how the <b>delim</b>
* parameter divides the <b>str</b> parameter. Therefore, if you use
* characters such parentheses and brackets that are used with regular
* expressions as a part of the <b>delim</b> parameter, you'll need to put
* two blackslashes (\\\\) in front of the character (see example above).
* You can read more about <a
* href="http://en.wikipedia.org/wiki/Regular_expression">regular
* expressions</a> and <a
* href="http://en.wikipedia.org/wiki/Escape_character">escape
* characters</a> on Wikipedia.
* -->
*
* ( end auto-generated )
* @webref data:string_functions
* @usage web_application
* @param value the String to be split
* @param delim the character or String used to separate the data
*/
static public String[] split(String value, char delim) {
// do this so that the exception occurs inside the user's
// program, rather than appearing to be a bug inside split()
if (value == null) return null;
//return split(what, String.valueOf(delim)); // huh
char chars[] = value.toCharArray();
int splitCount = 0; //1;
for (int i = 0; i < chars.length; i++) {
if (chars[i] == delim) splitCount++;
}
// make sure that there is something in the input string
//if (chars.length > 0) {
// if the last char is a delimeter, get rid of it..
//if (chars[chars.length-1] == delim) splitCount--;
// on second thought, i don't agree with this, will disable
//}
if (splitCount == 0) {
String splits[] = new String[1];
splits[0] = new String(value);
return splits;
}
//int pieceCount = splitCount + 1;
String splits[] = new String[splitCount + 1];
int splitIndex = 0;
int startIndex = 0;
for (int i = 0; i < chars.length; i++) {
if (chars[i] == delim) {
splits[splitIndex++] =
new String(chars, startIndex, i-startIndex);
startIndex = i + 1;
}
}
//if (startIndex != chars.length) {
splits[splitIndex] =
new String(chars, startIndex, chars.length-startIndex);
//}
return splits;
}
static public String[] split(String value, String delim) {
ArrayList<String> items = new ArrayList<String>();
int index;
int offset = 0;
while ((index = value.indexOf(delim, offset)) != -1) {
items.add(value.substring(offset, index));
offset = index + delim.length();
}
items.add(value.substring(offset));
String[] outgoing = new String[items.size()];
items.toArray(outgoing);
return outgoing;
}
static protected HashMap<String, Pattern> matchPatterns;
static Pattern matchPattern(String regexp) {
Pattern p = null;
if (matchPatterns == null) {
matchPatterns = new HashMap<String, Pattern>();
} else {
p = matchPatterns.get(regexp);
}
if (p == null) {
if (matchPatterns.size() == 10) {
// Just clear out the match patterns here if more than 10 are being
// used. It's not terribly efficient, but changes that you have >10
// different match patterns are very slim, unless you're doing
// something really tricky (like custom match() methods), in which
// case match() won't be efficient anyway. (And you should just be
// using your own Java code.) The alternative is using a queue here,
// but that's a silly amount of work for negligible benefit.
matchPatterns.clear();
}
p = Pattern.compile(regexp, Pattern.MULTILINE | Pattern.DOTALL);
matchPatterns.put(regexp, p);
}
return p;
}
/**
* ( begin auto-generated from match.xml )
*
* The match() function is used to apply a regular expression to a piece of
* text, and return matching groups (elements found inside parentheses) as
* a String array. No match will return null. If no groups are specified in
* the regexp, but the sequence matches, an array of length one (with the
* matched text as the first element of the array) will be returned.<br />
* <br />
* To use the function, first check to see if the result is null. If the
* result is null, then the sequence did not match. If the sequence did
* match, an array is returned.
* If there are groups (specified by sets of parentheses) in the regexp,
* then the contents of each will be returned in the array.
* Element [0] of a regexp match returns the entire matching string, and
* the match groups start at element [1] (the first group is [1], the
* second [2], and so on).<br />
* <br />
* The syntax can be found in the reference for Java's <a
* href="http://download.oracle.com/javase/6/docs/api/">Pattern</a> class.
* For regular expression syntax, read the <a
* href="http://download.oracle.com/javase/tutorial/essential/regex/">Java
* Tutorial</a> on the topic.
*
* ( end auto-generated )
* @webref data:string_functions
* @param str the String to be searched
* @param regexp the regexp to be used for matching
* @see PApplet#matchAll(String, String)
* @see PApplet#split(String, String)
* @see PApplet#splitTokens(String, String)
* @see PApplet#join(String[], String)
* @see PApplet#trim(String)
*/
static public String[] match(String str, String regexp) {
Pattern p = matchPattern(regexp);
Matcher m = p.matcher(str);
if (m.find()) {
int count = m.groupCount() + 1;
String[] groups = new String[count];
for (int i = 0; i < count; i++) {
groups[i] = m.group(i);
}
return groups;
}
return null;
}
/**
* ( begin auto-generated from matchAll.xml )
*
* This function is used to apply a regular expression to a piece of text,
* and return a list of matching groups (elements found inside parentheses)
* as a two-dimensional String array. No matches will return null. If no
* groups are specified in the regexp, but the sequence matches, a two
* dimensional array is still returned, but the second dimension is only of
* length one.<br />
* <br />
* To use the function, first check to see if the result is null. If the
* result is null, then the sequence did not match at all. If the sequence
* did match, a 2D array is returned. If there are groups (specified by
* sets of parentheses) in the regexp, then the contents of each will be
* returned in the array.
* Assuming, a loop with counter variable i, element [i][0] of a regexp
* match returns the entire matching string, and the match groups start at
* element [i][1] (the first group is [i][1], the second [i][2], and so
* on).<br />
* <br />
* The syntax can be found in the reference for Java's <a
* href="http://download.oracle.com/javase/6/docs/api/">Pattern</a> class.
* For regular expression syntax, read the <a
* href="http://download.oracle.com/javase/tutorial/essential/regex/">Java
* Tutorial</a> on the topic.
*
* ( end auto-generated )
* @webref data:string_functions
* @param str the String to be searched
* @param regexp the regexp to be used for matching
* @see PApplet#match(String, String)
* @see PApplet#split(String, String)
* @see PApplet#splitTokens(String, String)
* @see PApplet#join(String[], String)
* @see PApplet#trim(String)
*/
static public String[][] matchAll(String str, String regexp) {
Pattern p = matchPattern(regexp);
Matcher m = p.matcher(str);
ArrayList<String[]> results = new ArrayList<String[]>();
int count = m.groupCount() + 1;
while (m.find()) {
String[] groups = new String[count];
for (int i = 0; i < count; i++) {
groups[i] = m.group(i);
}
results.add(groups);
}
if (results.isEmpty()) {
return null;
}
String[][] matches = new String[results.size()][count];
for (int i = 0; i < matches.length; i++) {
matches[i] = results.get(i);
}
return matches;
}
//////////////////////////////////////////////////////////////
// CASTING FUNCTIONS, INSERTED BY PREPROC
/**
* Convert a char to a boolean. 'T', 't', and '1' will become the
* boolean value true, while 'F', 'f', or '0' will become false.
*/
/*
static final public boolean parseBoolean(char what) {
return ((what == 't') || (what == 'T') || (what == '1'));
}
*/
/**
* <p>Convert an integer to a boolean. Because of how Java handles upgrading
* numbers, this will also cover byte and char (as they will upgrade to
* an int without any sort of explicit cast).</p>
* <p>The preprocessor will convert boolean(what) to parseBoolean(what).</p>
* @return false if 0, true if any other number
*/
static final public boolean parseBoolean(int what) {
return (what != 0);
}
/*
// removed because this makes no useful sense
static final public boolean parseBoolean(float what) {
return (what != 0);
}
*/
/**
* Convert the string "true" or "false" to a boolean.
* @return true if 'what' is "true" or "TRUE", false otherwise
*/
static final public boolean parseBoolean(String what) {
return new Boolean(what).booleanValue();
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
/*
// removed, no need to introduce strange syntax from other languages
static final public boolean[] parseBoolean(char what[]) {
boolean outgoing[] = new boolean[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] =
((what[i] == 't') || (what[i] == 'T') || (what[i] == '1'));
}
return outgoing;
}
*/
/**
* Convert a byte array to a boolean array. Each element will be
* evaluated identical to the integer case, where a byte equal
* to zero will return false, and any other value will return true.
* @return array of boolean elements
*/
/*
static final public boolean[] parseBoolean(byte what[]) {
boolean outgoing[] = new boolean[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = (what[i] != 0);
}
return outgoing;
}
*/
/**
* Convert an int array to a boolean array. An int equal
* to zero will return false, and any other value will return true.
* @return array of boolean elements
*/
static final public boolean[] parseBoolean(int what[]) {
boolean outgoing[] = new boolean[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = (what[i] != 0);
}
return outgoing;
}
/*
// removed, not necessary... if necessary, convert to int array first
static final public boolean[] parseBoolean(float what[]) {
boolean outgoing[] = new boolean[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = (what[i] != 0);
}
return outgoing;
}
*/
static final public boolean[] parseBoolean(String what[]) {
boolean outgoing[] = new boolean[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = new Boolean(what[i]).booleanValue();
}
return outgoing;
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
static final public byte parseByte(boolean what) {
return what ? (byte)1 : 0;
}
static final public byte parseByte(char what) {
return (byte) what;
}
static final public byte parseByte(int what) {
return (byte) what;
}
static final public byte parseByte(float what) {
return (byte) what;
}
/*
// nixed, no precedent
static final public byte[] parseByte(String what) { // note: array[]
return what.getBytes();
}
*/
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
static final public byte[] parseByte(boolean what[]) {
byte outgoing[] = new byte[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = what[i] ? (byte)1 : 0;
}
return outgoing;
}
static final public byte[] parseByte(char what[]) {
byte outgoing[] = new byte[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = (byte) what[i];
}
return outgoing;
}
static final public byte[] parseByte(int what[]) {
byte outgoing[] = new byte[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = (byte) what[i];
}
return outgoing;
}
static final public byte[] parseByte(float what[]) {
byte outgoing[] = new byte[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = (byte) what[i];
}
return outgoing;
}
/*
static final public byte[][] parseByte(String what[]) { // note: array[][]
byte outgoing[][] = new byte[what.length][];
for (int i = 0; i < what.length; i++) {
outgoing[i] = what[i].getBytes();
}
return outgoing;
}
*/
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
/*
static final public char parseChar(boolean what) { // 0/1 or T/F ?
return what ? 't' : 'f';
}
*/
static final public char parseChar(byte what) {
return (char) (what & 0xff);
}
static final public char parseChar(int what) {
return (char) what;
}
/*
static final public char parseChar(float what) { // nonsensical
return (char) what;
}
static final public char[] parseChar(String what) { // note: array[]
return what.toCharArray();
}
*/
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
/*
static final public char[] parseChar(boolean what[]) { // 0/1 or T/F ?
char outgoing[] = new char[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = what[i] ? 't' : 'f';
}
return outgoing;
}
*/
static final public char[] parseChar(byte what[]) {
char outgoing[] = new char[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = (char) (what[i] & 0xff);
}
return outgoing;
}
static final public char[] parseChar(int what[]) {
char outgoing[] = new char[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = (char) what[i];
}
return outgoing;
}
/*
static final public char[] parseChar(float what[]) { // nonsensical
char outgoing[] = new char[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = (char) what[i];
}
return outgoing;
}
static final public char[][] parseChar(String what[]) { // note: array[][]
char outgoing[][] = new char[what.length][];
for (int i = 0; i < what.length; i++) {
outgoing[i] = what[i].toCharArray();
}
return outgoing;
}
*/
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
static final public int parseInt(boolean what) {
return what ? 1 : 0;
}
/**
* Note that parseInt() will un-sign a signed byte value.
*/
static final public int parseInt(byte what) {
return what & 0xff;
}
/**
* Note that parseInt('5') is unlike String in the sense that it
* won't return 5, but the ascii value. This is because ((int) someChar)
* returns the ascii value, and parseInt() is just longhand for the cast.
*/
static final public int parseInt(char what) {
return what;
}
/**
* Same as floor(), or an (int) cast.
*/
static final public int parseInt(float what) {
return (int) what;
}
/**
* Parse a String into an int value. Returns 0 if the value is bad.
*/
static final public int parseInt(String what) {
return parseInt(what, 0);
}
/**
* Parse a String to an int, and provide an alternate value that
* should be used when the number is invalid.
*/
static final public int parseInt(String what, int otherwise) {
try {
int offset = what.indexOf('.');
if (offset == -1) {
return Integer.parseInt(what);
} else {
return Integer.parseInt(what.substring(0, offset));
}
} catch (NumberFormatException e) { }
return otherwise;
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
static final public int[] parseInt(boolean what[]) {
int list[] = new int[what.length];
for (int i = 0; i < what.length; i++) {
list[i] = what[i] ? 1 : 0;
}
return list;
}
static final public int[] parseInt(byte what[]) { // note this unsigns
int list[] = new int[what.length];
for (int i = 0; i < what.length; i++) {
list[i] = (what[i] & 0xff);
}
return list;
}
static final public int[] parseInt(char what[]) {
int list[] = new int[what.length];
for (int i = 0; i < what.length; i++) {
list[i] = what[i];
}
return list;
}
static public int[] parseInt(float what[]) {
int inties[] = new int[what.length];
for (int i = 0; i < what.length; i++) {
inties[i] = (int)what[i];
}
return inties;
}
/**
* Make an array of int elements from an array of String objects.
* If the String can't be parsed as a number, it will be set to zero.
*
* String s[] = { "1", "300", "44" };
* int numbers[] = parseInt(s);
*
* numbers will contain { 1, 300, 44 }
*/
static public int[] parseInt(String what[]) {
return parseInt(what, 0);
}
/**
* Make an array of int elements from an array of String objects.
* If the String can't be parsed as a number, its entry in the
* array will be set to the value of the "missing" parameter.
*
* String s[] = { "1", "300", "apple", "44" };
* int numbers[] = parseInt(s, 9999);
*
* numbers will contain { 1, 300, 9999, 44 }
*/
static public int[] parseInt(String what[], int missing) {
int output[] = new int[what.length];
for (int i = 0; i < what.length; i++) {
try {
output[i] = Integer.parseInt(what[i]);
} catch (NumberFormatException e) {
output[i] = missing;
}
}
return output;
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
/*
static final public float parseFloat(boolean what) {
return what ? 1 : 0;
}
*/
/**
* Convert an int to a float value. Also handles bytes because of
* Java's rules for upgrading values.
*/
static final public float parseFloat(int what) { // also handles byte
return what;
}
static final public float parseFloat(String what) {
return parseFloat(what, Float.NaN);
}
static final public float parseFloat(String what, float otherwise) {
try {
return new Float(what).floatValue();
} catch (NumberFormatException e) { }
return otherwise;
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
/*
static final public float[] parseFloat(boolean what[]) {
float floaties[] = new float[what.length];
for (int i = 0; i < what.length; i++) {
floaties[i] = what[i] ? 1 : 0;
}
return floaties;
}
static final public float[] parseFloat(char what[]) {
float floaties[] = new float[what.length];
for (int i = 0; i < what.length; i++) {
floaties[i] = (char) what[i];
}
return floaties;
}
*/
static final public float[] parseByte(byte what[]) {
float floaties[] = new float[what.length];
for (int i = 0; i < what.length; i++) {
floaties[i] = what[i];
}
return floaties;
}
static final public float[] parseFloat(int what[]) {
float floaties[] = new float[what.length];
for (int i = 0; i < what.length; i++) {
floaties[i] = what[i];
}
return floaties;
}
static final public float[] parseFloat(String what[]) {
return parseFloat(what, Float.NaN);
}
static final public float[] parseFloat(String what[], float missing) {
float output[] = new float[what.length];
for (int i = 0; i < what.length; i++) {
try {
output[i] = new Float(what[i]).floatValue();
} catch (NumberFormatException e) {
output[i] = missing;
}
}
return output;
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
static final public String str(boolean x) {
return String.valueOf(x);
}
static final public String str(byte x) {
return String.valueOf(x);
}
static final public String str(char x) {
return String.valueOf(x);
}
static final public String str(int x) {
return String.valueOf(x);
}
static final public String str(float x) {
return String.valueOf(x);
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
static final public String[] str(boolean x[]) {
String s[] = new String[x.length];
for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]);
return s;
}
static final public String[] str(byte x[]) {
String s[] = new String[x.length];
for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]);
return s;
}
static final public String[] str(char x[]) {
String s[] = new String[x.length];
for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]);
return s;
}
static final public String[] str(int x[]) {
String s[] = new String[x.length];
for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]);
return s;
}
static final public String[] str(float x[]) {
String s[] = new String[x.length];
for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]);
return s;
}
//////////////////////////////////////////////////////////////
// INT NUMBER FORMATTING
/**
* Integer number formatter.
*/
static private NumberFormat int_nf;
static private int int_nf_digits;
static private boolean int_nf_commas;
static public String[] nf(int num[], int digits) {
String formatted[] = new String[num.length];
for (int i = 0; i < formatted.length; i++) {
formatted[i] = nf(num[i], digits);
}
return formatted;
}
/**
* ( begin auto-generated from nf.xml )
*
* Utility function for formatting numbers into strings. There are two
* versions, one for formatting floats and one for formatting ints. The
* values for the <b>digits</b>, <b>left</b>, and <b>right</b> parameters
* should always be positive integers.<br /><br />As shown in the above
* example, <b>nf()</b> is used to add zeros to the left and/or right of a
* number. This is typically for aligning a list of numbers. To
* <em>remove</em> digits from a floating-point number, use the
* <b>int()</b>, <b>ceil()</b>, <b>floor()</b>, or <b>round()</b>
* functions.
*
* ( end auto-generated )
* @webref data:string_functions
* @param num the number(s) to format
* @param digits number of digits to pad with zero
* @see PApplet#nfs(float, int, int)
* @see PApplet#nfp(float, int, int)
* @see PApplet#nfc(float, int)
* @see PApplet#int(float)
*/
static public String nf(int num, int digits) {
if ((int_nf != null) &&
(int_nf_digits == digits) &&
!int_nf_commas) {
return int_nf.format(num);
}
int_nf = NumberFormat.getInstance();
int_nf.setGroupingUsed(false); // no commas
int_nf_commas = false;
int_nf.setMinimumIntegerDigits(digits);
int_nf_digits = digits;
return int_nf.format(num);
}
/**
* ( begin auto-generated from nfc.xml )
*
* Utility function for formatting numbers into strings and placing
* appropriate commas to mark units of 1000. There are two versions, one
* for formatting ints and one for formatting an array of ints. The value
* for the <b>digits</b> parameter should always be a positive integer.
* <br/> <br/>
* For a non-US locale, this will insert periods instead of commas, or
* whatever is apprioriate for that region.
*
* ( end auto-generated )
* @webref data:string_functions
* @param num the number(s) to format
* @see PApplet#nf(float, int, int)
* @see PApplet#nfp(float, int, int)
* @see PApplet#nfc(float, int)
*/
static public String[] nfc(int num[]) {
String formatted[] = new String[num.length];
for (int i = 0; i < formatted.length; i++) {
formatted[i] = nfc(num[i]);
}
return formatted;
}
/**
* nfc() or "number format with commas". This is an unfortunate misnomer
* because in locales where a comma is not the separator for numbers, it
* won't actually be outputting a comma, it'll use whatever makes sense for
* the locale.
*/
static public String nfc(int num) {
if ((int_nf != null) &&
(int_nf_digits == 0) &&
int_nf_commas) {
return int_nf.format(num);
}
int_nf = NumberFormat.getInstance();
int_nf.setGroupingUsed(true);
int_nf_commas = true;
int_nf.setMinimumIntegerDigits(0);
int_nf_digits = 0;
return int_nf.format(num);
}
/**
* number format signed (or space)
* Formats a number but leaves a blank space in the front
* when it's positive so that it can be properly aligned with
* numbers that have a negative sign in front of them.
*/
/**
* ( begin auto-generated from nfs.xml )
*
* Utility function for formatting numbers into strings. Similar to
* <b>nf()</b> but leaves a blank space in front of positive numbers so
* they align with negative numbers in spite of the minus symbol. There are
* two versions, one for formatting floats and one for formatting ints. The
* values for the <b>digits</b>, <b>left</b>, and <b>right</b> parameters
* should always be positive integers.
*
* ( end auto-generated )
* @webref data:string_functions
* @param num the number(s) to format
* @param digits number of digits to pad with zeroes
* @see PApplet#nf(float, int, int)
* @see PApplet#nfp(float, int, int)
* @see PApplet#nfc(float, int)
*/
static public String nfs(int num, int digits) {
return (num < 0) ? nf(num, digits) : (' ' + nf(num, digits));
}
static public String[] nfs(int num[], int digits) {
String formatted[] = new String[num.length];
for (int i = 0; i < formatted.length; i++) {
formatted[i] = nfs(num[i], digits);
}
return formatted;
}
//
/**
* number format positive (or plus)
* Formats a number, always placing a - or + sign
* in the front when it's negative or positive.
*/
/**
* ( begin auto-generated from nfp.xml )
*
* Utility function for formatting numbers into strings. Similar to
* <b>nf()</b> but puts a "+" in front of positive numbers and a "-" in
* front of negative numbers. There are two versions, one for formatting
* floats and one for formatting ints. The values for the <b>digits</b>,
* <b>left</b>, and <b>right</b> parameters should always be positive integers.
*
* ( end auto-generated )
* @webref data:string_functions
* @param num the number(s) to format
* @param digits number of digits to pad with zeroes
* @see PApplet#nf(float, int, int)
* @see PApplet#nfs(float, int, int)
* @see PApplet#nfc(float, int)
*/
static public String nfp(int num, int digits) {
return (num < 0) ? nf(num, digits) : ('+' + nf(num, digits));
}
static public String[] nfp(int num[], int digits) {
String formatted[] = new String[num.length];
for (int i = 0; i < formatted.length; i++) {
formatted[i] = nfp(num[i], digits);
}
return formatted;
}
//////////////////////////////////////////////////////////////
// FLOAT NUMBER FORMATTING
static private NumberFormat float_nf;
static private int float_nf_left, float_nf_right;
static private boolean float_nf_commas;
static public String[] nf(float num[], int left, int right) {
String formatted[] = new String[num.length];
for (int i = 0; i < formatted.length; i++) {
formatted[i] = nf(num[i], left, right);
}
return formatted;
}
/**
* @param num[] the number(s) to format
* @param left number of digits to the left of the decimal point
* @param right number of digits to the right of the decimal point
*/
static public String nf(float num, int left, int right) {
if ((float_nf != null) &&
(float_nf_left == left) &&
(float_nf_right == right) &&
!float_nf_commas) {
return float_nf.format(num);
}
float_nf = NumberFormat.getInstance();
float_nf.setGroupingUsed(false);
float_nf_commas = false;
if (left != 0) float_nf.setMinimumIntegerDigits(left);
if (right != 0) {
float_nf.setMinimumFractionDigits(right);
float_nf.setMaximumFractionDigits(right);
}
float_nf_left = left;
float_nf_right = right;
return float_nf.format(num);
}
/**
* @param num[] the number(s) to format
* @param right number of digits to the right of the decimal point
*/
static public String[] nfc(float num[], int right) {
String formatted[] = new String[num.length];
for (int i = 0; i < formatted.length; i++) {
formatted[i] = nfc(num[i], right);
}
return formatted;
}
static public String nfc(float num, int right) {
if ((float_nf != null) &&
(float_nf_left == 0) &&
(float_nf_right == right) &&
float_nf_commas) {
return float_nf.format(num);
}
float_nf = NumberFormat.getInstance();
float_nf.setGroupingUsed(true);
float_nf_commas = true;
if (right != 0) {
float_nf.setMinimumFractionDigits(right);
float_nf.setMaximumFractionDigits(right);
}
float_nf_left = 0;
float_nf_right = right;
return float_nf.format(num);
}
/**
* @param num[] the number(s) to format
* @param left the number of digits to the left of the decimal point
* @param right the number of digits to the right of the decimal point
*/
static public String[] nfs(float num[], int left, int right) {
String formatted[] = new String[num.length];
for (int i = 0; i < formatted.length; i++) {
formatted[i] = nfs(num[i], left, right);
}
return formatted;
}
static public String nfs(float num, int left, int right) {
return (num < 0) ? nf(num, left, right) : (' ' + nf(num, left, right));
}
/**
* @param left the number of digits to the left of the decimal point
* @param right the number of digits to the right of the decimal point
*/
static public String[] nfp(float num[], int left, int right) {
String formatted[] = new String[num.length];
for (int i = 0; i < formatted.length; i++) {
formatted[i] = nfp(num[i], left, right);
}
return formatted;
}
static public String nfp(float num, int left, int right) {
return (num < 0) ? nf(num, left, right) : ('+' + nf(num, left, right));
}
//////////////////////////////////////////////////////////////
// HEX/BINARY CONVERSION
/**
* ( begin auto-generated from hex.xml )
*
* Converts a byte, char, int, or color to a String containing the
* equivalent hexadecimal notation. For example color(0, 102, 153) will
* convert to the String "FF006699". This function can help make your geeky
* debugging sessions much happier.
* <br/> <br/>
* Note that the maximum number of digits is 8, because an int value can
* only represent up to 32 bits. Specifying more than eight digits will
* simply shorten the string to eight anyway.
*
* ( end auto-generated )
* @webref data:conversion
* @param value the value to convert
* @see PApplet#unhex(String)
* @see PApplet#binary(byte)
* @see PApplet#unbinary(String)
*/
static final public String hex(byte value) {
return hex(value, 2);
}
static final public String hex(char value) {
return hex(value, 4);
}
static final public String hex(int value) {
return hex(value, 8);
}
/**
* @param digits the number of digits (maximum 8)
*/
static final public String hex(int value, int digits) {
String stuff = Integer.toHexString(value).toUpperCase();
if (digits > 8) {
digits = 8;
}
int length = stuff.length();
if (length > digits) {
return stuff.substring(length - digits);
} else if (length < digits) {
return "00000000".substring(8 - (digits-length)) + stuff;
}
return stuff;
}
/**
* ( begin auto-generated from unhex.xml )
*
* Converts a String representation of a hexadecimal number to its
* equivalent integer value.
*
* ( end auto-generated )
*
* @webref data:conversion
* @param value String to convert to an integer
* @see PApplet#hex(int, int)
* @see PApplet#binary(byte)
* @see PApplet#unbinary(String)
*/
static final public int unhex(String value) {
// has to parse as a Long so that it'll work for numbers bigger than 2^31
return (int) (Long.parseLong(value, 16));
}
//
/**
* Returns a String that contains the binary value of a byte.
* The returned value will always have 8 digits.
*/
static final public String binary(byte value) {
return binary(value, 8);
}
/**
* Returns a String that contains the binary value of a char.
* The returned value will always have 16 digits because chars
* are two bytes long.
*/
static final public String binary(char value) {
return binary(value, 16);
}
/**
* Returns a String that contains the binary value of an int. The length
* depends on the size of the number itself. If you want a specific number
* of digits use binary(int what, int digits) to specify how many.
*/
static final public String binary(int value) {
return binary(value, 32);
}
/*
* Returns a String that contains the binary value of an int.
* The digits parameter determines how many digits will be used.
*/
/**
* ( begin auto-generated from binary.xml )
*
* Converts a byte, char, int, or color to a String containing the
* equivalent binary notation. For example color(0, 102, 153, 255) will
* convert to the String "11111111000000000110011010011001". This function
* can help make your geeky debugging sessions much happier.
* <br/> <br/>
* Note that the maximum number of digits is 32, because an int value can
* only represent up to 32 bits. Specifying more than 32 digits will simply
* shorten the string to 32 anyway.
*
* ( end auto-generated )
* @webref data:conversion
* @param value value to convert
* @param digits number of digits to return
* @see PApplet#unbinary(String)
* @see PApplet#hex(int,int)
* @see PApplet#unhex(String)
*/
static final public String binary(int value, int digits) {
String stuff = Integer.toBinaryString(value);
if (digits > 32) {
digits = 32;
}
int length = stuff.length();
if (length > digits) {
return stuff.substring(length - digits);
} else if (length < digits) {
int offset = 32 - (digits-length);
return "00000000000000000000000000000000".substring(offset) + stuff;
}
return stuff;
}
/**
* ( begin auto-generated from unbinary.xml )
*
* Converts a String representation of a binary number to its equivalent
* integer value. For example, unbinary("00001000") will return 8.
*
* ( end auto-generated )
* @webref data:conversion
* @param value String to convert to an integer
* @see PApplet#binary(byte)
* @see PApplet#hex(int,int)
* @see PApplet#unhex(String)
*/
static final public int unbinary(String value) {
return Integer.parseInt(value, 2);
}
//////////////////////////////////////////////////////////////
// COLOR FUNCTIONS
// moved here so that they can work without
// the graphics actually being instantiated (outside setup)
/**
* ( begin auto-generated from color.xml )
*
* Creates colors for storing in variables of the <b>color</b> datatype.
* The parameters are interpreted as RGB or HSB values depending on the
* current <b>colorMode()</b>. The default mode is RGB values from 0 to 255
* and therefore, the function call <b>color(255, 204, 0)</b> will return a
* bright yellow color. More about how colors are stored can be found in
* the reference for the <a href="color_datatype.html">color</a> datatype.
*
* ( end auto-generated )
* @webref color:creating_reading
* @param gray number specifying value between white and black
* @see PApplet#colorMode(int)
*/
public final int color(int gray) {
if (g == null) {
if (gray > 255) gray = 255; else if (gray < 0) gray = 0;
return 0xff000000 | (gray << 16) | (gray << 8) | gray;
}
return g.color(gray);
}
/**
* @nowebref
* @param fgray number specifying value between white and black
*/
public final int color(float fgray) {
if (g == null) {
int gray = (int) fgray;
if (gray > 255) gray = 255; else if (gray < 0) gray = 0;
return 0xff000000 | (gray << 16) | (gray << 8) | gray;
}
return g.color(fgray);
}
/**
* As of 0116 this also takes color(#FF8800, alpha)
* @param alpha relative to current color range
*/
public final int color(int gray, int alpha) {
if (g == null) {
if (alpha > 255) alpha = 255; else if (alpha < 0) alpha = 0;
if (gray > 255) {
// then assume this is actually a #FF8800
return (alpha << 24) | (gray & 0xFFFFFF);
} else {
//if (gray > 255) gray = 255; else if (gray < 0) gray = 0;
return (alpha << 24) | (gray << 16) | (gray << 8) | gray;
}
}
return g.color(gray, alpha);
}
/**
* @nowebref
*/
public final int color(float fgray, float falpha) {
if (g == null) {
int gray = (int) fgray;
int alpha = (int) falpha;
if (gray > 255) gray = 255; else if (gray < 0) gray = 0;
if (alpha > 255) alpha = 255; else if (alpha < 0) alpha = 0;
return 0xff000000 | (gray << 16) | (gray << 8) | gray;
}
return g.color(fgray, falpha);
}
/**
* @param v1 red or hue values relative to the current color range
* @param v2 green or saturation values relative to the current color range
* @param v3 blue or brightness values relative to the current color range
*/
public final int color(int v1, int v2, int v3) {
if (g == null) {
if (v1 > 255) v1 = 255; else if (v1 < 0) v1 = 0;
if (v2 > 255) v2 = 255; else if (v2 < 0) v2 = 0;
if (v3 > 255) v3 = 255; else if (v3 < 0) v3 = 0;
return 0xff000000 | (v1 << 16) | (v2 << 8) | v3;
}
return g.color(v1, v2, v3);
}
public final int color(int v1, int v2, int v3, int alpha) {
if (g == null) {
if (alpha > 255) alpha = 255; else if (alpha < 0) alpha = 0;
if (v1 > 255) v1 = 255; else if (v1 < 0) v1 = 0;
if (v2 > 255) v2 = 255; else if (v2 < 0) v2 = 0;
if (v3 > 255) v3 = 255; else if (v3 < 0) v3 = 0;
return (alpha << 24) | (v1 << 16) | (v2 << 8) | v3;
}
return g.color(v1, v2, v3, alpha);
}
public final int color(float v1, float v2, float v3) {
if (g == null) {
if (v1 > 255) v1 = 255; else if (v1 < 0) v1 = 0;
if (v2 > 255) v2 = 255; else if (v2 < 0) v2 = 0;
if (v3 > 255) v3 = 255; else if (v3 < 0) v3 = 0;
return 0xff000000 | ((int)v1 << 16) | ((int)v2 << 8) | (int)v3;
}
return g.color(v1, v2, v3);
}
public final int color(float v1, float v2, float v3, float alpha) {
if (g == null) {
if (alpha > 255) alpha = 255; else if (alpha < 0) alpha = 0;
if (v1 > 255) v1 = 255; else if (v1 < 0) v1 = 0;
if (v2 > 255) v2 = 255; else if (v2 < 0) v2 = 0;
if (v3 > 255) v3 = 255; else if (v3 < 0) v3 = 0;
return ((int)alpha << 24) | ((int)v1 << 16) | ((int)v2 << 8) | (int)v3;
}
return g.color(v1, v2, v3, alpha);
}
static public int blendColor(int c1, int c2, int mode) {
return PImage.blendColor(c1, c2, mode);
}
//////////////////////////////////////////////////////////////
// MAIN
/**
* Set this sketch to communicate its state back to the PDE.
* <p/>
* This uses the stderr stream to write positions of the window
* (so that it will be saved by the PDE for the next run) and
* notify on quit. See more notes in the Worker class.
*/
public void setupExternalMessages() {
frame.addComponentListener(new ComponentAdapter() {
@Override
public void componentMoved(ComponentEvent e) {
Point where = ((Frame) e.getSource()).getLocation();
System.err.println(PApplet.EXTERNAL_MOVE + " " +
where.x + " " + where.y);
System.err.flush(); // doesn't seem to help or hurt
}
});
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
// System.err.println(PApplet.EXTERNAL_QUIT);
// System.err.flush(); // important
// System.exit(0);
exit(); // don't quit, need to just shut everything down (0133)
}
});
}
/**
* Set up a listener that will fire proper component resize events
* in cases where frame.setResizable(true) is called.
*/
public void setupFrameResizeListener() {
frame.addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
// Ignore bad resize events fired during setup to fix
// http://dev.processing.org/bugs/show_bug.cgi?id=341
// This should also fix the blank screen on Linux bug
// http://dev.processing.org/bugs/show_bug.cgi?id=282
if (frame.isResizable()) {
// might be multiple resize calls before visible (i.e. first
// when pack() is called, then when it's resized for use).
// ignore them because it's not the user resizing things.
Frame farm = (Frame) e.getComponent();
if (farm.isVisible()) {
Insets insets = farm.getInsets();
Dimension windowSize = farm.getSize();
// 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);
}
}
}
}
});
}
// /**
// * 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).
((JFrame)frame).getContentPane().setBackground(new Color(0xCC, 0xCC, 0xCC));
// 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).
*/
protected PImage loadImageTGA(String filename) throws IOException {
InputStream is = createInput(filename);
if (is == null) return null;
byte header[] = new byte[18];
int offset = 0;
do {
int count = is.read(header, offset, header.length - offset);
if (count == -1) return null;
offset += count;
} while (offset < 18);
/*
header[2] image type code
2 (0x02) - Uncompressed, RGB images.
3 (0x03) - Uncompressed, black and white images.
10 (0x0A) - Runlength encoded RGB images.
11 (0x0B) - Compressed, black and white images. (grayscale?)
header[16] is the bit depth (8, 24, 32)
header[17] image descriptor (packed bits)
0x20 is 32 = origin upper-left
0x28 is 32 + 8 = origin upper-left + 32 bits
7 6 5 4 3 2 1 0
128 64 32 16 8 4 2 1
*/
int format = 0;
if (((header[2] == 3) || (header[2] == 11)) && // B&W, plus RLE or not
(header[16] == 8) && // 8 bits
((header[17] == 0x8) || (header[17] == 0x28))) { // origin, 32 bit
format = ALPHA;
} else if (((header[2] == 2) || (header[2] == 10)) && // RGB, RLE or not
(header[16] == 24) && // 24 bits
((header[17] == 0x20) || (header[17] == 0))) { // origin
format = RGB;
} else if (((header[2] == 2) || (header[2] == 10)) &&
(header[16] == 32) &&
((header[17] == 0x8) || (header[17] == 0x28))) { // origin, 32
format = ARGB;
}
if (format == 0) {
System.err.println("Unknown .tga file format for " + filename);
//" (" + header[2] + " " +
//(header[16] & 0xff) + " " +
//hex(header[17], 2) + ")");
return null;
}
int w = ((header[13] & 0xff) << 8) + (header[12] & 0xff);
int h = ((header[15] & 0xff) << 8) + (header[14] & 0xff);
PImage outgoing = createImage(w, h, format);
// where "reversed" means upper-left corner (normal for most of
// the modernized world, but "reversed" for the tga spec)
//boolean reversed = (header[17] & 0x20) != 0;
// https://github.com/processing/processing/issues/1682
boolean reversed = (header[17] & 0x20) == 0;
if ((header[2] == 2) || (header[2] == 3)) { // not RLE encoded
if (reversed) {
int index = (h-1) * w;
switch (format) {
case ALPHA:
for (int y = h-1; y >= 0; y--) {
for (int x = 0; x < w; x++) {
outgoing.pixels[index + x] = is.read();
}
index -= w;
}
break;
case RGB:
for (int y = h-1; y >= 0; y--) {
for (int x = 0; x < w; x++) {
outgoing.pixels[index + x] =
is.read() | (is.read() << 8) | (is.read() << 16) |
0xff000000;
}
index -= w;
}
break;
case ARGB:
for (int y = h-1; y >= 0; y--) {
for (int x = 0; x < w; x++) {
outgoing.pixels[index + x] =
is.read() | (is.read() << 8) | (is.read() << 16) |
(is.read() << 24);
}
index -= w;
}
}
} else { // not reversed
int count = w * h;
switch (format) {
case ALPHA:
for (int i = 0; i < count; i++) {
outgoing.pixels[i] = is.read();
}
break;
case RGB:
for (int i = 0; i < count; i++) {
outgoing.pixels[i] =
is.read() | (is.read() << 8) | (is.read() << 16) |
0xff000000;
}
break;
case ARGB:
for (int i = 0; i < count; i++) {
outgoing.pixels[i] =
is.read() | (is.read() << 8) | (is.read() << 16) |
(is.read() << 24);
}
break;
}
}
} else { // header[2] is 10 or 11
int index = 0;
int px[] = outgoing.pixels;
while (index < px.length) {
int num = is.read();
boolean isRLE = (num & 0x80) != 0;
if (isRLE) {
num -= 127; // (num & 0x7F) + 1
int pixel = 0;
switch (format) {
case ALPHA:
pixel = is.read();
break;
case RGB:
pixel = 0xFF000000 |
is.read() | (is.read() << 8) | (is.read() << 16);
//(is.read() << 16) | (is.read() << 8) | is.read();
break;
case ARGB:
pixel = is.read() |
(is.read() << 8) | (is.read() << 16) | (is.read() << 24);
break;
}
for (int i = 0; i < num; i++) {
px[index++] = pixel;
if (index == px.length) break;
}
} else { // write up to 127 bytes as uncompressed
num += 1;
switch (format) {
case ALPHA:
for (int i = 0; i < num; i++) {
px[index++] = is.read();
}
break;
case RGB:
for (int i = 0; i < num; i++) {
px[index++] = 0xFF000000 |
is.read() | (is.read() << 8) | (is.read() << 16);
//(is.read() << 16) | (is.read() << 8) | is.read();
}
break;
case ARGB:
for (int i = 0; i < num; i++) {
px[index++] = is.read() | //(is.read() << 24) |
(is.read() << 8) | (is.read() << 16) | (is.read() << 24);
//(is.read() << 16) | (is.read() << 8) | is.read();
}
break;
}
}
}
if (!reversed) {
int[] temp = new int[w];
for (int y = 0; y < h/2; y++) {
int z = (h-1) - y;
System.arraycopy(px, y*w, temp, 0, w);
System.arraycopy(px, z*w, px, y*w, w);
System.arraycopy(temp, 0, px, z*w, w);
}
}
}
return outgoing;
}
//////////////////////////////////////////////////////////////
// DATA I/O
// /**
// * @webref input:files
// * @brief Creates a new XML object
// * @param name the name to be given to the root element of the new XML object
// * @return an XML object, or null
// * @see XML
// * @see PApplet#loadXML(String)
// * @see PApplet#parseXML(String)
// * @see PApplet#saveXML(XML, String)
// */
// public XML createXML(String name) {
// try {
// return new XML(name);
// } catch (Exception e) {
// e.printStackTrace();
// return null;
// }
// }
/**
* @webref input:files
* @param filename name of a file in the data folder or a URL.
* @see XML
* @see PApplet#parseXML(String)
* @see PApplet#saveXML(XML, String)
* @see PApplet#loadBytes(String)
* @see PApplet#loadStrings(String)
* @see PApplet#loadTable(String)
*/
public XML loadXML(String filename) {
return loadXML(filename, null);
}
// version that uses 'options' though there are currently no supported options
/**
* @nowebref
*/
public XML loadXML(String filename, String options) {
try {
return new XML(createReader(filename), options);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* @webref input:files
* @brief Converts String content to an XML object
* @param data the content to be parsed as XML
* @return an XML object, or null
* @see XML
* @see PApplet#loadXML(String)
* @see PApplet#saveXML(XML, String)
*/
public XML parseXML(String xmlString) {
return parseXML(xmlString, null);
}
public XML parseXML(String xmlString, String options) {
try {
return XML.parse(xmlString, options);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* @webref output:files
* @param xml the XML object to save to disk
* @param filename name of the file to write to
* @see XML
* @see PApplet#loadXML(String)
* @see PApplet#parseXML(String)
*/
public boolean saveXML(XML xml, String filename) {
return saveXML(xml, filename, null);
}
public boolean saveXML(XML xml, String filename, String options) {
return xml.save(saveFile(filename), options);
}
public JSONObject parseJSONObject(String input) {
return new JSONObject(new StringReader(input));
}
/**
* @webref 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));
}
/**
* Return a full path to an item in the data folder.
* <p>
* This is only available with applications, not applets or Android.
* On Windows and Linux, this is simply the data folder, which is located
* in the same directory as the EXE file and lib folders. On Mac OS X, this
* is a path to the data folder buried inside Contents/Resources/Java.
* For the latter point, that also means that the data folder should not be
* considered writable. Use sketchPath() for now, or inputPath() and
* outputPath() once they're available in the 2.0 release.
* <p>
* dataPath() is not supported with applets because applets have their data
* folder wrapped into the JAR file. To read data from the data folder that
* works with an applet, you should use other methods such as createInput(),
* createReader(), or loadStrings().
*/
public String dataPath(String where) {
return dataFile(where).getAbsolutePath();
}
/**
* Return a full path to an item in the data folder as a File object.
* See the dataPath() method for more information.
*/
public File dataFile(String where) {
// isAbsolute() could throw an access exception, but so will writing
// to the local disk using the sketch path, so this is safe here.
File why = new File(where);
if (why.isAbsolute()) return why;
String jarPath =
getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
if (jarPath.contains("Contents/Resources/Java/")) {
// The path will be URL encoded (%20 for spaces) coming from above
// http://code.google.com/p/processing/issues/detail?id=1073
File containingFolder = new File(urlDecode(jarPath)).getParentFile();
File dataFolder = new File(containingFolder, "data");
return new File(dataFolder, where);
}
// Windows, Linux, or when not using a Mac OS X .app file
return new File(sketchPath + File.separator + "data" + File.separator + where);
}
/**
* On Windows and Linux, this is simply the data folder. On Mac OS X, this is
* the path to the data folder buried inside Contents/Resources/Java
*/
// public File inputFile(String where) {
// }
// public String inputPath(String where) {
// }
/**
* Takes a path and creates any in-between folders if they don't
* already exist. Useful when trying to save to a subfolder that
* may not actually exist.
*/
static public void createPath(String path) {
createPath(new File(path));
}
static public void createPath(File file) {
try {
String parent = file.getParent();
if (parent != null) {
File unit = new File(parent);
if (!unit.exists()) unit.mkdirs();
}
} catch (SecurityException se) {
System.err.println("You don't have permissions to create " +
file.getAbsolutePath());
}
}
static public String getExtension(String filename) {
String extension;
String lower = filename.toLowerCase();
int dot = filename.lastIndexOf('.');
if (dot == -1) {
extension = "unknown"; // no extension found
}
extension = lower.substring(dot + 1);
// check for, and strip any parameters on the url, i.e.
// filename.jpg?blah=blah&something=that
int question = extension.indexOf('?');
if (question != -1) {
extension = extension.substring(0, question);
}
return extension;
}
//////////////////////////////////////////////////////////////
// URL ENCODING
static public String urlEncode(String str) {
try {
return URLEncoder.encode(str, "UTF-8");
} catch (UnsupportedEncodingException e) { // oh c'mon
return null;
}
}
static public String urlDecode(String str) {
try {
return URLDecoder.decode(str, "UTF-8");
} catch (UnsupportedEncodingException e) { // safe per the JDK source
return null;
}
}
//////////////////////////////////////////////////////////////
// SORT
/**
* ( begin auto-generated from sort.xml )
*
* Sorts an array of numbers from smallest to largest and puts an array of
* words in alphabetical order. The original array is not modified, a
* re-ordered array is returned. The <b>count</b> parameter states the
* number of elements to sort. For example if there are 12 elements in an
* array and if count is the value 5, only the first five elements on the
* array will be sorted. <!--As of release 0126, the alphabetical ordering
* is case insensitive.-->
*
* ( end auto-generated )
* @webref data:array_functions
* @param list array to sort
* @see PApplet#reverse(boolean[])
*/
static public byte[] sort(byte list[]) {
return sort(list, list.length);
}
/**
* @param count number of elements to sort, starting from 0
*/
static public byte[] sort(byte[] list, int count) {
byte[] outgoing = new byte[list.length];
System.arraycopy(list, 0, outgoing, 0, list.length);
Arrays.sort(outgoing, 0, count);
return outgoing;
}
static public char[] sort(char list[]) {
return sort(list, list.length);
}
static public char[] sort(char[] list, int count) {
char[] outgoing = new char[list.length];
System.arraycopy(list, 0, outgoing, 0, list.length);
Arrays.sort(outgoing, 0, count);
return outgoing;
}
static public int[] sort(int list[]) {
return sort(list, list.length);
}
static public int[] sort(int[] list, int count) {
int[] outgoing = new int[list.length];
System.arraycopy(list, 0, outgoing, 0, list.length);
Arrays.sort(outgoing, 0, count);
return outgoing;
}
static public float[] sort(float list[]) {
return sort(list, list.length);
}
static public float[] sort(float[] list, int count) {
float[] outgoing = new float[list.length];
System.arraycopy(list, 0, outgoing, 0, list.length);
Arrays.sort(outgoing, 0, count);
return outgoing;
}
static public String[] sort(String list[]) {
return sort(list, list.length);
}
static public String[] sort(String[] list, int count) {
String[] outgoing = new String[list.length];
System.arraycopy(list, 0, outgoing, 0, list.length);
Arrays.sort(outgoing, 0, count);
return outgoing;
}
//////////////////////////////////////////////////////////////
// ARRAY UTILITIES
/**
* ( begin auto-generated from arrayCopy.xml )
*
* Copies an array (or part of an array) to another array. The <b>src</b>
* array is copied to the <b>dst</b> array, beginning at the position
* specified by <b>srcPos</b> and into the position specified by
* <b>dstPos</b>. The number of elements to copy is determined by
* <b>length</b>. The simplified version with two arguments copies an
* entire array to another of the same size. It is equivalent to
* "arrayCopy(src, 0, dst, 0, src.length)". This function is far more
* efficient for copying array data than iterating through a <b>for</b> and
* copying each element.
*
* ( end auto-generated )
* @webref data:array_functions
* @param src the source array
* @param srcPosition starting position in the source array
* @param dst the destination array of the same data type as the source array
* @param dstPosition starting position in the destination array
* @param length number of array elements to be copied
* @see PApplet#concat(boolean[], boolean[])
*/
static public void arrayCopy(Object src, int srcPosition,
Object dst, int dstPosition,
int length) {
System.arraycopy(src, srcPosition, dst, dstPosition, length);
}
/**
* Convenience method for arraycopy().
* Identical to <CODE>arraycopy(src, 0, dst, 0, length);</CODE>
*/
static public void arrayCopy(Object src, Object dst, int length) {
System.arraycopy(src, 0, dst, 0, length);
}
/**
* Shortcut to copy the entire contents of
* the source into the destination array.
* Identical to <CODE>arraycopy(src, 0, dst, 0, src.length);</CODE>
*/
static public void arrayCopy(Object src, Object dst) {
System.arraycopy(src, 0, dst, 0, Array.getLength(src));
}
//
/**
* @deprecated Use arrayCopy() instead.
*/
static public void arraycopy(Object src, int srcPosition,
Object dst, int dstPosition,
int length) {
System.arraycopy(src, srcPosition, dst, dstPosition, length);
}
/**
* @deprecated Use arrayCopy() instead.
*/
static public void arraycopy(Object src, Object dst, int length) {
System.arraycopy(src, 0, dst, 0, length);
}
/**
* @deprecated Use arrayCopy() instead.
*/
static public void arraycopy(Object src, Object dst) {
System.arraycopy(src, 0, dst, 0, Array.getLength(src));
}
/**
* ( begin auto-generated from expand.xml )
*
* Increases the size of an array. By default, this function doubles the
* size of the array, but the optional <b>newSize</b> parameter provides
* precise control over the increase in size.
* <br/> <br/>
* When using an array of objects, the data returned from the function must
* be cast to the object array's data type. For example: <em>SomeClass[]
* items = (SomeClass[]) expand(originalArray)</em>.
*
* ( end auto-generated )
*
* @webref data:array_functions
* @param list the array to expand
* @see PApplet#shorten(boolean[])
*/
static public boolean[] expand(boolean list[]) {
return expand(list, list.length << 1);
}
/**
* @param newSize new size for the array
*/
static public boolean[] expand(boolean list[], int newSize) {
boolean temp[] = new boolean[newSize];
System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length));
return temp;
}
static public byte[] expand(byte list[]) {
return expand(list, list.length << 1);
}
static public byte[] expand(byte list[], int newSize) {
byte temp[] = new byte[newSize];
System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length));
return temp;
}
static public char[] expand(char list[]) {
return expand(list, list.length << 1);
}
static public char[] expand(char list[], int newSize) {
char temp[] = new char[newSize];
System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length));
return temp;
}
static public int[] expand(int list[]) {
return expand(list, list.length << 1);
}
static public int[] expand(int list[], int newSize) {
int temp[] = new int[newSize];
System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length));
return temp;
}
static public long[] expand(long list[]) {
return expand(list, list.length << 1);
}
static public long[] expand(long list[], int newSize) {
long temp[] = new long[newSize];
System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length));
return temp;
}
static public float[] expand(float list[]) {
return expand(list, list.length << 1);
}
static public float[] expand(float list[], int newSize) {
float temp[] = new float[newSize];
System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length));
return temp;
}
static public double[] expand(double list[]) {
return expand(list, list.length << 1);
}
static public double[] expand(double list[], int newSize) {
double temp[] = new double[newSize];
System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length));
return temp;
}
static public String[] expand(String list[]) {
return expand(list, list.length << 1);
}
static public String[] expand(String list[], int newSize) {
String temp[] = new String[newSize];
// in case the new size is smaller than list.length
System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length));
return temp;
}
/**
* @nowebref
*/
static public Object expand(Object array) {
return expand(array, Array.getLength(array) << 1);
}
static public Object expand(Object list, int newSize) {
Class<?> type = list.getClass().getComponentType();
Object temp = Array.newInstance(type, newSize);
System.arraycopy(list, 0, temp, 0,
Math.min(Array.getLength(list), newSize));
return temp;
}
// contract() has been removed in revision 0124, use subset() instead.
// (expand() is also functionally equivalent)
/**
* ( begin auto-generated from append.xml )
*
* Expands an array by one element and adds data to the new position. The
* datatype of the <b>element</b> parameter must be the same as the
* datatype of the array.
* <br/> <br/>
* When using an array of objects, the data returned from the function must
* be cast to the object array's data type. For example: <em>SomeClass[]
* items = (SomeClass[]) append(originalArray, element)</em>.
*
* ( end auto-generated )
*
* @webref data:array_functions
* @param array array to append
* @param value new data for the array
* @see PApplet#shorten(boolean[])
* @see PApplet#expand(boolean[])
*/
static public byte[] append(byte array[], byte value) {
array = expand(array, array.length + 1);
array[array.length-1] = value;
return array;
}
static public char[] append(char array[], char value) {
array = expand(array, array.length + 1);
array[array.length-1] = value;
return array;
}
static public int[] append(int array[], int value) {
array = expand(array, array.length + 1);
array[array.length-1] = value;
return array;
}
static public float[] append(float array[], float value) {
array = expand(array, array.length + 1);
array[array.length-1] = value;
return array;
}
static public String[] append(String array[], String value) {
array = expand(array, array.length + 1);
array[array.length-1] = value;
return array;
}
static public Object append(Object array, Object value) {
int length = Array.getLength(array);
array = expand(array, length + 1);
Array.set(array, length, value);
return array;
}
/**
* ( begin auto-generated from shorten.xml )
*
* Decreases an array by one element and returns the shortened array.
* <br/> <br/>
* When using an array of objects, the data returned from the function must
* be cast to the object array's data type. For example: <em>SomeClass[]
* items = (SomeClass[]) shorten(originalArray)</em>.
*
* ( end auto-generated )
*
* @webref data:array_functions
* @param list array to shorten
* @see PApplet#append(byte[], byte)
* @see PApplet#expand(boolean[])
*/
static public boolean[] shorten(boolean list[]) {
return subset(list, 0, list.length-1);
}
static public byte[] shorten(byte list[]) {
return subset(list, 0, list.length-1);
}
static public char[] shorten(char list[]) {
return subset(list, 0, list.length-1);
}
static public int[] shorten(int list[]) {
return subset(list, 0, list.length-1);
}
static public float[] shorten(float list[]) {
return subset(list, 0, list.length-1);
}
static public String[] shorten(String list[]) {
return subset(list, 0, list.length-1);
}
static public Object shorten(Object list) {
int length = Array.getLength(list);
return subset(list, 0, length - 1);
}
/**
* ( begin auto-generated from splice.xml )
*
* Inserts a value or array of values into an existing array. The first two
* parameters must be of the same datatype. The <b>array</b> parameter
* defines the array which will be modified and the second parameter
* defines the data which will be inserted.
* <br/> <br/>
* When using an array of objects, the data returned from the function must
* be cast to the object array's data type. For example: <em>SomeClass[]
* items = (SomeClass[]) splice(array1, array2, index)</em>.
*
* ( end auto-generated )
* @webref data:array_functions
* @param list array to splice into
* @param value value to be spliced in
* @param index position in the array from which to insert data
* @see PApplet#concat(boolean[], boolean[])
* @see PApplet#subset(boolean[], int, int)
*/
static final public boolean[] splice(boolean list[],
boolean value, int index) {
boolean outgoing[] = new boolean[list.length + 1];
System.arraycopy(list, 0, outgoing, 0, index);
outgoing[index] = value;
System.arraycopy(list, index, outgoing, index + 1,
list.length - index);
return outgoing;
}
static final public boolean[] splice(boolean list[],
boolean value[], int index) {
boolean outgoing[] = new boolean[list.length + value.length];
System.arraycopy(list, 0, outgoing, 0, index);
System.arraycopy(value, 0, outgoing, index, value.length);
System.arraycopy(list, index, outgoing, index + value.length,
list.length - index);
return outgoing;
}
static final public byte[] splice(byte list[],
byte value, int index) {
byte outgoing[] = new byte[list.length + 1];
System.arraycopy(list, 0, outgoing, 0, index);
outgoing[index] = value;
System.arraycopy(list, index, outgoing, index + 1,
list.length - index);
return outgoing;
}
static final public byte[] splice(byte list[],
byte value[], int index) {
byte outgoing[] = new byte[list.length + value.length];
System.arraycopy(list, 0, outgoing, 0, index);
System.arraycopy(value, 0, outgoing, index, value.length);
System.arraycopy(list, index, outgoing, index + value.length,
list.length - index);
return outgoing;
}
static final public char[] splice(char list[],
char value, int index) {
char outgoing[] = new char[list.length + 1];
System.arraycopy(list, 0, outgoing, 0, index);
outgoing[index] = value;
System.arraycopy(list, index, outgoing, index + 1,
list.length - index);
return outgoing;
}
static final public char[] splice(char list[],
char value[], int index) {
char outgoing[] = new char[list.length + value.length];
System.arraycopy(list, 0, outgoing, 0, index);
System.arraycopy(value, 0, outgoing, index, value.length);
System.arraycopy(list, index, outgoing, index + value.length,
list.length - index);
return outgoing;
}
static final public int[] splice(int list[],
int value, int index) {
int outgoing[] = new int[list.length + 1];
System.arraycopy(list, 0, outgoing, 0, index);
outgoing[index] = value;
System.arraycopy(list, index, outgoing, index + 1,
list.length - index);
return outgoing;
}
static final public int[] splice(int list[],
int value[], int index) {
int outgoing[] = new int[list.length + value.length];
System.arraycopy(list, 0, outgoing, 0, index);
System.arraycopy(value, 0, outgoing, index, value.length);
System.arraycopy(list, index, outgoing, index + value.length,
list.length - index);
return outgoing;
}
static final public float[] splice(float list[],
float value, int index) {
float outgoing[] = new float[list.length + 1];
System.arraycopy(list, 0, outgoing, 0, index);
outgoing[index] = value;
System.arraycopy(list, index, outgoing, index + 1,
list.length - index);
return outgoing;
}
static final public float[] splice(float list[],
float value[], int index) {
float outgoing[] = new float[list.length + value.length];
System.arraycopy(list, 0, outgoing, 0, index);
System.arraycopy(value, 0, outgoing, index, value.length);
System.arraycopy(list, index, outgoing, index + value.length,
list.length - index);
return outgoing;
}
static final public String[] splice(String list[],
String value, int index) {
String outgoing[] = new String[list.length + 1];
System.arraycopy(list, 0, outgoing, 0, index);
outgoing[index] = value;
System.arraycopy(list, index, outgoing, index + 1,
list.length - index);
return outgoing;
}
static final public String[] splice(String list[],
String value[], int index) {
String outgoing[] = new String[list.length + value.length];
System.arraycopy(list, 0, outgoing, 0, index);
System.arraycopy(value, 0, outgoing, index, value.length);
System.arraycopy(list, index, outgoing, index + value.length,
list.length - index);
return outgoing;
}
static final public Object splice(Object list, Object value, int index) {
Object[] outgoing = null;
int length = Array.getLength(list);
// check whether item being spliced in is an array
if (value.getClass().getName().charAt(0) == '[') {
int vlength = Array.getLength(value);
outgoing = new Object[length + vlength];
System.arraycopy(list, 0, outgoing, 0, index);
System.arraycopy(value, 0, outgoing, index, vlength);
System.arraycopy(list, index, outgoing, index + vlength, length - index);
} else {
outgoing = new Object[length + 1];
System.arraycopy(list, 0, outgoing, 0, index);
Array.set(outgoing, index, value);
System.arraycopy(list, index, outgoing, index + 1, length - index);
}
return outgoing;
}
static public boolean[] subset(boolean list[], int start) {
return subset(list, start, list.length - start);
}
/**
* ( begin auto-generated from subset.xml )
*
* Extracts an array of elements from an existing array. The <b>array</b>
* parameter defines the array from which the elements will be copied and
* the <b>offset</b> and <b>length</b> parameters determine which elements
* to extract. If no <b>length</b> is given, elements will be extracted
* from the <b>offset</b> to the end of the array. When specifying the
* <b>offset</b> remember the first array element is 0. This function does
* not change the source array.
* <br/> <br/>
* When using an array of objects, the data returned from the function must
* be cast to the object array's data type. For example: <em>SomeClass[]
* items = (SomeClass[]) subset(originalArray, 0, 4)</em>.
*
* ( end auto-generated )
* @webref data:array_functions
* @param list array to extract from
* @param start position to begin
* @param count number of values to extract
* @see PApplet#splice(boolean[], boolean, int)
*/
static public boolean[] subset(boolean list[], int start, int count) {
boolean output[] = new boolean[count];
System.arraycopy(list, start, output, 0, count);
return output;
}
static public byte[] subset(byte list[], int start) {
return subset(list, start, list.length - start);
}
static public byte[] subset(byte list[], int start, int count) {
byte output[] = new byte[count];
System.arraycopy(list, start, output, 0, count);
return output;
}
static public char[] subset(char list[], int start) {
return subset(list, start, list.length - start);
}
static public char[] subset(char list[], int start, int count) {
char output[] = new char[count];
System.arraycopy(list, start, output, 0, count);
return output;
}
static public int[] subset(int list[], int start) {
return subset(list, start, list.length - start);
}
static public int[] subset(int list[], int start, int count) {
int output[] = new int[count];
System.arraycopy(list, start, output, 0, count);
return output;
}
static public float[] subset(float list[], int start) {
return subset(list, start, list.length - start);
}
static public float[] subset(float list[], int start, int count) {
float output[] = new float[count];
System.arraycopy(list, start, output, 0, count);
return output;
}
static public String[] subset(String list[], int start) {
return subset(list, start, list.length - start);
}
static public String[] subset(String list[], int start, int count) {
String output[] = new String[count];
System.arraycopy(list, start, output, 0, count);
return output;
}
static public Object subset(Object list, int start) {
int length = Array.getLength(list);
return subset(list, start, length - start);
}
static public Object subset(Object list, int start, int count) {
Class<?> type = list.getClass().getComponentType();
Object outgoing = Array.newInstance(type, count);
System.arraycopy(list, start, outgoing, 0, count);
return outgoing;
}
/**
* ( begin auto-generated from concat.xml )
*
* Concatenates two arrays. For example, concatenating the array { 1, 2, 3
* } and the array { 4, 5, 6 } yields { 1, 2, 3, 4, 5, 6 }. Both parameters
* must be arrays of the same datatype.
* <br/> <br/>
* When using an array of objects, the data returned from the function must
* be cast to the object array's data type. For example: <em>SomeClass[]
* items = (SomeClass[]) concat(array1, array2)</em>.
*
* ( end auto-generated )
* @webref data:array_functions
* @param a first array to concatenate
* @param b second array to concatenate
* @see PApplet#splice(boolean[], boolean, int)
* @see PApplet#arrayCopy(Object, int, Object, int, int)
*/
static public boolean[] concat(boolean a[], boolean b[]) {
boolean c[] = new boolean[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
static public byte[] concat(byte a[], byte b[]) {
byte c[] = new byte[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
static public char[] concat(char a[], char b[]) {
char c[] = new char[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
static public int[] concat(int a[], int b[]) {
int c[] = new int[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
static public float[] concat(float a[], float b[]) {
float c[] = new float[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
static public String[] concat(String a[], String b[]) {
String c[] = new String[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
static public Object concat(Object a, Object b) {
Class<?> type = a.getClass().getComponentType();
int alength = Array.getLength(a);
int blength = Array.getLength(b);
Object outgoing = Array.newInstance(type, alength + blength);
System.arraycopy(a, 0, outgoing, 0, alength);
System.arraycopy(b, 0, outgoing, alength, blength);
return outgoing;
}
//
/**
* ( begin auto-generated from reverse.xml )
*
* Reverses the order of an array.
*
* ( end auto-generated )
* @webref data:array_functions
* @param list booleans[], bytes[], chars[], ints[], floats[], or Strings[]
* @see PApplet#sort(String[], int)
*/
static public boolean[] reverse(boolean list[]) {
boolean outgoing[] = new boolean[list.length];
int length1 = list.length - 1;
for (int i = 0; i < list.length; i++) {
outgoing[i] = list[length1 - i];
}
return outgoing;
}
static public byte[] reverse(byte list[]) {
byte outgoing[] = new byte[list.length];
int length1 = list.length - 1;
for (int i = 0; i < list.length; i++) {
outgoing[i] = list[length1 - i];
}
return outgoing;
}
static public char[] reverse(char list[]) {
char outgoing[] = new char[list.length];
int length1 = list.length - 1;
for (int i = 0; i < list.length; i++) {
outgoing[i] = list[length1 - i];
}
return outgoing;
}
static public int[] reverse(int list[]) {
int outgoing[] = new int[list.length];
int length1 = list.length - 1;
for (int i = 0; i < list.length; i++) {
outgoing[i] = list[length1 - i];
}
return outgoing;
}
static public float[] reverse(float list[]) {
float outgoing[] = new float[list.length];
int length1 = list.length - 1;
for (int i = 0; i < list.length; i++) {
outgoing[i] = list[length1 - i];
}
return outgoing;
}
static public String[] reverse(String list[]) {
String outgoing[] = new String[list.length];
int length1 = list.length - 1;
for (int i = 0; i < list.length; i++) {
outgoing[i] = list[length1 - i];
}
return outgoing;
}
static public Object reverse(Object list) {
Class<?> type = list.getClass().getComponentType();
int length = Array.getLength(list);
Object outgoing = Array.newInstance(type, length);
for (int i = 0; i < length; i++) {
Array.set(outgoing, i, Array.get(list, (length - 1) - i));
}
return outgoing;
}
//////////////////////////////////////////////////////////////
// STRINGS
/**
* ( begin auto-generated from trim.xml )
*
* Removes whitespace characters from the beginning and end of a String. In
* addition to standard whitespace characters such as space, carriage
* return, and tab, this function also removes the Unicode "nbsp" character.
*
* ( end auto-generated )
* @webref data:string_functions
* @param str any string
* @see PApplet#split(String, String)
* @see PApplet#join(String[], char)
*/
static public String trim(String str) {
return str.replace('\u00A0', ' ').trim();
}
/**
* @param array a String array
*/
static public String[] trim(String[] array) {
String[] outgoing = new String[array.length];
for (int i = 0; i < array.length; i++) {
if (array[i] != null) {
outgoing[i] = array[i].replace('\u00A0', ' ').trim();
}
}
return outgoing;
}
/**
* ( begin auto-generated from join.xml )
*
* Combines an array of Strings into one String, each separated by the
* character(s) used for the <b>separator</b> parameter. To join arrays of
* ints or floats, it's necessary to first convert them to strings using
* <b>nf()</b> or <b>nfs()</b>.
*
* ( end auto-generated )
* @webref data:string_functions
* @param list array of Strings
* @param separator char or String to be placed between each item
* @see PApplet#split(String, String)
* @see PApplet#trim(String)
* @see PApplet#nf(float, int, int)
* @see PApplet#nfs(float, int, int)
*/
static public String join(String[] list, char separator) {
return join(list, String.valueOf(separator));
}
static public String join(String[] list, String separator) {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < list.length; i++) {
if (i != 0) buffer.append(separator);
buffer.append(list[i]);
}
return buffer.toString();
}
static public String[] splitTokens(String value) {
return splitTokens(value, WHITESPACE);
}
/**
* ( begin auto-generated from splitTokens.xml )
*
* The splitTokens() function splits a String at one or many character
* "tokens." The <b>tokens</b> parameter specifies the character or
* characters to be used as a boundary.
* <br/> <br/>
* If no <b>tokens</b> character is specified, any whitespace character is
* used to split. Whitespace characters include tab (\\t), line feed (\\n),
* carriage return (\\r), form feed (\\f), and space. To convert a String
* to an array of integers or floats, use the datatype conversion functions
* <b>int()</b> and <b>float()</b> to convert the array of Strings.
*
* ( end auto-generated )
* @webref data:string_functions
* @param value the String to be split
* @param delim list of individual characters that will be used as separators
* @see PApplet#split(String, String)
* @see PApplet#join(String[], String)
* @see PApplet#trim(String)
*/
static public String[] splitTokens(String value, String delim) {
StringTokenizer toker = new StringTokenizer(value, delim);
String pieces[] = new String[toker.countTokens()];
int index = 0;
while (toker.hasMoreTokens()) {
pieces[index++] = toker.nextToken();
}
return pieces;
}
/**
* ( begin auto-generated from split.xml )
*
* The split() function breaks a string into pieces using a character or
* string as the divider. The <b>delim</b> parameter specifies the
* character or characters that mark the boundaries between each piece. A
* String[] array is returned that contains each of the pieces.
* <br/> <br/>
* If the result is a set of numbers, you can convert the String[] array to
* to a float[] or int[] array using the datatype conversion functions
* <b>int()</b> and <b>float()</b> (see example above).
* <br/> <br/>
* The <b>splitTokens()</b> function works in a similar fashion, except
* that it splits using a range of characters instead of a specific
* character or sequence.
* <!-- /><br />
* This function uses regular expressions to determine how the <b>delim</b>
* parameter divides the <b>str</b> parameter. Therefore, if you use
* characters such parentheses and brackets that are used with regular
* expressions as a part of the <b>delim</b> parameter, you'll need to put
* two blackslashes (\\\\) in front of the character (see example above).
* You can read more about <a
* href="http://en.wikipedia.org/wiki/Regular_expression">regular
* expressions</a> and <a
* href="http://en.wikipedia.org/wiki/Escape_character">escape
* characters</a> on Wikipedia.
* -->
*
* ( end auto-generated )
* @webref data:string_functions
* @usage web_application
* @param value the String to be split
* @param delim the character or String used to separate the data
*/
static public String[] split(String value, char delim) {
// do this so that the exception occurs inside the user's
// program, rather than appearing to be a bug inside split()
if (value == null) return null;
//return split(what, String.valueOf(delim)); // huh
char chars[] = value.toCharArray();
int splitCount = 0; //1;
for (int i = 0; i < chars.length; i++) {
if (chars[i] == delim) splitCount++;
}
// make sure that there is something in the input string
//if (chars.length > 0) {
// if the last char is a delimeter, get rid of it..
//if (chars[chars.length-1] == delim) splitCount--;
// on second thought, i don't agree with this, will disable
//}
if (splitCount == 0) {
String splits[] = new String[1];
splits[0] = new String(value);
return splits;
}
//int pieceCount = splitCount + 1;
String splits[] = new String[splitCount + 1];
int splitIndex = 0;
int startIndex = 0;
for (int i = 0; i < chars.length; i++) {
if (chars[i] == delim) {
splits[splitIndex++] =
new String(chars, startIndex, i-startIndex);
startIndex = i + 1;
}
}
//if (startIndex != chars.length) {
splits[splitIndex] =
new String(chars, startIndex, chars.length-startIndex);
//}
return splits;
}
static public String[] split(String value, String delim) {
ArrayList<String> items = new ArrayList<String>();
int index;
int offset = 0;
while ((index = value.indexOf(delim, offset)) != -1) {
items.add(value.substring(offset, index));
offset = index + delim.length();
}
items.add(value.substring(offset));
String[] outgoing = new String[items.size()];
items.toArray(outgoing);
return outgoing;
}
static protected HashMap<String, Pattern> matchPatterns;
static Pattern matchPattern(String regexp) {
Pattern p = null;
if (matchPatterns == null) {
matchPatterns = new HashMap<String, Pattern>();
} else {
p = matchPatterns.get(regexp);
}
if (p == null) {
if (matchPatterns.size() == 10) {
// Just clear out the match patterns here if more than 10 are being
// used. It's not terribly efficient, but changes that you have >10
// different match patterns are very slim, unless you're doing
// something really tricky (like custom match() methods), in which
// case match() won't be efficient anyway. (And you should just be
// using your own Java code.) The alternative is using a queue here,
// but that's a silly amount of work for negligible benefit.
matchPatterns.clear();
}
p = Pattern.compile(regexp, Pattern.MULTILINE | Pattern.DOTALL);
matchPatterns.put(regexp, p);
}
return p;
}
/**
* ( begin auto-generated from match.xml )
*
* The match() function is used to apply a regular expression to a piece of
* text, and return matching groups (elements found inside parentheses) as
* a String array. No match will return null. If no groups are specified in
* the regexp, but the sequence matches, an array of length one (with the
* matched text as the first element of the array) will be returned.<br />
* <br />
* To use the function, first check to see if the result is null. If the
* result is null, then the sequence did not match. If the sequence did
* match, an array is returned.
* If there are groups (specified by sets of parentheses) in the regexp,
* then the contents of each will be returned in the array.
* Element [0] of a regexp match returns the entire matching string, and
* the match groups start at element [1] (the first group is [1], the
* second [2], and so on).<br />
* <br />
* The syntax can be found in the reference for Java's <a
* href="http://download.oracle.com/javase/6/docs/api/">Pattern</a> class.
* For regular expression syntax, read the <a
* href="http://download.oracle.com/javase/tutorial/essential/regex/">Java
* Tutorial</a> on the topic.
*
* ( end auto-generated )
* @webref data:string_functions
* @param str the String to be searched
* @param regexp the regexp to be used for matching
* @see PApplet#matchAll(String, String)
* @see PApplet#split(String, String)
* @see PApplet#splitTokens(String, String)
* @see PApplet#join(String[], String)
* @see PApplet#trim(String)
*/
static public String[] match(String str, String regexp) {
Pattern p = matchPattern(regexp);
Matcher m = p.matcher(str);
if (m.find()) {
int count = m.groupCount() + 1;
String[] groups = new String[count];
for (int i = 0; i < count; i++) {
groups[i] = m.group(i);
}
return groups;
}
return null;
}
/**
* ( begin auto-generated from matchAll.xml )
*
* This function is used to apply a regular expression to a piece of text,
* and return a list of matching groups (elements found inside parentheses)
* as a two-dimensional String array. No matches will return null. If no
* groups are specified in the regexp, but the sequence matches, a two
* dimensional array is still returned, but the second dimension is only of
* length one.<br />
* <br />
* To use the function, first check to see if the result is null. If the
* result is null, then the sequence did not match at all. If the sequence
* did match, a 2D array is returned. If there are groups (specified by
* sets of parentheses) in the regexp, then the contents of each will be
* returned in the array.
* Assuming, a loop with counter variable i, element [i][0] of a regexp
* match returns the entire matching string, and the match groups start at
* element [i][1] (the first group is [i][1], the second [i][2], and so
* on).<br />
* <br />
* The syntax can be found in the reference for Java's <a
* href="http://download.oracle.com/javase/6/docs/api/">Pattern</a> class.
* For regular expression syntax, read the <a
* href="http://download.oracle.com/javase/tutorial/essential/regex/">Java
* Tutorial</a> on the topic.
*
* ( end auto-generated )
* @webref data:string_functions
* @param str the String to be searched
* @param regexp the regexp to be used for matching
* @see PApplet#match(String, String)
* @see PApplet#split(String, String)
* @see PApplet#splitTokens(String, String)
* @see PApplet#join(String[], String)
* @see PApplet#trim(String)
*/
static public String[][] matchAll(String str, String regexp) {
Pattern p = matchPattern(regexp);
Matcher m = p.matcher(str);
ArrayList<String[]> results = new ArrayList<String[]>();
int count = m.groupCount() + 1;
while (m.find()) {
String[] groups = new String[count];
for (int i = 0; i < count; i++) {
groups[i] = m.group(i);
}
results.add(groups);
}
if (results.isEmpty()) {
return null;
}
String[][] matches = new String[results.size()][count];
for (int i = 0; i < matches.length; i++) {
matches[i] = results.get(i);
}
return matches;
}
//////////////////////////////////////////////////////////////
// CASTING FUNCTIONS, INSERTED BY PREPROC
/**
* Convert a char to a boolean. 'T', 't', and '1' will become the
* boolean value true, while 'F', 'f', or '0' will become false.
*/
/*
static final public boolean parseBoolean(char what) {
return ((what == 't') || (what == 'T') || (what == '1'));
}
*/
/**
* <p>Convert an integer to a boolean. Because of how Java handles upgrading
* numbers, this will also cover byte and char (as they will upgrade to
* an int without any sort of explicit cast).</p>
* <p>The preprocessor will convert boolean(what) to parseBoolean(what).</p>
* @return false if 0, true if any other number
*/
static final public boolean parseBoolean(int what) {
return (what != 0);
}
/*
// removed because this makes no useful sense
static final public boolean parseBoolean(float what) {
return (what != 0);
}
*/
/**
* Convert the string "true" or "false" to a boolean.
* @return true if 'what' is "true" or "TRUE", false otherwise
*/
static final public boolean parseBoolean(String what) {
return new Boolean(what).booleanValue();
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
/*
// removed, no need to introduce strange syntax from other languages
static final public boolean[] parseBoolean(char what[]) {
boolean outgoing[] = new boolean[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] =
((what[i] == 't') || (what[i] == 'T') || (what[i] == '1'));
}
return outgoing;
}
*/
/**
* Convert a byte array to a boolean array. Each element will be
* evaluated identical to the integer case, where a byte equal
* to zero will return false, and any other value will return true.
* @return array of boolean elements
*/
/*
static final public boolean[] parseBoolean(byte what[]) {
boolean outgoing[] = new boolean[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = (what[i] != 0);
}
return outgoing;
}
*/
/**
* Convert an int array to a boolean array. An int equal
* to zero will return false, and any other value will return true.
* @return array of boolean elements
*/
static final public boolean[] parseBoolean(int what[]) {
boolean outgoing[] = new boolean[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = (what[i] != 0);
}
return outgoing;
}
/*
// removed, not necessary... if necessary, convert to int array first
static final public boolean[] parseBoolean(float what[]) {
boolean outgoing[] = new boolean[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = (what[i] != 0);
}
return outgoing;
}
*/
static final public boolean[] parseBoolean(String what[]) {
boolean outgoing[] = new boolean[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = new Boolean(what[i]).booleanValue();
}
return outgoing;
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
static final public byte parseByte(boolean what) {
return what ? (byte)1 : 0;
}
static final public byte parseByte(char what) {
return (byte) what;
}
static final public byte parseByte(int what) {
return (byte) what;
}
static final public byte parseByte(float what) {
return (byte) what;
}
/*
// nixed, no precedent
static final public byte[] parseByte(String what) { // note: array[]
return what.getBytes();
}
*/
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
static final public byte[] parseByte(boolean what[]) {
byte outgoing[] = new byte[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = what[i] ? (byte)1 : 0;
}
return outgoing;
}
static final public byte[] parseByte(char what[]) {
byte outgoing[] = new byte[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = (byte) what[i];
}
return outgoing;
}
static final public byte[] parseByte(int what[]) {
byte outgoing[] = new byte[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = (byte) what[i];
}
return outgoing;
}
static final public byte[] parseByte(float what[]) {
byte outgoing[] = new byte[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = (byte) what[i];
}
return outgoing;
}
/*
static final public byte[][] parseByte(String what[]) { // note: array[][]
byte outgoing[][] = new byte[what.length][];
for (int i = 0; i < what.length; i++) {
outgoing[i] = what[i].getBytes();
}
return outgoing;
}
*/
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
/*
static final public char parseChar(boolean what) { // 0/1 or T/F ?
return what ? 't' : 'f';
}
*/
static final public char parseChar(byte what) {
return (char) (what & 0xff);
}
static final public char parseChar(int what) {
return (char) what;
}
/*
static final public char parseChar(float what) { // nonsensical
return (char) what;
}
static final public char[] parseChar(String what) { // note: array[]
return what.toCharArray();
}
*/
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
/*
static final public char[] parseChar(boolean what[]) { // 0/1 or T/F ?
char outgoing[] = new char[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = what[i] ? 't' : 'f';
}
return outgoing;
}
*/
static final public char[] parseChar(byte what[]) {
char outgoing[] = new char[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = (char) (what[i] & 0xff);
}
return outgoing;
}
static final public char[] parseChar(int what[]) {
char outgoing[] = new char[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = (char) what[i];
}
return outgoing;
}
/*
static final public char[] parseChar(float what[]) { // nonsensical
char outgoing[] = new char[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = (char) what[i];
}
return outgoing;
}
static final public char[][] parseChar(String what[]) { // note: array[][]
char outgoing[][] = new char[what.length][];
for (int i = 0; i < what.length; i++) {
outgoing[i] = what[i].toCharArray();
}
return outgoing;
}
*/
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
static final public int parseInt(boolean what) {
return what ? 1 : 0;
}
/**
* Note that parseInt() will un-sign a signed byte value.
*/
static final public int parseInt(byte what) {
return what & 0xff;
}
/**
* Note that parseInt('5') is unlike String in the sense that it
* won't return 5, but the ascii value. This is because ((int) someChar)
* returns the ascii value, and parseInt() is just longhand for the cast.
*/
static final public int parseInt(char what) {
return what;
}
/**
* Same as floor(), or an (int) cast.
*/
static final public int parseInt(float what) {
return (int) what;
}
/**
* Parse a String into an int value. Returns 0 if the value is bad.
*/
static final public int parseInt(String what) {
return parseInt(what, 0);
}
/**
* Parse a String to an int, and provide an alternate value that
* should be used when the number is invalid.
*/
static final public int parseInt(String what, int otherwise) {
try {
int offset = what.indexOf('.');
if (offset == -1) {
return Integer.parseInt(what);
} else {
return Integer.parseInt(what.substring(0, offset));
}
} catch (NumberFormatException e) { }
return otherwise;
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
static final public int[] parseInt(boolean what[]) {
int list[] = new int[what.length];
for (int i = 0; i < what.length; i++) {
list[i] = what[i] ? 1 : 0;
}
return list;
}
static final public int[] parseInt(byte what[]) { // note this unsigns
int list[] = new int[what.length];
for (int i = 0; i < what.length; i++) {
list[i] = (what[i] & 0xff);
}
return list;
}
static final public int[] parseInt(char what[]) {
int list[] = new int[what.length];
for (int i = 0; i < what.length; i++) {
list[i] = what[i];
}
return list;
}
static public int[] parseInt(float what[]) {
int inties[] = new int[what.length];
for (int i = 0; i < what.length; i++) {
inties[i] = (int)what[i];
}
return inties;
}
/**
* Make an array of int elements from an array of String objects.
* If the String can't be parsed as a number, it will be set to zero.
*
* String s[] = { "1", "300", "44" };
* int numbers[] = parseInt(s);
*
* numbers will contain { 1, 300, 44 }
*/
static public int[] parseInt(String what[]) {
return parseInt(what, 0);
}
/**
* Make an array of int elements from an array of String objects.
* If the String can't be parsed as a number, its entry in the
* array will be set to the value of the "missing" parameter.
*
* String s[] = { "1", "300", "apple", "44" };
* int numbers[] = parseInt(s, 9999);
*
* numbers will contain { 1, 300, 9999, 44 }
*/
static public int[] parseInt(String what[], int missing) {
int output[] = new int[what.length];
for (int i = 0; i < what.length; i++) {
try {
output[i] = Integer.parseInt(what[i]);
} catch (NumberFormatException e) {
output[i] = missing;
}
}
return output;
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
/*
static final public float parseFloat(boolean what) {
return what ? 1 : 0;
}
*/
/**
* Convert an int to a float value. Also handles bytes because of
* Java's rules for upgrading values.
*/
static final public float parseFloat(int what) { // also handles byte
return what;
}
static final public float parseFloat(String what) {
return parseFloat(what, Float.NaN);
}
static final public float parseFloat(String what, float otherwise) {
try {
return new Float(what).floatValue();
} catch (NumberFormatException e) { }
return otherwise;
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
/*
static final public float[] parseFloat(boolean what[]) {
float floaties[] = new float[what.length];
for (int i = 0; i < what.length; i++) {
floaties[i] = what[i] ? 1 : 0;
}
return floaties;
}
static final public float[] parseFloat(char what[]) {
float floaties[] = new float[what.length];
for (int i = 0; i < what.length; i++) {
floaties[i] = (char) what[i];
}
return floaties;
}
*/
static final public float[] parseByte(byte what[]) {
float floaties[] = new float[what.length];
for (int i = 0; i < what.length; i++) {
floaties[i] = what[i];
}
return floaties;
}
static final public float[] parseFloat(int what[]) {
float floaties[] = new float[what.length];
for (int i = 0; i < what.length; i++) {
floaties[i] = what[i];
}
return floaties;
}
static final public float[] parseFloat(String what[]) {
return parseFloat(what, Float.NaN);
}
static final public float[] parseFloat(String what[], float missing) {
float output[] = new float[what.length];
for (int i = 0; i < what.length; i++) {
try {
output[i] = new Float(what[i]).floatValue();
} catch (NumberFormatException e) {
output[i] = missing;
}
}
return output;
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
static final public String str(boolean x) {
return String.valueOf(x);
}
static final public String str(byte x) {
return String.valueOf(x);
}
static final public String str(char x) {
return String.valueOf(x);
}
static final public String str(int x) {
return String.valueOf(x);
}
static final public String str(float x) {
return String.valueOf(x);
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
static final public String[] str(boolean x[]) {
String s[] = new String[x.length];
for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]);
return s;
}
static final public String[] str(byte x[]) {
String s[] = new String[x.length];
for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]);
return s;
}
static final public String[] str(char x[]) {
String s[] = new String[x.length];
for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]);
return s;
}
static final public String[] str(int x[]) {
String s[] = new String[x.length];
for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]);
return s;
}
static final public String[] str(float x[]) {
String s[] = new String[x.length];
for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]);
return s;
}
//////////////////////////////////////////////////////////////
// INT NUMBER FORMATTING
/**
* Integer number formatter.
*/
static private NumberFormat int_nf;
static private int int_nf_digits;
static private boolean int_nf_commas;
static public String[] nf(int num[], int digits) {
String formatted[] = new String[num.length];
for (int i = 0; i < formatted.length; i++) {
formatted[i] = nf(num[i], digits);
}
return formatted;
}
/**
* ( begin auto-generated from nf.xml )
*
* Utility function for formatting numbers into strings. There are two
* versions, one for formatting floats and one for formatting ints. The
* values for the <b>digits</b>, <b>left</b>, and <b>right</b> parameters
* should always be positive integers.<br /><br />As shown in the above
* example, <b>nf()</b> is used to add zeros to the left and/or right of a
* number. This is typically for aligning a list of numbers. To
* <em>remove</em> digits from a floating-point number, use the
* <b>int()</b>, <b>ceil()</b>, <b>floor()</b>, or <b>round()</b>
* functions.
*
* ( end auto-generated )
* @webref data:string_functions
* @param num the number(s) to format
* @param digits number of digits to pad with zero
* @see PApplet#nfs(float, int, int)
* @see PApplet#nfp(float, int, int)
* @see PApplet#nfc(float, int)
* @see PApplet#int(float)
*/
static public String nf(int num, int digits) {
if ((int_nf != null) &&
(int_nf_digits == digits) &&
!int_nf_commas) {
return int_nf.format(num);
}
int_nf = NumberFormat.getInstance();
int_nf.setGroupingUsed(false); // no commas
int_nf_commas = false;
int_nf.setMinimumIntegerDigits(digits);
int_nf_digits = digits;
return int_nf.format(num);
}
/**
* ( begin auto-generated from nfc.xml )
*
* Utility function for formatting numbers into strings and placing
* appropriate commas to mark units of 1000. There are two versions, one
* for formatting ints and one for formatting an array of ints. The value
* for the <b>digits</b> parameter should always be a positive integer.
* <br/> <br/>
* For a non-US locale, this will insert periods instead of commas, or
* whatever is apprioriate for that region.
*
* ( end auto-generated )
* @webref data:string_functions
* @param num the number(s) to format
* @see PApplet#nf(float, int, int)
* @see PApplet#nfp(float, int, int)
* @see PApplet#nfc(float, int)
*/
static public String[] nfc(int num[]) {
String formatted[] = new String[num.length];
for (int i = 0; i < formatted.length; i++) {
formatted[i] = nfc(num[i]);
}
return formatted;
}
/**
* nfc() or "number format with commas". This is an unfortunate misnomer
* because in locales where a comma is not the separator for numbers, it
* won't actually be outputting a comma, it'll use whatever makes sense for
* the locale.
*/
static public String nfc(int num) {
if ((int_nf != null) &&
(int_nf_digits == 0) &&
int_nf_commas) {
return int_nf.format(num);
}
int_nf = NumberFormat.getInstance();
int_nf.setGroupingUsed(true);
int_nf_commas = true;
int_nf.setMinimumIntegerDigits(0);
int_nf_digits = 0;
return int_nf.format(num);
}
/**
* number format signed (or space)
* Formats a number but leaves a blank space in the front
* when it's positive so that it can be properly aligned with
* numbers that have a negative sign in front of them.
*/
/**
* ( begin auto-generated from nfs.xml )
*
* Utility function for formatting numbers into strings. Similar to
* <b>nf()</b> but leaves a blank space in front of positive numbers so
* they align with negative numbers in spite of the minus symbol. There are
* two versions, one for formatting floats and one for formatting ints. The
* values for the <b>digits</b>, <b>left</b>, and <b>right</b> parameters
* should always be positive integers.
*
* ( end auto-generated )
* @webref data:string_functions
* @param num the number(s) to format
* @param digits number of digits to pad with zeroes
* @see PApplet#nf(float, int, int)
* @see PApplet#nfp(float, int, int)
* @see PApplet#nfc(float, int)
*/
static public String nfs(int num, int digits) {
return (num < 0) ? nf(num, digits) : (' ' + nf(num, digits));
}
static public String[] nfs(int num[], int digits) {
String formatted[] = new String[num.length];
for (int i = 0; i < formatted.length; i++) {
formatted[i] = nfs(num[i], digits);
}
return formatted;
}
//
/**
* number format positive (or plus)
* Formats a number, always placing a - or + sign
* in the front when it's negative or positive.
*/
/**
* ( begin auto-generated from nfp.xml )
*
* Utility function for formatting numbers into strings. Similar to
* <b>nf()</b> but puts a "+" in front of positive numbers and a "-" in
* front of negative numbers. There are two versions, one for formatting
* floats and one for formatting ints. The values for the <b>digits</b>,
* <b>left</b>, and <b>right</b> parameters should always be positive integers.
*
* ( end auto-generated )
* @webref data:string_functions
* @param num the number(s) to format
* @param digits number of digits to pad with zeroes
* @see PApplet#nf(float, int, int)
* @see PApplet#nfs(float, int, int)
* @see PApplet#nfc(float, int)
*/
static public String nfp(int num, int digits) {
return (num < 0) ? nf(num, digits) : ('+' + nf(num, digits));
}
static public String[] nfp(int num[], int digits) {
String formatted[] = new String[num.length];
for (int i = 0; i < formatted.length; i++) {
formatted[i] = nfp(num[i], digits);
}
return formatted;
}
//////////////////////////////////////////////////////////////
// FLOAT NUMBER FORMATTING
static private NumberFormat float_nf;
static private int float_nf_left, float_nf_right;
static private boolean float_nf_commas;
static public String[] nf(float num[], int left, int right) {
String formatted[] = new String[num.length];
for (int i = 0; i < formatted.length; i++) {
formatted[i] = nf(num[i], left, right);
}
return formatted;
}
/**
* @param num[] the number(s) to format
* @param left number of digits to the left of the decimal point
* @param right number of digits to the right of the decimal point
*/
static public String nf(float num, int left, int right) {
if ((float_nf != null) &&
(float_nf_left == left) &&
(float_nf_right == right) &&
!float_nf_commas) {
return float_nf.format(num);
}
float_nf = NumberFormat.getInstance();
float_nf.setGroupingUsed(false);
float_nf_commas = false;
if (left != 0) float_nf.setMinimumIntegerDigits(left);
if (right != 0) {
float_nf.setMinimumFractionDigits(right);
float_nf.setMaximumFractionDigits(right);
}
float_nf_left = left;
float_nf_right = right;
return float_nf.format(num);
}
/**
* @param num[] the number(s) to format
* @param right number of digits to the right of the decimal point
*/
static public String[] nfc(float num[], int right) {
String formatted[] = new String[num.length];
for (int i = 0; i < formatted.length; i++) {
formatted[i] = nfc(num[i], right);
}
return formatted;
}
static public String nfc(float num, int right) {
if ((float_nf != null) &&
(float_nf_left == 0) &&
(float_nf_right == right) &&
float_nf_commas) {
return float_nf.format(num);
}
float_nf = NumberFormat.getInstance();
float_nf.setGroupingUsed(true);
float_nf_commas = true;
if (right != 0) {
float_nf.setMinimumFractionDigits(right);
float_nf.setMaximumFractionDigits(right);
}
float_nf_left = 0;
float_nf_right = right;
return float_nf.format(num);
}
/**
* @param num[] the number(s) to format
* @param left the number of digits to the left of the decimal point
* @param right the number of digits to the right of the decimal point
*/
static public String[] nfs(float num[], int left, int right) {
String formatted[] = new String[num.length];
for (int i = 0; i < formatted.length; i++) {
formatted[i] = nfs(num[i], left, right);
}
return formatted;
}
static public String nfs(float num, int left, int right) {
return (num < 0) ? nf(num, left, right) : (' ' + nf(num, left, right));
}
/**
* @param left the number of digits to the left of the decimal point
* @param right the number of digits to the right of the decimal point
*/
static public String[] nfp(float num[], int left, int right) {
String formatted[] = new String[num.length];
for (int i = 0; i < formatted.length; i++) {
formatted[i] = nfp(num[i], left, right);
}
return formatted;
}
static public String nfp(float num, int left, int right) {
return (num < 0) ? nf(num, left, right) : ('+' + nf(num, left, right));
}
//////////////////////////////////////////////////////////////
// HEX/BINARY CONVERSION
/**
* ( begin auto-generated from hex.xml )
*
* Converts a byte, char, int, or color to a String containing the
* equivalent hexadecimal notation. For example color(0, 102, 153) will
* convert to the String "FF006699". This function can help make your geeky
* debugging sessions much happier.
* <br/> <br/>
* Note that the maximum number of digits is 8, because an int value can
* only represent up to 32 bits. Specifying more than eight digits will
* simply shorten the string to eight anyway.
*
* ( end auto-generated )
* @webref data:conversion
* @param value the value to convert
* @see PApplet#unhex(String)
* @see PApplet#binary(byte)
* @see PApplet#unbinary(String)
*/
static final public String hex(byte value) {
return hex(value, 2);
}
static final public String hex(char value) {
return hex(value, 4);
}
static final public String hex(int value) {
return hex(value, 8);
}
/**
* @param digits the number of digits (maximum 8)
*/
static final public String hex(int value, int digits) {
String stuff = Integer.toHexString(value).toUpperCase();
if (digits > 8) {
digits = 8;
}
int length = stuff.length();
if (length > digits) {
return stuff.substring(length - digits);
} else if (length < digits) {
return "00000000".substring(8 - (digits-length)) + stuff;
}
return stuff;
}
/**
* ( begin auto-generated from unhex.xml )
*
* Converts a String representation of a hexadecimal number to its
* equivalent integer value.
*
* ( end auto-generated )
*
* @webref data:conversion
* @param value String to convert to an integer
* @see PApplet#hex(int, int)
* @see PApplet#binary(byte)
* @see PApplet#unbinary(String)
*/
static final public int unhex(String value) {
// has to parse as a Long so that it'll work for numbers bigger than 2^31
return (int) (Long.parseLong(value, 16));
}
//
/**
* Returns a String that contains the binary value of a byte.
* The returned value will always have 8 digits.
*/
static final public String binary(byte value) {
return binary(value, 8);
}
/**
* Returns a String that contains the binary value of a char.
* The returned value will always have 16 digits because chars
* are two bytes long.
*/
static final public String binary(char value) {
return binary(value, 16);
}
/**
* Returns a String that contains the binary value of an int. The length
* depends on the size of the number itself. If you want a specific number
* of digits use binary(int what, int digits) to specify how many.
*/
static final public String binary(int value) {
return binary(value, 32);
}
/*
* Returns a String that contains the binary value of an int.
* The digits parameter determines how many digits will be used.
*/
/**
* ( begin auto-generated from binary.xml )
*
* Converts a byte, char, int, or color to a String containing the
* equivalent binary notation. For example color(0, 102, 153, 255) will
* convert to the String "11111111000000000110011010011001". This function
* can help make your geeky debugging sessions much happier.
* <br/> <br/>
* Note that the maximum number of digits is 32, because an int value can
* only represent up to 32 bits. Specifying more than 32 digits will simply
* shorten the string to 32 anyway.
*
* ( end auto-generated )
* @webref data:conversion
* @param value value to convert
* @param digits number of digits to return
* @see PApplet#unbinary(String)
* @see PApplet#hex(int,int)
* @see PApplet#unhex(String)
*/
static final public String binary(int value, int digits) {
String stuff = Integer.toBinaryString(value);
if (digits > 32) {
digits = 32;
}
int length = stuff.length();
if (length > digits) {
return stuff.substring(length - digits);
} else if (length < digits) {
int offset = 32 - (digits-length);
return "00000000000000000000000000000000".substring(offset) + stuff;
}
return stuff;
}
/**
* ( begin auto-generated from unbinary.xml )
*
* Converts a String representation of a binary number to its equivalent
* integer value. For example, unbinary("00001000") will return 8.
*
* ( end auto-generated )
* @webref data:conversion
* @param value String to convert to an integer
* @see PApplet#binary(byte)
* @see PApplet#hex(int,int)
* @see PApplet#unhex(String)
*/
static final public int unbinary(String value) {
return Integer.parseInt(value, 2);
}
//////////////////////////////////////////////////////////////
// COLOR FUNCTIONS
// moved here so that they can work without
// the graphics actually being instantiated (outside setup)
/**
* ( begin auto-generated from color.xml )
*
* Creates colors for storing in variables of the <b>color</b> datatype.
* The parameters are interpreted as RGB or HSB values depending on the
* current <b>colorMode()</b>. The default mode is RGB values from 0 to 255
* and therefore, the function call <b>color(255, 204, 0)</b> will return a
* bright yellow color. More about how colors are stored can be found in
* the reference for the <a href="color_datatype.html">color</a> datatype.
*
* ( end auto-generated )
* @webref color:creating_reading
* @param gray number specifying value between white and black
* @see PApplet#colorMode(int)
*/
public final int color(int gray) {
if (g == null) {
if (gray > 255) gray = 255; else if (gray < 0) gray = 0;
return 0xff000000 | (gray << 16) | (gray << 8) | gray;
}
return g.color(gray);
}
/**
* @nowebref
* @param fgray number specifying value between white and black
*/
public final int color(float fgray) {
if (g == null) {
int gray = (int) fgray;
if (gray > 255) gray = 255; else if (gray < 0) gray = 0;
return 0xff000000 | (gray << 16) | (gray << 8) | gray;
}
return g.color(fgray);
}
/**
* As of 0116 this also takes color(#FF8800, alpha)
* @param alpha relative to current color range
*/
public final int color(int gray, int alpha) {
if (g == null) {
if (alpha > 255) alpha = 255; else if (alpha < 0) alpha = 0;
if (gray > 255) {
// then assume this is actually a #FF8800
return (alpha << 24) | (gray & 0xFFFFFF);
} else {
//if (gray > 255) gray = 255; else if (gray < 0) gray = 0;
return (alpha << 24) | (gray << 16) | (gray << 8) | gray;
}
}
return g.color(gray, alpha);
}
/**
* @nowebref
*/
public final int color(float fgray, float falpha) {
if (g == null) {
int gray = (int) fgray;
int alpha = (int) falpha;
if (gray > 255) gray = 255; else if (gray < 0) gray = 0;
if (alpha > 255) alpha = 255; else if (alpha < 0) alpha = 0;
return 0xff000000 | (gray << 16) | (gray << 8) | gray;
}
return g.color(fgray, falpha);
}
/**
* @param v1 red or hue values relative to the current color range
* @param v2 green or saturation values relative to the current color range
* @param v3 blue or brightness values relative to the current color range
*/
public final int color(int v1, int v2, int v3) {
if (g == null) {
if (v1 > 255) v1 = 255; else if (v1 < 0) v1 = 0;
if (v2 > 255) v2 = 255; else if (v2 < 0) v2 = 0;
if (v3 > 255) v3 = 255; else if (v3 < 0) v3 = 0;
return 0xff000000 | (v1 << 16) | (v2 << 8) | v3;
}
return g.color(v1, v2, v3);
}
public final int color(int v1, int v2, int v3, int alpha) {
if (g == null) {
if (alpha > 255) alpha = 255; else if (alpha < 0) alpha = 0;
if (v1 > 255) v1 = 255; else if (v1 < 0) v1 = 0;
if (v2 > 255) v2 = 255; else if (v2 < 0) v2 = 0;
if (v3 > 255) v3 = 255; else if (v3 < 0) v3 = 0;
return (alpha << 24) | (v1 << 16) | (v2 << 8) | v3;
}
return g.color(v1, v2, v3, alpha);
}
public final int color(float v1, float v2, float v3) {
if (g == null) {
if (v1 > 255) v1 = 255; else if (v1 < 0) v1 = 0;
if (v2 > 255) v2 = 255; else if (v2 < 0) v2 = 0;
if (v3 > 255) v3 = 255; else if (v3 < 0) v3 = 0;
return 0xff000000 | ((int)v1 << 16) | ((int)v2 << 8) | (int)v3;
}
return g.color(v1, v2, v3);
}
public final int color(float v1, float v2, float v3, float alpha) {
if (g == null) {
if (alpha > 255) alpha = 255; else if (alpha < 0) alpha = 0;
if (v1 > 255) v1 = 255; else if (v1 < 0) v1 = 0;
if (v2 > 255) v2 = 255; else if (v2 < 0) v2 = 0;
if (v3 > 255) v3 = 255; else if (v3 < 0) v3 = 0;
return ((int)alpha << 24) | ((int)v1 << 16) | ((int)v2 << 8) | (int)v3;
}
return g.color(v1, v2, v3, alpha);
}
static public int blendColor(int c1, int c2, int mode) {
return PImage.blendColor(c1, c2, mode);
}
//////////////////////////////////////////////////////////////
// MAIN
/**
* Set this sketch to communicate its state back to the PDE.
* <p/>
* This uses the stderr stream to write positions of the window
* (so that it will be saved by the PDE for the next run) and
* notify on quit. See more notes in the Worker class.
*/
public void setupExternalMessages() {
frame.addComponentListener(new ComponentAdapter() {
@Override
public void componentMoved(ComponentEvent e) {
Point where = ((Frame) e.getSource()).getLocation();
System.err.println(PApplet.EXTERNAL_MOVE + " " +
where.x + " " + where.y);
System.err.flush(); // doesn't seem to help or hurt
}
});
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
// System.err.println(PApplet.EXTERNAL_QUIT);
// System.err.flush(); // important
// System.exit(0);
exit(); // don't quit, need to just shut everything down (0133)
}
});
}
/**
* Set up a listener that will fire proper component resize events
* in cases where frame.setResizable(true) is called.
*/
public void setupFrameResizeListener() {
frame.addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
// Ignore bad resize events fired during setup to fix
// http://dev.processing.org/bugs/show_bug.cgi?id=341
// This should also fix the blank screen on Linux bug
// http://dev.processing.org/bugs/show_bug.cgi?id=282
if (frame.isResizable()) {
// might be multiple resize calls before visible (i.e. first
// when pack() is called, then when it's resized for use).
// ignore them because it's not the user resizing things.
Frame farm = (Frame) e.getComponent();
if (farm.isVisible()) {
Insets insets = farm.getInsets();
Dimension windowSize = farm.getSize();
// 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);
}
}
}
}
});
}
// /**
// * 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/com/android/settings/inputmethod/InputMethodAndLanguageSettings.java b/src/com/android/settings/inputmethod/InputMethodAndLanguageSettings.java
index 015ed15e8..8a077ee32 100644
--- a/src/com/android/settings/inputmethod/InputMethodAndLanguageSettings.java
+++ b/src/com/android/settings/inputmethod/InputMethodAndLanguageSettings.java
@@ -1,582 +1,583 @@
/*
* 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.settings.inputmethod;
import com.android.settings.R;
import com.android.settings.Settings.KeyboardLayoutPickerActivity;
import com.android.settings.Settings.SpellCheckersSettingsActivity;
import com.android.settings.SettingsPreferenceFragment;
import com.android.settings.Utils;
import com.android.settings.VoiceInputOutputSettings;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.ContentObserver;
import android.hardware.input.InputManager;
import android.hardware.input.KeyboardLayout;
import android.os.Bundle;
import android.os.Handler;
import android.preference.CheckBoxPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceCategory;
import android.preference.PreferenceScreen;
import android.provider.Settings;
import android.provider.Settings.System;
import android.text.TextUtils;
import android.view.InputDevice;
import android.view.inputmethod.InputMethodInfo;
import android.view.inputmethod.InputMethodManager;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.TreeSet;
public class InputMethodAndLanguageSettings extends SettingsPreferenceFragment
implements Preference.OnPreferenceChangeListener, InputManager.InputDeviceListener,
KeyboardLayoutDialogFragment.OnSetupKeyboardLayoutsListener {
private static final String KEY_PHONE_LANGUAGE = "phone_language";
private static final String KEY_CURRENT_INPUT_METHOD = "current_input_method";
private static final String KEY_INPUT_METHOD_SELECTOR = "input_method_selector";
private static final String KEY_USER_DICTIONARY_SETTINGS = "key_user_dictionary_settings";
private static final String VOLUME_KEY_CURSOR_CONTROL = "volume_key_cursor_control";
// false: on ICS or later
private static final boolean SHOW_INPUT_METHOD_SWITCHER_SETTINGS = false;
private static final String[] sSystemSettingNames = {
System.TEXT_AUTO_REPLACE, System.TEXT_AUTO_CAPS, System.TEXT_AUTO_PUNCTUATE,
};
private static final String[] sHardKeyboardKeys = {
"auto_replace", "auto_caps", "auto_punctuate",
};
private int mDefaultInputMethodSelectorVisibility = 0;
private ListPreference mShowInputMethodSelectorPref;
private PreferenceCategory mKeyboardSettingsCategory;
private PreferenceCategory mHardKeyboardCategory;
private PreferenceCategory mGameControllerCategory;
private Preference mLanguagePref;
private final ArrayList<InputMethodPreference> mInputMethodPreferenceList =
new ArrayList<InputMethodPreference>();
private final ArrayList<PreferenceScreen> mHardKeyboardPreferenceList =
new ArrayList<PreferenceScreen>();
private InputManager mIm;
private InputMethodManager mImm;
private List<InputMethodInfo> mImis;
private boolean mIsOnlyImeSettings;
private Handler mHandler;
@SuppressWarnings("unused")
private SettingsObserver mSettingsObserver;
private Intent mIntentWaitingForResult;
private ListPreference mVolumeKeyCursorControl;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
addPreferencesFromResource(R.xml.language_settings);
try {
mDefaultInputMethodSelectorVisibility = Integer.valueOf(
getString(R.string.input_method_selector_visibility_default_value));
} catch (NumberFormatException e) {
}
if (getActivity().getAssets().getLocales().length == 1) {
// No "Select language" pref if there's only one system locale available.
getPreferenceScreen().removePreference(findPreference(KEY_PHONE_LANGUAGE));
} else {
mLanguagePref = findPreference(KEY_PHONE_LANGUAGE);
}
if (SHOW_INPUT_METHOD_SWITCHER_SETTINGS) {
mShowInputMethodSelectorPref = (ListPreference)findPreference(
KEY_INPUT_METHOD_SELECTOR);
mShowInputMethodSelectorPref.setOnPreferenceChangeListener(this);
// TODO: Update current input method name on summary
updateInputMethodSelectorSummary(loadInputMethodSelectorVisibility());
}
new VoiceInputOutputSettings(this).onCreate();
// Get references to dynamically constructed categories.
mHardKeyboardCategory = (PreferenceCategory)findPreference("hard_keyboard");
mKeyboardSettingsCategory = (PreferenceCategory)findPreference(
"keyboard_settings_category");
mGameControllerCategory = (PreferenceCategory)findPreference(
"game_controller_settings_category");
// Filter out irrelevant features if invoked from IME settings button.
mIsOnlyImeSettings = Settings.ACTION_INPUT_METHOD_SETTINGS.equals(
getActivity().getIntent().getAction());
getActivity().getIntent().setAction(null);
if (mIsOnlyImeSettings) {
getPreferenceScreen().removeAll();
getPreferenceScreen().addPreference(mHardKeyboardCategory);
if (SHOW_INPUT_METHOD_SWITCHER_SETTINGS) {
getPreferenceScreen().addPreference(mShowInputMethodSelectorPref);
}
getPreferenceScreen().addPreference(mKeyboardSettingsCategory);
}
// Build IME preference category.
mImm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mImis = mImm.getInputMethodList();
mKeyboardSettingsCategory.removeAll();
if (!mIsOnlyImeSettings) {
final PreferenceScreen currentIme = new PreferenceScreen(getActivity(), null);
currentIme.setKey(KEY_CURRENT_INPUT_METHOD);
currentIme.setTitle(getResources().getString(R.string.current_input_method));
mKeyboardSettingsCategory.addPreference(currentIme);
}
mInputMethodPreferenceList.clear();
final int N = (mImis == null ? 0 : mImis.size());
for (int i = 0; i < N; ++i) {
final InputMethodInfo imi = mImis.get(i);
final InputMethodPreference pref = getInputMethodPreference(imi, N);
mInputMethodPreferenceList.add(pref);
}
if (!mInputMethodPreferenceList.isEmpty()) {
Collections.sort(mInputMethodPreferenceList);
for (int i = 0; i < N; ++i) {
mKeyboardSettingsCategory.addPreference(mInputMethodPreferenceList.get(i));
}
}
// Build hard keyboard and game controller preference categories.
mIm = (InputManager)getActivity().getSystemService(Context.INPUT_SERVICE);
updateInputDevices();
// Spell Checker
final Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setClass(getActivity(), SpellCheckersSettingsActivity.class);
final SpellCheckersPreference scp = ((SpellCheckersPreference)findPreference(
"spellcheckers_settings"));
if (scp != null) {
scp.setFragmentIntent(this, intent);
}
- mVolumeKeyCursorControl = (ListPreference) findPreference(VOLUME_KEY_CURSOR_CONTROL);
- mVolumeKeyCursorControl.setOnPreferenceChangeListener(this);
- mVolumeKeyCursorControl.setValue(Integer.toString(Settings.System.getInt(getActivity()
- .getContentResolver(), Settings.System.VOLUME_KEY_CURSOR_CONTROL, 0)));
- mVolumeKeyCursorControl.setSummary(mVolumeKeyCursorControl.getEntry());
+ if(mVolumeKeyCursorControl != null) {
+ mVolumeKeyCursorControl.setOnPreferenceChangeListener(this);
+ mVolumeKeyCursorControl.setValue(Integer.toString(Settings.System.getInt(getActivity()
+ .getContentResolver(), Settings.System.VOLUME_KEY_CURSOR_CONTROL, 0)));
+ mVolumeKeyCursorControl.setSummary(mVolumeKeyCursorControl.getEntry());
+ }
mHandler = new Handler();
mSettingsObserver = new SettingsObserver(mHandler, getActivity());
}
private void updateInputMethodSelectorSummary(int value) {
String[] inputMethodSelectorTitles = getResources().getStringArray(
R.array.input_method_selector_titles);
if (inputMethodSelectorTitles.length > value) {
mShowInputMethodSelectorPref.setSummary(inputMethodSelectorTitles[value]);
mShowInputMethodSelectorPref.setValue(String.valueOf(value));
}
}
private void updateUserDictionaryPreference(Preference userDictionaryPreference) {
final Activity activity = getActivity();
final TreeSet<String> localeList = UserDictionaryList.getUserDictionaryLocalesSet(activity);
if (null == localeList) {
// The locale list is null if and only if the user dictionary service is
// not present or disabled. In this case we need to remove the preference.
getPreferenceScreen().removePreference(userDictionaryPreference);
} else if (localeList.size() <= 1) {
final Intent intent =
new Intent(UserDictionaryList.USER_DICTIONARY_SETTINGS_INTENT_ACTION);
userDictionaryPreference.setTitle(R.string.user_dict_single_settings_title);
userDictionaryPreference.setIntent(intent);
userDictionaryPreference.setFragment(
com.android.settings.UserDictionarySettings.class.getName());
// If the size of localeList is 0, we don't set the locale parameter in the
// extras. This will be interpreted by the UserDictionarySettings class as
// meaning "the current locale".
// Note that with the current code for UserDictionaryList#getUserDictionaryLocalesSet()
// the locale list always has at least one element, since it always includes the current
// locale explicitly. @see UserDictionaryList.getUserDictionaryLocalesSet().
if (localeList.size() == 1) {
final String locale = (String)localeList.toArray()[0];
userDictionaryPreference.getExtras().putString("locale", locale);
}
} else {
userDictionaryPreference.setTitle(R.string.user_dict_multiple_settings_title);
userDictionaryPreference.setFragment(UserDictionaryList.class.getName());
}
}
@Override
public void onResume() {
super.onResume();
mSettingsObserver.resume();
mIm.registerInputDeviceListener(this, null);
if (!mIsOnlyImeSettings) {
if (mLanguagePref != null) {
Configuration conf = getResources().getConfiguration();
String language = conf.locale.getLanguage();
String localeString;
// TODO: This is not an accurate way to display the locale, as it is
// just working around the fact that we support limited dialects
// and want to pretend that the language is valid for all locales.
// We need a way to support languages that aren't tied to a particular
// locale instead of hiding the locale qualifier.
if (hasOnlyOneLanguageInstance(language,
Resources.getSystem().getAssets().getLocales())) {
localeString = conf.locale.getDisplayLanguage(conf.locale);
} else {
localeString = conf.locale.getDisplayName(conf.locale);
}
if (localeString.length() > 1) {
localeString = Character.toUpperCase(localeString.charAt(0))
+ localeString.substring(1);
mLanguagePref.setSummary(localeString);
}
}
updateUserDictionaryPreference(findPreference(KEY_USER_DICTIONARY_SETTINGS));
if (SHOW_INPUT_METHOD_SWITCHER_SETTINGS) {
mShowInputMethodSelectorPref.setOnPreferenceChangeListener(this);
}
}
// Hard keyboard
if (!mHardKeyboardPreferenceList.isEmpty()) {
for (int i = 0; i < sHardKeyboardKeys.length; ++i) {
CheckBoxPreference chkPref = (CheckBoxPreference)
mHardKeyboardCategory.findPreference(sHardKeyboardKeys[i]);
chkPref.setChecked(
System.getInt(getContentResolver(), sSystemSettingNames[i], 1) > 0);
}
}
updateInputDevices();
// IME
InputMethodAndSubtypeUtil.loadInputMethodSubtypeList(
this, getContentResolver(), mImis, null);
updateActiveInputMethodsSummary();
}
@Override
public void onPause() {
super.onPause();
mIm.unregisterInputDeviceListener(this);
mSettingsObserver.pause();
if (SHOW_INPUT_METHOD_SWITCHER_SETTINGS) {
mShowInputMethodSelectorPref.setOnPreferenceChangeListener(null);
}
InputMethodAndSubtypeUtil.saveInputMethodSubtypeList(
this, getContentResolver(), mImis, !mHardKeyboardPreferenceList.isEmpty());
}
@Override
public void onInputDeviceAdded(int deviceId) {
updateInputDevices();
}
@Override
public void onInputDeviceChanged(int deviceId) {
updateInputDevices();
}
@Override
public void onInputDeviceRemoved(int deviceId) {
updateInputDevices();
}
@Override
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
// Input Method stuff
if (Utils.isMonkeyRunning()) {
return false;
}
if (preference instanceof PreferenceScreen) {
if (preference.getFragment() != null) {
// Fragment will be handled correctly by the super class.
} else if (KEY_CURRENT_INPUT_METHOD.equals(preference.getKey())) {
final InputMethodManager imm = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showInputMethodPicker();
}
} else if (preference instanceof CheckBoxPreference) {
final CheckBoxPreference chkPref = (CheckBoxPreference) preference;
if (!mHardKeyboardPreferenceList.isEmpty()) {
for (int i = 0; i < sHardKeyboardKeys.length; ++i) {
if (chkPref == mHardKeyboardCategory.findPreference(sHardKeyboardKeys[i])) {
System.putInt(getContentResolver(), sSystemSettingNames[i],
chkPref.isChecked() ? 1 : 0);
return true;
}
}
}
if (chkPref == mGameControllerCategory.findPreference("vibrate_input_devices")) {
System.putInt(getContentResolver(), Settings.System.VIBRATE_INPUT_DEVICES,
chkPref.isChecked() ? 1 : 0);
return true;
}
}
return super.onPreferenceTreeClick(preferenceScreen, preference);
}
private boolean hasOnlyOneLanguageInstance(String languageCode, String[] locales) {
int count = 0;
for (String localeCode : locales) {
if (localeCode.length() > 2
&& localeCode.startsWith(languageCode)) {
count++;
if (count > 1) {
return false;
}
}
}
return count == 1;
}
private void saveInputMethodSelectorVisibility(String value) {
try {
int intValue = Integer.valueOf(value);
Settings.Secure.putInt(getContentResolver(),
Settings.Secure.INPUT_METHOD_SELECTOR_VISIBILITY, intValue);
updateInputMethodSelectorSummary(intValue);
} catch(NumberFormatException e) {
}
}
private int loadInputMethodSelectorVisibility() {
return Settings.Secure.getInt(getContentResolver(),
Settings.Secure.INPUT_METHOD_SELECTOR_VISIBILITY,
mDefaultInputMethodSelectorVisibility);
}
@Override
public boolean onPreferenceChange(Preference preference, Object value) {
if (SHOW_INPUT_METHOD_SWITCHER_SETTINGS) {
if (preference == mShowInputMethodSelectorPref) {
if (value instanceof String) {
saveInputMethodSelectorVisibility((String)value);
}
}
}
if (preference == mVolumeKeyCursorControl) {
String volumeKeyCursorControl = (String) value;
int val = Integer.parseInt(volumeKeyCursorControl);
Settings.System.putInt(getActivity().getContentResolver(),
Settings.System.VOLUME_KEY_CURSOR_CONTROL, val);
int index = mVolumeKeyCursorControl.findIndexOfValue(volumeKeyCursorControl);
mVolumeKeyCursorControl.setSummary(mVolumeKeyCursorControl.getEntries()[index]);
return true;
}
return false;
}
private void updateActiveInputMethodsSummary() {
for (Preference pref : mInputMethodPreferenceList) {
if (pref instanceof InputMethodPreference) {
((InputMethodPreference)pref).updateSummary();
}
}
updateCurrentImeName();
}
private void updateCurrentImeName() {
final Context context = getActivity();
if (context == null || mImm == null) return;
final Preference curPref = getPreferenceScreen().findPreference(KEY_CURRENT_INPUT_METHOD);
if (curPref != null) {
final CharSequence curIme = InputMethodAndSubtypeUtil.getCurrentInputMethodName(
context, getContentResolver(), mImm, mImis, getPackageManager());
if (!TextUtils.isEmpty(curIme)) {
synchronized(this) {
curPref.setSummary(curIme);
}
}
}
}
private InputMethodPreference getInputMethodPreference(InputMethodInfo imi, int imiSize) {
final PackageManager pm = getPackageManager();
final CharSequence label = imi.loadLabel(pm);
// IME settings
final Intent intent;
final String settingsActivity = imi.getSettingsActivity();
if (!TextUtils.isEmpty(settingsActivity)) {
intent = new Intent(Intent.ACTION_MAIN);
intent.setClassName(imi.getPackageName(), settingsActivity);
} else {
intent = null;
}
// Add a check box for enabling/disabling IME
InputMethodPreference pref = new InputMethodPreference(this, intent, mImm, imi, imiSize);
pref.setKey(imi.getId());
pref.setTitle(label);
return pref;
}
private void updateInputDevices() {
updateHardKeyboards();
updateGameControllers();
}
private void updateHardKeyboards() {
mHardKeyboardPreferenceList.clear();
if (getResources().getConfiguration().keyboard == Configuration.KEYBOARD_QWERTY) {
final int[] devices = InputDevice.getDeviceIds();
for (int i = 0; i < devices.length; i++) {
InputDevice device = InputDevice.getDevice(devices[i]);
if (device != null
&& !device.isVirtual()
&& device.isFullKeyboard()) {
final String inputDeviceDescriptor = device.getDescriptor();
final String keyboardLayoutDescriptor =
mIm.getCurrentKeyboardLayoutForInputDevice(inputDeviceDescriptor);
final KeyboardLayout keyboardLayout = keyboardLayoutDescriptor != null ?
mIm.getKeyboardLayout(keyboardLayoutDescriptor) : null;
final PreferenceScreen pref = new PreferenceScreen(getActivity(), null);
pref.setTitle(device.getName());
if (keyboardLayout != null) {
pref.setSummary(keyboardLayout.toString());
} else {
pref.setSummary(R.string.keyboard_layout_default_label);
}
pref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
showKeyboardLayoutDialog(inputDeviceDescriptor);
return true;
}
});
mHardKeyboardPreferenceList.add(pref);
}
}
}
if (!mHardKeyboardPreferenceList.isEmpty()) {
for (int i = mHardKeyboardCategory.getPreferenceCount(); i-- > 0; ) {
final Preference pref = mHardKeyboardCategory.getPreference(i);
if (pref.getOrder() < 1000) {
mHardKeyboardCategory.removePreference(pref);
}
}
Collections.sort(mHardKeyboardPreferenceList);
final int count = mHardKeyboardPreferenceList.size();
for (int i = 0; i < count; i++) {
final Preference pref = mHardKeyboardPreferenceList.get(i);
pref.setOrder(i);
mHardKeyboardCategory.addPreference(pref);
}
getPreferenceScreen().addPreference(mHardKeyboardCategory);
} else {
getPreferenceScreen().removePreference(mHardKeyboardCategory);
}
}
private void showKeyboardLayoutDialog(String inputDeviceDescriptor) {
KeyboardLayoutDialogFragment fragment =
new KeyboardLayoutDialogFragment(inputDeviceDescriptor);
fragment.setTargetFragment(this, 0);
fragment.show(getActivity().getFragmentManager(), "keyboardLayout");
}
@Override
public void onSetupKeyboardLayouts(String inputDeviceDescriptor) {
final Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setClass(getActivity(), KeyboardLayoutPickerActivity.class);
intent.putExtra(KeyboardLayoutPickerFragment.EXTRA_INPUT_DEVICE_DESCRIPTOR,
inputDeviceDescriptor);
mIntentWaitingForResult = intent;
startActivityForResult(intent, 0);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (mIntentWaitingForResult != null) {
String inputDeviceDescriptor = mIntentWaitingForResult.getStringExtra(
KeyboardLayoutPickerFragment.EXTRA_INPUT_DEVICE_DESCRIPTOR);
mIntentWaitingForResult = null;
showKeyboardLayoutDialog(inputDeviceDescriptor);
}
}
private void updateGameControllers() {
if (haveInputDeviceWithVibrator()) {
getPreferenceScreen().addPreference(mGameControllerCategory);
CheckBoxPreference chkPref = (CheckBoxPreference)
mGameControllerCategory.findPreference("vibrate_input_devices");
chkPref.setChecked(System.getInt(getContentResolver(),
Settings.System.VIBRATE_INPUT_DEVICES, 1) > 0);
} else {
getPreferenceScreen().removePreference(mGameControllerCategory);
}
}
private boolean haveInputDeviceWithVibrator() {
final int[] devices = InputDevice.getDeviceIds();
for (int i = 0; i < devices.length; i++) {
InputDevice device = InputDevice.getDevice(devices[i]);
if (device != null && !device.isVirtual() && device.getVibrator().hasVibrator()) {
return true;
}
}
return false;
}
private class SettingsObserver extends ContentObserver {
private Context mContext;
public SettingsObserver(Handler handler, Context context) {
super(handler);
mContext = context;
}
@Override public void onChange(boolean selfChange) {
updateCurrentImeName();
}
public void resume() {
final ContentResolver cr = mContext.getContentResolver();
cr.registerContentObserver(
Settings.Secure.getUriFor(Settings.Secure.DEFAULT_INPUT_METHOD), false, this);
cr.registerContentObserver(Settings.Secure.getUriFor(
Settings.Secure.SELECTED_INPUT_METHOD_SUBTYPE), false, this);
}
public void pause() {
mContext.getContentResolver().unregisterContentObserver(this);
}
}
}
| true | true | public void onCreate(Bundle icicle) {
super.onCreate(icicle);
addPreferencesFromResource(R.xml.language_settings);
try {
mDefaultInputMethodSelectorVisibility = Integer.valueOf(
getString(R.string.input_method_selector_visibility_default_value));
} catch (NumberFormatException e) {
}
if (getActivity().getAssets().getLocales().length == 1) {
// No "Select language" pref if there's only one system locale available.
getPreferenceScreen().removePreference(findPreference(KEY_PHONE_LANGUAGE));
} else {
mLanguagePref = findPreference(KEY_PHONE_LANGUAGE);
}
if (SHOW_INPUT_METHOD_SWITCHER_SETTINGS) {
mShowInputMethodSelectorPref = (ListPreference)findPreference(
KEY_INPUT_METHOD_SELECTOR);
mShowInputMethodSelectorPref.setOnPreferenceChangeListener(this);
// TODO: Update current input method name on summary
updateInputMethodSelectorSummary(loadInputMethodSelectorVisibility());
}
new VoiceInputOutputSettings(this).onCreate();
// Get references to dynamically constructed categories.
mHardKeyboardCategory = (PreferenceCategory)findPreference("hard_keyboard");
mKeyboardSettingsCategory = (PreferenceCategory)findPreference(
"keyboard_settings_category");
mGameControllerCategory = (PreferenceCategory)findPreference(
"game_controller_settings_category");
// Filter out irrelevant features if invoked from IME settings button.
mIsOnlyImeSettings = Settings.ACTION_INPUT_METHOD_SETTINGS.equals(
getActivity().getIntent().getAction());
getActivity().getIntent().setAction(null);
if (mIsOnlyImeSettings) {
getPreferenceScreen().removeAll();
getPreferenceScreen().addPreference(mHardKeyboardCategory);
if (SHOW_INPUT_METHOD_SWITCHER_SETTINGS) {
getPreferenceScreen().addPreference(mShowInputMethodSelectorPref);
}
getPreferenceScreen().addPreference(mKeyboardSettingsCategory);
}
// Build IME preference category.
mImm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mImis = mImm.getInputMethodList();
mKeyboardSettingsCategory.removeAll();
if (!mIsOnlyImeSettings) {
final PreferenceScreen currentIme = new PreferenceScreen(getActivity(), null);
currentIme.setKey(KEY_CURRENT_INPUT_METHOD);
currentIme.setTitle(getResources().getString(R.string.current_input_method));
mKeyboardSettingsCategory.addPreference(currentIme);
}
mInputMethodPreferenceList.clear();
final int N = (mImis == null ? 0 : mImis.size());
for (int i = 0; i < N; ++i) {
final InputMethodInfo imi = mImis.get(i);
final InputMethodPreference pref = getInputMethodPreference(imi, N);
mInputMethodPreferenceList.add(pref);
}
if (!mInputMethodPreferenceList.isEmpty()) {
Collections.sort(mInputMethodPreferenceList);
for (int i = 0; i < N; ++i) {
mKeyboardSettingsCategory.addPreference(mInputMethodPreferenceList.get(i));
}
}
// Build hard keyboard and game controller preference categories.
mIm = (InputManager)getActivity().getSystemService(Context.INPUT_SERVICE);
updateInputDevices();
// Spell Checker
final Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setClass(getActivity(), SpellCheckersSettingsActivity.class);
final SpellCheckersPreference scp = ((SpellCheckersPreference)findPreference(
"spellcheckers_settings"));
if (scp != null) {
scp.setFragmentIntent(this, intent);
}
mVolumeKeyCursorControl = (ListPreference) findPreference(VOLUME_KEY_CURSOR_CONTROL);
mVolumeKeyCursorControl.setOnPreferenceChangeListener(this);
mVolumeKeyCursorControl.setValue(Integer.toString(Settings.System.getInt(getActivity()
.getContentResolver(), Settings.System.VOLUME_KEY_CURSOR_CONTROL, 0)));
mVolumeKeyCursorControl.setSummary(mVolumeKeyCursorControl.getEntry());
mHandler = new Handler();
mSettingsObserver = new SettingsObserver(mHandler, getActivity());
}
| public void onCreate(Bundle icicle) {
super.onCreate(icicle);
addPreferencesFromResource(R.xml.language_settings);
try {
mDefaultInputMethodSelectorVisibility = Integer.valueOf(
getString(R.string.input_method_selector_visibility_default_value));
} catch (NumberFormatException e) {
}
if (getActivity().getAssets().getLocales().length == 1) {
// No "Select language" pref if there's only one system locale available.
getPreferenceScreen().removePreference(findPreference(KEY_PHONE_LANGUAGE));
} else {
mLanguagePref = findPreference(KEY_PHONE_LANGUAGE);
}
if (SHOW_INPUT_METHOD_SWITCHER_SETTINGS) {
mShowInputMethodSelectorPref = (ListPreference)findPreference(
KEY_INPUT_METHOD_SELECTOR);
mShowInputMethodSelectorPref.setOnPreferenceChangeListener(this);
// TODO: Update current input method name on summary
updateInputMethodSelectorSummary(loadInputMethodSelectorVisibility());
}
new VoiceInputOutputSettings(this).onCreate();
// Get references to dynamically constructed categories.
mHardKeyboardCategory = (PreferenceCategory)findPreference("hard_keyboard");
mKeyboardSettingsCategory = (PreferenceCategory)findPreference(
"keyboard_settings_category");
mGameControllerCategory = (PreferenceCategory)findPreference(
"game_controller_settings_category");
// Filter out irrelevant features if invoked from IME settings button.
mIsOnlyImeSettings = Settings.ACTION_INPUT_METHOD_SETTINGS.equals(
getActivity().getIntent().getAction());
getActivity().getIntent().setAction(null);
if (mIsOnlyImeSettings) {
getPreferenceScreen().removeAll();
getPreferenceScreen().addPreference(mHardKeyboardCategory);
if (SHOW_INPUT_METHOD_SWITCHER_SETTINGS) {
getPreferenceScreen().addPreference(mShowInputMethodSelectorPref);
}
getPreferenceScreen().addPreference(mKeyboardSettingsCategory);
}
// Build IME preference category.
mImm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mImis = mImm.getInputMethodList();
mKeyboardSettingsCategory.removeAll();
if (!mIsOnlyImeSettings) {
final PreferenceScreen currentIme = new PreferenceScreen(getActivity(), null);
currentIme.setKey(KEY_CURRENT_INPUT_METHOD);
currentIme.setTitle(getResources().getString(R.string.current_input_method));
mKeyboardSettingsCategory.addPreference(currentIme);
}
mInputMethodPreferenceList.clear();
final int N = (mImis == null ? 0 : mImis.size());
for (int i = 0; i < N; ++i) {
final InputMethodInfo imi = mImis.get(i);
final InputMethodPreference pref = getInputMethodPreference(imi, N);
mInputMethodPreferenceList.add(pref);
}
if (!mInputMethodPreferenceList.isEmpty()) {
Collections.sort(mInputMethodPreferenceList);
for (int i = 0; i < N; ++i) {
mKeyboardSettingsCategory.addPreference(mInputMethodPreferenceList.get(i));
}
}
// Build hard keyboard and game controller preference categories.
mIm = (InputManager)getActivity().getSystemService(Context.INPUT_SERVICE);
updateInputDevices();
// Spell Checker
final Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setClass(getActivity(), SpellCheckersSettingsActivity.class);
final SpellCheckersPreference scp = ((SpellCheckersPreference)findPreference(
"spellcheckers_settings"));
if (scp != null) {
scp.setFragmentIntent(this, intent);
}
if(mVolumeKeyCursorControl != null) {
mVolumeKeyCursorControl.setOnPreferenceChangeListener(this);
mVolumeKeyCursorControl.setValue(Integer.toString(Settings.System.getInt(getActivity()
.getContentResolver(), Settings.System.VOLUME_KEY_CURSOR_CONTROL, 0)));
mVolumeKeyCursorControl.setSummary(mVolumeKeyCursorControl.getEntry());
}
mHandler = new Handler();
mSettingsObserver = new SettingsObserver(mHandler, getActivity());
}
|
diff --git a/JavaSource/org/unitime/timetable/action/EventDetailAction.java b/JavaSource/org/unitime/timetable/action/EventDetailAction.java
index 70b1af3b..60877bbf 100644
--- a/JavaSource/org/unitime/timetable/action/EventDetailAction.java
+++ b/JavaSource/org/unitime/timetable/action/EventDetailAction.java
@@ -1,551 +1,551 @@
/*
* UniTime 3.1 (University Timetabling Application)
* Copyright (C) 2008, UniTime LLC, and individual contributors
* as indicated by the @authors tag.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package org.unitime.timetable.action;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Locale;
import java.util.Set;
import java.util.TreeSet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.hibernate.Transaction;
import org.unitime.commons.User;
import org.unitime.commons.web.Web;
import org.unitime.commons.web.WebTable;
import org.unitime.timetable.ApplicationProperties;
import org.unitime.timetable.form.EventDetailForm;
import org.unitime.timetable.form.EventDetailForm.MeetingBean;
import org.unitime.timetable.model.ChangeLog;
import org.unitime.timetable.model.ClassEvent;
import org.unitime.timetable.model.Class_;
import org.unitime.timetable.model.CourseEvent;
import org.unitime.timetable.model.CourseOffering;
import org.unitime.timetable.model.Department;
import org.unitime.timetable.model.Event;
import org.unitime.timetable.model.EventContact;
import org.unitime.timetable.model.EventNote;
import org.unitime.timetable.model.ExamEvent;
import org.unitime.timetable.model.ExamOwner;
import org.unitime.timetable.model.InstrOfferingConfig;
import org.unitime.timetable.model.InstructionalOffering;
import org.unitime.timetable.model.Location;
import org.unitime.timetable.model.Meeting;
import org.unitime.timetable.model.RelatedCourseInfo;
import org.unitime.timetable.model.Roles;
import org.unitime.timetable.model.TimetableManager;
import org.unitime.timetable.model.dao.ClassEventDAO;
import org.unitime.timetable.model.dao.CourseEventDAO;
import org.unitime.timetable.model.dao.EventDAO;
import org.unitime.timetable.model.dao.MeetingDAO;
import org.unitime.timetable.webutil.BackTracker;
import org.unitime.timetable.webutil.EventEmail;
import org.unitime.timetable.webutil.Navigation;
/**
* @author Zuzana Mullerova
*/
public class EventDetailAction extends Action {
/**
* Method execute
* @param mapping
* @param form
* @param request
* @param response
* @return ActionForward
*/
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception {
EventDetailForm myForm = (EventDetailForm) form;
HttpSession webSession = request.getSession();
if (!Web.isLoggedIn(webSession)) {
throw new Exception("Access Denied.");
}
ActionMessages errors1 = myForm.validate(mapping, request);
if (!errors1.isEmpty()) {
saveErrors(request, errors1);
} else {
String iOp = myForm.getOp();
User user = Web.getUser(webSession);
Event event = EventDAO.getInstance().get(Long.valueOf(myForm.getId()));
Set<Department> userDepartments = null;
String uname = (event==null || event.getMainContact()==null?user.getName():event.getMainContact().getShortName());
if (user!=null && Roles.EVENT_MGR_ROLE.equals(user.getRole())) {
TimetableManager mgr = TimetableManager.getManager(user);
if (mgr!=null) {
userDepartments = mgr.getDepartments();
uname = mgr.getShortName();
}
} else if (user!=null && user.isAdmin()) {
TimetableManager mgr = TimetableManager.getManager(user);
if (mgr!=null) uname = mgr.getShortName();
}
if (iOp != null) {
if("Edit Event".equals(iOp)) {
response.sendRedirect("eventEdit.do?id="+myForm.getId());
}
//return to event list
if(iOp.equals("Back")) {
if (myForm.getId()!=null)
request.setAttribute("hash", "A"+myForm.getId());
return mapping.findForward("showEventList");
}
if(iOp.equals("Previous")) {
if (myForm.getPreviousId() != null)
response.sendRedirect(response.encodeURL("eventDetail.do?id="+myForm.getPreviousId()));
return null;
}
if(iOp.equals("Next")) {
if (myForm.getPreviousId() != null)
response.sendRedirect(response.encodeURL("eventDetail.do?id="+myForm.getNextId()));
return null;
}
if(iOp.equals("Add Meetings")) {
response.sendRedirect(response.encodeURL("eventAdd.do?op=view&id="+myForm.getId()));
return null;
}
if(iOp.equals("Approve") && myForm.getSelectedMeetings()!=null && myForm.getSelectedMeetings().length>0) {
Long[] selectedMeetings = myForm.getSelectedMeetings();
org.hibernate.Session hibSession = new EventDAO().getSession();
Transaction tx = null;
try {
tx = hibSession.beginTransaction();
ActionMessages errors = new ActionMessages();
HashSet<Meeting> meetings = new HashSet();
for (int i=0; i<selectedMeetings.length; i++) {
Meeting approvedMeeting = MeetingDAO.getInstance().get(selectedMeetings[i]);
if (Roles.EVENT_MGR_ROLE.equals(user.getRole())) {
Location location = approvedMeeting.getLocation();
if (location!=null && (userDepartments==null || location.getControllingDepartment()==null || !userDepartments.contains(location.getControllingDepartment()))) {
errors.add("approve", new ActionMessage("errors.generic", "Insufficient rights to approve "+approvedMeeting.toString()+" (controlling department does not match)."));
continue;
}
}
approvedMeeting.setApprovedDate(new Date());
meetings.add(approvedMeeting);
hibSession.saveOrUpdate(approvedMeeting);
ChangeLog.addChange(
hibSession,
request,
event,
approvedMeeting.toString()+" of "+event.getEventName(),
ChangeLog.Source.EVENT_EDIT,
ChangeLog.Operation.APPROVE,
null,null);
}
if (!meetings.isEmpty()) {
EventNote en = new EventNote();
en.setTimeStamp(new Date());
en.setNoteType(EventNote.sEventNoteTypeApproval);
en.setUser(uname);
en.setMeetingCollection(meetings);
en.setTextNote(myForm.getNewEventNote());
en.setEvent(event);
hibSession.saveOrUpdate(en);
event.getNotes().add(en);
hibSession.saveOrUpdate(event);
new EventEmail(event, EventEmail.sActionApprove, Event.getMultiMeetings(meetings), myForm.getNewEventNote()).send(request);
myForm.setSelectedMeetings(null);
myForm.setNewEventNote(null);
}
tx.commit();
if (!errors.isEmpty())
saveErrors(request, errors);
} catch (Exception e) {
if (tx!=null) tx.rollback();
throw e;
}
}
if (iOp.equals("Reject") && myForm.getSelectedMeetings()!=null && myForm.getSelectedMeetings().length>0) {
Long[] selectedMeetings = myForm.getSelectedMeetings();
org.hibernate.Session hibSession = new EventDAO().getSession();
Transaction tx = null;
boolean eventDeleted = false;
try {
tx = hibSession.beginTransaction();
ActionMessages errors = new ActionMessages();
HashSet<Meeting> meetings = new HashSet();
for (int i=0; i<selectedMeetings.length; i++) {
Meeting rejectedMeeting = MeetingDAO.getInstance().get(selectedMeetings[i]);
if (Roles.EVENT_MGR_ROLE.equals(user.getRole())) {
Location location = rejectedMeeting.getLocation();
if (location!=null && (userDepartments==null || location.getControllingDepartment()==null || !userDepartments.contains(location.getControllingDepartment()))) {
errors.add("approve", new ActionMessage("errors.generic", "Insufficient rights to reject "+rejectedMeeting.toString()+" (controlling department does not match)."));
continue;
}
}
event.getMeetings().remove(rejectedMeeting);
meetings.add(rejectedMeeting);
ChangeLog.addChange(
hibSession,
request,
event,
rejectedMeeting.toString()+" of "+event.getEventName(),
ChangeLog.Source.EVENT_EDIT,
ChangeLog.Operation.REJECT,
null,null);
}
if (!meetings.isEmpty()) {
EventNote en = new EventNote();
en.setTimeStamp(new Date());
en.setNoteType(EventNote.sEventNoteTypeRejection);
en.setUser(uname);
en.setMeetingCollection(meetings);
en.setTextNote(myForm.getNewEventNote());
en.setEvent(event);
hibSession.saveOrUpdate(en);
event.getNotes().add(en);
hibSession.saveOrUpdate(event);
new EventEmail(event, EventEmail.sActionReject, Event.getMultiMeetings(meetings), myForm.getNewEventNote()).send(request);
myForm.setSelectedMeetings(null);
myForm.setNewEventNote(null);
}
if (event.getMeetings().isEmpty()) {
String msg = "All meetings of "+event.getEventName()+" ("+event.getEventTypeLabel()+") have been deleted.";
ChangeLog.addChange(
hibSession,
request,
event,
msg,
ChangeLog.Source.EVENT_EDIT,
ChangeLog.Operation.DELETE,
null,null);
hibSession.delete(event);
eventDeleted = true;
} else {
hibSession.saveOrUpdate(event);
}
tx.commit();
if (!errors.isEmpty())
saveErrors(request, errors);
} catch (Exception e) {
if (tx!=null) tx.rollback();
throw e;
}
if (eventDeleted) return mapping.findForward("showEventList");
}
- if(iOp.equals("Delete")) {
+ if(iOp.equals("Delete") && myForm.getSelectedMeetings()!=null && myForm.getSelectedMeetings().length>0) {
Long[] selectedMeetings = myForm.getSelectedMeetings();
org.hibernate.Session hibSession = new EventDAO().getSession();
Transaction tx = null;
boolean eventDeleted = false;
try {
tx = hibSession.beginTransaction();
HashSet<Meeting> meetings = new HashSet();
for (int i=0; i<selectedMeetings.length; i++) {
Meeting deletedMeeting = MeetingDAO.getInstance().get(selectedMeetings[i]);
meetings.add(deletedMeeting);
event.getMeetings().remove(deletedMeeting);
ChangeLog.addChange(
hibSession,
request,
event,
deletedMeeting.toString()+" of "+event.getEventName(),
ChangeLog.Source.EVENT_EDIT,
ChangeLog.Operation.UPDATE,
null,null);
}
EventNote en = new EventNote();
en.setTimeStamp(new Date());
en.setNoteType(EventNote.sEventNoteTypeDeletion);
en.setUser(uname);
en.setMeetingCollection(meetings);
en.setTextNote(myForm.getNewEventNote());
en.setEvent(event);
hibSession.saveOrUpdate(en);
event.getNotes().add(en);
hibSession.saveOrUpdate(event);
new EventEmail(event, EventEmail.sActionDelete, Event.getMultiMeetings(meetings), myForm.getNewEventNote()).send(request);
if (event.getMeetings().isEmpty()) {
String msg = "All meetings of "+event.getEventName()+" ("+event.getEventTypeLabel()+") have been deleted.";
ChangeLog.addChange(
hibSession,
request,
event,
msg,
ChangeLog.Source.EVENT_EDIT,
ChangeLog.Operation.DELETE,
null,null);
hibSession.delete(event);
eventDeleted = true;
} else {
hibSession.saveOrUpdate(event);
}
tx.commit();
} catch (Exception e) {
if (tx!=null) tx.rollback();
throw e;
}
if (eventDeleted) return mapping.findForward("showEventList");
}
}
if (request.getParameter("id")==null && myForm.getId()==null)
return mapping.findForward("showEventList");
if (request.getParameter("id")!=null) {
String id = request.getParameter("id");
myForm.setEvent(event);
if (event!=null) {
myForm.setEventName(event.getEventName()==null?"":event.getEventName());
myForm.setEventType(event.getEventTypeLabel());
if ("Class Event".equals(myForm.getEventType())){
ClassEvent ce = (ClassEvent) event;
if (ce.getClazz().getEnrollment() != null)
myForm.setEnrollment(ce.getClazz().getEnrollment().toString());
else
myForm.setEnrollment("0");
}
myForm.setMinCapacity(event.getMinCapacity()==null?"":event.getMinCapacity().toString());
myForm.setMaxCapacity(event.getMaxCapacity()==null?"":event.getMaxCapacity().toString());
myForm.setAdditionalEmails(event.getEmail());
if ("Course Related Event".equals(myForm.getEventType())) {
myForm.setAttendanceRequired(((CourseEvent) event).isReqAttendance());
} else
myForm.setSponsoringOrgName(event.getSponsoringOrganization()==null?"":event.getSponsoringOrganization().getName());
myForm.setIsManager(user.isAdmin()||user.hasRole(Roles.EVENT_MGR_ROLE));
for (Iterator i = new TreeSet(event.getNotes()).iterator(); i.hasNext();) {
EventNote en = (EventNote) i.next();
myForm.addNote(en.toHtmlString(myForm.getIsManager()));
}
if (event.getMainContact()!=null)
myForm.setMainContact(event.getMainContact());
for (Iterator i = event.getAdditionalContacts().iterator(); i.hasNext();) {
EventContact ec = (EventContact) i.next();
myForm.addAdditionalContact(
(ec.getFirstName()==null?"":ec.getFirstName()),
(ec.getMiddleName()==null?"":ec.getMiddleName()),
(ec.getLastName()==null?"":ec.getLastName()),
(ec.getEmailAddress()==null?"":ec.getEmailAddress()),
(ec.getPhone()==null?"":ec.getPhone()));
}
SimpleDateFormat iDateFormat = new SimpleDateFormat("EEE MM/dd, yyyy", Locale.US);
if (event.getMainContact()!=null && user.getId().equals(event.getMainContact().getExternalUniqueId())) {
myForm.setCanDelete(true);
myForm.setCanEdit(true);
}
if (user.isAdmin()||user.hasRole(Roles.EVENT_MGR_ROLE)) {
myForm.setCanApprove(true);
myForm.setCanEdit(true);
}
if (event instanceof ClassEvent || event instanceof ExamEvent) {
//myForm.setCanEdit(false);
myForm.setCanApprove(false);
myForm.setCanDelete(false);
}
for (Iterator i=new TreeSet(event.getMeetings()).iterator();i.hasNext();) {
Meeting meeting = (Meeting)i.next();
Location location = meeting.getLocation();
MeetingBean mb = new MeetingBean(meeting);
if (myForm.getCanEdit() && (!mb.getIsPast() || "true".equals(ApplicationProperties.getProperty("tmtbl.event.allowEditPast","false")))) {
if (myForm.getCanDelete()) {
mb.setCanSelect(true);
} else if (user.isAdmin()) {
mb.setCanSelect(myForm.getCanApprove());
} else if (userDepartments!=null && location!=null && location.getControllingDepartment()!=null) {
mb.setCanSelect(myForm.getCanApprove() && userDepartments.contains(location.getControllingDepartment()));
}
}
for (Meeting overlap : meeting.getTimeRoomOverlaps())
mb.getOverlaps().add(new MeetingBean(overlap));
myForm.addMeeting(mb);
}
if (myForm.getCanApprove() && !myForm.getCanSelectAll())
myForm.setCanApprove(false);
Long nextId = Navigation.getNext(request.getSession(), Navigation.sInstructionalOfferingLevel, event.getUniqueId());
Long prevId = Navigation.getPrevious(request.getSession(), Navigation.sInstructionalOfferingLevel, event.getUniqueId());
myForm.setPreviousId(prevId==null?null:prevId.toString());
myForm.setNextId(nextId==null?null:nextId.toString());
if (Event.sEventTypes[Event.sEventTypeCourse].equals(myForm.getEventType())) {
CourseEvent courseEvent = new CourseEventDAO().get(Long.valueOf(id));
if (!courseEvent.getRelatedCourses().isEmpty()) {
WebTable table = new WebTable(5, null, new String[] {"Object", "Type", "Title","Limit","Assignment"}, new String[] {"left", "left", "left","right","left"}, new boolean[] {true, true, true, true,true});
for (Iterator i=new TreeSet(courseEvent.getRelatedCourses()).iterator();i.hasNext();) {
RelatedCourseInfo rci = (RelatedCourseInfo)i.next();
String onclick = null, name = null, type = null, title = null, assignment = null;
String students = String.valueOf(rci.countStudents());
switch (rci.getOwnerType()) {
case ExamOwner.sOwnerTypeClass :
Class_ clazz = (Class_)rci.getOwnerObject();
if (user.getRole()!=null && clazz.isViewableBy(user))
onclick = "onClick=\"document.location='classDetail.do?cid="+clazz.getUniqueId()+"';\"";
name = rci.getLabel();//clazz.getClassLabel();
type = "Class";
title = clazz.getSchedulePrintNote();
if (title==null || title.length()==0) title=clazz.getSchedulingSubpart().getControllingCourseOffering().getTitle();
if (clazz.getCommittedAssignment()!=null)
assignment = clazz.getCommittedAssignment().getPlacement().getLongName();
break;
case ExamOwner.sOwnerTypeConfig :
InstrOfferingConfig config = (InstrOfferingConfig)rci.getOwnerObject();
if (user.getRole()!=null && config.isViewableBy(user))
onclick = "onClick=\"document.location='instructionalOfferingDetail.do?io="+config.getInstructionalOffering().getUniqueId()+"';\"";
name = rci.getLabel();//config.getCourseName()+" ["+config.getName()+"]";
type = "Configuration";
title = config.getControllingCourseOffering().getTitle();
break;
case ExamOwner.sOwnerTypeOffering :
InstructionalOffering offering = (InstructionalOffering)rci.getOwnerObject();
if (user.getRole()!=null && offering.isViewableBy(user))
onclick = "onClick=\"document.location='instructionalOfferingDetail.do?io="+offering.getUniqueId()+"';\"";
name = rci.getLabel();//offering.getCourseName();
type = "Offering";
title = offering.getControllingCourseOffering().getTitle();
break;
case ExamOwner.sOwnerTypeCourse :
CourseOffering course = (CourseOffering)rci.getOwnerObject();
if (user.getRole()!=null && course.isViewableBy(user))
onclick = "onClick=\"document.location='instructionalOfferingDetail.do?io="+course.getInstructionalOffering().getUniqueId()+"';\"";
name = rci.getLabel();//course.getCourseName();
type = "Course";
title = course.getTitle();
break;
}
table.addLine(onclick, new String[] { name, type, title, students, assignment}, null);
}
request.setAttribute("EventDetail.table",table.printTable());
}
}
/*
if (Event.sEventTypes[Event.sEventTypeFinalExam].equals(myForm.getEventType()) || Event.sEventTypes[Event.sEventTypeMidtermExam].equals(myForm.getEventType())) {
ExamEvent examEvent = new ExamEventDAO().get(Long.valueOf(id));
if (examEvent.getExam()!=null && !examEvent.getExam().getOwners().isEmpty()) {
WebTable table = new WebTable(5, null, new String[] {"Object", "Type", "Title","Limit","Assignment"}, new String[] {"left", "left", "left","right","left"}, new boolean[] {true, true, true, true,true});
for (Iterator i=new TreeSet(examEvent.getExam().getOwners()).iterator();i.hasNext();) {
ExamOwner owner = (ExamOwner)i.next();
String onclick = null, name = null, type = null, title = null, assignment = null;
String students = String.valueOf(owner.countStudents());
switch (owner.getOwnerType()) {
case ExamOwner.sOwnerTypeClass :
Class_ clazz = (Class_)owner.getOwnerObject();
if (user.getRole()!=null && clazz.isViewableBy(user))
onclick = "onClick=\"document.location='classDetail.do?cid="+clazz.getUniqueId()+"';\"";
name = owner.getLabel();//clazz.getClassLabel();
type = "Class";
title = clazz.getSchedulePrintNote();
if (title==null || title.length()==0) title=clazz.getSchedulingSubpart().getControllingCourseOffering().getTitle();
if (clazz.getCommittedAssignment()!=null)
assignment = clazz.getCommittedAssignment().getPlacement().getLongName();
break;
case ExamOwner.sOwnerTypeConfig :
InstrOfferingConfig config = (InstrOfferingConfig)owner.getOwnerObject();
if (user.getRole()!=null && config.isViewableBy(user))
onclick = "onClick=\"document.location='instructionalOfferingDetail.do?io="+config.getInstructionalOffering().getUniqueId()+"';\"";
name = owner.getLabel();//config.getCourseName()+" ["+config.getName()+"]";
type = "Configuration";
title = config.getControllingCourseOffering().getTitle();
break;
case ExamOwner.sOwnerTypeOffering :
InstructionalOffering offering = (InstructionalOffering)owner.getOwnerObject();
if (user.getRole()!=null && offering.isViewableBy(user))
onclick = "onClick=\"document.location='instructionalOfferingDetail.do?io="+offering.getUniqueId()+"';\"";
name = owner.getLabel();//offering.getCourseName();
type = "Offering";
title = offering.getControllingCourseOffering().getTitle();
break;
case ExamOwner.sOwnerTypeCourse :
CourseOffering course = (CourseOffering)owner.getOwnerObject();
if (user.getRole()!=null && course.isViewableBy(user))
onclick = "onClick=\"document.location='instructionalOfferingDetail.do?io="+course.getInstructionalOffering().getUniqueId()+"';\"";
name = owner.getLabel();//course.getCourseName();
type = "Course";
title = course.getTitle();
break;
}
table.addLine(onclick, new String[] { name, type, title, students, assignment}, null);
}
request.setAttribute("EventDetail.table",table.printTable());
}
}
*/
if (Event.sEventTypes[Event.sEventTypeClass].equals(myForm.getEventType())) {
ClassEvent classEvent = new ClassEventDAO().get(Long.valueOf(id));
if (classEvent.getClazz()!=null) {
WebTable table = new WebTable(4, null, new String[] {"Name","Title","Limit","Assignment"}, new String[] {"left","left","right","left"}, new boolean[] {true, true, true, true});
Class_ clazz = (Class_)classEvent.getClazz();
String onclick = null, assignment = null;
if (user.getRole()!=null && clazz.isViewableBy(user))
onclick = "onClick=\"document.location='classDetail.do?cid="+clazz.getUniqueId()+"';\"";
String name = clazz.getClassLabel();
String title = clazz.getSchedulePrintNote();
String students = String.valueOf(clazz.getStudentEnrollments().size());
if (title==null || title.length()==0) title=clazz.getSchedulingSubpart().getControllingCourseOffering().getTitle();
if (clazz.getCommittedAssignment()!=null)
assignment = clazz.getCommittedAssignment().getPlacement().getLongName();
table.addLine(onclick, new String[] { name, title, students, assignment}, null);
request.setAttribute("EventDetail.table",table.printTable());
}
}
} else {
throw new Exception("There is no event with this ID");
}
}
BackTracker.markForBack(
request,
"eventDetail.do?op=view&id=" + myForm.getId(),
myForm.getEventName(),
true, false);
}
return mapping.findForward("show");
}
}
| true | true | public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception {
EventDetailForm myForm = (EventDetailForm) form;
HttpSession webSession = request.getSession();
if (!Web.isLoggedIn(webSession)) {
throw new Exception("Access Denied.");
}
ActionMessages errors1 = myForm.validate(mapping, request);
if (!errors1.isEmpty()) {
saveErrors(request, errors1);
} else {
String iOp = myForm.getOp();
User user = Web.getUser(webSession);
Event event = EventDAO.getInstance().get(Long.valueOf(myForm.getId()));
Set<Department> userDepartments = null;
String uname = (event==null || event.getMainContact()==null?user.getName():event.getMainContact().getShortName());
if (user!=null && Roles.EVENT_MGR_ROLE.equals(user.getRole())) {
TimetableManager mgr = TimetableManager.getManager(user);
if (mgr!=null) {
userDepartments = mgr.getDepartments();
uname = mgr.getShortName();
}
} else if (user!=null && user.isAdmin()) {
TimetableManager mgr = TimetableManager.getManager(user);
if (mgr!=null) uname = mgr.getShortName();
}
if (iOp != null) {
if("Edit Event".equals(iOp)) {
response.sendRedirect("eventEdit.do?id="+myForm.getId());
}
//return to event list
if(iOp.equals("Back")) {
if (myForm.getId()!=null)
request.setAttribute("hash", "A"+myForm.getId());
return mapping.findForward("showEventList");
}
if(iOp.equals("Previous")) {
if (myForm.getPreviousId() != null)
response.sendRedirect(response.encodeURL("eventDetail.do?id="+myForm.getPreviousId()));
return null;
}
if(iOp.equals("Next")) {
if (myForm.getPreviousId() != null)
response.sendRedirect(response.encodeURL("eventDetail.do?id="+myForm.getNextId()));
return null;
}
if(iOp.equals("Add Meetings")) {
response.sendRedirect(response.encodeURL("eventAdd.do?op=view&id="+myForm.getId()));
return null;
}
if(iOp.equals("Approve") && myForm.getSelectedMeetings()!=null && myForm.getSelectedMeetings().length>0) {
Long[] selectedMeetings = myForm.getSelectedMeetings();
org.hibernate.Session hibSession = new EventDAO().getSession();
Transaction tx = null;
try {
tx = hibSession.beginTransaction();
ActionMessages errors = new ActionMessages();
HashSet<Meeting> meetings = new HashSet();
for (int i=0; i<selectedMeetings.length; i++) {
Meeting approvedMeeting = MeetingDAO.getInstance().get(selectedMeetings[i]);
if (Roles.EVENT_MGR_ROLE.equals(user.getRole())) {
Location location = approvedMeeting.getLocation();
if (location!=null && (userDepartments==null || location.getControllingDepartment()==null || !userDepartments.contains(location.getControllingDepartment()))) {
errors.add("approve", new ActionMessage("errors.generic", "Insufficient rights to approve "+approvedMeeting.toString()+" (controlling department does not match)."));
continue;
}
}
approvedMeeting.setApprovedDate(new Date());
meetings.add(approvedMeeting);
hibSession.saveOrUpdate(approvedMeeting);
ChangeLog.addChange(
hibSession,
request,
event,
approvedMeeting.toString()+" of "+event.getEventName(),
ChangeLog.Source.EVENT_EDIT,
ChangeLog.Operation.APPROVE,
null,null);
}
if (!meetings.isEmpty()) {
EventNote en = new EventNote();
en.setTimeStamp(new Date());
en.setNoteType(EventNote.sEventNoteTypeApproval);
en.setUser(uname);
en.setMeetingCollection(meetings);
en.setTextNote(myForm.getNewEventNote());
en.setEvent(event);
hibSession.saveOrUpdate(en);
event.getNotes().add(en);
hibSession.saveOrUpdate(event);
new EventEmail(event, EventEmail.sActionApprove, Event.getMultiMeetings(meetings), myForm.getNewEventNote()).send(request);
myForm.setSelectedMeetings(null);
myForm.setNewEventNote(null);
}
tx.commit();
if (!errors.isEmpty())
saveErrors(request, errors);
} catch (Exception e) {
if (tx!=null) tx.rollback();
throw e;
}
}
if (iOp.equals("Reject") && myForm.getSelectedMeetings()!=null && myForm.getSelectedMeetings().length>0) {
Long[] selectedMeetings = myForm.getSelectedMeetings();
org.hibernate.Session hibSession = new EventDAO().getSession();
Transaction tx = null;
boolean eventDeleted = false;
try {
tx = hibSession.beginTransaction();
ActionMessages errors = new ActionMessages();
HashSet<Meeting> meetings = new HashSet();
for (int i=0; i<selectedMeetings.length; i++) {
Meeting rejectedMeeting = MeetingDAO.getInstance().get(selectedMeetings[i]);
if (Roles.EVENT_MGR_ROLE.equals(user.getRole())) {
Location location = rejectedMeeting.getLocation();
if (location!=null && (userDepartments==null || location.getControllingDepartment()==null || !userDepartments.contains(location.getControllingDepartment()))) {
errors.add("approve", new ActionMessage("errors.generic", "Insufficient rights to reject "+rejectedMeeting.toString()+" (controlling department does not match)."));
continue;
}
}
event.getMeetings().remove(rejectedMeeting);
meetings.add(rejectedMeeting);
ChangeLog.addChange(
hibSession,
request,
event,
rejectedMeeting.toString()+" of "+event.getEventName(),
ChangeLog.Source.EVENT_EDIT,
ChangeLog.Operation.REJECT,
null,null);
}
if (!meetings.isEmpty()) {
EventNote en = new EventNote();
en.setTimeStamp(new Date());
en.setNoteType(EventNote.sEventNoteTypeRejection);
en.setUser(uname);
en.setMeetingCollection(meetings);
en.setTextNote(myForm.getNewEventNote());
en.setEvent(event);
hibSession.saveOrUpdate(en);
event.getNotes().add(en);
hibSession.saveOrUpdate(event);
new EventEmail(event, EventEmail.sActionReject, Event.getMultiMeetings(meetings), myForm.getNewEventNote()).send(request);
myForm.setSelectedMeetings(null);
myForm.setNewEventNote(null);
}
if (event.getMeetings().isEmpty()) {
String msg = "All meetings of "+event.getEventName()+" ("+event.getEventTypeLabel()+") have been deleted.";
ChangeLog.addChange(
hibSession,
request,
event,
msg,
ChangeLog.Source.EVENT_EDIT,
ChangeLog.Operation.DELETE,
null,null);
hibSession.delete(event);
eventDeleted = true;
} else {
hibSession.saveOrUpdate(event);
}
tx.commit();
if (!errors.isEmpty())
saveErrors(request, errors);
} catch (Exception e) {
if (tx!=null) tx.rollback();
throw e;
}
if (eventDeleted) return mapping.findForward("showEventList");
}
if(iOp.equals("Delete")) {
Long[] selectedMeetings = myForm.getSelectedMeetings();
org.hibernate.Session hibSession = new EventDAO().getSession();
Transaction tx = null;
boolean eventDeleted = false;
try {
tx = hibSession.beginTransaction();
HashSet<Meeting> meetings = new HashSet();
for (int i=0; i<selectedMeetings.length; i++) {
Meeting deletedMeeting = MeetingDAO.getInstance().get(selectedMeetings[i]);
meetings.add(deletedMeeting);
event.getMeetings().remove(deletedMeeting);
ChangeLog.addChange(
hibSession,
request,
event,
deletedMeeting.toString()+" of "+event.getEventName(),
ChangeLog.Source.EVENT_EDIT,
ChangeLog.Operation.UPDATE,
null,null);
}
EventNote en = new EventNote();
en.setTimeStamp(new Date());
en.setNoteType(EventNote.sEventNoteTypeDeletion);
en.setUser(uname);
en.setMeetingCollection(meetings);
en.setTextNote(myForm.getNewEventNote());
en.setEvent(event);
hibSession.saveOrUpdate(en);
event.getNotes().add(en);
hibSession.saveOrUpdate(event);
new EventEmail(event, EventEmail.sActionDelete, Event.getMultiMeetings(meetings), myForm.getNewEventNote()).send(request);
if (event.getMeetings().isEmpty()) {
String msg = "All meetings of "+event.getEventName()+" ("+event.getEventTypeLabel()+") have been deleted.";
ChangeLog.addChange(
hibSession,
request,
event,
msg,
ChangeLog.Source.EVENT_EDIT,
ChangeLog.Operation.DELETE,
null,null);
hibSession.delete(event);
eventDeleted = true;
} else {
hibSession.saveOrUpdate(event);
}
tx.commit();
} catch (Exception e) {
if (tx!=null) tx.rollback();
throw e;
}
if (eventDeleted) return mapping.findForward("showEventList");
}
}
if (request.getParameter("id")==null && myForm.getId()==null)
return mapping.findForward("showEventList");
if (request.getParameter("id")!=null) {
String id = request.getParameter("id");
myForm.setEvent(event);
if (event!=null) {
myForm.setEventName(event.getEventName()==null?"":event.getEventName());
myForm.setEventType(event.getEventTypeLabel());
if ("Class Event".equals(myForm.getEventType())){
ClassEvent ce = (ClassEvent) event;
if (ce.getClazz().getEnrollment() != null)
myForm.setEnrollment(ce.getClazz().getEnrollment().toString());
else
myForm.setEnrollment("0");
}
myForm.setMinCapacity(event.getMinCapacity()==null?"":event.getMinCapacity().toString());
myForm.setMaxCapacity(event.getMaxCapacity()==null?"":event.getMaxCapacity().toString());
myForm.setAdditionalEmails(event.getEmail());
if ("Course Related Event".equals(myForm.getEventType())) {
myForm.setAttendanceRequired(((CourseEvent) event).isReqAttendance());
} else
myForm.setSponsoringOrgName(event.getSponsoringOrganization()==null?"":event.getSponsoringOrganization().getName());
myForm.setIsManager(user.isAdmin()||user.hasRole(Roles.EVENT_MGR_ROLE));
for (Iterator i = new TreeSet(event.getNotes()).iterator(); i.hasNext();) {
EventNote en = (EventNote) i.next();
myForm.addNote(en.toHtmlString(myForm.getIsManager()));
}
if (event.getMainContact()!=null)
myForm.setMainContact(event.getMainContact());
for (Iterator i = event.getAdditionalContacts().iterator(); i.hasNext();) {
EventContact ec = (EventContact) i.next();
myForm.addAdditionalContact(
(ec.getFirstName()==null?"":ec.getFirstName()),
(ec.getMiddleName()==null?"":ec.getMiddleName()),
(ec.getLastName()==null?"":ec.getLastName()),
(ec.getEmailAddress()==null?"":ec.getEmailAddress()),
(ec.getPhone()==null?"":ec.getPhone()));
}
SimpleDateFormat iDateFormat = new SimpleDateFormat("EEE MM/dd, yyyy", Locale.US);
if (event.getMainContact()!=null && user.getId().equals(event.getMainContact().getExternalUniqueId())) {
myForm.setCanDelete(true);
myForm.setCanEdit(true);
}
if (user.isAdmin()||user.hasRole(Roles.EVENT_MGR_ROLE)) {
myForm.setCanApprove(true);
myForm.setCanEdit(true);
}
if (event instanceof ClassEvent || event instanceof ExamEvent) {
//myForm.setCanEdit(false);
myForm.setCanApprove(false);
myForm.setCanDelete(false);
}
for (Iterator i=new TreeSet(event.getMeetings()).iterator();i.hasNext();) {
Meeting meeting = (Meeting)i.next();
Location location = meeting.getLocation();
MeetingBean mb = new MeetingBean(meeting);
if (myForm.getCanEdit() && (!mb.getIsPast() || "true".equals(ApplicationProperties.getProperty("tmtbl.event.allowEditPast","false")))) {
if (myForm.getCanDelete()) {
mb.setCanSelect(true);
} else if (user.isAdmin()) {
mb.setCanSelect(myForm.getCanApprove());
} else if (userDepartments!=null && location!=null && location.getControllingDepartment()!=null) {
mb.setCanSelect(myForm.getCanApprove() && userDepartments.contains(location.getControllingDepartment()));
}
}
for (Meeting overlap : meeting.getTimeRoomOverlaps())
mb.getOverlaps().add(new MeetingBean(overlap));
myForm.addMeeting(mb);
}
if (myForm.getCanApprove() && !myForm.getCanSelectAll())
myForm.setCanApprove(false);
Long nextId = Navigation.getNext(request.getSession(), Navigation.sInstructionalOfferingLevel, event.getUniqueId());
Long prevId = Navigation.getPrevious(request.getSession(), Navigation.sInstructionalOfferingLevel, event.getUniqueId());
myForm.setPreviousId(prevId==null?null:prevId.toString());
myForm.setNextId(nextId==null?null:nextId.toString());
if (Event.sEventTypes[Event.sEventTypeCourse].equals(myForm.getEventType())) {
CourseEvent courseEvent = new CourseEventDAO().get(Long.valueOf(id));
if (!courseEvent.getRelatedCourses().isEmpty()) {
WebTable table = new WebTable(5, null, new String[] {"Object", "Type", "Title","Limit","Assignment"}, new String[] {"left", "left", "left","right","left"}, new boolean[] {true, true, true, true,true});
for (Iterator i=new TreeSet(courseEvent.getRelatedCourses()).iterator();i.hasNext();) {
RelatedCourseInfo rci = (RelatedCourseInfo)i.next();
String onclick = null, name = null, type = null, title = null, assignment = null;
String students = String.valueOf(rci.countStudents());
switch (rci.getOwnerType()) {
case ExamOwner.sOwnerTypeClass :
Class_ clazz = (Class_)rci.getOwnerObject();
if (user.getRole()!=null && clazz.isViewableBy(user))
onclick = "onClick=\"document.location='classDetail.do?cid="+clazz.getUniqueId()+"';\"";
name = rci.getLabel();//clazz.getClassLabel();
type = "Class";
title = clazz.getSchedulePrintNote();
if (title==null || title.length()==0) title=clazz.getSchedulingSubpart().getControllingCourseOffering().getTitle();
if (clazz.getCommittedAssignment()!=null)
assignment = clazz.getCommittedAssignment().getPlacement().getLongName();
break;
case ExamOwner.sOwnerTypeConfig :
InstrOfferingConfig config = (InstrOfferingConfig)rci.getOwnerObject();
if (user.getRole()!=null && config.isViewableBy(user))
onclick = "onClick=\"document.location='instructionalOfferingDetail.do?io="+config.getInstructionalOffering().getUniqueId()+"';\"";
name = rci.getLabel();//config.getCourseName()+" ["+config.getName()+"]";
type = "Configuration";
title = config.getControllingCourseOffering().getTitle();
break;
case ExamOwner.sOwnerTypeOffering :
InstructionalOffering offering = (InstructionalOffering)rci.getOwnerObject();
if (user.getRole()!=null && offering.isViewableBy(user))
onclick = "onClick=\"document.location='instructionalOfferingDetail.do?io="+offering.getUniqueId()+"';\"";
name = rci.getLabel();//offering.getCourseName();
type = "Offering";
title = offering.getControllingCourseOffering().getTitle();
break;
case ExamOwner.sOwnerTypeCourse :
CourseOffering course = (CourseOffering)rci.getOwnerObject();
if (user.getRole()!=null && course.isViewableBy(user))
onclick = "onClick=\"document.location='instructionalOfferingDetail.do?io="+course.getInstructionalOffering().getUniqueId()+"';\"";
name = rci.getLabel();//course.getCourseName();
type = "Course";
title = course.getTitle();
break;
}
table.addLine(onclick, new String[] { name, type, title, students, assignment}, null);
}
request.setAttribute("EventDetail.table",table.printTable());
}
}
/*
if (Event.sEventTypes[Event.sEventTypeFinalExam].equals(myForm.getEventType()) || Event.sEventTypes[Event.sEventTypeMidtermExam].equals(myForm.getEventType())) {
ExamEvent examEvent = new ExamEventDAO().get(Long.valueOf(id));
if (examEvent.getExam()!=null && !examEvent.getExam().getOwners().isEmpty()) {
WebTable table = new WebTable(5, null, new String[] {"Object", "Type", "Title","Limit","Assignment"}, new String[] {"left", "left", "left","right","left"}, new boolean[] {true, true, true, true,true});
for (Iterator i=new TreeSet(examEvent.getExam().getOwners()).iterator();i.hasNext();) {
ExamOwner owner = (ExamOwner)i.next();
String onclick = null, name = null, type = null, title = null, assignment = null;
String students = String.valueOf(owner.countStudents());
switch (owner.getOwnerType()) {
case ExamOwner.sOwnerTypeClass :
Class_ clazz = (Class_)owner.getOwnerObject();
if (user.getRole()!=null && clazz.isViewableBy(user))
onclick = "onClick=\"document.location='classDetail.do?cid="+clazz.getUniqueId()+"';\"";
name = owner.getLabel();//clazz.getClassLabel();
type = "Class";
title = clazz.getSchedulePrintNote();
if (title==null || title.length()==0) title=clazz.getSchedulingSubpart().getControllingCourseOffering().getTitle();
if (clazz.getCommittedAssignment()!=null)
assignment = clazz.getCommittedAssignment().getPlacement().getLongName();
break;
case ExamOwner.sOwnerTypeConfig :
InstrOfferingConfig config = (InstrOfferingConfig)owner.getOwnerObject();
if (user.getRole()!=null && config.isViewableBy(user))
onclick = "onClick=\"document.location='instructionalOfferingDetail.do?io="+config.getInstructionalOffering().getUniqueId()+"';\"";
name = owner.getLabel();//config.getCourseName()+" ["+config.getName()+"]";
type = "Configuration";
title = config.getControllingCourseOffering().getTitle();
break;
case ExamOwner.sOwnerTypeOffering :
InstructionalOffering offering = (InstructionalOffering)owner.getOwnerObject();
if (user.getRole()!=null && offering.isViewableBy(user))
onclick = "onClick=\"document.location='instructionalOfferingDetail.do?io="+offering.getUniqueId()+"';\"";
name = owner.getLabel();//offering.getCourseName();
type = "Offering";
title = offering.getControllingCourseOffering().getTitle();
break;
case ExamOwner.sOwnerTypeCourse :
CourseOffering course = (CourseOffering)owner.getOwnerObject();
if (user.getRole()!=null && course.isViewableBy(user))
onclick = "onClick=\"document.location='instructionalOfferingDetail.do?io="+course.getInstructionalOffering().getUniqueId()+"';\"";
name = owner.getLabel();//course.getCourseName();
type = "Course";
title = course.getTitle();
break;
}
table.addLine(onclick, new String[] { name, type, title, students, assignment}, null);
}
request.setAttribute("EventDetail.table",table.printTable());
}
}
*/
if (Event.sEventTypes[Event.sEventTypeClass].equals(myForm.getEventType())) {
ClassEvent classEvent = new ClassEventDAO().get(Long.valueOf(id));
if (classEvent.getClazz()!=null) {
WebTable table = new WebTable(4, null, new String[] {"Name","Title","Limit","Assignment"}, new String[] {"left","left","right","left"}, new boolean[] {true, true, true, true});
Class_ clazz = (Class_)classEvent.getClazz();
String onclick = null, assignment = null;
if (user.getRole()!=null && clazz.isViewableBy(user))
onclick = "onClick=\"document.location='classDetail.do?cid="+clazz.getUniqueId()+"';\"";
String name = clazz.getClassLabel();
String title = clazz.getSchedulePrintNote();
String students = String.valueOf(clazz.getStudentEnrollments().size());
if (title==null || title.length()==0) title=clazz.getSchedulingSubpart().getControllingCourseOffering().getTitle();
if (clazz.getCommittedAssignment()!=null)
assignment = clazz.getCommittedAssignment().getPlacement().getLongName();
table.addLine(onclick, new String[] { name, title, students, assignment}, null);
request.setAttribute("EventDetail.table",table.printTable());
}
}
} else {
throw new Exception("There is no event with this ID");
}
}
BackTracker.markForBack(
request,
"eventDetail.do?op=view&id=" + myForm.getId(),
myForm.getEventName(),
true, false);
}
return mapping.findForward("show");
}
| public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception {
EventDetailForm myForm = (EventDetailForm) form;
HttpSession webSession = request.getSession();
if (!Web.isLoggedIn(webSession)) {
throw new Exception("Access Denied.");
}
ActionMessages errors1 = myForm.validate(mapping, request);
if (!errors1.isEmpty()) {
saveErrors(request, errors1);
} else {
String iOp = myForm.getOp();
User user = Web.getUser(webSession);
Event event = EventDAO.getInstance().get(Long.valueOf(myForm.getId()));
Set<Department> userDepartments = null;
String uname = (event==null || event.getMainContact()==null?user.getName():event.getMainContact().getShortName());
if (user!=null && Roles.EVENT_MGR_ROLE.equals(user.getRole())) {
TimetableManager mgr = TimetableManager.getManager(user);
if (mgr!=null) {
userDepartments = mgr.getDepartments();
uname = mgr.getShortName();
}
} else if (user!=null && user.isAdmin()) {
TimetableManager mgr = TimetableManager.getManager(user);
if (mgr!=null) uname = mgr.getShortName();
}
if (iOp != null) {
if("Edit Event".equals(iOp)) {
response.sendRedirect("eventEdit.do?id="+myForm.getId());
}
//return to event list
if(iOp.equals("Back")) {
if (myForm.getId()!=null)
request.setAttribute("hash", "A"+myForm.getId());
return mapping.findForward("showEventList");
}
if(iOp.equals("Previous")) {
if (myForm.getPreviousId() != null)
response.sendRedirect(response.encodeURL("eventDetail.do?id="+myForm.getPreviousId()));
return null;
}
if(iOp.equals("Next")) {
if (myForm.getPreviousId() != null)
response.sendRedirect(response.encodeURL("eventDetail.do?id="+myForm.getNextId()));
return null;
}
if(iOp.equals("Add Meetings")) {
response.sendRedirect(response.encodeURL("eventAdd.do?op=view&id="+myForm.getId()));
return null;
}
if(iOp.equals("Approve") && myForm.getSelectedMeetings()!=null && myForm.getSelectedMeetings().length>0) {
Long[] selectedMeetings = myForm.getSelectedMeetings();
org.hibernate.Session hibSession = new EventDAO().getSession();
Transaction tx = null;
try {
tx = hibSession.beginTransaction();
ActionMessages errors = new ActionMessages();
HashSet<Meeting> meetings = new HashSet();
for (int i=0; i<selectedMeetings.length; i++) {
Meeting approvedMeeting = MeetingDAO.getInstance().get(selectedMeetings[i]);
if (Roles.EVENT_MGR_ROLE.equals(user.getRole())) {
Location location = approvedMeeting.getLocation();
if (location!=null && (userDepartments==null || location.getControllingDepartment()==null || !userDepartments.contains(location.getControllingDepartment()))) {
errors.add("approve", new ActionMessage("errors.generic", "Insufficient rights to approve "+approvedMeeting.toString()+" (controlling department does not match)."));
continue;
}
}
approvedMeeting.setApprovedDate(new Date());
meetings.add(approvedMeeting);
hibSession.saveOrUpdate(approvedMeeting);
ChangeLog.addChange(
hibSession,
request,
event,
approvedMeeting.toString()+" of "+event.getEventName(),
ChangeLog.Source.EVENT_EDIT,
ChangeLog.Operation.APPROVE,
null,null);
}
if (!meetings.isEmpty()) {
EventNote en = new EventNote();
en.setTimeStamp(new Date());
en.setNoteType(EventNote.sEventNoteTypeApproval);
en.setUser(uname);
en.setMeetingCollection(meetings);
en.setTextNote(myForm.getNewEventNote());
en.setEvent(event);
hibSession.saveOrUpdate(en);
event.getNotes().add(en);
hibSession.saveOrUpdate(event);
new EventEmail(event, EventEmail.sActionApprove, Event.getMultiMeetings(meetings), myForm.getNewEventNote()).send(request);
myForm.setSelectedMeetings(null);
myForm.setNewEventNote(null);
}
tx.commit();
if (!errors.isEmpty())
saveErrors(request, errors);
} catch (Exception e) {
if (tx!=null) tx.rollback();
throw e;
}
}
if (iOp.equals("Reject") && myForm.getSelectedMeetings()!=null && myForm.getSelectedMeetings().length>0) {
Long[] selectedMeetings = myForm.getSelectedMeetings();
org.hibernate.Session hibSession = new EventDAO().getSession();
Transaction tx = null;
boolean eventDeleted = false;
try {
tx = hibSession.beginTransaction();
ActionMessages errors = new ActionMessages();
HashSet<Meeting> meetings = new HashSet();
for (int i=0; i<selectedMeetings.length; i++) {
Meeting rejectedMeeting = MeetingDAO.getInstance().get(selectedMeetings[i]);
if (Roles.EVENT_MGR_ROLE.equals(user.getRole())) {
Location location = rejectedMeeting.getLocation();
if (location!=null && (userDepartments==null || location.getControllingDepartment()==null || !userDepartments.contains(location.getControllingDepartment()))) {
errors.add("approve", new ActionMessage("errors.generic", "Insufficient rights to reject "+rejectedMeeting.toString()+" (controlling department does not match)."));
continue;
}
}
event.getMeetings().remove(rejectedMeeting);
meetings.add(rejectedMeeting);
ChangeLog.addChange(
hibSession,
request,
event,
rejectedMeeting.toString()+" of "+event.getEventName(),
ChangeLog.Source.EVENT_EDIT,
ChangeLog.Operation.REJECT,
null,null);
}
if (!meetings.isEmpty()) {
EventNote en = new EventNote();
en.setTimeStamp(new Date());
en.setNoteType(EventNote.sEventNoteTypeRejection);
en.setUser(uname);
en.setMeetingCollection(meetings);
en.setTextNote(myForm.getNewEventNote());
en.setEvent(event);
hibSession.saveOrUpdate(en);
event.getNotes().add(en);
hibSession.saveOrUpdate(event);
new EventEmail(event, EventEmail.sActionReject, Event.getMultiMeetings(meetings), myForm.getNewEventNote()).send(request);
myForm.setSelectedMeetings(null);
myForm.setNewEventNote(null);
}
if (event.getMeetings().isEmpty()) {
String msg = "All meetings of "+event.getEventName()+" ("+event.getEventTypeLabel()+") have been deleted.";
ChangeLog.addChange(
hibSession,
request,
event,
msg,
ChangeLog.Source.EVENT_EDIT,
ChangeLog.Operation.DELETE,
null,null);
hibSession.delete(event);
eventDeleted = true;
} else {
hibSession.saveOrUpdate(event);
}
tx.commit();
if (!errors.isEmpty())
saveErrors(request, errors);
} catch (Exception e) {
if (tx!=null) tx.rollback();
throw e;
}
if (eventDeleted) return mapping.findForward("showEventList");
}
if(iOp.equals("Delete") && myForm.getSelectedMeetings()!=null && myForm.getSelectedMeetings().length>0) {
Long[] selectedMeetings = myForm.getSelectedMeetings();
org.hibernate.Session hibSession = new EventDAO().getSession();
Transaction tx = null;
boolean eventDeleted = false;
try {
tx = hibSession.beginTransaction();
HashSet<Meeting> meetings = new HashSet();
for (int i=0; i<selectedMeetings.length; i++) {
Meeting deletedMeeting = MeetingDAO.getInstance().get(selectedMeetings[i]);
meetings.add(deletedMeeting);
event.getMeetings().remove(deletedMeeting);
ChangeLog.addChange(
hibSession,
request,
event,
deletedMeeting.toString()+" of "+event.getEventName(),
ChangeLog.Source.EVENT_EDIT,
ChangeLog.Operation.UPDATE,
null,null);
}
EventNote en = new EventNote();
en.setTimeStamp(new Date());
en.setNoteType(EventNote.sEventNoteTypeDeletion);
en.setUser(uname);
en.setMeetingCollection(meetings);
en.setTextNote(myForm.getNewEventNote());
en.setEvent(event);
hibSession.saveOrUpdate(en);
event.getNotes().add(en);
hibSession.saveOrUpdate(event);
new EventEmail(event, EventEmail.sActionDelete, Event.getMultiMeetings(meetings), myForm.getNewEventNote()).send(request);
if (event.getMeetings().isEmpty()) {
String msg = "All meetings of "+event.getEventName()+" ("+event.getEventTypeLabel()+") have been deleted.";
ChangeLog.addChange(
hibSession,
request,
event,
msg,
ChangeLog.Source.EVENT_EDIT,
ChangeLog.Operation.DELETE,
null,null);
hibSession.delete(event);
eventDeleted = true;
} else {
hibSession.saveOrUpdate(event);
}
tx.commit();
} catch (Exception e) {
if (tx!=null) tx.rollback();
throw e;
}
if (eventDeleted) return mapping.findForward("showEventList");
}
}
if (request.getParameter("id")==null && myForm.getId()==null)
return mapping.findForward("showEventList");
if (request.getParameter("id")!=null) {
String id = request.getParameter("id");
myForm.setEvent(event);
if (event!=null) {
myForm.setEventName(event.getEventName()==null?"":event.getEventName());
myForm.setEventType(event.getEventTypeLabel());
if ("Class Event".equals(myForm.getEventType())){
ClassEvent ce = (ClassEvent) event;
if (ce.getClazz().getEnrollment() != null)
myForm.setEnrollment(ce.getClazz().getEnrollment().toString());
else
myForm.setEnrollment("0");
}
myForm.setMinCapacity(event.getMinCapacity()==null?"":event.getMinCapacity().toString());
myForm.setMaxCapacity(event.getMaxCapacity()==null?"":event.getMaxCapacity().toString());
myForm.setAdditionalEmails(event.getEmail());
if ("Course Related Event".equals(myForm.getEventType())) {
myForm.setAttendanceRequired(((CourseEvent) event).isReqAttendance());
} else
myForm.setSponsoringOrgName(event.getSponsoringOrganization()==null?"":event.getSponsoringOrganization().getName());
myForm.setIsManager(user.isAdmin()||user.hasRole(Roles.EVENT_MGR_ROLE));
for (Iterator i = new TreeSet(event.getNotes()).iterator(); i.hasNext();) {
EventNote en = (EventNote) i.next();
myForm.addNote(en.toHtmlString(myForm.getIsManager()));
}
if (event.getMainContact()!=null)
myForm.setMainContact(event.getMainContact());
for (Iterator i = event.getAdditionalContacts().iterator(); i.hasNext();) {
EventContact ec = (EventContact) i.next();
myForm.addAdditionalContact(
(ec.getFirstName()==null?"":ec.getFirstName()),
(ec.getMiddleName()==null?"":ec.getMiddleName()),
(ec.getLastName()==null?"":ec.getLastName()),
(ec.getEmailAddress()==null?"":ec.getEmailAddress()),
(ec.getPhone()==null?"":ec.getPhone()));
}
SimpleDateFormat iDateFormat = new SimpleDateFormat("EEE MM/dd, yyyy", Locale.US);
if (event.getMainContact()!=null && user.getId().equals(event.getMainContact().getExternalUniqueId())) {
myForm.setCanDelete(true);
myForm.setCanEdit(true);
}
if (user.isAdmin()||user.hasRole(Roles.EVENT_MGR_ROLE)) {
myForm.setCanApprove(true);
myForm.setCanEdit(true);
}
if (event instanceof ClassEvent || event instanceof ExamEvent) {
//myForm.setCanEdit(false);
myForm.setCanApprove(false);
myForm.setCanDelete(false);
}
for (Iterator i=new TreeSet(event.getMeetings()).iterator();i.hasNext();) {
Meeting meeting = (Meeting)i.next();
Location location = meeting.getLocation();
MeetingBean mb = new MeetingBean(meeting);
if (myForm.getCanEdit() && (!mb.getIsPast() || "true".equals(ApplicationProperties.getProperty("tmtbl.event.allowEditPast","false")))) {
if (myForm.getCanDelete()) {
mb.setCanSelect(true);
} else if (user.isAdmin()) {
mb.setCanSelect(myForm.getCanApprove());
} else if (userDepartments!=null && location!=null && location.getControllingDepartment()!=null) {
mb.setCanSelect(myForm.getCanApprove() && userDepartments.contains(location.getControllingDepartment()));
}
}
for (Meeting overlap : meeting.getTimeRoomOverlaps())
mb.getOverlaps().add(new MeetingBean(overlap));
myForm.addMeeting(mb);
}
if (myForm.getCanApprove() && !myForm.getCanSelectAll())
myForm.setCanApprove(false);
Long nextId = Navigation.getNext(request.getSession(), Navigation.sInstructionalOfferingLevel, event.getUniqueId());
Long prevId = Navigation.getPrevious(request.getSession(), Navigation.sInstructionalOfferingLevel, event.getUniqueId());
myForm.setPreviousId(prevId==null?null:prevId.toString());
myForm.setNextId(nextId==null?null:nextId.toString());
if (Event.sEventTypes[Event.sEventTypeCourse].equals(myForm.getEventType())) {
CourseEvent courseEvent = new CourseEventDAO().get(Long.valueOf(id));
if (!courseEvent.getRelatedCourses().isEmpty()) {
WebTable table = new WebTable(5, null, new String[] {"Object", "Type", "Title","Limit","Assignment"}, new String[] {"left", "left", "left","right","left"}, new boolean[] {true, true, true, true,true});
for (Iterator i=new TreeSet(courseEvent.getRelatedCourses()).iterator();i.hasNext();) {
RelatedCourseInfo rci = (RelatedCourseInfo)i.next();
String onclick = null, name = null, type = null, title = null, assignment = null;
String students = String.valueOf(rci.countStudents());
switch (rci.getOwnerType()) {
case ExamOwner.sOwnerTypeClass :
Class_ clazz = (Class_)rci.getOwnerObject();
if (user.getRole()!=null && clazz.isViewableBy(user))
onclick = "onClick=\"document.location='classDetail.do?cid="+clazz.getUniqueId()+"';\"";
name = rci.getLabel();//clazz.getClassLabel();
type = "Class";
title = clazz.getSchedulePrintNote();
if (title==null || title.length()==0) title=clazz.getSchedulingSubpart().getControllingCourseOffering().getTitle();
if (clazz.getCommittedAssignment()!=null)
assignment = clazz.getCommittedAssignment().getPlacement().getLongName();
break;
case ExamOwner.sOwnerTypeConfig :
InstrOfferingConfig config = (InstrOfferingConfig)rci.getOwnerObject();
if (user.getRole()!=null && config.isViewableBy(user))
onclick = "onClick=\"document.location='instructionalOfferingDetail.do?io="+config.getInstructionalOffering().getUniqueId()+"';\"";
name = rci.getLabel();//config.getCourseName()+" ["+config.getName()+"]";
type = "Configuration";
title = config.getControllingCourseOffering().getTitle();
break;
case ExamOwner.sOwnerTypeOffering :
InstructionalOffering offering = (InstructionalOffering)rci.getOwnerObject();
if (user.getRole()!=null && offering.isViewableBy(user))
onclick = "onClick=\"document.location='instructionalOfferingDetail.do?io="+offering.getUniqueId()+"';\"";
name = rci.getLabel();//offering.getCourseName();
type = "Offering";
title = offering.getControllingCourseOffering().getTitle();
break;
case ExamOwner.sOwnerTypeCourse :
CourseOffering course = (CourseOffering)rci.getOwnerObject();
if (user.getRole()!=null && course.isViewableBy(user))
onclick = "onClick=\"document.location='instructionalOfferingDetail.do?io="+course.getInstructionalOffering().getUniqueId()+"';\"";
name = rci.getLabel();//course.getCourseName();
type = "Course";
title = course.getTitle();
break;
}
table.addLine(onclick, new String[] { name, type, title, students, assignment}, null);
}
request.setAttribute("EventDetail.table",table.printTable());
}
}
/*
if (Event.sEventTypes[Event.sEventTypeFinalExam].equals(myForm.getEventType()) || Event.sEventTypes[Event.sEventTypeMidtermExam].equals(myForm.getEventType())) {
ExamEvent examEvent = new ExamEventDAO().get(Long.valueOf(id));
if (examEvent.getExam()!=null && !examEvent.getExam().getOwners().isEmpty()) {
WebTable table = new WebTable(5, null, new String[] {"Object", "Type", "Title","Limit","Assignment"}, new String[] {"left", "left", "left","right","left"}, new boolean[] {true, true, true, true,true});
for (Iterator i=new TreeSet(examEvent.getExam().getOwners()).iterator();i.hasNext();) {
ExamOwner owner = (ExamOwner)i.next();
String onclick = null, name = null, type = null, title = null, assignment = null;
String students = String.valueOf(owner.countStudents());
switch (owner.getOwnerType()) {
case ExamOwner.sOwnerTypeClass :
Class_ clazz = (Class_)owner.getOwnerObject();
if (user.getRole()!=null && clazz.isViewableBy(user))
onclick = "onClick=\"document.location='classDetail.do?cid="+clazz.getUniqueId()+"';\"";
name = owner.getLabel();//clazz.getClassLabel();
type = "Class";
title = clazz.getSchedulePrintNote();
if (title==null || title.length()==0) title=clazz.getSchedulingSubpart().getControllingCourseOffering().getTitle();
if (clazz.getCommittedAssignment()!=null)
assignment = clazz.getCommittedAssignment().getPlacement().getLongName();
break;
case ExamOwner.sOwnerTypeConfig :
InstrOfferingConfig config = (InstrOfferingConfig)owner.getOwnerObject();
if (user.getRole()!=null && config.isViewableBy(user))
onclick = "onClick=\"document.location='instructionalOfferingDetail.do?io="+config.getInstructionalOffering().getUniqueId()+"';\"";
name = owner.getLabel();//config.getCourseName()+" ["+config.getName()+"]";
type = "Configuration";
title = config.getControllingCourseOffering().getTitle();
break;
case ExamOwner.sOwnerTypeOffering :
InstructionalOffering offering = (InstructionalOffering)owner.getOwnerObject();
if (user.getRole()!=null && offering.isViewableBy(user))
onclick = "onClick=\"document.location='instructionalOfferingDetail.do?io="+offering.getUniqueId()+"';\"";
name = owner.getLabel();//offering.getCourseName();
type = "Offering";
title = offering.getControllingCourseOffering().getTitle();
break;
case ExamOwner.sOwnerTypeCourse :
CourseOffering course = (CourseOffering)owner.getOwnerObject();
if (user.getRole()!=null && course.isViewableBy(user))
onclick = "onClick=\"document.location='instructionalOfferingDetail.do?io="+course.getInstructionalOffering().getUniqueId()+"';\"";
name = owner.getLabel();//course.getCourseName();
type = "Course";
title = course.getTitle();
break;
}
table.addLine(onclick, new String[] { name, type, title, students, assignment}, null);
}
request.setAttribute("EventDetail.table",table.printTable());
}
}
*/
if (Event.sEventTypes[Event.sEventTypeClass].equals(myForm.getEventType())) {
ClassEvent classEvent = new ClassEventDAO().get(Long.valueOf(id));
if (classEvent.getClazz()!=null) {
WebTable table = new WebTable(4, null, new String[] {"Name","Title","Limit","Assignment"}, new String[] {"left","left","right","left"}, new boolean[] {true, true, true, true});
Class_ clazz = (Class_)classEvent.getClazz();
String onclick = null, assignment = null;
if (user.getRole()!=null && clazz.isViewableBy(user))
onclick = "onClick=\"document.location='classDetail.do?cid="+clazz.getUniqueId()+"';\"";
String name = clazz.getClassLabel();
String title = clazz.getSchedulePrintNote();
String students = String.valueOf(clazz.getStudentEnrollments().size());
if (title==null || title.length()==0) title=clazz.getSchedulingSubpart().getControllingCourseOffering().getTitle();
if (clazz.getCommittedAssignment()!=null)
assignment = clazz.getCommittedAssignment().getPlacement().getLongName();
table.addLine(onclick, new String[] { name, title, students, assignment}, null);
request.setAttribute("EventDetail.table",table.printTable());
}
}
} else {
throw new Exception("There is no event with this ID");
}
}
BackTracker.markForBack(
request,
"eventDetail.do?op=view&id=" + myForm.getId(),
myForm.getEventName(),
true, false);
}
return mapping.findForward("show");
}
|
diff --git a/src/main/java/org/vivoweb/harvester/update/ChangeNamespace.java b/src/main/java/org/vivoweb/harvester/update/ChangeNamespace.java
index 3fc72542..83a969ea 100644
--- a/src/main/java/org/vivoweb/harvester/update/ChangeNamespace.java
+++ b/src/main/java/org/vivoweb/harvester/update/ChangeNamespace.java
@@ -1,298 +1,298 @@
/*******************************************************************************
* Copyright (c) 2010 Christopher Haines, Dale Scheppler, Nicholas Skaggs, Stephen V. Williams, James Pence. All rights reserved.
* This program and the accompanying materials are made available under the terms of the new BSD license which
* accompanies this distribution, and is available at http://www.opensource.org/licenses/bsd-license.html Contributors:
* Christopher Haines, Dale Scheppler, Nicholas Skaggs, Stephen V. Williams, James Pence - initial API and implementation
******************************************************************************/
package org.vivoweb.harvester.update;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.xml.parsers.ParserConfigurationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.vivoweb.harvester.util.InitLog;
import org.vivoweb.harvester.util.IterableAdaptor;
import org.vivoweb.harvester.util.args.ArgDef;
import org.vivoweb.harvester.util.args.ArgList;
import org.vivoweb.harvester.util.args.ArgParser;
import org.vivoweb.harvester.util.repo.JenaConnect;
import org.xml.sax.SAXException;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.rdf.model.ResourceFactory;
import com.hp.hpl.jena.rdf.model.Statement;
import com.hp.hpl.jena.sparql.util.StringUtils;
import com.hp.hpl.jena.util.ResourceUtils;
/**
* Changes the namespace for all matching uris
* @author Christopher Haines ([email protected])
*/
public class ChangeNamespace {
/**
* SLF4J Logger
*/
private static Logger log = LoggerFactory.getLogger(ChangeNamespace.class);
/**
* The model to change uris in
*/
private JenaConnect model;
/**
* The old namespace
*/
private String oldNamespace;
/**
* The new namespace
*/
private String newNamespace;
/**
* the propeties to match on
*/
private List<Property> properties;
/**
* The search model
*/
private JenaConnect vivo;
/**
* Constructor
* @param argList parsed argument list
* @throws IOException error reading config
* @throws SAXException error parsing config
* @throws ParserConfigurationException error parsing config
*/
public ChangeNamespace(ArgList argList) throws ParserConfigurationException, SAXException, IOException {
this.model = JenaConnect.parseConfig(argList.get("i"), argList.getProperties("I"));
this.vivo = JenaConnect.parseConfig(argList.get("v"), argList.getProperties("V"));
this.oldNamespace = argList.get("o");
this.newNamespace = argList.get("n");
List<String> predicates = argList.getAll("p");
this.properties = new ArrayList<Property>(predicates.size());
for(String pred : predicates) {
this.properties.add(ResourceFactory.createProperty(pred));
}
}
/**
* Get either a matching uri from the given model or an unused uri
* @param current the current resource
* @param namespace the namespace to match in
* @param properties the propeties to match on
* @param vivo the model to match in
* @param model models to check for duplicates
* @return the uri of the first matched resource or an unused uri if none found
*/
public static String getURI(Resource current, String namespace, List<Property> properties, JenaConnect vivo, JenaConnect model) {
String uri = null;
String matchURI = null;
if (properties != null && !properties.isEmpty()) {
matchURI = getMatchingURI(current, namespace, properties, vivo);
}
if (matchURI != null) {
uri = matchURI;
} else {
uri = getUnusedURI(namespace, vivo, model);
}
log.debug("Using URI: <"+uri+">");
return uri;
}
/**
* Gets an unused URI in the the given namespace for the given models
* @param namespace the namespace
* @param vivo primary model to check in
* @param models additional models to check in
* @return the uri
* @throws IllegalArgumentException empty namespace
*/
public static String getUnusedURI(String namespace, JenaConnect vivo, JenaConnect... models) throws IllegalArgumentException {
if(namespace == null || namespace.equals("")) {
throw new IllegalArgumentException("namespace cannot be empty");
}
String uri = null;
Random random = new Random();
while(uri == null) {
uri = namespace + "n" + random.nextInt(Integer.MAX_VALUE);
if(vivo.containsURI(uri)) {
uri = null;
}
for(JenaConnect model : models) {
if(model.containsURI(uri)) {
uri = null;
}
}
}
log.debug("Using new URI: <"+uri+">");
return uri;
}
/**
* Matches the current resource to a resource in the given namespace in the given model based on the given properties
* @param current the current resource
* @param namespace the namespace to match in
* @param properties the propeties to match on
* @param vivo the model to match in
* @return the uri of the first matched resource or null if none found
*/
public static String getMatchingURI(Resource current, String namespace, List<Property> properties, JenaConnect vivo) {
List<String> uris = getMatchingURIs(current, namespace, properties, vivo);
String uri = uris.isEmpty()?null:uris.get(0);
log.debug("Matched URI: <"+uri+">");
return uri;
}
/**
* Matches the current resource to resources in the given namespace in the given model based on the given properties
* @param current the current resource
* @param namespace the namespace to match in
* @param properties the propeties to match on
* @param vivo the model to match in
* @return the uris of the matched resources (empty set if none found)
*/
public static List<String> getMatchingURIs(Resource current, String namespace, List<Property> properties, JenaConnect vivo) {
StringBuilder sbQuery = new StringBuilder();
ArrayList<String> filters = new ArrayList<String>();
int valueCount = 0;
sbQuery.append("SELECT ?uri\nWHERE\n{");
for(Property p : properties) {
for(Statement s : IterableAdaptor.adapt(current.listProperties(p))) {
sbQuery.append("\t?uri <");
sbQuery.append(p.getURI());
sbQuery.append("> ");
if(s.getObject().isResource()) {
sbQuery.append("<");
sbQuery.append(s.getObject().asResource().getURI());
sbQuery.append(">");
} else {
filters.add("( str(?value"+valueCount+") = \""+s.getObject().asLiteral().getValue().toString()+"\" )");
sbQuery.append("?value");
sbQuery.append(valueCount);
valueCount++;
}
sbQuery.append(" .\n");
}
}
- sbQuery.append("\tFILTER (");
// sbQuery.append("regex( ?uri , \"");
// sbQuery.append(namespace);
// sbQuery.append("\" )");
if(!filters.isEmpty()) {
+ sbQuery.append("\tFILTER (");
// sbQuery.append(" && ");
sbQuery.append(StringUtils.join(" && ", filters));
}
sbQuery.append(")\n}");
ArrayList<String> retVal = new ArrayList<String>();
int count = 0;
log.debug("Query:\n"+sbQuery.toString());
log.debug("namespace: "+namespace);
for(QuerySolution qs : IterableAdaptor.adapt(vivo.executeQuery(sbQuery.toString()))) {
Resource res = qs.getResource("uri");
if(res.getNameSpace().equals(namespace)) {
String uri = res.getURI();
retVal.add(uri);
log.debug("Matched URI["+count+"]: <"+uri+">");
count++;
}
}
return retVal;
}
/**
* Changes the namespace for all matching uris
* @param model the model to change namespaces for
* @param vivo the model to search for uris in
* @param oldNamespace the old namespace
* @param newNamespace the new namespace
* @param properties the propeties to match on
* @throws IllegalArgumentException empty namespace
*/
public static void changeNS(JenaConnect model, JenaConnect vivo, String oldNamespace, String newNamespace, List<Property> properties) throws IllegalArgumentException {
if(oldNamespace == null || oldNamespace.equals("")) {
throw new IllegalArgumentException("old namespace cannot be empty");
}
if(newNamespace == null || newNamespace.equals("")) {
throw new IllegalArgumentException("new namespace cannot be empty");
}
if(oldNamespace.equals(newNamespace)) {
return;
}
ArrayList<String> uriCheck = new ArrayList<String>();
int count = 0;
for(Resource res : IterableAdaptor.adapt(model.getJenaModel().listSubjects())) {
if(oldNamespace.equals(res.getNameSpace())) {
log.debug("Finding match for <"+res.getURI()+">");
String uri = null;
boolean uriFound = false;
//find valid URI
while (!uriFound) {
uri = getURI(res, newNamespace, properties, vivo, model);
log.trace("urlCheck: "+uriCheck.contains(uri));
//if matched in VIVO or not previously used
if (vivo.containsURI(uri) || !uriCheck.contains(uri)) {
//note URI as being used
uriCheck.add(uri);
//use this URI
uriFound = true;
}
}
ResourceUtils.renameResource(res, uri);
count++;
}
}
log.info("Changed namespace for "+count+" rdf nodes");
}
/**
* Change namespace
*/
private void execute() {
changeNS(this.model, this.vivo, this.oldNamespace, this.newNamespace, this.properties);
}
/**
* Get the ArgParser for this task
* @return the ArgParser
*/
private static ArgParser getParser() {
ArgParser parser = new ArgParser("ChangeNamespace");
// Inputs
parser.addArgument(new ArgDef().setShortOption('i').setLongOpt("inputModel").withParameter(true, "CONFIG_FILE").setDescription("config file for input jena model").setRequired(true));
parser.addArgument(new ArgDef().setShortOption('I').setLongOpt("inputModelOverride").withParameterProperties("JENA_PARAM", "VALUE").setDescription("override the JENA_PARAM of input jena model config using VALUE").setRequired(false));
parser.addArgument(new ArgDef().setShortOption('v').setLongOpt("vivoModel").withParameter(true, "CONFIG_FILE").setDescription("config file for vivo jena model").setRequired(true));
parser.addArgument(new ArgDef().setShortOption('V').setLongOpt("vivoModelOverride").withParameterProperties("JENA_PARAM", "VALUE").setDescription("override the JENA_PARAM of vivo jena model config using VALUE").setRequired(false));
// Params
parser.addArgument(new ArgDef().setShortOption('o').setLongOpt("oldNamespace").withParameter(true, "OLD_NAMESPACE").setDescription("The old namespace").setRequired(true));
parser.addArgument(new ArgDef().setShortOption('n').setLongOpt("newNamespace").withParameter(true, "NEW_NAMESPACE").setDescription("The new namespace").setRequired(true));
parser.addArgument(new ArgDef().setShortOption('p').setLongOpt("predicate").withParameters(true, "MATCH_PREDICATE").setDescription("Predicate to match on").setRequired(true));
return parser;
}
/**
* Main method
* @param args commandline arguments
*/
public static void main(String... args) {
InitLog.initLogger(ChangeNamespace.class);
log.info(getParser().getAppName()+": Start");
try {
new ChangeNamespace(new ArgList(getParser(), args)).execute();
} catch(IllegalArgumentException e) {
log.error(e.getMessage());
System.out.println(getParser().getUsage());
} catch(IOException e) {
log.error(e.getMessage(), e);
// System.out.println(getParser().getUsage());
} catch(Exception e) {
log.error(e.getMessage(), e);
}
log.info(getParser().getAppName()+": End");
}
}
| false | true | public static List<String> getMatchingURIs(Resource current, String namespace, List<Property> properties, JenaConnect vivo) {
StringBuilder sbQuery = new StringBuilder();
ArrayList<String> filters = new ArrayList<String>();
int valueCount = 0;
sbQuery.append("SELECT ?uri\nWHERE\n{");
for(Property p : properties) {
for(Statement s : IterableAdaptor.adapt(current.listProperties(p))) {
sbQuery.append("\t?uri <");
sbQuery.append(p.getURI());
sbQuery.append("> ");
if(s.getObject().isResource()) {
sbQuery.append("<");
sbQuery.append(s.getObject().asResource().getURI());
sbQuery.append(">");
} else {
filters.add("( str(?value"+valueCount+") = \""+s.getObject().asLiteral().getValue().toString()+"\" )");
sbQuery.append("?value");
sbQuery.append(valueCount);
valueCount++;
}
sbQuery.append(" .\n");
}
}
sbQuery.append("\tFILTER (");
// sbQuery.append("regex( ?uri , \"");
// sbQuery.append(namespace);
// sbQuery.append("\" )");
if(!filters.isEmpty()) {
// sbQuery.append(" && ");
sbQuery.append(StringUtils.join(" && ", filters));
}
sbQuery.append(")\n}");
ArrayList<String> retVal = new ArrayList<String>();
int count = 0;
log.debug("Query:\n"+sbQuery.toString());
log.debug("namespace: "+namespace);
for(QuerySolution qs : IterableAdaptor.adapt(vivo.executeQuery(sbQuery.toString()))) {
Resource res = qs.getResource("uri");
if(res.getNameSpace().equals(namespace)) {
String uri = res.getURI();
retVal.add(uri);
log.debug("Matched URI["+count+"]: <"+uri+">");
count++;
}
}
return retVal;
}
| public static List<String> getMatchingURIs(Resource current, String namespace, List<Property> properties, JenaConnect vivo) {
StringBuilder sbQuery = new StringBuilder();
ArrayList<String> filters = new ArrayList<String>();
int valueCount = 0;
sbQuery.append("SELECT ?uri\nWHERE\n{");
for(Property p : properties) {
for(Statement s : IterableAdaptor.adapt(current.listProperties(p))) {
sbQuery.append("\t?uri <");
sbQuery.append(p.getURI());
sbQuery.append("> ");
if(s.getObject().isResource()) {
sbQuery.append("<");
sbQuery.append(s.getObject().asResource().getURI());
sbQuery.append(">");
} else {
filters.add("( str(?value"+valueCount+") = \""+s.getObject().asLiteral().getValue().toString()+"\" )");
sbQuery.append("?value");
sbQuery.append(valueCount);
valueCount++;
}
sbQuery.append(" .\n");
}
}
// sbQuery.append("regex( ?uri , \"");
// sbQuery.append(namespace);
// sbQuery.append("\" )");
if(!filters.isEmpty()) {
sbQuery.append("\tFILTER (");
// sbQuery.append(" && ");
sbQuery.append(StringUtils.join(" && ", filters));
}
sbQuery.append(")\n}");
ArrayList<String> retVal = new ArrayList<String>();
int count = 0;
log.debug("Query:\n"+sbQuery.toString());
log.debug("namespace: "+namespace);
for(QuerySolution qs : IterableAdaptor.adapt(vivo.executeQuery(sbQuery.toString()))) {
Resource res = qs.getResource("uri");
if(res.getNameSpace().equals(namespace)) {
String uri = res.getURI();
retVal.add(uri);
log.debug("Matched URI["+count+"]: <"+uri+">");
count++;
}
}
return retVal;
}
|
diff --git a/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/AspectDeclaration.java b/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/AspectDeclaration.java
index 1039559cc..9203a43ab 100644
--- a/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/AspectDeclaration.java
+++ b/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/AspectDeclaration.java
@@ -1,1118 +1,1119 @@
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.ast;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory;
import org.aspectj.ajdt.internal.compiler.lookup.EclipseScope;
import org.aspectj.ajdt.internal.compiler.lookup.EclipseSourceType;
import org.aspectj.ajdt.internal.compiler.lookup.EclipseTypeMunger;
import org.aspectj.ajdt.internal.compiler.lookup.HelperInterfaceBinding;
import org.aspectj.ajdt.internal.compiler.lookup.InlineAccessFieldBinding;
import org.aspectj.ajdt.internal.compiler.lookup.PrivilegedHandler;
import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation;
import org.aspectj.org.eclipse.jdt.internal.compiler.ClassFile;
import org.aspectj.org.eclipse.jdt.internal.compiler.CompilationResult;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Annotation;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Clinit;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.MethodDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.codegen.CodeStream;
import org.aspectj.org.eclipse.jdt.internal.compiler.codegen.ExceptionLabel;
import org.aspectj.org.eclipse.jdt.internal.compiler.codegen.Label;
import org.aspectj.org.eclipse.jdt.internal.compiler.env.IGenericType;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.BaseTypes;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.BinaryTypeBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.Binding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ClassScope;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.FieldBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.InvocationSite;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.MethodBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.Scope;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
import org.aspectj.weaver.AjAttribute;
import org.aspectj.weaver.AjcMemberMaker;
import org.aspectj.weaver.NameMangler;
import org.aspectj.weaver.ReferenceType;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.patterns.Declare;
import org.aspectj.weaver.patterns.FormalBinding;
import org.aspectj.weaver.patterns.PerClause;
import org.aspectj.weaver.patterns.PerFromSuper;
import org.aspectj.weaver.patterns.PerSingleton;
import org.aspectj.weaver.patterns.TypePattern;
//import org.aspectj.org.eclipse.jdt.internal.compiler.parser.Parser;
// (we used to...) making all aspects member types avoids a nasty hierarchy pain
// switched from MemberTypeDeclaration to TypeDeclaration
public class AspectDeclaration extends TypeDeclaration {
//public IAjDeclaration[] ajDeclarations;
private AjAttribute.Aspect aspectAttribute;
public PerClause perClause;
public ResolvedMember aspectOfMethod;
public ResolvedMember hasAspectMethod;
public Map accessForInline = new HashMap();
public Map superAccessForInline = new HashMap();
public boolean isPrivileged;
public EclipseSourceType concreteName;
public ReferenceType typeX;
public EclipseFactory factory; //??? should use this consistently
public int adviceCounter = 1; // Used as a part of the generated name for advice methods
public int declareCounter= 1; // Used as a part of the generated name for methods representing declares
// for better error messages in 1.0 to 1.1 transition
public TypePattern dominatesPattern;
public AspectDeclaration(CompilationResult compilationResult) {
super(compilationResult);
//perClause = new PerSingleton();
}
public boolean isAbstract() {
return (modifiers & AccAbstract) != 0;
}
public void resolve() {
if (binding == null) {
ignoreFurtherInvestigation = true;
return;
}
super.resolve();
}
public void checkSpec(ClassScope scope) {
if (ignoreFurtherInvestigation) return;
if (dominatesPattern != null) {
scope.problemReporter().signalError(
dominatesPattern.getStart(), dominatesPattern.getEnd(),
"dominates has changed for 1.1, use 'declare precedence: " +
new String(this.name) + ", " + dominatesPattern.toString() + ";' " +
"in the body of the aspect instead");
}
if (!isAbstract()) {
MethodBinding[] methods = binding.methods();
for (int i=0, len = methods.length; i < len; i++) {
MethodBinding m = methods[i];
if (m.isConstructor()) {
// this make all constructors in aspects invisible and thus uncallable
//XXX this only works for aspects that come from source
methods[i] = new MethodBinding(m, binding) {
public boolean canBeSeenBy(
InvocationSite invocationSite,
Scope scope) {
return false;
}
};
if (m.parameters != null && m.parameters.length != 0) {
scope.problemReporter().signalError(m.sourceStart(), m.sourceEnd(),
"only zero-argument constructors allowed in concrete aspect");
}
}
}
// check the aspect was not declared generic, only abstract aspects can have type params
if (typeParameters != null && typeParameters.length > 0) {
scope.problemReporter().signalError(sourceStart(), sourceEnd(),
"only abstract aspects can have type parameters");
}
}
if (this.enclosingType != null) {
if (!Modifier.isStatic(modifiers)) {
scope.problemReporter().signalError(sourceStart, sourceEnd,
"inner aspects must be static");
ignoreFurtherInvestigation = true;
return;
}
}
EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(scope);
ResolvedType myType = typeX;
//if (myType == null) System.err.println("bad myType for: " + this);
ResolvedType superType = myType.getSuperclass();
// can't be Serializable/Cloneable unless -XserializableAspects
if (!world.isXSerializableAspects()) {
if (world.getWorld().getCoreType(UnresolvedType.SERIALIZABLE).isAssignableFrom(myType)) {
scope.problemReporter().signalError(sourceStart, sourceEnd,
"aspects may not implement Serializable");
ignoreFurtherInvestigation = true;
return;
}
if (world.getWorld().getCoreType(UnresolvedType.CLONEABLE).isAssignableFrom(myType)) {
scope.problemReporter().signalError(sourceStart, sourceEnd,
"aspects may not implement Cloneable");
ignoreFurtherInvestigation = true;
return;
}
}
if (superType.isAspect()) {
if (!superType.isAbstract()) {
scope.problemReporter().signalError(sourceStart, sourceEnd,
"can not extend a concrete aspect");
ignoreFurtherInvestigation = true;
return;
}
// if super type is generic, check that we have fully parameterized it
if (superType.isRawType()) {
scope.problemReporter().signalError(sourceStart, sourceEnd,
"a generic super-aspect must be fully parameterized in an extends clause");
ignoreFurtherInvestigation = true;
return;
}
}
}
private FieldBinding initFailureField= null;
/**
* AMC - this method is called by the AtAspectJVisitor during beforeCompilation processing in
* the AjCompiler adapter. We use this hook to add in the @AspectJ annotations.
*/
public void addAtAspectJAnnotations() {
Annotation atAspectAnnotation = AtAspectJAnnotationFactory.createAspectAnnotation(perClause.toDeclarationString(), declarationSourceStart);
Annotation privilegedAnnotation = null;
if (isPrivileged) privilegedAnnotation = AtAspectJAnnotationFactory.createPrivilegedAnnotation(declarationSourceStart);
Annotation[] toAdd = new Annotation[isPrivileged ? 2 : 1];
toAdd[0] = atAspectAnnotation;
if (isPrivileged) toAdd[1] = privilegedAnnotation;
if (annotations == null) {
annotations = toAdd;
} else {
Annotation[] old = annotations;
annotations = new Annotation[annotations.length + toAdd.length];
System.arraycopy(old,0,annotations,0,old.length);
System.arraycopy(toAdd,0,annotations,old.length,toAdd.length);
}
}
public void generateCode(ClassFile enclosingClassFile) {
if (ignoreFurtherInvestigation) {
if (binding == null)
return;
ClassFile.createProblemType(
this,
scope.referenceCompilationUnit().compilationResult);
return;
}
// make me and my binding public
this.modifiers = AstUtil.makePublic(this.modifiers);
this.binding.modifiers = AstUtil.makePublic(this.binding.modifiers);
if (!isAbstract()) {
initFailureField = factory.makeFieldBinding(AjcMemberMaker.initFailureCauseField(typeX));
binding.addField(initFailureField);
if (perClause == null) {
// we've already produced an error for this
} else if (perClause.getKind() == PerClause.SINGLETON) {
binding.addField(factory.makeFieldBinding(AjcMemberMaker.perSingletonField(
typeX)));
methods[0] = new AspectClinit((Clinit)methods[0], compilationResult, false, true, initFailureField);
} else if (perClause.getKind() == PerClause.PERCFLOW) {
binding.addField(
factory.makeFieldBinding(
AjcMemberMaker.perCflowField(
typeX)));
methods[0] = new AspectClinit((Clinit)methods[0], compilationResult, true, false, null);
} else if (perClause.getKind() == PerClause.PEROBJECT) {
// binding.addField(
// world.makeFieldBinding(
// AjcMemberMaker.perCflowField(
// typeX)));
} else if (perClause.getKind() == PerClause.PERTYPEWITHIN) {
//PTWIMPL Add field for storing typename in aspect for which the aspect instance exists
binding.addField(factory.makeFieldBinding(AjcMemberMaker.perTypeWithinWithinTypeField(typeX,typeX)));
} else {
throw new RuntimeException("unimplemented");
}
}
if (EclipseFactory.DEBUG) System.out.println(toString());
super.generateCode(enclosingClassFile);
}
public boolean needClassInitMethod() {
return true;
}
protected void generateAttributes(ClassFile classFile) {
if (!isAbstract()) generatePerSupportMembers(classFile);
generateInlineAccessMembers(classFile);
addVersionAttributeIfNecessary(classFile);
classFile.extraAttributes.add(
new EclipseAttributeAdapter(new AjAttribute.Aspect(perClause)));
if (binding.privilegedHandler != null) {
ResolvedMember[] members = ((PrivilegedHandler)binding.privilegedHandler).getMembers();
classFile.extraAttributes.add(
new EclipseAttributeAdapter(new AjAttribute.PrivilegedAttribute(members)));
}
//XXX need to get this attribute on anyone with a pointcut for good errors
classFile.extraAttributes.add(
new EclipseAttributeAdapter(new AjAttribute.SourceContextAttribute(
new String(compilationResult().getFileName()),
compilationResult().lineSeparatorPositions)));
super.generateAttributes(classFile);
}
/**
* A pointcut might have already added the attribute, let's not add it again.
*/
private void addVersionAttributeIfNecessary(ClassFile classFile) {
for (Iterator iter = classFile.extraAttributes.iterator(); iter.hasNext();) {
EclipseAttributeAdapter element = (EclipseAttributeAdapter) iter.next();
if (CharOperation.equals(element.getNameChars(),weaverVersionChars)) return;
}
classFile.extraAttributes.add(new EclipseAttributeAdapter(new AjAttribute.WeaverVersionInfo()));
}
private static char[] weaverVersionChars = "org.aspectj.weaver.WeaverVersion".toCharArray();
private void generateInlineAccessMembers(ClassFile classFile) {
for (Iterator i = superAccessForInline.values().iterator(); i.hasNext(); ) {
AccessForInlineVisitor.SuperAccessMethodPair pair = (AccessForInlineVisitor.SuperAccessMethodPair)i.next();
generateSuperAccessMethod(classFile, pair.accessMethod, pair.originalMethod);
}
for (Iterator i = accessForInline.entrySet().iterator(); i.hasNext(); ) {
Map.Entry e = (Map.Entry)i.next();
generateInlineAccessMethod(classFile, (Binding)e.getValue(), (ResolvedMember)e.getKey());
}
}
private void generatePerSupportMembers(ClassFile classFile) {
if (isAbstract()) return;
//XXX otherwise we need to have this (error handling?)
if (aspectOfMethod == null) return;
if (perClause == null) {
System.err.println("has null perClause: " + this);
return;
}
EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
if (perClause.getKind() == PerClause.SINGLETON) {
generatePerSingletonAspectOfMethod(classFile);
generatePerSingletonHasAspectMethod(classFile);
generatePerSingletonAjcClinitMethod(classFile);
} else if (perClause.getKind() == PerClause.PERCFLOW) {
generatePerCflowAspectOfMethod(classFile);
generatePerCflowHasAspectMethod(classFile);
generatePerCflowPushMethod(classFile);
generatePerCflowAjcClinitMethod(classFile);
} else if (perClause.getKind() == PerClause.PEROBJECT) {
TypeBinding interfaceType =
generatePerObjectInterface(classFile);
world.addTypeBinding(interfaceType);
generatePerObjectAspectOfMethod(classFile, interfaceType);
generatePerObjectHasAspectMethod(classFile, interfaceType);
generatePerObjectBindMethod(classFile, interfaceType);
} else if (perClause.getKind() == PerClause.PERTYPEWITHIN) {
//PTWIMPL Generate the methods required *in the aspect*
generatePerTypeWithinAspectOfMethod(classFile); // public static <aspecttype> aspectOf(java.lang.Class)
generatePerTypeWithinGetInstanceMethod(classFile); // private static <aspecttype> ajc$getInstance(Class c) throws Exception
generatePerTypeWithinHasAspectMethod(classFile);
generatePerTypeWithinCreateAspectInstanceMethod(classFile); // generate public static X ajc$createAspectInstance(Class forClass) {
// PTWIMPL getWithinType() would need this...
// generatePerTypeWithinGetWithinTypeMethod(classFile); // generate public Class getWithinType() {
} else {
throw new RuntimeException("unimplemented");
}
}
private static interface BodyGenerator {
public void generate(CodeStream codeStream);
}
private void generateMethod(ClassFile classFile, ResolvedMember member, BodyGenerator gen) {
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, world.makeMethodBinding(member), gen);
}
private void generateMethod(ClassFile classFile, MethodBinding methodBinding, BodyGenerator gen) {
generateMethod(classFile,methodBinding,null,gen);
}
protected List makeEffectiveSignatureAttribute(ResolvedMember sig,Shadow.Kind kind,boolean weaveBody) {
List l = new ArrayList(1);
l.add(new EclipseAttributeAdapter(
new AjAttribute.EffectiveSignatureAttribute(sig, kind, weaveBody)));
return l;
}
/*
* additionalAttributes allows us to pass some optional attributes we want to attach to the method we generate.
* Currently this is used for inline accessor methods that have been generated to allow private field references or
* private method calls to be inlined (PR71377). In these cases the optional attribute is an effective signature
* attribute which means calls to these methods are able to masquerade as any join point (a field set, field get or
* method call). The effective signature attribute is 'unwrapped' in BcelClassWeaver.matchInvokeInstruction()
*/
private void generateMethod(ClassFile classFile, MethodBinding methodBinding, List additionalAttributes/*ResolvedMember realMember*/, BodyGenerator gen) {
// EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
classFile.generateMethodInfoHeader(methodBinding);
int methodAttributeOffset = classFile.contentsOffset;
int attributeNumber;
if (additionalAttributes!=null) { // mini optimization
List attrs = new ArrayList();
attrs.addAll(AstUtil.getAjSyntheticAttribute());
attrs.addAll(additionalAttributes);
attributeNumber = classFile.generateMethodInfoAttribute(methodBinding, false, attrs);
} else {
attributeNumber = classFile.generateMethodInfoAttribute(methodBinding, false, AstUtil.getAjSyntheticAttribute());
}
int codeAttributeOffset = classFile.contentsOffset;
classFile.generateCodeAttributeHeader();
CodeStream codeStream = classFile.codeStream;
// Use reset() rather than init()
// XXX We need a scope to keep reset happy, initializerScope is *not* the right one, but it works !
// codeStream.init(classFile);
// codeStream.initializeMaxLocals(methodBinding);
MethodDeclaration md = AstUtil.makeMethodDeclaration(methodBinding);
md.scope = initializerScope;
codeStream.reset(md,classFile);
// body starts here
gen.generate(codeStream);
// body ends here
classFile.completeCodeAttribute(codeAttributeOffset);
attributeNumber++;
classFile.completeMethodInfo(methodAttributeOffset, attributeNumber);
}
private void generatePerCflowAspectOfMethod(
ClassFile classFile)
{
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, aspectOfMethod, new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
codeStream.getstatic(
world.makeFieldBinding(
AjcMemberMaker.perCflowField(
typeX)));
codeStream.invokevirtual(world.makeMethodBindingForCall(
AjcMemberMaker.cflowStackPeekInstance()));
codeStream.checkcast(binding);
codeStream.areturn();
// body ends here
}});
}
private void generatePerCflowHasAspectMethod(ClassFile classFile) {
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, hasAspectMethod, new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
codeStream.getstatic(
world.makeFieldBinding(
AjcMemberMaker.perCflowField(
typeX)));
codeStream.invokevirtual(world.makeMethodBindingForCall(
AjcMemberMaker.cflowStackIsValid()));
codeStream.ireturn();
// body ends here
}});
}
private void generatePerCflowPushMethod(
ClassFile classFile)
{
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, world.makeMethodBinding(AjcMemberMaker.perCflowPush(
factory.fromBinding(binding))),
new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
codeStream.getstatic(
world.makeFieldBinding(
AjcMemberMaker.perCflowField(
typeX)));
codeStream.new_(binding);
codeStream.dup();
codeStream.invokespecial(
new MethodBinding(0, "<init>".toCharArray(),
BaseTypes.VoidBinding, new TypeBinding[0],
new ReferenceBinding[0], binding));
codeStream.invokevirtual(world.makeMethodBindingForCall(
AjcMemberMaker.cflowStackPushInstance()));
codeStream.return_();
// body ends here
}});
}
private void generatePerCflowAjcClinitMethod(
ClassFile classFile)
{
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, world.makeMethodBinding(AjcMemberMaker.ajcPreClinitMethod(
world.fromBinding(binding))),
new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
codeStream.new_(world.makeTypeBinding(AjcMemberMaker.CFLOW_STACK_TYPE));
codeStream.dup();
codeStream.invokespecial(world.makeMethodBindingForCall(AjcMemberMaker.cflowStackInit()));
codeStream.putstatic(
world.makeFieldBinding(
AjcMemberMaker.perCflowField(
typeX)));
codeStream.return_();
// body ends here
}});
}
private TypeBinding generatePerObjectInterface(
ClassFile classFile)
{
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
UnresolvedType interfaceTypeX =
AjcMemberMaker.perObjectInterfaceType(typeX);
HelperInterfaceBinding interfaceType =
new HelperInterfaceBinding(this.binding, interfaceTypeX);
world.addTypeBinding(interfaceType);
interfaceType.addMethod(world, AjcMemberMaker.perObjectInterfaceGet(typeX));
interfaceType.addMethod(world, AjcMemberMaker.perObjectInterfaceSet(typeX));
interfaceType.generateClass(compilationResult, classFile);
return interfaceType;
}
// PTWIMPL Generate aspectOf() method
private void generatePerTypeWithinAspectOfMethod(ClassFile classFile) {
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, aspectOfMethod, new BodyGenerator() {
public void generate(CodeStream codeStream) {
Label instanceFound = new Label(codeStream);
ExceptionLabel anythingGoesWrong = new ExceptionLabel(codeStream,world.makeTypeBinding(UnresolvedType.JAVA_LANG_EXCEPTION));
codeStream.aload_0();
codeStream.invokestatic(world.makeMethodBindingForCall(AjcMemberMaker.perTypeWithinGetInstance(typeX)));
codeStream.astore_1();
codeStream.aload_1();
codeStream.ifnonnull(instanceFound);
codeStream.new_(world.makeTypeBinding(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION));
codeStream.dup();
codeStream.ldc(typeX.getName());
codeStream.aconst_null();
codeStream.invokespecial(world.makeMethodBindingForCall(AjcMemberMaker.noAspectBoundExceptionInit2()));
codeStream.athrow();
instanceFound.place();
codeStream.aload_1();
codeStream.areturn();
anythingGoesWrong.placeEnd();
anythingGoesWrong.place();
codeStream.astore_1();
codeStream.new_(world.makeTypeBinding(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION));
codeStream.dup();
// Run the simple ctor for NABE
codeStream.invokespecial(world.makeMethodBindingForCall(AjcMemberMaker.noAspectBoundExceptionInit()));
codeStream.athrow();
}});
}
private void generatePerObjectAspectOfMethod(
ClassFile classFile,
final TypeBinding interfaceType)
{
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, aspectOfMethod, new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
Label wrongType = new Label(codeStream);
Label popWrongType = new Label(codeStream);
codeStream.aload_0();
codeStream.instance_of(interfaceType);
codeStream.ifeq(wrongType);
codeStream.aload_0();
codeStream.checkcast(interfaceType);
codeStream.invokeinterface(world.makeMethodBindingForCall(
AjcMemberMaker.perObjectInterfaceGet(typeX)));
codeStream.dup();
codeStream.ifnull(popWrongType);
codeStream.areturn();
popWrongType.place();
codeStream.pop();
wrongType.place();
codeStream.new_(world.makeTypeBinding(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION));
codeStream.dup();
codeStream.invokespecial(world.makeMethodBindingForCall(
AjcMemberMaker.noAspectBoundExceptionInit()
));
codeStream.athrow();
// body ends here
}});
}
private void generatePerObjectHasAspectMethod(ClassFile classFile,
final TypeBinding interfaceType) {
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, hasAspectMethod, new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
Label wrongType = new Label(codeStream);
codeStream.aload_0();
codeStream.instance_of(interfaceType);
codeStream.ifeq(wrongType);
codeStream.aload_0();
codeStream.checkcast(interfaceType);
codeStream.invokeinterface(world.makeMethodBindingForCall(
AjcMemberMaker.perObjectInterfaceGet(typeX)));
codeStream.ifnull(wrongType);
codeStream.iconst_1();
codeStream.ireturn();
wrongType.place();
codeStream.iconst_0();
codeStream.ireturn();
// body ends here
}});
}
// PTWIMPL Generate hasAspect() method
private void generatePerTypeWithinHasAspectMethod(ClassFile classFile) {
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, hasAspectMethod, new BodyGenerator() {
public void generate(CodeStream codeStream) {
ExceptionLabel goneBang = new ExceptionLabel(codeStream,world.makeTypeBinding(UnresolvedType.JAVA_LANG_EXCEPTION));
Label noInstanceExists = new Label(codeStream);
Label leave = new Label(codeStream);
goneBang.placeStart();
codeStream.aload_0();
codeStream.invokestatic(world.makeMethodBinding(AjcMemberMaker.perTypeWithinGetInstance(typeX)));
codeStream.ifnull(noInstanceExists);
codeStream.iconst_1();
codeStream.goto_(leave);
noInstanceExists.place();
codeStream.iconst_0();
leave.place();
goneBang.placeEnd();
codeStream.ireturn();
goneBang.place();
codeStream.astore_1();
codeStream.iconst_0();
codeStream.ireturn();
}});
}
private void generatePerObjectBindMethod(
ClassFile classFile,
final TypeBinding interfaceType)
{
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, AjcMemberMaker.perObjectBind(world.fromBinding(binding)),
new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
Label wrongType = new Label(codeStream);
codeStream.aload_0();
codeStream.instance_of(interfaceType);
codeStream.ifeq(wrongType); //XXX this case might call for screaming
codeStream.aload_0();
codeStream.checkcast(interfaceType);
codeStream.invokeinterface(world.makeMethodBindingForCall(
AjcMemberMaker.perObjectInterfaceGet(typeX)));
//XXX should do a check for null here and throw a NoAspectBound
codeStream.ifnonnull(wrongType);
codeStream.aload_0();
codeStream.checkcast(interfaceType);
codeStream.new_(binding);
codeStream.dup();
codeStream.invokespecial(
new MethodBinding(0, "<init>".toCharArray(),
BaseTypes.VoidBinding, new TypeBinding[0],
new ReferenceBinding[0], binding));
codeStream.invokeinterface(world.makeMethodBindingForCall(
AjcMemberMaker.perObjectInterfaceSet(typeX)));
wrongType.place();
codeStream.return_();
// body ends here
}});
}
// PTWIMPL Generate getInstance method
private void generatePerTypeWithinGetInstanceMethod(ClassFile classFile) {
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, AjcMemberMaker.perTypeWithinGetInstance(world.fromBinding(binding)),
new BodyGenerator() {
public void generate(CodeStream codeStream) {
ExceptionLabel exc = new ExceptionLabel(codeStream,world.makeTypeBinding(UnresolvedType.JAVA_LANG_EXCEPTION));
exc.placeStart();
codeStream.aload_0();
codeStream.ldc(NameMangler.perTypeWithinLocalAspectOf(typeX));
codeStream.aconst_null();
codeStream.invokevirtual(
new MethodBinding(
0,
"getDeclaredMethod".toCharArray(),
world.makeTypeBinding(UnresolvedType.forSignature("Ljava/lang/reflect/Method;")), // return type
new TypeBinding[]{world.makeTypeBinding(UnresolvedType.forSignature("Ljava/lang/String;")),
world.makeTypeBinding(UnresolvedType.forSignature("[Ljava/lang/Class;"))},
new ReferenceBinding[0],
(ReferenceBinding)world.makeTypeBinding(UnresolvedType.JAVA_LANG_CLASS)));
codeStream.astore_1();
codeStream.aload_1();
codeStream.aconst_null();
codeStream.aconst_null();
codeStream.invokevirtual(
new MethodBinding(
0,
"invoke".toCharArray(),
world.makeTypeBinding(UnresolvedType.OBJECT),
new TypeBinding[]{world.makeTypeBinding(UnresolvedType.OBJECT),world.makeTypeBinding(UnresolvedType.forSignature("[Ljava/lang/Object;"))},
new ReferenceBinding[0],
(ReferenceBinding)world.makeTypeBinding(UnresolvedType.JAVA_LANG_REFLECT_METHOD)));
codeStream.checkcast(world.makeTypeBinding(typeX));
codeStream.astore_2();
codeStream.aload_2();
exc.placeEnd();
codeStream.areturn();
exc.place();
+ codeStream.astore_1();
// this just returns null now - the old version used to throw the caught exception!
codeStream.aconst_null();
codeStream.areturn();
}});
}
private void generatePerTypeWithinCreateAspectInstanceMethod(ClassFile classFile) {
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, AjcMemberMaker.perTypeWithinCreateAspectInstance(world.fromBinding(binding)),
new BodyGenerator() {
public void generate(CodeStream codeStream) {
codeStream.new_(world.makeTypeBinding(typeX));
codeStream.dup();
codeStream.invokespecial(new MethodBinding(0, "<init>".toCharArray(),
BaseTypes.VoidBinding, new TypeBinding[0],
new ReferenceBinding[0], binding));
codeStream.astore_1();
codeStream.aload_1();
codeStream.aload_0();
codeStream.putfield(world.makeFieldBinding(AjcMemberMaker.perTypeWithinWithinTypeField(typeX,typeX)));
codeStream.aload_1();
codeStream.areturn();
}});
}
private void generatePerSingletonAspectOfMethod(ClassFile classFile) {
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, aspectOfMethod, new BodyGenerator() {
public void generate(CodeStream codeStream) {
// Old style aspectOf() method which confused decompilers
// // body starts here
// codeStream.getstatic(world.makeFieldBinding(AjcMemberMaker.perSingletonField(
// typeX)));
// Label isNull = new Label(codeStream);
// codeStream.dup();
// codeStream.ifnull(isNull);
// codeStream.areturn();
// isNull.place();
//
// codeStream.incrStackSize(+1); // the dup trick above confuses the stack counter
// codeStream.new_(world.makeTypeBinding(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION));
// codeStream.dup();
// codeStream.ldc(typeX.getNameAsIdentifier());
// codeStream.getstatic(initFailureField);
// codeStream.invokespecial(world.makeMethodBindingForCall(
// AjcMemberMaker.noAspectBoundExceptionInitWithCause()
// ));
// codeStream.athrow();
// // body ends here
// The stuff below generates code that looks like this:
/*
* if (ajc$perSingletonInstance == null)
* throw new NoAspectBoundException("A", ajc$initFailureCause);
* else
* return ajc$perSingletonInstance;
*/
// body starts here (see end of each line for what it is doing!)
FieldBinding fb = world.makeFieldBinding(AjcMemberMaker.perSingletonField(typeX));
codeStream.getstatic(fb); // GETSTATIC
Label isNonNull = new Label(codeStream);
codeStream.ifnonnull(isNonNull); // IFNONNULL
codeStream.new_(world.makeTypeBinding(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION)); // NEW
codeStream.dup(); // DUP
codeStream.ldc(typeX.getNameAsIdentifier()); // LDC
codeStream.getstatic(initFailureField); // GETSTATIC
codeStream.invokespecial(world.makeMethodBindingForCall(
AjcMemberMaker.noAspectBoundExceptionInitWithCause())); // INVOKESPECIAL
codeStream.athrow(); // ATHROW
isNonNull.place();
codeStream.getstatic(fb); // GETSTATIC
codeStream.areturn(); // ARETURN
// body ends here
}});
}
private void generatePerSingletonHasAspectMethod(ClassFile classFile) {
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, hasAspectMethod, new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
codeStream.getstatic(world.makeFieldBinding(AjcMemberMaker.perSingletonField(
typeX)));
Label isNull = new Label(codeStream);
codeStream.ifnull(isNull);
codeStream.iconst_1();
codeStream.ireturn();
isNull.place();
codeStream.iconst_0();
codeStream.ireturn();
// body ends here
}});
}
private void generatePerSingletonAjcClinitMethod(
ClassFile classFile)
{
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, world.makeMethodBinding(AjcMemberMaker.ajcPostClinitMethod(
world.fromBinding(binding))),
new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
codeStream.new_(binding);
codeStream.dup();
codeStream.invokespecial(
new MethodBinding(0, "<init>".toCharArray(),
BaseTypes.VoidBinding, new TypeBinding[0],
new ReferenceBinding[0], binding));
codeStream.putstatic(
world.makeFieldBinding(
AjcMemberMaker.perSingletonField(
typeX)));
codeStream.return_();
// body ends here
}});
}
private void generateSuperAccessMethod(ClassFile classFile, final MethodBinding accessMethod, final ResolvedMember method) {
generateMethod(classFile, accessMethod,
new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
codeStream.aload_0();
AstUtil.generateParameterLoads(accessMethod.parameters, codeStream);
codeStream.invokespecial(
factory.makeMethodBinding(method));
AstUtil.generateReturn(accessMethod.returnType, codeStream);
// body ends here
}});
}
private void generateInlineAccessMethod(ClassFile classFile, final Binding binding, final ResolvedMember member) {
if (binding instanceof InlineAccessFieldBinding) {
generateInlineAccessors(classFile, (InlineAccessFieldBinding)binding, member);
} else {
generateInlineAccessMethod(classFile, (MethodBinding)binding, member);
}
}
private void generateInlineAccessors(ClassFile classFile, final InlineAccessFieldBinding accessField, final ResolvedMember field) {
final FieldBinding fieldBinding = factory.makeFieldBinding(field);
generateMethod(classFile, accessField.reader,
makeEffectiveSignatureAttribute(field,Shadow.FieldGet,false),
new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
if (field.isStatic()) {
codeStream.getstatic(fieldBinding);
} else {
codeStream.aload_0();
codeStream.getfield(fieldBinding);
}
AstUtil.generateReturn(accessField.reader.returnType, codeStream);
// body ends here
}});
generateMethod(classFile, accessField.writer,
makeEffectiveSignatureAttribute(field,Shadow.FieldSet,false),
new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
if (field.isStatic()) {
codeStream.load(fieldBinding.type, 0);
codeStream.putstatic(fieldBinding);
} else {
codeStream.aload_0();
codeStream.load(fieldBinding.type, 1);
codeStream.putfield(fieldBinding);
}
codeStream.return_();
// body ends here
}});
}
private void generateInlineAccessMethod(ClassFile classFile, final MethodBinding accessMethod, final ResolvedMember method) {
generateMethod(classFile, accessMethod,
makeEffectiveSignatureAttribute(method, Shadow.MethodCall, false),
new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
AstUtil.generateParameterLoads(accessMethod.parameters, codeStream);
if (method.isStatic()) {
codeStream.invokestatic(factory.makeMethodBinding(method));
} else {
codeStream.invokevirtual(factory.makeMethodBinding(method));
}
AstUtil.generateReturn(accessMethod.returnType, codeStream);
// body ends here
}});
}
private PerClause.Kind lookupPerClauseKind(ReferenceBinding binding) {
PerClause perClause;
if (binding instanceof BinaryTypeBinding) {
ResolvedType superTypeX = factory.fromEclipse(binding);
perClause = superTypeX.getPerClause();
} else if (binding instanceof SourceTypeBinding ) {
SourceTypeBinding sourceSc = (SourceTypeBinding)binding;
if (sourceSc.scope.referenceContext instanceof AspectDeclaration) {
perClause = ((AspectDeclaration)sourceSc.scope.referenceContext).perClause;
} else {
return null;
}
} else {
//XXX need to handle this too
return null;
}
if (perClause == null) {
return lookupPerClauseKind(binding.superclass());
} else {
return perClause.getKind();
}
}
private void buildPerClause(ClassScope scope) {
EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(scope);
if (perClause == null) {
PerClause.Kind kind = lookupPerClauseKind(binding.superclass);
if (kind == null) {
perClause = new PerSingleton();
} else {
perClause = new PerFromSuper(kind);
}
}
aspectAttribute = new AjAttribute.Aspect(perClause);
if (ignoreFurtherInvestigation) return; //???
if (!isAbstract()) {
if (perClause.getKind() == PerClause.SINGLETON) {
aspectOfMethod = AjcMemberMaker.perSingletonAspectOfMethod(typeX);
hasAspectMethod = AjcMemberMaker.perSingletonHasAspectMethod(typeX);
} else if (perClause.getKind() == PerClause.PERCFLOW) {
aspectOfMethod = AjcMemberMaker.perCflowAspectOfMethod(typeX);
hasAspectMethod = AjcMemberMaker.perCflowHasAspectMethod(typeX);
} else if (perClause.getKind() == PerClause.PEROBJECT) {
aspectOfMethod = AjcMemberMaker.perObjectAspectOfMethod(typeX);
hasAspectMethod = AjcMemberMaker.perObjectHasAspectMethod(typeX);
} else if (perClause.getKind() == PerClause.PERTYPEWITHIN) {
// PTWIMPL Use these variants of aspectOf()/hasAspect()
aspectOfMethod = AjcMemberMaker.perTypeWithinAspectOfMethod(typeX);
hasAspectMethod = AjcMemberMaker.perTypeWithinHasAspectMethod(typeX);
} else {
throw new RuntimeException("bad per clause: " + perClause);
}
binding.addMethod(world.makeMethodBinding(aspectOfMethod));
binding.addMethod(world.makeMethodBinding(hasAspectMethod));
}
resolvePerClause(); //XXX might be too soon for some error checking
}
private PerClause resolvePerClause() {
EclipseScope iscope = new EclipseScope(new FormalBinding[0], scope);
perClause.resolve(iscope);
return perClause;
}
public void buildInterTypeAndPerClause(ClassScope classScope) {
factory = EclipseFactory.fromScopeLookupEnvironment(scope);
if (isPrivileged) {
binding.privilegedHandler = new PrivilegedHandler(this);
}
checkSpec(classScope);
if (ignoreFurtherInvestigation) return;
buildPerClause(scope);
if (methods != null) {
for (int i = 0; i < methods.length; i++) {
if (methods[i] instanceof InterTypeDeclaration) {
EclipseTypeMunger m = ((InterTypeDeclaration)methods[i]).build(classScope);
if (m != null) concreteName.typeMungers.add(m);
} else if (methods[i] instanceof DeclareDeclaration) {
Declare d = ((DeclareDeclaration)methods[i]).build(classScope);
if (d != null) concreteName.declares.add(d);
}
}
}
concreteName.getDeclaredPointcuts();
}
// public String toString(int tab) {
// return tabString(tab) + toStringHeader() + toStringBody(tab);
// }
//
// public String toStringBody(int tab) {
//
// String s = " {"; //$NON-NLS-1$
//
//
// if (memberTypes != null) {
// for (int i = 0; i < memberTypes.length; i++) {
// if (memberTypes[i] != null) {
// s += "\n" + memberTypes[i].toString(tab + 1); //$NON-NLS-1$
// }
// }
// }
// if (fields != null) {
// for (int fieldI = 0; fieldI < fields.length; fieldI++) {
// if (fields[fieldI] != null) {
// s += "\n" + fields[fieldI].toString(tab + 1); //$NON-NLS-1$
// if (fields[fieldI].isField())
// s += ";"; //$NON-NLS-1$
// }
// }
// }
// if (methods != null) {
// for (int i = 0; i < methods.length; i++) {
// if (methods[i] != null) {
// s += "\n" + methods[i].toString(tab + 1); //$NON-NLS-1$
// }
// }
// }
// s += "\n" + tabString(tab) + "}"; //$NON-NLS-2$ //$NON-NLS-1$
// return s;
// }
public StringBuffer printHeader(int indent, StringBuffer output) {
printModifiers(this.modifiers, output);
output.append("aspect " );
output.append(name);
if (superclass != null) {
output.append(" extends "); //$NON-NLS-1$
superclass.print(0, output);
}
if (superInterfaces != null && superInterfaces.length > 0) {
output.append((kind() == IGenericType.INTERFACE_DECL) ? " extends " : " implements ");//$NON-NLS-2$ //$NON-NLS-1$
for (int i = 0; i < superInterfaces.length; i++) {
if (i > 0) output.append( ", "); //$NON-NLS-1$
superInterfaces[i].print(0, output);
}
}
return output;
//XXX we should append the per-clause
}
}
| true | true | private void generatePerSupportMembers(ClassFile classFile) {
if (isAbstract()) return;
//XXX otherwise we need to have this (error handling?)
if (aspectOfMethod == null) return;
if (perClause == null) {
System.err.println("has null perClause: " + this);
return;
}
EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
if (perClause.getKind() == PerClause.SINGLETON) {
generatePerSingletonAspectOfMethod(classFile);
generatePerSingletonHasAspectMethod(classFile);
generatePerSingletonAjcClinitMethod(classFile);
} else if (perClause.getKind() == PerClause.PERCFLOW) {
generatePerCflowAspectOfMethod(classFile);
generatePerCflowHasAspectMethod(classFile);
generatePerCflowPushMethod(classFile);
generatePerCflowAjcClinitMethod(classFile);
} else if (perClause.getKind() == PerClause.PEROBJECT) {
TypeBinding interfaceType =
generatePerObjectInterface(classFile);
world.addTypeBinding(interfaceType);
generatePerObjectAspectOfMethod(classFile, interfaceType);
generatePerObjectHasAspectMethod(classFile, interfaceType);
generatePerObjectBindMethod(classFile, interfaceType);
} else if (perClause.getKind() == PerClause.PERTYPEWITHIN) {
//PTWIMPL Generate the methods required *in the aspect*
generatePerTypeWithinAspectOfMethod(classFile); // public static <aspecttype> aspectOf(java.lang.Class)
generatePerTypeWithinGetInstanceMethod(classFile); // private static <aspecttype> ajc$getInstance(Class c) throws Exception
generatePerTypeWithinHasAspectMethod(classFile);
generatePerTypeWithinCreateAspectInstanceMethod(classFile); // generate public static X ajc$createAspectInstance(Class forClass) {
// PTWIMPL getWithinType() would need this...
// generatePerTypeWithinGetWithinTypeMethod(classFile); // generate public Class getWithinType() {
} else {
throw new RuntimeException("unimplemented");
}
}
private static interface BodyGenerator {
public void generate(CodeStream codeStream);
}
private void generateMethod(ClassFile classFile, ResolvedMember member, BodyGenerator gen) {
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, world.makeMethodBinding(member), gen);
}
private void generateMethod(ClassFile classFile, MethodBinding methodBinding, BodyGenerator gen) {
generateMethod(classFile,methodBinding,null,gen);
}
protected List makeEffectiveSignatureAttribute(ResolvedMember sig,Shadow.Kind kind,boolean weaveBody) {
List l = new ArrayList(1);
l.add(new EclipseAttributeAdapter(
new AjAttribute.EffectiveSignatureAttribute(sig, kind, weaveBody)));
return l;
}
/*
* additionalAttributes allows us to pass some optional attributes we want to attach to the method we generate.
* Currently this is used for inline accessor methods that have been generated to allow private field references or
* private method calls to be inlined (PR71377). In these cases the optional attribute is an effective signature
* attribute which means calls to these methods are able to masquerade as any join point (a field set, field get or
* method call). The effective signature attribute is 'unwrapped' in BcelClassWeaver.matchInvokeInstruction()
*/
private void generateMethod(ClassFile classFile, MethodBinding methodBinding, List additionalAttributes/*ResolvedMember realMember*/, BodyGenerator gen) {
// EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
classFile.generateMethodInfoHeader(methodBinding);
int methodAttributeOffset = classFile.contentsOffset;
int attributeNumber;
if (additionalAttributes!=null) { // mini optimization
List attrs = new ArrayList();
attrs.addAll(AstUtil.getAjSyntheticAttribute());
attrs.addAll(additionalAttributes);
attributeNumber = classFile.generateMethodInfoAttribute(methodBinding, false, attrs);
} else {
attributeNumber = classFile.generateMethodInfoAttribute(methodBinding, false, AstUtil.getAjSyntheticAttribute());
}
int codeAttributeOffset = classFile.contentsOffset;
classFile.generateCodeAttributeHeader();
CodeStream codeStream = classFile.codeStream;
// Use reset() rather than init()
// XXX We need a scope to keep reset happy, initializerScope is *not* the right one, but it works !
// codeStream.init(classFile);
// codeStream.initializeMaxLocals(methodBinding);
MethodDeclaration md = AstUtil.makeMethodDeclaration(methodBinding);
md.scope = initializerScope;
codeStream.reset(md,classFile);
// body starts here
gen.generate(codeStream);
// body ends here
classFile.completeCodeAttribute(codeAttributeOffset);
attributeNumber++;
classFile.completeMethodInfo(methodAttributeOffset, attributeNumber);
}
private void generatePerCflowAspectOfMethod(
ClassFile classFile)
{
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, aspectOfMethod, new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
codeStream.getstatic(
world.makeFieldBinding(
AjcMemberMaker.perCflowField(
typeX)));
codeStream.invokevirtual(world.makeMethodBindingForCall(
AjcMemberMaker.cflowStackPeekInstance()));
codeStream.checkcast(binding);
codeStream.areturn();
// body ends here
}});
}
private void generatePerCflowHasAspectMethod(ClassFile classFile) {
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, hasAspectMethod, new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
codeStream.getstatic(
world.makeFieldBinding(
AjcMemberMaker.perCflowField(
typeX)));
codeStream.invokevirtual(world.makeMethodBindingForCall(
AjcMemberMaker.cflowStackIsValid()));
codeStream.ireturn();
// body ends here
}});
}
private void generatePerCflowPushMethod(
ClassFile classFile)
{
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, world.makeMethodBinding(AjcMemberMaker.perCflowPush(
factory.fromBinding(binding))),
new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
codeStream.getstatic(
world.makeFieldBinding(
AjcMemberMaker.perCflowField(
typeX)));
codeStream.new_(binding);
codeStream.dup();
codeStream.invokespecial(
new MethodBinding(0, "<init>".toCharArray(),
BaseTypes.VoidBinding, new TypeBinding[0],
new ReferenceBinding[0], binding));
codeStream.invokevirtual(world.makeMethodBindingForCall(
AjcMemberMaker.cflowStackPushInstance()));
codeStream.return_();
// body ends here
}});
}
private void generatePerCflowAjcClinitMethod(
ClassFile classFile)
{
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, world.makeMethodBinding(AjcMemberMaker.ajcPreClinitMethod(
world.fromBinding(binding))),
new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
codeStream.new_(world.makeTypeBinding(AjcMemberMaker.CFLOW_STACK_TYPE));
codeStream.dup();
codeStream.invokespecial(world.makeMethodBindingForCall(AjcMemberMaker.cflowStackInit()));
codeStream.putstatic(
world.makeFieldBinding(
AjcMemberMaker.perCflowField(
typeX)));
codeStream.return_();
// body ends here
}});
}
private TypeBinding generatePerObjectInterface(
ClassFile classFile)
{
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
UnresolvedType interfaceTypeX =
AjcMemberMaker.perObjectInterfaceType(typeX);
HelperInterfaceBinding interfaceType =
new HelperInterfaceBinding(this.binding, interfaceTypeX);
world.addTypeBinding(interfaceType);
interfaceType.addMethod(world, AjcMemberMaker.perObjectInterfaceGet(typeX));
interfaceType.addMethod(world, AjcMemberMaker.perObjectInterfaceSet(typeX));
interfaceType.generateClass(compilationResult, classFile);
return interfaceType;
}
// PTWIMPL Generate aspectOf() method
private void generatePerTypeWithinAspectOfMethod(ClassFile classFile) {
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, aspectOfMethod, new BodyGenerator() {
public void generate(CodeStream codeStream) {
Label instanceFound = new Label(codeStream);
ExceptionLabel anythingGoesWrong = new ExceptionLabel(codeStream,world.makeTypeBinding(UnresolvedType.JAVA_LANG_EXCEPTION));
codeStream.aload_0();
codeStream.invokestatic(world.makeMethodBindingForCall(AjcMemberMaker.perTypeWithinGetInstance(typeX)));
codeStream.astore_1();
codeStream.aload_1();
codeStream.ifnonnull(instanceFound);
codeStream.new_(world.makeTypeBinding(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION));
codeStream.dup();
codeStream.ldc(typeX.getName());
codeStream.aconst_null();
codeStream.invokespecial(world.makeMethodBindingForCall(AjcMemberMaker.noAspectBoundExceptionInit2()));
codeStream.athrow();
instanceFound.place();
codeStream.aload_1();
codeStream.areturn();
anythingGoesWrong.placeEnd();
anythingGoesWrong.place();
codeStream.astore_1();
codeStream.new_(world.makeTypeBinding(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION));
codeStream.dup();
// Run the simple ctor for NABE
codeStream.invokespecial(world.makeMethodBindingForCall(AjcMemberMaker.noAspectBoundExceptionInit()));
codeStream.athrow();
}});
}
private void generatePerObjectAspectOfMethod(
ClassFile classFile,
final TypeBinding interfaceType)
{
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, aspectOfMethod, new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
Label wrongType = new Label(codeStream);
Label popWrongType = new Label(codeStream);
codeStream.aload_0();
codeStream.instance_of(interfaceType);
codeStream.ifeq(wrongType);
codeStream.aload_0();
codeStream.checkcast(interfaceType);
codeStream.invokeinterface(world.makeMethodBindingForCall(
AjcMemberMaker.perObjectInterfaceGet(typeX)));
codeStream.dup();
codeStream.ifnull(popWrongType);
codeStream.areturn();
popWrongType.place();
codeStream.pop();
wrongType.place();
codeStream.new_(world.makeTypeBinding(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION));
codeStream.dup();
codeStream.invokespecial(world.makeMethodBindingForCall(
AjcMemberMaker.noAspectBoundExceptionInit()
));
codeStream.athrow();
// body ends here
}});
}
private void generatePerObjectHasAspectMethod(ClassFile classFile,
final TypeBinding interfaceType) {
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, hasAspectMethod, new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
Label wrongType = new Label(codeStream);
codeStream.aload_0();
codeStream.instance_of(interfaceType);
codeStream.ifeq(wrongType);
codeStream.aload_0();
codeStream.checkcast(interfaceType);
codeStream.invokeinterface(world.makeMethodBindingForCall(
AjcMemberMaker.perObjectInterfaceGet(typeX)));
codeStream.ifnull(wrongType);
codeStream.iconst_1();
codeStream.ireturn();
wrongType.place();
codeStream.iconst_0();
codeStream.ireturn();
// body ends here
}});
}
// PTWIMPL Generate hasAspect() method
private void generatePerTypeWithinHasAspectMethod(ClassFile classFile) {
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, hasAspectMethod, new BodyGenerator() {
public void generate(CodeStream codeStream) {
ExceptionLabel goneBang = new ExceptionLabel(codeStream,world.makeTypeBinding(UnresolvedType.JAVA_LANG_EXCEPTION));
Label noInstanceExists = new Label(codeStream);
Label leave = new Label(codeStream);
goneBang.placeStart();
codeStream.aload_0();
codeStream.invokestatic(world.makeMethodBinding(AjcMemberMaker.perTypeWithinGetInstance(typeX)));
codeStream.ifnull(noInstanceExists);
codeStream.iconst_1();
codeStream.goto_(leave);
noInstanceExists.place();
codeStream.iconst_0();
leave.place();
goneBang.placeEnd();
codeStream.ireturn();
goneBang.place();
codeStream.astore_1();
codeStream.iconst_0();
codeStream.ireturn();
}});
}
private void generatePerObjectBindMethod(
ClassFile classFile,
final TypeBinding interfaceType)
{
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, AjcMemberMaker.perObjectBind(world.fromBinding(binding)),
new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
Label wrongType = new Label(codeStream);
codeStream.aload_0();
codeStream.instance_of(interfaceType);
codeStream.ifeq(wrongType); //XXX this case might call for screaming
codeStream.aload_0();
codeStream.checkcast(interfaceType);
codeStream.invokeinterface(world.makeMethodBindingForCall(
AjcMemberMaker.perObjectInterfaceGet(typeX)));
//XXX should do a check for null here and throw a NoAspectBound
codeStream.ifnonnull(wrongType);
codeStream.aload_0();
codeStream.checkcast(interfaceType);
codeStream.new_(binding);
codeStream.dup();
codeStream.invokespecial(
new MethodBinding(0, "<init>".toCharArray(),
BaseTypes.VoidBinding, new TypeBinding[0],
new ReferenceBinding[0], binding));
codeStream.invokeinterface(world.makeMethodBindingForCall(
AjcMemberMaker.perObjectInterfaceSet(typeX)));
wrongType.place();
codeStream.return_();
// body ends here
}});
}
// PTWIMPL Generate getInstance method
private void generatePerTypeWithinGetInstanceMethod(ClassFile classFile) {
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, AjcMemberMaker.perTypeWithinGetInstance(world.fromBinding(binding)),
new BodyGenerator() {
public void generate(CodeStream codeStream) {
ExceptionLabel exc = new ExceptionLabel(codeStream,world.makeTypeBinding(UnresolvedType.JAVA_LANG_EXCEPTION));
exc.placeStart();
codeStream.aload_0();
codeStream.ldc(NameMangler.perTypeWithinLocalAspectOf(typeX));
codeStream.aconst_null();
codeStream.invokevirtual(
new MethodBinding(
0,
"getDeclaredMethod".toCharArray(),
world.makeTypeBinding(UnresolvedType.forSignature("Ljava/lang/reflect/Method;")), // return type
new TypeBinding[]{world.makeTypeBinding(UnresolvedType.forSignature("Ljava/lang/String;")),
world.makeTypeBinding(UnresolvedType.forSignature("[Ljava/lang/Class;"))},
new ReferenceBinding[0],
(ReferenceBinding)world.makeTypeBinding(UnresolvedType.JAVA_LANG_CLASS)));
codeStream.astore_1();
codeStream.aload_1();
codeStream.aconst_null();
codeStream.aconst_null();
codeStream.invokevirtual(
new MethodBinding(
0,
"invoke".toCharArray(),
world.makeTypeBinding(UnresolvedType.OBJECT),
new TypeBinding[]{world.makeTypeBinding(UnresolvedType.OBJECT),world.makeTypeBinding(UnresolvedType.forSignature("[Ljava/lang/Object;"))},
new ReferenceBinding[0],
(ReferenceBinding)world.makeTypeBinding(UnresolvedType.JAVA_LANG_REFLECT_METHOD)));
codeStream.checkcast(world.makeTypeBinding(typeX));
codeStream.astore_2();
codeStream.aload_2();
exc.placeEnd();
codeStream.areturn();
exc.place();
// this just returns null now - the old version used to throw the caught exception!
codeStream.aconst_null();
codeStream.areturn();
}});
}
private void generatePerTypeWithinCreateAspectInstanceMethod(ClassFile classFile) {
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, AjcMemberMaker.perTypeWithinCreateAspectInstance(world.fromBinding(binding)),
new BodyGenerator() {
public void generate(CodeStream codeStream) {
codeStream.new_(world.makeTypeBinding(typeX));
codeStream.dup();
codeStream.invokespecial(new MethodBinding(0, "<init>".toCharArray(),
BaseTypes.VoidBinding, new TypeBinding[0],
new ReferenceBinding[0], binding));
codeStream.astore_1();
codeStream.aload_1();
codeStream.aload_0();
codeStream.putfield(world.makeFieldBinding(AjcMemberMaker.perTypeWithinWithinTypeField(typeX,typeX)));
codeStream.aload_1();
codeStream.areturn();
}});
}
private void generatePerSingletonAspectOfMethod(ClassFile classFile) {
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, aspectOfMethod, new BodyGenerator() {
public void generate(CodeStream codeStream) {
// Old style aspectOf() method which confused decompilers
// // body starts here
// codeStream.getstatic(world.makeFieldBinding(AjcMemberMaker.perSingletonField(
// typeX)));
// Label isNull = new Label(codeStream);
// codeStream.dup();
// codeStream.ifnull(isNull);
// codeStream.areturn();
// isNull.place();
//
// codeStream.incrStackSize(+1); // the dup trick above confuses the stack counter
// codeStream.new_(world.makeTypeBinding(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION));
// codeStream.dup();
// codeStream.ldc(typeX.getNameAsIdentifier());
// codeStream.getstatic(initFailureField);
// codeStream.invokespecial(world.makeMethodBindingForCall(
// AjcMemberMaker.noAspectBoundExceptionInitWithCause()
// ));
// codeStream.athrow();
// // body ends here
// The stuff below generates code that looks like this:
/*
* if (ajc$perSingletonInstance == null)
* throw new NoAspectBoundException("A", ajc$initFailureCause);
* else
* return ajc$perSingletonInstance;
*/
// body starts here (see end of each line for what it is doing!)
FieldBinding fb = world.makeFieldBinding(AjcMemberMaker.perSingletonField(typeX));
codeStream.getstatic(fb); // GETSTATIC
Label isNonNull = new Label(codeStream);
codeStream.ifnonnull(isNonNull); // IFNONNULL
codeStream.new_(world.makeTypeBinding(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION)); // NEW
codeStream.dup(); // DUP
codeStream.ldc(typeX.getNameAsIdentifier()); // LDC
codeStream.getstatic(initFailureField); // GETSTATIC
codeStream.invokespecial(world.makeMethodBindingForCall(
AjcMemberMaker.noAspectBoundExceptionInitWithCause())); // INVOKESPECIAL
codeStream.athrow(); // ATHROW
isNonNull.place();
codeStream.getstatic(fb); // GETSTATIC
codeStream.areturn(); // ARETURN
// body ends here
}});
}
private void generatePerSingletonHasAspectMethod(ClassFile classFile) {
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, hasAspectMethod, new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
codeStream.getstatic(world.makeFieldBinding(AjcMemberMaker.perSingletonField(
typeX)));
Label isNull = new Label(codeStream);
codeStream.ifnull(isNull);
codeStream.iconst_1();
codeStream.ireturn();
isNull.place();
codeStream.iconst_0();
codeStream.ireturn();
// body ends here
}});
}
private void generatePerSingletonAjcClinitMethod(
ClassFile classFile)
{
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, world.makeMethodBinding(AjcMemberMaker.ajcPostClinitMethod(
world.fromBinding(binding))),
new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
codeStream.new_(binding);
codeStream.dup();
codeStream.invokespecial(
new MethodBinding(0, "<init>".toCharArray(),
BaseTypes.VoidBinding, new TypeBinding[0],
new ReferenceBinding[0], binding));
codeStream.putstatic(
world.makeFieldBinding(
AjcMemberMaker.perSingletonField(
typeX)));
codeStream.return_();
// body ends here
}});
}
private void generateSuperAccessMethod(ClassFile classFile, final MethodBinding accessMethod, final ResolvedMember method) {
generateMethod(classFile, accessMethod,
new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
codeStream.aload_0();
AstUtil.generateParameterLoads(accessMethod.parameters, codeStream);
codeStream.invokespecial(
factory.makeMethodBinding(method));
AstUtil.generateReturn(accessMethod.returnType, codeStream);
// body ends here
}});
}
private void generateInlineAccessMethod(ClassFile classFile, final Binding binding, final ResolvedMember member) {
if (binding instanceof InlineAccessFieldBinding) {
generateInlineAccessors(classFile, (InlineAccessFieldBinding)binding, member);
} else {
generateInlineAccessMethod(classFile, (MethodBinding)binding, member);
}
}
private void generateInlineAccessors(ClassFile classFile, final InlineAccessFieldBinding accessField, final ResolvedMember field) {
final FieldBinding fieldBinding = factory.makeFieldBinding(field);
generateMethod(classFile, accessField.reader,
makeEffectiveSignatureAttribute(field,Shadow.FieldGet,false),
new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
if (field.isStatic()) {
codeStream.getstatic(fieldBinding);
} else {
codeStream.aload_0();
codeStream.getfield(fieldBinding);
}
AstUtil.generateReturn(accessField.reader.returnType, codeStream);
// body ends here
}});
generateMethod(classFile, accessField.writer,
makeEffectiveSignatureAttribute(field,Shadow.FieldSet,false),
new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
if (field.isStatic()) {
codeStream.load(fieldBinding.type, 0);
codeStream.putstatic(fieldBinding);
} else {
codeStream.aload_0();
codeStream.load(fieldBinding.type, 1);
codeStream.putfield(fieldBinding);
}
codeStream.return_();
// body ends here
}});
}
private void generateInlineAccessMethod(ClassFile classFile, final MethodBinding accessMethod, final ResolvedMember method) {
generateMethod(classFile, accessMethod,
makeEffectiveSignatureAttribute(method, Shadow.MethodCall, false),
new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
AstUtil.generateParameterLoads(accessMethod.parameters, codeStream);
if (method.isStatic()) {
codeStream.invokestatic(factory.makeMethodBinding(method));
} else {
codeStream.invokevirtual(factory.makeMethodBinding(method));
}
AstUtil.generateReturn(accessMethod.returnType, codeStream);
// body ends here
}});
}
private PerClause.Kind lookupPerClauseKind(ReferenceBinding binding) {
PerClause perClause;
if (binding instanceof BinaryTypeBinding) {
ResolvedType superTypeX = factory.fromEclipse(binding);
perClause = superTypeX.getPerClause();
} else if (binding instanceof SourceTypeBinding ) {
SourceTypeBinding sourceSc = (SourceTypeBinding)binding;
if (sourceSc.scope.referenceContext instanceof AspectDeclaration) {
perClause = ((AspectDeclaration)sourceSc.scope.referenceContext).perClause;
} else {
return null;
}
} else {
//XXX need to handle this too
return null;
}
if (perClause == null) {
return lookupPerClauseKind(binding.superclass());
} else {
return perClause.getKind();
}
}
private void buildPerClause(ClassScope scope) {
EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(scope);
if (perClause == null) {
PerClause.Kind kind = lookupPerClauseKind(binding.superclass);
if (kind == null) {
perClause = new PerSingleton();
} else {
perClause = new PerFromSuper(kind);
}
}
aspectAttribute = new AjAttribute.Aspect(perClause);
if (ignoreFurtherInvestigation) return; //???
if (!isAbstract()) {
if (perClause.getKind() == PerClause.SINGLETON) {
aspectOfMethod = AjcMemberMaker.perSingletonAspectOfMethod(typeX);
hasAspectMethod = AjcMemberMaker.perSingletonHasAspectMethod(typeX);
} else if (perClause.getKind() == PerClause.PERCFLOW) {
aspectOfMethod = AjcMemberMaker.perCflowAspectOfMethod(typeX);
hasAspectMethod = AjcMemberMaker.perCflowHasAspectMethod(typeX);
} else if (perClause.getKind() == PerClause.PEROBJECT) {
aspectOfMethod = AjcMemberMaker.perObjectAspectOfMethod(typeX);
hasAspectMethod = AjcMemberMaker.perObjectHasAspectMethod(typeX);
} else if (perClause.getKind() == PerClause.PERTYPEWITHIN) {
// PTWIMPL Use these variants of aspectOf()/hasAspect()
aspectOfMethod = AjcMemberMaker.perTypeWithinAspectOfMethod(typeX);
hasAspectMethod = AjcMemberMaker.perTypeWithinHasAspectMethod(typeX);
} else {
throw new RuntimeException("bad per clause: " + perClause);
}
binding.addMethod(world.makeMethodBinding(aspectOfMethod));
binding.addMethod(world.makeMethodBinding(hasAspectMethod));
}
resolvePerClause(); //XXX might be too soon for some error checking
}
private PerClause resolvePerClause() {
EclipseScope iscope = new EclipseScope(new FormalBinding[0], scope);
perClause.resolve(iscope);
return perClause;
}
public void buildInterTypeAndPerClause(ClassScope classScope) {
factory = EclipseFactory.fromScopeLookupEnvironment(scope);
if (isPrivileged) {
binding.privilegedHandler = new PrivilegedHandler(this);
}
checkSpec(classScope);
if (ignoreFurtherInvestigation) return;
buildPerClause(scope);
if (methods != null) {
for (int i = 0; i < methods.length; i++) {
if (methods[i] instanceof InterTypeDeclaration) {
EclipseTypeMunger m = ((InterTypeDeclaration)methods[i]).build(classScope);
if (m != null) concreteName.typeMungers.add(m);
} else if (methods[i] instanceof DeclareDeclaration) {
Declare d = ((DeclareDeclaration)methods[i]).build(classScope);
if (d != null) concreteName.declares.add(d);
}
}
}
concreteName.getDeclaredPointcuts();
}
// public String toString(int tab) {
// return tabString(tab) + toStringHeader() + toStringBody(tab);
// }
//
// public String toStringBody(int tab) {
//
// String s = " {"; //$NON-NLS-1$
//
//
// if (memberTypes != null) {
// for (int i = 0; i < memberTypes.length; i++) {
// if (memberTypes[i] != null) {
// s += "\n" + memberTypes[i].toString(tab + 1); //$NON-NLS-1$
// }
// }
// }
// if (fields != null) {
// for (int fieldI = 0; fieldI < fields.length; fieldI++) {
// if (fields[fieldI] != null) {
// s += "\n" + fields[fieldI].toString(tab + 1); //$NON-NLS-1$
// if (fields[fieldI].isField())
// s += ";"; //$NON-NLS-1$
// }
// }
// }
// if (methods != null) {
// for (int i = 0; i < methods.length; i++) {
// if (methods[i] != null) {
// s += "\n" + methods[i].toString(tab + 1); //$NON-NLS-1$
// }
// }
// }
// s += "\n" + tabString(tab) + "}"; //$NON-NLS-2$ //$NON-NLS-1$
// return s;
// }
public StringBuffer printHeader(int indent, StringBuffer output) {
printModifiers(this.modifiers, output);
output.append("aspect " );
output.append(name);
if (superclass != null) {
output.append(" extends "); //$NON-NLS-1$
superclass.print(0, output);
}
if (superInterfaces != null && superInterfaces.length > 0) {
output.append((kind() == IGenericType.INTERFACE_DECL) ? " extends " : " implements ");//$NON-NLS-2$ //$NON-NLS-1$
for (int i = 0; i < superInterfaces.length; i++) {
if (i > 0) output.append( ", "); //$NON-NLS-1$
superInterfaces[i].print(0, output);
}
}
return output;
//XXX we should append the per-clause
}
}
| private void generatePerSupportMembers(ClassFile classFile) {
if (isAbstract()) return;
//XXX otherwise we need to have this (error handling?)
if (aspectOfMethod == null) return;
if (perClause == null) {
System.err.println("has null perClause: " + this);
return;
}
EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
if (perClause.getKind() == PerClause.SINGLETON) {
generatePerSingletonAspectOfMethod(classFile);
generatePerSingletonHasAspectMethod(classFile);
generatePerSingletonAjcClinitMethod(classFile);
} else if (perClause.getKind() == PerClause.PERCFLOW) {
generatePerCflowAspectOfMethod(classFile);
generatePerCflowHasAspectMethod(classFile);
generatePerCflowPushMethod(classFile);
generatePerCflowAjcClinitMethod(classFile);
} else if (perClause.getKind() == PerClause.PEROBJECT) {
TypeBinding interfaceType =
generatePerObjectInterface(classFile);
world.addTypeBinding(interfaceType);
generatePerObjectAspectOfMethod(classFile, interfaceType);
generatePerObjectHasAspectMethod(classFile, interfaceType);
generatePerObjectBindMethod(classFile, interfaceType);
} else if (perClause.getKind() == PerClause.PERTYPEWITHIN) {
//PTWIMPL Generate the methods required *in the aspect*
generatePerTypeWithinAspectOfMethod(classFile); // public static <aspecttype> aspectOf(java.lang.Class)
generatePerTypeWithinGetInstanceMethod(classFile); // private static <aspecttype> ajc$getInstance(Class c) throws Exception
generatePerTypeWithinHasAspectMethod(classFile);
generatePerTypeWithinCreateAspectInstanceMethod(classFile); // generate public static X ajc$createAspectInstance(Class forClass) {
// PTWIMPL getWithinType() would need this...
// generatePerTypeWithinGetWithinTypeMethod(classFile); // generate public Class getWithinType() {
} else {
throw new RuntimeException("unimplemented");
}
}
private static interface BodyGenerator {
public void generate(CodeStream codeStream);
}
private void generateMethod(ClassFile classFile, ResolvedMember member, BodyGenerator gen) {
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, world.makeMethodBinding(member), gen);
}
private void generateMethod(ClassFile classFile, MethodBinding methodBinding, BodyGenerator gen) {
generateMethod(classFile,methodBinding,null,gen);
}
protected List makeEffectiveSignatureAttribute(ResolvedMember sig,Shadow.Kind kind,boolean weaveBody) {
List l = new ArrayList(1);
l.add(new EclipseAttributeAdapter(
new AjAttribute.EffectiveSignatureAttribute(sig, kind, weaveBody)));
return l;
}
/*
* additionalAttributes allows us to pass some optional attributes we want to attach to the method we generate.
* Currently this is used for inline accessor methods that have been generated to allow private field references or
* private method calls to be inlined (PR71377). In these cases the optional attribute is an effective signature
* attribute which means calls to these methods are able to masquerade as any join point (a field set, field get or
* method call). The effective signature attribute is 'unwrapped' in BcelClassWeaver.matchInvokeInstruction()
*/
private void generateMethod(ClassFile classFile, MethodBinding methodBinding, List additionalAttributes/*ResolvedMember realMember*/, BodyGenerator gen) {
// EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
classFile.generateMethodInfoHeader(methodBinding);
int methodAttributeOffset = classFile.contentsOffset;
int attributeNumber;
if (additionalAttributes!=null) { // mini optimization
List attrs = new ArrayList();
attrs.addAll(AstUtil.getAjSyntheticAttribute());
attrs.addAll(additionalAttributes);
attributeNumber = classFile.generateMethodInfoAttribute(methodBinding, false, attrs);
} else {
attributeNumber = classFile.generateMethodInfoAttribute(methodBinding, false, AstUtil.getAjSyntheticAttribute());
}
int codeAttributeOffset = classFile.contentsOffset;
classFile.generateCodeAttributeHeader();
CodeStream codeStream = classFile.codeStream;
// Use reset() rather than init()
// XXX We need a scope to keep reset happy, initializerScope is *not* the right one, but it works !
// codeStream.init(classFile);
// codeStream.initializeMaxLocals(methodBinding);
MethodDeclaration md = AstUtil.makeMethodDeclaration(methodBinding);
md.scope = initializerScope;
codeStream.reset(md,classFile);
// body starts here
gen.generate(codeStream);
// body ends here
classFile.completeCodeAttribute(codeAttributeOffset);
attributeNumber++;
classFile.completeMethodInfo(methodAttributeOffset, attributeNumber);
}
private void generatePerCflowAspectOfMethod(
ClassFile classFile)
{
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, aspectOfMethod, new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
codeStream.getstatic(
world.makeFieldBinding(
AjcMemberMaker.perCflowField(
typeX)));
codeStream.invokevirtual(world.makeMethodBindingForCall(
AjcMemberMaker.cflowStackPeekInstance()));
codeStream.checkcast(binding);
codeStream.areturn();
// body ends here
}});
}
private void generatePerCflowHasAspectMethod(ClassFile classFile) {
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, hasAspectMethod, new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
codeStream.getstatic(
world.makeFieldBinding(
AjcMemberMaker.perCflowField(
typeX)));
codeStream.invokevirtual(world.makeMethodBindingForCall(
AjcMemberMaker.cflowStackIsValid()));
codeStream.ireturn();
// body ends here
}});
}
private void generatePerCflowPushMethod(
ClassFile classFile)
{
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, world.makeMethodBinding(AjcMemberMaker.perCflowPush(
factory.fromBinding(binding))),
new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
codeStream.getstatic(
world.makeFieldBinding(
AjcMemberMaker.perCflowField(
typeX)));
codeStream.new_(binding);
codeStream.dup();
codeStream.invokespecial(
new MethodBinding(0, "<init>".toCharArray(),
BaseTypes.VoidBinding, new TypeBinding[0],
new ReferenceBinding[0], binding));
codeStream.invokevirtual(world.makeMethodBindingForCall(
AjcMemberMaker.cflowStackPushInstance()));
codeStream.return_();
// body ends here
}});
}
private void generatePerCflowAjcClinitMethod(
ClassFile classFile)
{
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, world.makeMethodBinding(AjcMemberMaker.ajcPreClinitMethod(
world.fromBinding(binding))),
new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
codeStream.new_(world.makeTypeBinding(AjcMemberMaker.CFLOW_STACK_TYPE));
codeStream.dup();
codeStream.invokespecial(world.makeMethodBindingForCall(AjcMemberMaker.cflowStackInit()));
codeStream.putstatic(
world.makeFieldBinding(
AjcMemberMaker.perCflowField(
typeX)));
codeStream.return_();
// body ends here
}});
}
private TypeBinding generatePerObjectInterface(
ClassFile classFile)
{
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
UnresolvedType interfaceTypeX =
AjcMemberMaker.perObjectInterfaceType(typeX);
HelperInterfaceBinding interfaceType =
new HelperInterfaceBinding(this.binding, interfaceTypeX);
world.addTypeBinding(interfaceType);
interfaceType.addMethod(world, AjcMemberMaker.perObjectInterfaceGet(typeX));
interfaceType.addMethod(world, AjcMemberMaker.perObjectInterfaceSet(typeX));
interfaceType.generateClass(compilationResult, classFile);
return interfaceType;
}
// PTWIMPL Generate aspectOf() method
private void generatePerTypeWithinAspectOfMethod(ClassFile classFile) {
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, aspectOfMethod, new BodyGenerator() {
public void generate(CodeStream codeStream) {
Label instanceFound = new Label(codeStream);
ExceptionLabel anythingGoesWrong = new ExceptionLabel(codeStream,world.makeTypeBinding(UnresolvedType.JAVA_LANG_EXCEPTION));
codeStream.aload_0();
codeStream.invokestatic(world.makeMethodBindingForCall(AjcMemberMaker.perTypeWithinGetInstance(typeX)));
codeStream.astore_1();
codeStream.aload_1();
codeStream.ifnonnull(instanceFound);
codeStream.new_(world.makeTypeBinding(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION));
codeStream.dup();
codeStream.ldc(typeX.getName());
codeStream.aconst_null();
codeStream.invokespecial(world.makeMethodBindingForCall(AjcMemberMaker.noAspectBoundExceptionInit2()));
codeStream.athrow();
instanceFound.place();
codeStream.aload_1();
codeStream.areturn();
anythingGoesWrong.placeEnd();
anythingGoesWrong.place();
codeStream.astore_1();
codeStream.new_(world.makeTypeBinding(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION));
codeStream.dup();
// Run the simple ctor for NABE
codeStream.invokespecial(world.makeMethodBindingForCall(AjcMemberMaker.noAspectBoundExceptionInit()));
codeStream.athrow();
}});
}
private void generatePerObjectAspectOfMethod(
ClassFile classFile,
final TypeBinding interfaceType)
{
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, aspectOfMethod, new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
Label wrongType = new Label(codeStream);
Label popWrongType = new Label(codeStream);
codeStream.aload_0();
codeStream.instance_of(interfaceType);
codeStream.ifeq(wrongType);
codeStream.aload_0();
codeStream.checkcast(interfaceType);
codeStream.invokeinterface(world.makeMethodBindingForCall(
AjcMemberMaker.perObjectInterfaceGet(typeX)));
codeStream.dup();
codeStream.ifnull(popWrongType);
codeStream.areturn();
popWrongType.place();
codeStream.pop();
wrongType.place();
codeStream.new_(world.makeTypeBinding(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION));
codeStream.dup();
codeStream.invokespecial(world.makeMethodBindingForCall(
AjcMemberMaker.noAspectBoundExceptionInit()
));
codeStream.athrow();
// body ends here
}});
}
private void generatePerObjectHasAspectMethod(ClassFile classFile,
final TypeBinding interfaceType) {
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, hasAspectMethod, new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
Label wrongType = new Label(codeStream);
codeStream.aload_0();
codeStream.instance_of(interfaceType);
codeStream.ifeq(wrongType);
codeStream.aload_0();
codeStream.checkcast(interfaceType);
codeStream.invokeinterface(world.makeMethodBindingForCall(
AjcMemberMaker.perObjectInterfaceGet(typeX)));
codeStream.ifnull(wrongType);
codeStream.iconst_1();
codeStream.ireturn();
wrongType.place();
codeStream.iconst_0();
codeStream.ireturn();
// body ends here
}});
}
// PTWIMPL Generate hasAspect() method
private void generatePerTypeWithinHasAspectMethod(ClassFile classFile) {
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, hasAspectMethod, new BodyGenerator() {
public void generate(CodeStream codeStream) {
ExceptionLabel goneBang = new ExceptionLabel(codeStream,world.makeTypeBinding(UnresolvedType.JAVA_LANG_EXCEPTION));
Label noInstanceExists = new Label(codeStream);
Label leave = new Label(codeStream);
goneBang.placeStart();
codeStream.aload_0();
codeStream.invokestatic(world.makeMethodBinding(AjcMemberMaker.perTypeWithinGetInstance(typeX)));
codeStream.ifnull(noInstanceExists);
codeStream.iconst_1();
codeStream.goto_(leave);
noInstanceExists.place();
codeStream.iconst_0();
leave.place();
goneBang.placeEnd();
codeStream.ireturn();
goneBang.place();
codeStream.astore_1();
codeStream.iconst_0();
codeStream.ireturn();
}});
}
private void generatePerObjectBindMethod(
ClassFile classFile,
final TypeBinding interfaceType)
{
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, AjcMemberMaker.perObjectBind(world.fromBinding(binding)),
new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
Label wrongType = new Label(codeStream);
codeStream.aload_0();
codeStream.instance_of(interfaceType);
codeStream.ifeq(wrongType); //XXX this case might call for screaming
codeStream.aload_0();
codeStream.checkcast(interfaceType);
codeStream.invokeinterface(world.makeMethodBindingForCall(
AjcMemberMaker.perObjectInterfaceGet(typeX)));
//XXX should do a check for null here and throw a NoAspectBound
codeStream.ifnonnull(wrongType);
codeStream.aload_0();
codeStream.checkcast(interfaceType);
codeStream.new_(binding);
codeStream.dup();
codeStream.invokespecial(
new MethodBinding(0, "<init>".toCharArray(),
BaseTypes.VoidBinding, new TypeBinding[0],
new ReferenceBinding[0], binding));
codeStream.invokeinterface(world.makeMethodBindingForCall(
AjcMemberMaker.perObjectInterfaceSet(typeX)));
wrongType.place();
codeStream.return_();
// body ends here
}});
}
// PTWIMPL Generate getInstance method
private void generatePerTypeWithinGetInstanceMethod(ClassFile classFile) {
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, AjcMemberMaker.perTypeWithinGetInstance(world.fromBinding(binding)),
new BodyGenerator() {
public void generate(CodeStream codeStream) {
ExceptionLabel exc = new ExceptionLabel(codeStream,world.makeTypeBinding(UnresolvedType.JAVA_LANG_EXCEPTION));
exc.placeStart();
codeStream.aload_0();
codeStream.ldc(NameMangler.perTypeWithinLocalAspectOf(typeX));
codeStream.aconst_null();
codeStream.invokevirtual(
new MethodBinding(
0,
"getDeclaredMethod".toCharArray(),
world.makeTypeBinding(UnresolvedType.forSignature("Ljava/lang/reflect/Method;")), // return type
new TypeBinding[]{world.makeTypeBinding(UnresolvedType.forSignature("Ljava/lang/String;")),
world.makeTypeBinding(UnresolvedType.forSignature("[Ljava/lang/Class;"))},
new ReferenceBinding[0],
(ReferenceBinding)world.makeTypeBinding(UnresolvedType.JAVA_LANG_CLASS)));
codeStream.astore_1();
codeStream.aload_1();
codeStream.aconst_null();
codeStream.aconst_null();
codeStream.invokevirtual(
new MethodBinding(
0,
"invoke".toCharArray(),
world.makeTypeBinding(UnresolvedType.OBJECT),
new TypeBinding[]{world.makeTypeBinding(UnresolvedType.OBJECT),world.makeTypeBinding(UnresolvedType.forSignature("[Ljava/lang/Object;"))},
new ReferenceBinding[0],
(ReferenceBinding)world.makeTypeBinding(UnresolvedType.JAVA_LANG_REFLECT_METHOD)));
codeStream.checkcast(world.makeTypeBinding(typeX));
codeStream.astore_2();
codeStream.aload_2();
exc.placeEnd();
codeStream.areturn();
exc.place();
codeStream.astore_1();
// this just returns null now - the old version used to throw the caught exception!
codeStream.aconst_null();
codeStream.areturn();
}});
}
private void generatePerTypeWithinCreateAspectInstanceMethod(ClassFile classFile) {
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, AjcMemberMaker.perTypeWithinCreateAspectInstance(world.fromBinding(binding)),
new BodyGenerator() {
public void generate(CodeStream codeStream) {
codeStream.new_(world.makeTypeBinding(typeX));
codeStream.dup();
codeStream.invokespecial(new MethodBinding(0, "<init>".toCharArray(),
BaseTypes.VoidBinding, new TypeBinding[0],
new ReferenceBinding[0], binding));
codeStream.astore_1();
codeStream.aload_1();
codeStream.aload_0();
codeStream.putfield(world.makeFieldBinding(AjcMemberMaker.perTypeWithinWithinTypeField(typeX,typeX)));
codeStream.aload_1();
codeStream.areturn();
}});
}
private void generatePerSingletonAspectOfMethod(ClassFile classFile) {
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, aspectOfMethod, new BodyGenerator() {
public void generate(CodeStream codeStream) {
// Old style aspectOf() method which confused decompilers
// // body starts here
// codeStream.getstatic(world.makeFieldBinding(AjcMemberMaker.perSingletonField(
// typeX)));
// Label isNull = new Label(codeStream);
// codeStream.dup();
// codeStream.ifnull(isNull);
// codeStream.areturn();
// isNull.place();
//
// codeStream.incrStackSize(+1); // the dup trick above confuses the stack counter
// codeStream.new_(world.makeTypeBinding(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION));
// codeStream.dup();
// codeStream.ldc(typeX.getNameAsIdentifier());
// codeStream.getstatic(initFailureField);
// codeStream.invokespecial(world.makeMethodBindingForCall(
// AjcMemberMaker.noAspectBoundExceptionInitWithCause()
// ));
// codeStream.athrow();
// // body ends here
// The stuff below generates code that looks like this:
/*
* if (ajc$perSingletonInstance == null)
* throw new NoAspectBoundException("A", ajc$initFailureCause);
* else
* return ajc$perSingletonInstance;
*/
// body starts here (see end of each line for what it is doing!)
FieldBinding fb = world.makeFieldBinding(AjcMemberMaker.perSingletonField(typeX));
codeStream.getstatic(fb); // GETSTATIC
Label isNonNull = new Label(codeStream);
codeStream.ifnonnull(isNonNull); // IFNONNULL
codeStream.new_(world.makeTypeBinding(AjcMemberMaker.NO_ASPECT_BOUND_EXCEPTION)); // NEW
codeStream.dup(); // DUP
codeStream.ldc(typeX.getNameAsIdentifier()); // LDC
codeStream.getstatic(initFailureField); // GETSTATIC
codeStream.invokespecial(world.makeMethodBindingForCall(
AjcMemberMaker.noAspectBoundExceptionInitWithCause())); // INVOKESPECIAL
codeStream.athrow(); // ATHROW
isNonNull.place();
codeStream.getstatic(fb); // GETSTATIC
codeStream.areturn(); // ARETURN
// body ends here
}});
}
private void generatePerSingletonHasAspectMethod(ClassFile classFile) {
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, hasAspectMethod, new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
codeStream.getstatic(world.makeFieldBinding(AjcMemberMaker.perSingletonField(
typeX)));
Label isNull = new Label(codeStream);
codeStream.ifnull(isNull);
codeStream.iconst_1();
codeStream.ireturn();
isNull.place();
codeStream.iconst_0();
codeStream.ireturn();
// body ends here
}});
}
private void generatePerSingletonAjcClinitMethod(
ClassFile classFile)
{
final EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(this.scope);
generateMethod(classFile, world.makeMethodBinding(AjcMemberMaker.ajcPostClinitMethod(
world.fromBinding(binding))),
new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
codeStream.new_(binding);
codeStream.dup();
codeStream.invokespecial(
new MethodBinding(0, "<init>".toCharArray(),
BaseTypes.VoidBinding, new TypeBinding[0],
new ReferenceBinding[0], binding));
codeStream.putstatic(
world.makeFieldBinding(
AjcMemberMaker.perSingletonField(
typeX)));
codeStream.return_();
// body ends here
}});
}
private void generateSuperAccessMethod(ClassFile classFile, final MethodBinding accessMethod, final ResolvedMember method) {
generateMethod(classFile, accessMethod,
new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
codeStream.aload_0();
AstUtil.generateParameterLoads(accessMethod.parameters, codeStream);
codeStream.invokespecial(
factory.makeMethodBinding(method));
AstUtil.generateReturn(accessMethod.returnType, codeStream);
// body ends here
}});
}
private void generateInlineAccessMethod(ClassFile classFile, final Binding binding, final ResolvedMember member) {
if (binding instanceof InlineAccessFieldBinding) {
generateInlineAccessors(classFile, (InlineAccessFieldBinding)binding, member);
} else {
generateInlineAccessMethod(classFile, (MethodBinding)binding, member);
}
}
private void generateInlineAccessors(ClassFile classFile, final InlineAccessFieldBinding accessField, final ResolvedMember field) {
final FieldBinding fieldBinding = factory.makeFieldBinding(field);
generateMethod(classFile, accessField.reader,
makeEffectiveSignatureAttribute(field,Shadow.FieldGet,false),
new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
if (field.isStatic()) {
codeStream.getstatic(fieldBinding);
} else {
codeStream.aload_0();
codeStream.getfield(fieldBinding);
}
AstUtil.generateReturn(accessField.reader.returnType, codeStream);
// body ends here
}});
generateMethod(classFile, accessField.writer,
makeEffectiveSignatureAttribute(field,Shadow.FieldSet,false),
new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
if (field.isStatic()) {
codeStream.load(fieldBinding.type, 0);
codeStream.putstatic(fieldBinding);
} else {
codeStream.aload_0();
codeStream.load(fieldBinding.type, 1);
codeStream.putfield(fieldBinding);
}
codeStream.return_();
// body ends here
}});
}
private void generateInlineAccessMethod(ClassFile classFile, final MethodBinding accessMethod, final ResolvedMember method) {
generateMethod(classFile, accessMethod,
makeEffectiveSignatureAttribute(method, Shadow.MethodCall, false),
new BodyGenerator() {
public void generate(CodeStream codeStream) {
// body starts here
AstUtil.generateParameterLoads(accessMethod.parameters, codeStream);
if (method.isStatic()) {
codeStream.invokestatic(factory.makeMethodBinding(method));
} else {
codeStream.invokevirtual(factory.makeMethodBinding(method));
}
AstUtil.generateReturn(accessMethod.returnType, codeStream);
// body ends here
}});
}
private PerClause.Kind lookupPerClauseKind(ReferenceBinding binding) {
PerClause perClause;
if (binding instanceof BinaryTypeBinding) {
ResolvedType superTypeX = factory.fromEclipse(binding);
perClause = superTypeX.getPerClause();
} else if (binding instanceof SourceTypeBinding ) {
SourceTypeBinding sourceSc = (SourceTypeBinding)binding;
if (sourceSc.scope.referenceContext instanceof AspectDeclaration) {
perClause = ((AspectDeclaration)sourceSc.scope.referenceContext).perClause;
} else {
return null;
}
} else {
//XXX need to handle this too
return null;
}
if (perClause == null) {
return lookupPerClauseKind(binding.superclass());
} else {
return perClause.getKind();
}
}
private void buildPerClause(ClassScope scope) {
EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(scope);
if (perClause == null) {
PerClause.Kind kind = lookupPerClauseKind(binding.superclass);
if (kind == null) {
perClause = new PerSingleton();
} else {
perClause = new PerFromSuper(kind);
}
}
aspectAttribute = new AjAttribute.Aspect(perClause);
if (ignoreFurtherInvestigation) return; //???
if (!isAbstract()) {
if (perClause.getKind() == PerClause.SINGLETON) {
aspectOfMethod = AjcMemberMaker.perSingletonAspectOfMethod(typeX);
hasAspectMethod = AjcMemberMaker.perSingletonHasAspectMethod(typeX);
} else if (perClause.getKind() == PerClause.PERCFLOW) {
aspectOfMethod = AjcMemberMaker.perCflowAspectOfMethod(typeX);
hasAspectMethod = AjcMemberMaker.perCflowHasAspectMethod(typeX);
} else if (perClause.getKind() == PerClause.PEROBJECT) {
aspectOfMethod = AjcMemberMaker.perObjectAspectOfMethod(typeX);
hasAspectMethod = AjcMemberMaker.perObjectHasAspectMethod(typeX);
} else if (perClause.getKind() == PerClause.PERTYPEWITHIN) {
// PTWIMPL Use these variants of aspectOf()/hasAspect()
aspectOfMethod = AjcMemberMaker.perTypeWithinAspectOfMethod(typeX);
hasAspectMethod = AjcMemberMaker.perTypeWithinHasAspectMethod(typeX);
} else {
throw new RuntimeException("bad per clause: " + perClause);
}
binding.addMethod(world.makeMethodBinding(aspectOfMethod));
binding.addMethod(world.makeMethodBinding(hasAspectMethod));
}
resolvePerClause(); //XXX might be too soon for some error checking
}
private PerClause resolvePerClause() {
EclipseScope iscope = new EclipseScope(new FormalBinding[0], scope);
perClause.resolve(iscope);
return perClause;
}
public void buildInterTypeAndPerClause(ClassScope classScope) {
factory = EclipseFactory.fromScopeLookupEnvironment(scope);
if (isPrivileged) {
binding.privilegedHandler = new PrivilegedHandler(this);
}
checkSpec(classScope);
if (ignoreFurtherInvestigation) return;
buildPerClause(scope);
if (methods != null) {
for (int i = 0; i < methods.length; i++) {
if (methods[i] instanceof InterTypeDeclaration) {
EclipseTypeMunger m = ((InterTypeDeclaration)methods[i]).build(classScope);
if (m != null) concreteName.typeMungers.add(m);
} else if (methods[i] instanceof DeclareDeclaration) {
Declare d = ((DeclareDeclaration)methods[i]).build(classScope);
if (d != null) concreteName.declares.add(d);
}
}
}
concreteName.getDeclaredPointcuts();
}
// public String toString(int tab) {
// return tabString(tab) + toStringHeader() + toStringBody(tab);
// }
//
// public String toStringBody(int tab) {
//
// String s = " {"; //$NON-NLS-1$
//
//
// if (memberTypes != null) {
// for (int i = 0; i < memberTypes.length; i++) {
// if (memberTypes[i] != null) {
// s += "\n" + memberTypes[i].toString(tab + 1); //$NON-NLS-1$
// }
// }
// }
// if (fields != null) {
// for (int fieldI = 0; fieldI < fields.length; fieldI++) {
// if (fields[fieldI] != null) {
// s += "\n" + fields[fieldI].toString(tab + 1); //$NON-NLS-1$
// if (fields[fieldI].isField())
// s += ";"; //$NON-NLS-1$
// }
// }
// }
// if (methods != null) {
// for (int i = 0; i < methods.length; i++) {
// if (methods[i] != null) {
// s += "\n" + methods[i].toString(tab + 1); //$NON-NLS-1$
// }
// }
// }
// s += "\n" + tabString(tab) + "}"; //$NON-NLS-2$ //$NON-NLS-1$
// return s;
// }
public StringBuffer printHeader(int indent, StringBuffer output) {
printModifiers(this.modifiers, output);
output.append("aspect " );
output.append(name);
if (superclass != null) {
output.append(" extends "); //$NON-NLS-1$
superclass.print(0, output);
}
if (superInterfaces != null && superInterfaces.length > 0) {
output.append((kind() == IGenericType.INTERFACE_DECL) ? " extends " : " implements ");//$NON-NLS-2$ //$NON-NLS-1$
for (int i = 0; i < superInterfaces.length; i++) {
if (i > 0) output.append( ", "); //$NON-NLS-1$
superInterfaces[i].print(0, output);
}
}
return output;
//XXX we should append the per-clause
}
}
|
diff --git a/src/main/java/jewas/persistence/rowMapper/LongRowMapper.java b/src/main/java/jewas/persistence/rowMapper/LongRowMapper.java
index c364efc..35bc944 100644
--- a/src/main/java/jewas/persistence/rowMapper/LongRowMapper.java
+++ b/src/main/java/jewas/persistence/rowMapper/LongRowMapper.java
@@ -1,14 +1,14 @@
package jewas.persistence.rowMapper;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* @author driccio
*/
public class LongRowMapper implements RowMapper<Long> {
@Override
public Long processRow(ResultSet rs) throws SQLException {
- return rs.getLong(0);
+ return rs.getLong(1);
}
}
| true | true | public Long processRow(ResultSet rs) throws SQLException {
return rs.getLong(0);
}
| public Long processRow(ResultSet rs) throws SQLException {
return rs.getLong(1);
}
|
diff --git a/finance/service/src/main/java/com/lavida/service/remote/google/GoogleSpreadsheetWorker.java b/finance/service/src/main/java/com/lavida/service/remote/google/GoogleSpreadsheetWorker.java
index 5428288..180e780 100644
--- a/finance/service/src/main/java/com/lavida/service/remote/google/GoogleSpreadsheetWorker.java
+++ b/finance/service/src/main/java/com/lavida/service/remote/google/GoogleSpreadsheetWorker.java
@@ -1,93 +1,93 @@
package com.lavida.service.remote.google;
import com.google.gdata.client.spreadsheet.CellQuery;
import com.google.gdata.client.spreadsheet.FeedURLFactory;
import com.google.gdata.client.spreadsheet.SpreadsheetService;
import com.google.gdata.data.spreadsheet.CellEntry;
import com.google.gdata.data.spreadsheet.CellFeed;
import com.google.gdata.data.spreadsheet.SpreadsheetEntry;
import com.google.gdata.data.spreadsheet.SpreadsheetFeed;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;
import com.lavida.service.settings.Settings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.URL;
import java.util.List;
/**
* GoogleSpreadsheetWorker
* Created: 22:15 15.08.13
*
* @author Pavel
*/
public class GoogleSpreadsheetWorker {
private static final Logger logger = LoggerFactory.getLogger(GoogleSpreadsheetWorker.class);
private static final String APPLICATION_NAME = "LA VIDA Finance.";
private SpreadsheetService spreadsheetService = new SpreadsheetService(APPLICATION_NAME);
private URL worksheetUrl;
public GoogleSpreadsheetWorker(Settings settings) throws ServiceException, IOException {
loginToGmail(spreadsheetService, settings.getRemoteUser(), settings.getRemotePass());
List spreadsheets = getSpreadsheetList(spreadsheetService);
SpreadsheetEntry spreadsheet = getSpreadsheetByName(spreadsheets, settings.getSpreadsheetName());
worksheetUrl = getWorksheetUrl(spreadsheet, settings.getWorksheetNumber());
}
public CellFeed getWholeDocument() throws IOException, ServiceException {
return spreadsheetService.getFeed(worksheetUrl, CellFeed.class);
}
public CellFeed getCellsInRange(Integer minRow, Integer maxRow, Integer minCol, Integer maxCol) throws IOException, ServiceException {
CellQuery query = new CellQuery(worksheetUrl);
query.setMinimumRow(minRow);
query.setMaximumRow(maxRow);
query.setMinimumCol(minCol);
query.setMaximumCol(maxCol);
return spreadsheetService.query(query, CellFeed.class);
}
public void saveOrUpdateCells(List<CellEntry> cellEntries) throws IOException, ServiceException {
for (CellEntry cellEntry : cellEntries) {
spreadsheetService.insert(worksheetUrl, cellEntry);
}
}
public CellFeed getRow(int row) throws IOException, ServiceException {
return getCellsInRange(row, row, null, null);
}
private void loginToGmail(SpreadsheetService spreadsheetService, String username, String password) throws AuthenticationException {
spreadsheetService.setUserCredentials(username, password);
}
private List getSpreadsheetList(SpreadsheetService spreadsheetService) throws IOException, ServiceException {
FeedURLFactory factory = FeedURLFactory.getDefault();
SpreadsheetFeed feed = spreadsheetService.getFeed(factory.getSpreadsheetsFeedUrl(), SpreadsheetFeed.class);
return feed.getEntries();
}
private SpreadsheetEntry getSpreadsheetByName(List spreadsheets, String spreadsheetName) {
for (Object spreadsheetObject : spreadsheets) {
if (spreadsheetObject instanceof SpreadsheetEntry) {
SpreadsheetEntry spreadsheet = (SpreadsheetEntry) spreadsheetObject;
String sheetTitle = spreadsheet.getTitle().getPlainText();
- if (sheetTitle != null && sheetTitle.equals(spreadsheetName)) {
+ if (sheetTitle != null && sheetTitle.trim().equals(spreadsheetName.trim())) {
return spreadsheet;
}
} else {
logger.warn("Found spreadsheet which is not SpreadsheetEntry instance: " + spreadsheetObject);
}
}
throw new RuntimeException("No spreadsheet found with name");
// todo change exception
}
private URL getWorksheetUrl(SpreadsheetEntry spreadsheet, int worksheetNumber) throws IOException, ServiceException {
return spreadsheet.getWorksheets().get(worksheetNumber).getCellFeedUrl();
}
}
| true | true | private SpreadsheetEntry getSpreadsheetByName(List spreadsheets, String spreadsheetName) {
for (Object spreadsheetObject : spreadsheets) {
if (spreadsheetObject instanceof SpreadsheetEntry) {
SpreadsheetEntry spreadsheet = (SpreadsheetEntry) spreadsheetObject;
String sheetTitle = spreadsheet.getTitle().getPlainText();
if (sheetTitle != null && sheetTitle.equals(spreadsheetName)) {
return spreadsheet;
}
} else {
logger.warn("Found spreadsheet which is not SpreadsheetEntry instance: " + spreadsheetObject);
}
}
throw new RuntimeException("No spreadsheet found with name");
// todo change exception
}
| private SpreadsheetEntry getSpreadsheetByName(List spreadsheets, String spreadsheetName) {
for (Object spreadsheetObject : spreadsheets) {
if (spreadsheetObject instanceof SpreadsheetEntry) {
SpreadsheetEntry spreadsheet = (SpreadsheetEntry) spreadsheetObject;
String sheetTitle = spreadsheet.getTitle().getPlainText();
if (sheetTitle != null && sheetTitle.trim().equals(spreadsheetName.trim())) {
return spreadsheet;
}
} else {
logger.warn("Found spreadsheet which is not SpreadsheetEntry instance: " + spreadsheetObject);
}
}
throw new RuntimeException("No spreadsheet found with name");
// todo change exception
}
|
diff --git a/bundles/org.eclipse.rap.demo/src/org/eclipse/rap/demo/controls/ErrorHandlingTab.java b/bundles/org.eclipse.rap.demo/src/org/eclipse/rap/demo/controls/ErrorHandlingTab.java
index 3b7d7c059..29654da81 100644
--- a/bundles/org.eclipse.rap.demo/src/org/eclipse/rap/demo/controls/ErrorHandlingTab.java
+++ b/bundles/org.eclipse.rap.demo/src/org/eclipse/rap/demo/controls/ErrorHandlingTab.java
@@ -1,111 +1,111 @@
/*******************************************************************************
* Copyright (c) 2002, 2007 Innoopract Informationssysteme GmbH.
* 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:
* Innoopract Informationssysteme GmbH - initial API and implementation
******************************************************************************/
package org.eclipse.rap.demo.controls;
import javax.servlet.http.HttpSession;
import org.eclipse.rwt.RWT;
import org.eclipse.rwt.internal.lifecycle.HtmlResponseWriter;
import org.eclipse.rwt.internal.service.ContextProvider;
import org.eclipse.rwt.internal.service.IServiceStateInfo;
import org.eclipse.rwt.lifecycle.*;
import org.eclipse.swt.SWT;
import org.eclipse.swt.SWTError;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.*;
public class ErrorHandlingTab extends ExampleTab {
private static final int DELAY = 2000;
public ErrorHandlingTab( final CTabFolder topFolder ) {
super( topFolder, "Error Handling" );
}
protected void createStyleControls( final Composite parent ) {
}
protected void createExampleControls( final Composite parent ) {
parent.setLayout( new GridLayout( 1, false ) );
Label lblInfo = new Label( parent, SWT.WRAP );
lblInfo.setLayoutData( new GridData( SWT.FILL, SWT.DEFAULT, true, false ) );
String info
= "Simulate a server-side session timeout.\n"
+ "Click the 'Invalidate Session' button that will invalidate the "
+ "session after a short delay.\n"
+ "Thereafter, try to proceed using the application. With the next "
- + "request, a new session is created. You are informaed about that and"
+ + "request, a new session is created. You are informed about that and "
+ "can start working with the new session";
lblInfo.setText( info );
Button btnInvalidateSession = new Button( parent, SWT.PUSH );
String msg = "Invalidate Session";
btnInvalidateSession.setText( msg );
final Label lblFeedback = new Label( parent, SWT.NONE );
btnInvalidateSession.addSelectionListener( new SelectionAdapter() {
public void widgetSelected( final SelectionEvent event ) {
lblFeedback.setText( "The session will be invalidated shortly." );
lblFeedback.getParent().layout();
final HttpSession session = RWT.getSessionStore().getHttpSession();
Thread thread = new Thread( new Runnable() {
public void run() {
try {
Thread.sleep( DELAY );
session.invalidate();
} catch( InterruptedException e ) {
// ignore, invalidate won't be executed
}
}
} );
thread.start();
}
} );
Button btnErrorResponse = new Button( parent, SWT.PUSH );
btnErrorResponse.setText( "Deliver response with JavaScript error" );
btnErrorResponse.addSelectionListener( new SelectionAdapter() {
public void widgetSelected( final SelectionEvent event ) {
RWT.getLifeCycle().addPhaseListener( new PhaseListener() {
private static final long serialVersionUID = 1L;
public void beforePhase( final PhaseEvent event ) {
}
public void afterPhase( final PhaseEvent event ) {
IServiceStateInfo stateInfo = ContextProvider.getStateInfo();
HtmlResponseWriter writer = stateInfo.getResponseWriter();
writer.append( "this is no valid JavaScript!" );
RWT.getLifeCycle().removePhaseListener( this );
}
public PhaseId getPhaseId() {
return PhaseId.RENDER;
}
} );
}
} );
Button btnServerException = new Button( parent, SWT.PUSH );
btnServerException.setText( "Throw uncaught server-side exeption" );
btnServerException.addSelectionListener( new SelectionAdapter() {
public void widgetSelected( final SelectionEvent event ) {
throw new RuntimeException( "Shit happens, rama rama ding ding" );
}
} );
Button btnServerError = new Button( parent, SWT.PUSH );
btnServerError.setText( "Throw uncaught server-side error" );
btnServerError.addSelectionListener( new SelectionAdapter() {
public void widgetSelected( final SelectionEvent event ) {
throw new SWTError( "Some error occured" );
}
} );
}
}
| true | true | protected void createExampleControls( final Composite parent ) {
parent.setLayout( new GridLayout( 1, false ) );
Label lblInfo = new Label( parent, SWT.WRAP );
lblInfo.setLayoutData( new GridData( SWT.FILL, SWT.DEFAULT, true, false ) );
String info
= "Simulate a server-side session timeout.\n"
+ "Click the 'Invalidate Session' button that will invalidate the "
+ "session after a short delay.\n"
+ "Thereafter, try to proceed using the application. With the next "
+ "request, a new session is created. You are informaed about that and"
+ "can start working with the new session";
lblInfo.setText( info );
Button btnInvalidateSession = new Button( parent, SWT.PUSH );
String msg = "Invalidate Session";
btnInvalidateSession.setText( msg );
final Label lblFeedback = new Label( parent, SWT.NONE );
btnInvalidateSession.addSelectionListener( new SelectionAdapter() {
public void widgetSelected( final SelectionEvent event ) {
lblFeedback.setText( "The session will be invalidated shortly." );
lblFeedback.getParent().layout();
final HttpSession session = RWT.getSessionStore().getHttpSession();
Thread thread = new Thread( new Runnable() {
public void run() {
try {
Thread.sleep( DELAY );
session.invalidate();
} catch( InterruptedException e ) {
// ignore, invalidate won't be executed
}
}
} );
thread.start();
}
} );
Button btnErrorResponse = new Button( parent, SWT.PUSH );
btnErrorResponse.setText( "Deliver response with JavaScript error" );
btnErrorResponse.addSelectionListener( new SelectionAdapter() {
public void widgetSelected( final SelectionEvent event ) {
RWT.getLifeCycle().addPhaseListener( new PhaseListener() {
private static final long serialVersionUID = 1L;
public void beforePhase( final PhaseEvent event ) {
}
public void afterPhase( final PhaseEvent event ) {
IServiceStateInfo stateInfo = ContextProvider.getStateInfo();
HtmlResponseWriter writer = stateInfo.getResponseWriter();
writer.append( "this is no valid JavaScript!" );
RWT.getLifeCycle().removePhaseListener( this );
}
public PhaseId getPhaseId() {
return PhaseId.RENDER;
}
} );
}
} );
Button btnServerException = new Button( parent, SWT.PUSH );
btnServerException.setText( "Throw uncaught server-side exeption" );
btnServerException.addSelectionListener( new SelectionAdapter() {
public void widgetSelected( final SelectionEvent event ) {
throw new RuntimeException( "Shit happens, rama rama ding ding" );
}
} );
Button btnServerError = new Button( parent, SWT.PUSH );
btnServerError.setText( "Throw uncaught server-side error" );
btnServerError.addSelectionListener( new SelectionAdapter() {
public void widgetSelected( final SelectionEvent event ) {
throw new SWTError( "Some error occured" );
}
} );
}
| protected void createExampleControls( final Composite parent ) {
parent.setLayout( new GridLayout( 1, false ) );
Label lblInfo = new Label( parent, SWT.WRAP );
lblInfo.setLayoutData( new GridData( SWT.FILL, SWT.DEFAULT, true, false ) );
String info
= "Simulate a server-side session timeout.\n"
+ "Click the 'Invalidate Session' button that will invalidate the "
+ "session after a short delay.\n"
+ "Thereafter, try to proceed using the application. With the next "
+ "request, a new session is created. You are informed about that and "
+ "can start working with the new session";
lblInfo.setText( info );
Button btnInvalidateSession = new Button( parent, SWT.PUSH );
String msg = "Invalidate Session";
btnInvalidateSession.setText( msg );
final Label lblFeedback = new Label( parent, SWT.NONE );
btnInvalidateSession.addSelectionListener( new SelectionAdapter() {
public void widgetSelected( final SelectionEvent event ) {
lblFeedback.setText( "The session will be invalidated shortly." );
lblFeedback.getParent().layout();
final HttpSession session = RWT.getSessionStore().getHttpSession();
Thread thread = new Thread( new Runnable() {
public void run() {
try {
Thread.sleep( DELAY );
session.invalidate();
} catch( InterruptedException e ) {
// ignore, invalidate won't be executed
}
}
} );
thread.start();
}
} );
Button btnErrorResponse = new Button( parent, SWT.PUSH );
btnErrorResponse.setText( "Deliver response with JavaScript error" );
btnErrorResponse.addSelectionListener( new SelectionAdapter() {
public void widgetSelected( final SelectionEvent event ) {
RWT.getLifeCycle().addPhaseListener( new PhaseListener() {
private static final long serialVersionUID = 1L;
public void beforePhase( final PhaseEvent event ) {
}
public void afterPhase( final PhaseEvent event ) {
IServiceStateInfo stateInfo = ContextProvider.getStateInfo();
HtmlResponseWriter writer = stateInfo.getResponseWriter();
writer.append( "this is no valid JavaScript!" );
RWT.getLifeCycle().removePhaseListener( this );
}
public PhaseId getPhaseId() {
return PhaseId.RENDER;
}
} );
}
} );
Button btnServerException = new Button( parent, SWT.PUSH );
btnServerException.setText( "Throw uncaught server-side exeption" );
btnServerException.addSelectionListener( new SelectionAdapter() {
public void widgetSelected( final SelectionEvent event ) {
throw new RuntimeException( "Shit happens, rama rama ding ding" );
}
} );
Button btnServerError = new Button( parent, SWT.PUSH );
btnServerError.setText( "Throw uncaught server-side error" );
btnServerError.addSelectionListener( new SelectionAdapter() {
public void widgetSelected( final SelectionEvent event ) {
throw new SWTError( "Some error occured" );
}
} );
}
|
diff --git a/src/com/example/staggeredgridviewdemo/views/ScaleImageView.java b/src/com/example/staggeredgridviewdemo/views/ScaleImageView.java
index 56e2813..917b4b9 100644
--- a/src/com/example/staggeredgridviewdemo/views/ScaleImageView.java
+++ b/src/com/example/staggeredgridviewdemo/views/ScaleImageView.java
@@ -1,138 +1,138 @@
package com.example.staggeredgridviewdemo.views;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View.MeasureSpec;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.RelativeLayout;
/**
*
* This view will auto determine the width or height by determining if the
* height or width is set and scale the other dimension depending on the images dimension
*
* This view also contains an ImageChangeListener which calls changed(boolean isEmpty) once a
* change has been made to the ImageView
*
* @author Maurycy Wojtowicz
*
*/
public class ScaleImageView extends ImageView {
private ImageChangeListener imageChangeListener;
private boolean scaleToWidth = false; // this flag determines if should measure height manually dependent of width
public ScaleImageView(Context context) {
super(context);
init();
}
public ScaleImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public ScaleImageView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init(){
this.setScaleType(ScaleType.CENTER_INSIDE);
}
@Override
public void setImageBitmap(Bitmap bm) {
super.setImageBitmap(bm);
if (imageChangeListener != null)
imageChangeListener.changed((bm == null));
}
@Override
public void setImageDrawable(Drawable d) {
super.setImageDrawable(d);
if (imageChangeListener != null)
imageChangeListener.changed((d == null));
}
@Override
public void setImageResource(int id){
super.setImageResource(id);
}
public interface ImageChangeListener {
// a callback for when a change has been made to this imageView
void changed(boolean isEmpty);
}
public ImageChangeListener getImageChangeListener() {
return imageChangeListener;
}
public void setImageChangeListener(ImageChangeListener imageChangeListener) {
this.imageChangeListener = imageChangeListener;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
/**
* if both width and height are set scale width first. modify in future if necessary
*/
if(widthMode == MeasureSpec.EXACTLY || widthMode == MeasureSpec.AT_MOST){
scaleToWidth = true;
}else if(heightMode == MeasureSpec.EXACTLY || heightMode == MeasureSpec.AT_MOST){
scaleToWidth = false;
}else throw new IllegalStateException("width or height needs to be set to match_parent or a specific dimension");
if(getDrawable()==null || getDrawable().getIntrinsicWidth()==0 ){
// nothing to measure
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
return;
}else{
if(scaleToWidth){
int iw = this.getDrawable().getIntrinsicWidth();
int ih = this.getDrawable().getIntrinsicHeight();
int heightC = width*ih/iw;
if(height > 0)
if(heightC>height){
// dont let hegiht be greater then set max
heightC = height;
width = heightC*iw/ih;
}
this.setScaleType(ScaleType.CENTER_CROP);
- setMeasuredDimension(MeasureSpec.makeMeasureSpec(width, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(heightC, MeasureSpec.UNSPECIFIED));
+ setMeasuredDimension(width, heightC);
}else{
// need to scale to height instead
int marg = 0;
if(getParent()!=null){
if(getParent().getParent()!=null){
marg+= ((RelativeLayout) getParent().getParent()).getPaddingTop();
marg+= ((RelativeLayout) getParent().getParent()).getPaddingBottom();
}
}
int iw = this.getDrawable().getIntrinsicWidth();
int ih = this.getDrawable().getIntrinsicHeight();
width = height*iw/ih;
height-=marg;
- setMeasuredDimension(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
+ setMeasuredDimension(width, height);
}
}
}
}
| false | true | protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
/**
* if both width and height are set scale width first. modify in future if necessary
*/
if(widthMode == MeasureSpec.EXACTLY || widthMode == MeasureSpec.AT_MOST){
scaleToWidth = true;
}else if(heightMode == MeasureSpec.EXACTLY || heightMode == MeasureSpec.AT_MOST){
scaleToWidth = false;
}else throw new IllegalStateException("width or height needs to be set to match_parent or a specific dimension");
if(getDrawable()==null || getDrawable().getIntrinsicWidth()==0 ){
// nothing to measure
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
return;
}else{
if(scaleToWidth){
int iw = this.getDrawable().getIntrinsicWidth();
int ih = this.getDrawable().getIntrinsicHeight();
int heightC = width*ih/iw;
if(height > 0)
if(heightC>height){
// dont let hegiht be greater then set max
heightC = height;
width = heightC*iw/ih;
}
this.setScaleType(ScaleType.CENTER_CROP);
setMeasuredDimension(MeasureSpec.makeMeasureSpec(width, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(heightC, MeasureSpec.UNSPECIFIED));
}else{
// need to scale to height instead
int marg = 0;
if(getParent()!=null){
if(getParent().getParent()!=null){
marg+= ((RelativeLayout) getParent().getParent()).getPaddingTop();
marg+= ((RelativeLayout) getParent().getParent()).getPaddingBottom();
}
}
int iw = this.getDrawable().getIntrinsicWidth();
int ih = this.getDrawable().getIntrinsicHeight();
width = height*iw/ih;
height-=marg;
setMeasuredDimension(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
}
}
}
| protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
/**
* if both width and height are set scale width first. modify in future if necessary
*/
if(widthMode == MeasureSpec.EXACTLY || widthMode == MeasureSpec.AT_MOST){
scaleToWidth = true;
}else if(heightMode == MeasureSpec.EXACTLY || heightMode == MeasureSpec.AT_MOST){
scaleToWidth = false;
}else throw new IllegalStateException("width or height needs to be set to match_parent or a specific dimension");
if(getDrawable()==null || getDrawable().getIntrinsicWidth()==0 ){
// nothing to measure
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
return;
}else{
if(scaleToWidth){
int iw = this.getDrawable().getIntrinsicWidth();
int ih = this.getDrawable().getIntrinsicHeight();
int heightC = width*ih/iw;
if(height > 0)
if(heightC>height){
// dont let hegiht be greater then set max
heightC = height;
width = heightC*iw/ih;
}
this.setScaleType(ScaleType.CENTER_CROP);
setMeasuredDimension(width, heightC);
}else{
// need to scale to height instead
int marg = 0;
if(getParent()!=null){
if(getParent().getParent()!=null){
marg+= ((RelativeLayout) getParent().getParent()).getPaddingTop();
marg+= ((RelativeLayout) getParent().getParent()).getPaddingBottom();
}
}
int iw = this.getDrawable().getIntrinsicWidth();
int ih = this.getDrawable().getIntrinsicHeight();
width = height*iw/ih;
height-=marg;
setMeasuredDimension(width, height);
}
}
}
|
diff --git a/nuxeo-theme-webengine/src/main/java/org/nuxeo/theme/webengine/fm/extensions/NXThemesHeadDirective.java b/nuxeo-theme-webengine/src/main/java/org/nuxeo/theme/webengine/fm/extensions/NXThemesHeadDirective.java
index f5db06a..9665ca8 100644
--- a/nuxeo-theme-webengine/src/main/java/org/nuxeo/theme/webengine/fm/extensions/NXThemesHeadDirective.java
+++ b/nuxeo-theme-webengine/src/main/java/org/nuxeo/theme/webengine/fm/extensions/NXThemesHeadDirective.java
@@ -1,81 +1,81 @@
/*
* (C) Copyright 2006-2008 Nuxeo SAS (http://nuxeo.com/) and contributors.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl.html
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Contributors:
* Jean-Marc Orliaguet, Chalmers
*
* $Id$
*/
package org.nuxeo.theme.webengine.fm.extensions;
import java.io.IOException;
import java.io.Writer;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.nuxeo.ecm.webengine.WebEngine;
import org.nuxeo.ecm.webengine.model.WebContext;
import org.nuxeo.theme.html.ui.Head;
import org.nuxeo.theme.themes.ThemeManager;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;
/**
* @author <a href="mailto:[email protected]">Jean-Marc Orliaguet</a>
*
*/
public class NXThemesHeadDirective implements TemplateDirectiveModel {
@SuppressWarnings("unchecked")
public void execute(Environment env, Map params, TemplateModel[] loopVars,
TemplateDirectiveBody body) throws TemplateException, IOException {
if (!params.isEmpty()) {
throw new TemplateModelException(
"This directive doesn't allow parameters.");
}
if (loopVars.length != 0) {
throw new TemplateModelException(
"This directive doesn't allow loop variables.");
}
if (body != null) {
throw new TemplateModelException("Didn't expect a body");
}
Writer writer = env.getOut();
WebContext context = WebEngine.getActiveContext();
HttpServletRequest request = context.getRequest();
final URL themeUrl = (URL) request.getAttribute("org.nuxeo.theme.url");
- String baseUrl = context.getHead().getURL();
+ String baseUrl = context.head().getURL();
if (!baseUrl.endsWith("/")) {
baseUrl += "/";
}
Map<String, String> attributes = new HashMap<String, String>();
attributes.put("themeName", ThemeManager.getThemeNameByUrl(themeUrl));
attributes.put("path", context.getModulePath());
attributes.put("baseUrl", baseUrl);
writer.write(Head.render(attributes));
}
}
| true | true | public void execute(Environment env, Map params, TemplateModel[] loopVars,
TemplateDirectiveBody body) throws TemplateException, IOException {
if (!params.isEmpty()) {
throw new TemplateModelException(
"This directive doesn't allow parameters.");
}
if (loopVars.length != 0) {
throw new TemplateModelException(
"This directive doesn't allow loop variables.");
}
if (body != null) {
throw new TemplateModelException("Didn't expect a body");
}
Writer writer = env.getOut();
WebContext context = WebEngine.getActiveContext();
HttpServletRequest request = context.getRequest();
final URL themeUrl = (URL) request.getAttribute("org.nuxeo.theme.url");
String baseUrl = context.getHead().getURL();
if (!baseUrl.endsWith("/")) {
baseUrl += "/";
}
Map<String, String> attributes = new HashMap<String, String>();
attributes.put("themeName", ThemeManager.getThemeNameByUrl(themeUrl));
attributes.put("path", context.getModulePath());
attributes.put("baseUrl", baseUrl);
writer.write(Head.render(attributes));
}
| public void execute(Environment env, Map params, TemplateModel[] loopVars,
TemplateDirectiveBody body) throws TemplateException, IOException {
if (!params.isEmpty()) {
throw new TemplateModelException(
"This directive doesn't allow parameters.");
}
if (loopVars.length != 0) {
throw new TemplateModelException(
"This directive doesn't allow loop variables.");
}
if (body != null) {
throw new TemplateModelException("Didn't expect a body");
}
Writer writer = env.getOut();
WebContext context = WebEngine.getActiveContext();
HttpServletRequest request = context.getRequest();
final URL themeUrl = (URL) request.getAttribute("org.nuxeo.theme.url");
String baseUrl = context.head().getURL();
if (!baseUrl.endsWith("/")) {
baseUrl += "/";
}
Map<String, String> attributes = new HashMap<String, String>();
attributes.put("themeName", ThemeManager.getThemeNameByUrl(themeUrl));
attributes.put("path", context.getModulePath());
attributes.put("baseUrl", baseUrl);
writer.write(Head.render(attributes));
}
|
diff --git a/api/src/test/java/org/asynchttpclient/multipart/MultipartBodyTest.java b/api/src/test/java/org/asynchttpclient/multipart/MultipartBodyTest.java
index 9cbccb9ac..1e8ba2860 100644
--- a/api/src/test/java/org/asynchttpclient/multipart/MultipartBodyTest.java
+++ b/api/src/test/java/org/asynchttpclient/multipart/MultipartBodyTest.java
@@ -1,109 +1,109 @@
/*
* Copyright (c) 2013 Sonatype, Inc. All rights reserved.
*
* This program is licensed to you under the Apache License Version 2.0,
* and you may not use this file except in compliance with the Apache License Version 2.0.
* You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Apache License Version 2.0 is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
package org.asynchttpclient.multipart;
import org.asynchttpclient.*;
import org.asynchttpclient.Part;
import org.asynchttpclient.util.AsyncHttpProviderUtils;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
public class MultipartBodyTest {
@Test(groups = "fast")
public void testBasics() {
final List<Part> parts = new ArrayList<Part>();
// add a file
final File testFile = getTestfile();
try {
parts.add(new FilePart("filePart", testFile));
} catch (FileNotFoundException fne) {
Assert.fail("file not found: " + testFile);
}
// add a byte array
try {
parts.add(new ByteArrayPart("baPart", "fileName", "testMultiPart".getBytes("utf-8"), "application/test", "utf-8"));
} catch (UnsupportedEncodingException ignore) {
}
// add a string
parts.add(new StringPart("stringPart", "testString", "utf-8"));
compareContentLength(parts);
}
private static File getTestfile() {
final ClassLoader cl = MultipartBodyTest.class.getClassLoader();
final URL url = cl.getResource("textfile.txt");
Assert.assertNotNull(url);
File file = null;
try {
file = new File(url.toURI());
} catch (URISyntaxException use) {
Assert.fail("uri syntax error");
}
return file;
}
private static void compareContentLength(final List<Part> parts) {
Assert.assertNotNull(parts);
// get expected values
MultipartRequestEntity mre = null;
try {
mre = AsyncHttpProviderUtils.createMultipartRequestEntity(parts, new FluentCaseInsensitiveStringsMap());
} catch (FileNotFoundException fne) {
Assert.fail("file not found: " + parts);
}
final long expectedContentLength = mre.getContentLength();
// get real bytes
final Body multipartBody = new MultipartBody(parts, mre.getContentType(), String.valueOf(expectedContentLength));
try {
final ByteBuffer buffer = ByteBuffer.allocate(8192);
boolean last = false;
long totalBytes = 0;
while (!last) {
long readBytes = 0;
try {
readBytes = multipartBody.read(buffer);
} catch (IOException ie) {
Assert.fail("read failure");
}
- if (readBytes >= 0) {
+ if (readBytes > 0) {
totalBytes += readBytes;
} else {
last = true;
}
buffer.clear();
}
Assert.assertEquals(totalBytes, expectedContentLength);
} finally {
try {
multipartBody.close();
} catch (IOException ignore) {
}
}
}
}
| true | true | private static void compareContentLength(final List<Part> parts) {
Assert.assertNotNull(parts);
// get expected values
MultipartRequestEntity mre = null;
try {
mre = AsyncHttpProviderUtils.createMultipartRequestEntity(parts, new FluentCaseInsensitiveStringsMap());
} catch (FileNotFoundException fne) {
Assert.fail("file not found: " + parts);
}
final long expectedContentLength = mre.getContentLength();
// get real bytes
final Body multipartBody = new MultipartBody(parts, mre.getContentType(), String.valueOf(expectedContentLength));
try {
final ByteBuffer buffer = ByteBuffer.allocate(8192);
boolean last = false;
long totalBytes = 0;
while (!last) {
long readBytes = 0;
try {
readBytes = multipartBody.read(buffer);
} catch (IOException ie) {
Assert.fail("read failure");
}
if (readBytes >= 0) {
totalBytes += readBytes;
} else {
last = true;
}
buffer.clear();
}
Assert.assertEquals(totalBytes, expectedContentLength);
} finally {
try {
multipartBody.close();
} catch (IOException ignore) {
}
}
}
| private static void compareContentLength(final List<Part> parts) {
Assert.assertNotNull(parts);
// get expected values
MultipartRequestEntity mre = null;
try {
mre = AsyncHttpProviderUtils.createMultipartRequestEntity(parts, new FluentCaseInsensitiveStringsMap());
} catch (FileNotFoundException fne) {
Assert.fail("file not found: " + parts);
}
final long expectedContentLength = mre.getContentLength();
// get real bytes
final Body multipartBody = new MultipartBody(parts, mre.getContentType(), String.valueOf(expectedContentLength));
try {
final ByteBuffer buffer = ByteBuffer.allocate(8192);
boolean last = false;
long totalBytes = 0;
while (!last) {
long readBytes = 0;
try {
readBytes = multipartBody.read(buffer);
} catch (IOException ie) {
Assert.fail("read failure");
}
if (readBytes > 0) {
totalBytes += readBytes;
} else {
last = true;
}
buffer.clear();
}
Assert.assertEquals(totalBytes, expectedContentLength);
} finally {
try {
multipartBody.close();
} catch (IOException ignore) {
}
}
}
|
diff --git a/user/src/com/google/gwt/core/client/GWT.java b/user/src/com/google/gwt/core/client/GWT.java
index ecc37391c..ff295f7a5 100644
--- a/user/src/com/google/gwt/core/client/GWT.java
+++ b/user/src/com/google/gwt/core/client/GWT.java
@@ -1,152 +1,156 @@
/*
* Copyright 2007 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.gwt.core.client;
/**
* Supports core functionality that in some cases requires direct support from
* the compiler and runtime systems such as runtime type information and
* deferred binding.
*/
public final class GWT {
/*
* This is the web mode version of this class. Because it's so special,
* there's also a hosted mode version. See GWT.java-hosted.
*/
/**
* This interface is used to catch exceptions at the "top level" just before
* they escape to the browser. This is used in places where the browser calls
* into user code such as event callbacks, timers, and RPC.
*
* In hosted mode, the default handler prints a stack trace to the log window.
* In web mode, the default handler is null and thus exceptions are allowed to
* escape, which provides an opportunity to use a JavaScript debugger.
*/
public interface UncaughtExceptionHandler {
void onUncaughtException(Throwable e);
}
// web mode default is to let the exception go
private static UncaughtExceptionHandler sUncaughtExceptionHandler = null;
/**
* Instantiates a class via deferred binding.
*
* <p>
* The argument to {@link #create(Class)} <i>must</i> be a class
* literal because the web mode compiler must be able to statically determine
* the requested type at compile-time. This can be tricky because using a
* {@link Class} variable may appear to work correctly in hosted mode.
* </p>
*
* @param classLiteral a class literal specifying the base class to be
* instantiated
* @return the new instance, which must be typecast to the requested class.
*/
public static Object create(Class classLiteral) {
/*
* In web mode, the compiler directly replaces calls to this method with a
* new Object() type expression of the correct rebound type.
*/
- throw new RuntimeException(
- "GWT has not been properly initialized; if you are running a unit test, check that your test case extends GWTTestCase");
+ throw new UnsupportedOperationException(
+ "ERROR: GWT.create() is only usable in client code! It cannot be called, "
+ + "for example, from server code. If you are running a unit test, "
+ + "check that your test case extends GWTTestCase and that GWT.create() "
+ + "is not called from within an initializer, constructor, or "
+ + "setUp()/tearDown().");
}
/**
* Gets the URL prefix of the hosting page, useful for prepending to relative
* paths of resources which may be relative to the host page. Typically, you
* should use {@link #getModuleBaseURL()} unless you have a specific reason to
* load a resource relative to the host page.
*
* @return if non-empty, the base URL is guaranteed to end with a slash
*/
public static String getHostPageBaseURL() {
return Impl.getHostPageBaseURL();
}
/**
* Gets the URL prefix of the module which should be prepended to URLs that
* are intended to be module-relative, such as RPC entry points and files in
* the module's public path.
*
* @return if non-empty, the base URL is guaranteed to end with a slash
*/
public static String getModuleBaseURL() {
return Impl.getModuleBaseURL();
}
/**
* Gets the name of the running module.
*/
public static String getModuleName() {
return Impl.getModuleName();
}
/**
* Gets the class name of the specified object, as would be returned by
* <code>o.getClass().getName()</code>.
*
* @param o the object whose class name is being sought, or <code>null</code>
* @return the class name of the specified object, or <code>null</code> if
* <code>o</code> is <code>null</code>
*/
public static native String getTypeName(Object o) /*-{
return (o == null) ? null : [email protected]::typeName;
}-*/;
/**
* Returns the currently active uncaughtExceptionHandler. "Top level" methods
* that dispatch events from the browser into user code must call this method
* on entry to get the active handler. If the active handler is null, the
* entry point must allow exceptions to escape into the browser. If the
* handler is non-null, exceptions must be caught and routed to the handler.
* See the source code for <code>DOM.dispatchEvent()</code> for an example
* of how to handle this correctly.
*
* @return the currently active handler, or null if no handler is active.
*/
public static UncaughtExceptionHandler getUncaughtExceptionHandler() {
return sUncaughtExceptionHandler;
};
/**
* Determines whether or not the running program is script or bytecode.
*/
public static boolean isScript() {
return true;
}
/**
* Logs a message to the development shell logger in hosted mode. Calls are
* optimized out in web mode.
*/
public static void log(String message, Throwable e) {
// intentionally empty in web mode.
}
/**
* Sets a custom uncaught exception handler. See
* {@link #getUncaughtExceptionHandler()} for details.
*
* @param handler the handler that should be called when an exception is about
* to escape to the browser, or <code>null</code> to clear the
* handler and allow exceptions to escape.
*/
public static void setUncaughtExceptionHandler(
UncaughtExceptionHandler handler) {
sUncaughtExceptionHandler = handler;
};
}
| true | true | public static Object create(Class classLiteral) {
/*
* In web mode, the compiler directly replaces calls to this method with a
* new Object() type expression of the correct rebound type.
*/
throw new RuntimeException(
"GWT has not been properly initialized; if you are running a unit test, check that your test case extends GWTTestCase");
}
| public static Object create(Class classLiteral) {
/*
* In web mode, the compiler directly replaces calls to this method with a
* new Object() type expression of the correct rebound type.
*/
throw new UnsupportedOperationException(
"ERROR: GWT.create() is only usable in client code! It cannot be called, "
+ "for example, from server code. If you are running a unit test, "
+ "check that your test case extends GWTTestCase and that GWT.create() "
+ "is not called from within an initializer, constructor, or "
+ "setUp()/tearDown().");
}
|
diff --git a/src/main/java/org/dspace/ctask/replicate/store/LocalObjectStore.java b/src/main/java/org/dspace/ctask/replicate/store/LocalObjectStore.java
index 3f79184..3bae622 100644
--- a/src/main/java/org/dspace/ctask/replicate/store/LocalObjectStore.java
+++ b/src/main/java/org/dspace/ctask/replicate/store/LocalObjectStore.java
@@ -1,144 +1,144 @@
/**
* 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.ctask.replicate.store;
import java.io.File;
import java.io.IOException;
import org.dspace.core.ConfigurationManager;
import org.dspace.ctask.replicate.ObjectStore;
import org.dspace.curate.Utils;
/**
* LocalObjectStore uses the local file system to manage replicas or other
* content. As such, it is not intended to provide the level of assurance that
* a remote, externally managed service can provide. It's primary use is in
* testing and validating the replication service, not as a production replica
* store. Note in particular that certain filesystem limits on number of files
* in a directory may limit its use. It stores replicas as archive files.
* Also note that for efficiency, this store assumes that File.renameTo will
* succeed, and renames are preferred to copies when possible. Where this
* assumption is not valid (e.g. with an NFS-mounted store), use the
* MountableObjectStore class instead.
*
* @author richardrodgers
*/
public class LocalObjectStore implements ObjectStore {
// where replicas are kept
protected String storeDir = null;
// need no-arg constructor for PluginManager
public LocalObjectStore() {
}
@Override
public void init() throws IOException
{
storeDir = ConfigurationManager.getProperty("replicate", "store.dir");
File storeFile = new File(storeDir);
if (! storeFile.exists())
{
storeFile.mkdirs();
}
}
@Override
public long fetchObject(String group, String id, File file) throws IOException
{
// locate archive and copy to file
long size = 0L;
File archFile = new File(storeDir + File.separator + group, id);
if (archFile.exists())
{
size = archFile.length();
Utils.copy(archFile, file);
}
return size;
}
@Override
public boolean objectExists(String group, String id)
{
// do we have a copy in our managed area?
return new File(storeDir + File.separator + group, id).exists();
}
@Override
public long removeObject(String group, String id)
{
// remove file if present
long size = 0L;
File remFile = new File(storeDir + File.separator + group, id);
if (remFile.exists())
{
size = remFile.length();
remFile.delete();
}
return size;
}
@Override
public long transferObject(String group, File file) throws IOException
{
// local transfer is a simple matter of renaming the file,
// we don't bother checking if replica is really new, since
// local deletes/copies are cheap
File archDir = new File(storeDir, group);
if (! archDir.isDirectory())
{
archDir.mkdirs();
}
File archFile = new File(archDir, file.getName());
if (archFile.exists())
{
archFile.delete();
}
if (! file.renameTo(archFile))
{
throw new UnsupportedOperationException("Store does not support rename");
}
- return file.length();
+ return archFile.length();
}
@Override
public String objectAttribute(String group, String id, String attrName) throws IOException
{
File archFile = new File(storeDir + File.separator + group, id);
if ("checksum".equals(attrName))
{
return Utils.checksum(archFile, "MD5");
}
else if ("sizebytes".equals(attrName))
{
return String.valueOf(archFile.length());
}
else if ("modified".equals(attrName))
{
return String.valueOf(archFile.lastModified());
}
return null;
}
@Override
public long moveObject(String srcGroup, String destGroup, String id) throws IOException
{
long size = 0L;
//Find the file
File file = new File(storeDir + File.separator + srcGroup, id);
if (file.exists())
{
//If file is found, just transfer it to destination,
// as transferObject() just does a file rename
size = transferObject(destGroup, file);
}
return size;
}
}
| true | true | public long transferObject(String group, File file) throws IOException
{
// local transfer is a simple matter of renaming the file,
// we don't bother checking if replica is really new, since
// local deletes/copies are cheap
File archDir = new File(storeDir, group);
if (! archDir.isDirectory())
{
archDir.mkdirs();
}
File archFile = new File(archDir, file.getName());
if (archFile.exists())
{
archFile.delete();
}
if (! file.renameTo(archFile))
{
throw new UnsupportedOperationException("Store does not support rename");
}
return file.length();
}
| public long transferObject(String group, File file) throws IOException
{
// local transfer is a simple matter of renaming the file,
// we don't bother checking if replica is really new, since
// local deletes/copies are cheap
File archDir = new File(storeDir, group);
if (! archDir.isDirectory())
{
archDir.mkdirs();
}
File archFile = new File(archDir, file.getName());
if (archFile.exists())
{
archFile.delete();
}
if (! file.renameTo(archFile))
{
throw new UnsupportedOperationException("Store does not support rename");
}
return archFile.length();
}
|
diff --git a/sonar/sonar-plugin-sourcemonitor/src/test/java/org/sonar/plugin/dotnet/srcmon/SourceMonitorResultParserTest.java b/sonar/sonar-plugin-sourcemonitor/src/test/java/org/sonar/plugin/dotnet/srcmon/SourceMonitorResultParserTest.java
index 54b7e16..4c1bf31 100644
--- a/sonar/sonar-plugin-sourcemonitor/src/test/java/org/sonar/plugin/dotnet/srcmon/SourceMonitorResultParserTest.java
+++ b/sonar/sonar-plugin-sourcemonitor/src/test/java/org/sonar/plugin/dotnet/srcmon/SourceMonitorResultParserTest.java
@@ -1,74 +1,73 @@
/*
* Maven and Sonar plugin for .Net
* Copyright (C) 2010 Jose Chillan and Alexandre Victoor
* mailto: [email protected] or [email protected]
*
* Sonar 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.
*
* Sonar 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 Sonar; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
*/
package org.sonar.plugin.dotnet.srcmon;
import static org.junit.Assert.*;
import java.io.File;
import java.io.IOException;
import java.util.List;
import org.junit.Test;
import org.sonar.plugin.dotnet.srcmon.model.FileMetrics;
public class SourceMonitorResultParserTest {
@Test
public void testParse() throws IOException {
File reportFile = new File("target/test-classes/solution/MessyTestSolution/target/metrics-report.xml");
simpleTest(reportFile);
}
/**
* Same as above with a latinlocale where ',' is the decimal delimiter instead of '.'
* See http://jira.codehaus.org/browse/SONARPLUGINS-965
* @throws IOException
*/
@Test
public void testParseLatinLocale() throws IOException {
File reportFile = new File("target/test-classes/solution/MessyTestSolution/target/metrics-report-latin.xml");
simpleTest(reportFile);
}
private void simpleTest(File reportFile) throws IOException {
SourceMonitorResultParser parser = new SourceMonitorResultStaxParser();
- File moneyFile = new File("target/test-classes/solution/MessyTestSolution/MessyTestApplication/Money.cs");
List<FileMetrics> metrics = parser.parse(reportFile);
assertNotNull(metrics);
assertEquals(5, metrics.size());
FileMetrics firstFile = metrics.get(0);
assertEquals(62, firstFile.getComplexity());
- assertEquals(moneyFile.getCanonicalPath(), firstFile.getSourcePath().getCanonicalPath());
+ assertTrue(firstFile.getSourcePath().getCanonicalPath().endsWith("Money.cs"));
assertEquals(3, firstFile.getCountClasses());
assertEquals(29, firstFile.getCommentLines());
assertEquals(1.77, firstFile.getAverageComplexity(),0.00001D);
assertEquals("MessyTestApplication.Money", firstFile.getClassName());
assertEquals(10, firstFile.getCountAccessors());
assertEquals(53, firstFile.getCountBlankLines());
assertEquals(3, firstFile.getCountCalls());
assertEquals(387, firstFile.getCountLines());
assertEquals(11, firstFile.getCountMethods());
assertEquals(4, firstFile.getCountMethodStatements());
assertEquals(199, firstFile.getCountStatements());
assertEquals(10, firstFile.getDocumentationLines());
}
}
| false | true | private void simpleTest(File reportFile) throws IOException {
SourceMonitorResultParser parser = new SourceMonitorResultStaxParser();
File moneyFile = new File("target/test-classes/solution/MessyTestSolution/MessyTestApplication/Money.cs");
List<FileMetrics> metrics = parser.parse(reportFile);
assertNotNull(metrics);
assertEquals(5, metrics.size());
FileMetrics firstFile = metrics.get(0);
assertEquals(62, firstFile.getComplexity());
assertEquals(moneyFile.getCanonicalPath(), firstFile.getSourcePath().getCanonicalPath());
assertEquals(3, firstFile.getCountClasses());
assertEquals(29, firstFile.getCommentLines());
assertEquals(1.77, firstFile.getAverageComplexity(),0.00001D);
assertEquals("MessyTestApplication.Money", firstFile.getClassName());
assertEquals(10, firstFile.getCountAccessors());
assertEquals(53, firstFile.getCountBlankLines());
assertEquals(3, firstFile.getCountCalls());
assertEquals(387, firstFile.getCountLines());
assertEquals(11, firstFile.getCountMethods());
assertEquals(4, firstFile.getCountMethodStatements());
assertEquals(199, firstFile.getCountStatements());
assertEquals(10, firstFile.getDocumentationLines());
}
| private void simpleTest(File reportFile) throws IOException {
SourceMonitorResultParser parser = new SourceMonitorResultStaxParser();
List<FileMetrics> metrics = parser.parse(reportFile);
assertNotNull(metrics);
assertEquals(5, metrics.size());
FileMetrics firstFile = metrics.get(0);
assertEquals(62, firstFile.getComplexity());
assertTrue(firstFile.getSourcePath().getCanonicalPath().endsWith("Money.cs"));
assertEquals(3, firstFile.getCountClasses());
assertEquals(29, firstFile.getCommentLines());
assertEquals(1.77, firstFile.getAverageComplexity(),0.00001D);
assertEquals("MessyTestApplication.Money", firstFile.getClassName());
assertEquals(10, firstFile.getCountAccessors());
assertEquals(53, firstFile.getCountBlankLines());
assertEquals(3, firstFile.getCountCalls());
assertEquals(387, firstFile.getCountLines());
assertEquals(11, firstFile.getCountMethods());
assertEquals(4, firstFile.getCountMethodStatements());
assertEquals(199, firstFile.getCountStatements());
assertEquals(10, firstFile.getDocumentationLines());
}
|
diff --git a/src/main/java/net/praqma/drmemory/DrMemoryResult.java b/src/main/java/net/praqma/drmemory/DrMemoryResult.java
index 6014195..9cadd47 100644
--- a/src/main/java/net/praqma/drmemory/DrMemoryResult.java
+++ b/src/main/java/net/praqma/drmemory/DrMemoryResult.java
@@ -1,362 +1,362 @@
package net.praqma.drmemory;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.praqma.drmemory.exceptions.InvalidInputException;
import net.praqma.util.debug.Logger;
public class DrMemoryResult {
private static Logger logger = Logger.getLogger();
public static class ErrorSummary {
public String header = "";
public Integer unique;
public Integer total;
public String toString() {
return header;
}
}
private ErrorSummary unaddressableAccesses = new ErrorSummary();
private ErrorSummary uninitializedAccess = new ErrorSummary();
private ErrorSummary invalidHeapArguments = new ErrorSummary();
private ErrorSummary warnings = new ErrorSummary();
private ErrorSummary bytesOfLeaks = new ErrorSummary();
private ErrorSummary leakCount = new ErrorSummary();
private ErrorSummary possibleLeakCount = new ErrorSummary();
private ErrorSummary bytesOfPossibleLeaks = new ErrorSummary();
private ErrorSummary stillReachableAllocations = new ErrorSummary();
private List<ErrorSummary> list = new ArrayList<ErrorSummary>();
private String version;
private String date;
private String cmd;
private List<String> elements;
private Map<Integer, DrMemoryError> errors = new HashMap<Integer, DrMemoryError>();
private DrMemoryResult() {
}
public String getVersion() {
return version;
}
public String getDate() {
return date;
}
public String getCmd() {
return cmd;
}
public List<String> getElements() {
return elements;
}
public Map<Integer, DrMemoryError> getErrors() {
return errors;
}
public ErrorSummary getUnaddressableAccesses() {
return unaddressableAccesses;
}
public ErrorSummary getUninitializedAccess() {
return uninitializedAccess;
}
public ErrorSummary getInvalidHeapArguments() {
return invalidHeapArguments;
}
public ErrorSummary getWarnings() {
return warnings;
}
public ErrorSummary getBytesOfLeaks() {
return bytesOfLeaks;
}
public ErrorSummary getLeakCount() {
return leakCount;
}
public ErrorSummary getBytesOfPossibleLeaks() {
return bytesOfPossibleLeaks;
}
public ErrorSummary getPossibleLeakCount() {
return possibleLeakCount;
}
public ErrorSummary getStillReachableAllocations() {
return stillReachableAllocations;
}
public List<ErrorSummary> getSummaries() {
return list;
}
public static final Pattern rx_version = Pattern.compile( "^.*version (.*?) built on (.*?)$", Pattern.MULTILINE );
public static final Pattern rx_command = Pattern.compile( "^Application cmdline: \"(.*)\"\\s*$", Pattern.MULTILINE );
//public static final Pattern rx_duplicates = Pattern.compile( "^DUPLICATE ERROR COUNTS:\\s*$(.*?)^\\s*$", Pattern.MULTILINE | Pattern.DOTALL );
public static final Pattern rx_duplicates = Pattern.compile( "^DUPLICATE ERROR COUNTS:\\s*$", Pattern.MULTILINE | Pattern.DOTALL );
public static final Pattern rx_duplicates_finder = Pattern.compile( "^\\s*Error #\\s*(\\d+):\\s*(\\d+)\\s*$", Pattern.MULTILINE | Pattern.DOTALL );
public static final Pattern rx_errors_found = Pattern.compile( "^\\s*ERRORS FOUND:\\s*$", Pattern.MULTILINE | Pattern.DOTALL );
public static final int __TOP_COUNT = 3;
public static DrMemoryResult parse( File file ) throws IOException, InvalidInputException {
String[] top = getTop( file );
DrMemoryResult result = new DrMemoryResult();
Matcher mv = rx_version.matcher( top[0] );
result.version = "0";
result.date = "?";
if( mv.find() ) {
result.version = mv.group( 1 );
result.date = mv.group( 2 );
} else {
logger.error( "Possibly a style change!!!" );
logger.error( "Could not get version" );
}
Matcher mcmd = rx_command.matcher( top[1] );
result.cmd = "?";
if( mcmd.find() ) {
result.cmd = mcmd.group( 1 );
} else {
logger.error( "Possibly a style change!!!" );
logger.error( "Could not get command line" );
}
/* Get the elements and retrieve the individual errors */
result.elements = DrMemoryResult.getElements( file );
for( String e : result.elements ) {
if( e.startsWith( "Error #" ) ) {
//logger.debug( "HERE" );
DrMemoryError error = DrMemoryError.parse( e );
result.errors.put( error.getIdentifier(), error );
continue;
}
/* Get duplicate count */
Matcher m = rx_duplicates.matcher( e );
if( m.find() ) {
logger.debug( "Found duplicates" );
getDuplicates( result, e );
continue;
}
/* Get error summary */
Matcher sum = rx_errors_found.matcher( e );
if( sum.find() ) {
logger.debug( "Found error summary" );
getErrorSummary( result, e );
continue;
}
}
/* Make list */
result.list.add( result.possibleLeakCount );
result.list.add( result.leakCount );
result.list.add( result.bytesOfLeaks );
result.list.add( result.bytesOfPossibleLeaks );
result.list.add( result.invalidHeapArguments );
result.list.add( result.stillReachableAllocations );
result.list.add( result.unaddressableAccesses );
result.list.add( result.uninitializedAccess );
result.list.add( result.warnings );
return result;
}
public static final Pattern rx_error_unaddr = Pattern.compile( "^\\s*(\\d+) unique,\\s*(\\d+) total unaddressable access\\(es\\)\\s*$", Pattern.MULTILINE );
public static final Pattern rx_error_uninit = Pattern.compile( "^\\s*(\\d+) unique,\\s*(\\d+) total uninitialized access\\(es\\)\\s*$", Pattern.MULTILINE );
public static final Pattern rx_error_unvali = Pattern.compile( "^\\s*(\\d+) unique,\\s*(\\d+) total invalid heap argument\\(s\\)\\s*$", Pattern.MULTILINE );
public static final Pattern rx_error_warnin = Pattern.compile( "^\\s*(\\d+) unique,\\s*(\\d+) total warning\\(s\\)\\s*$", Pattern.MULTILINE );
public static final Pattern rx_error_leaks = Pattern.compile( "^\\s*(\\d+) unique,\\s*(\\d+) total,\\s*(\\d+) byte\\(s\\) of leak\\(s\\)\\s*$", Pattern.MULTILINE );
public static final Pattern rx_error_possib = Pattern.compile( "^\\s*(\\d+) unique,\\s*(\\d+) total,\\s*(\\d+) byte\\(s\\) of possible leak\\(s\\)\\s*$", Pattern.MULTILINE );
public static final Pattern rx_error_still_ = Pattern.compile( "^\\s*(\\d+) still-reachable allocation\\(s\\)\\s*$", Pattern.MULTILINE );
public static void getErrorSummary( DrMemoryResult result, String summary ) {
//logger.debug( summary );
Matcher m_unaddr = rx_error_unaddr.matcher( summary );
if( m_unaddr.find() ) {
logger.debug( "Found unaddressble accesses!" );
ErrorSummary es = new ErrorSummary();
es.header = "Unaddressable accesses";
es.unique = Integer.parseInt( m_unaddr.group( 1 ) );
es.total = Integer.parseInt( m_unaddr.group( 2 ) );
result.unaddressableAccesses = es;
}
Matcher m_uninit = rx_error_uninit.matcher( summary );
if( m_uninit.find() ) {
logger.debug( "Found uninitialized accesses!" );
ErrorSummary es = new ErrorSummary();
es.header = "Uninitialized accesses";
es.unique = Integer.parseInt( m_uninit.group( 1 ) );
es.total = Integer.parseInt( m_uninit.group( 2 ) );
result.uninitializedAccess = es;
}
Matcher m_invali = rx_error_unvali.matcher( summary );
if( m_invali.find() ) {
logger.debug( "Found invalid heap argument!" );
ErrorSummary es = new ErrorSummary();
es.header = "Invalid heap arguments";
es.unique = Integer.parseInt( m_invali.group( 1 ) );
es.total = Integer.parseInt( m_invali.group( 2 ) );
result.invalidHeapArguments = es;
}
Matcher m_warnin = rx_error_warnin.matcher( summary );
if( m_warnin.find() ) {
logger.debug( "Found warning!" );
ErrorSummary es = new ErrorSummary();
es.header = "Warnings";
es.unique = Integer.parseInt( m_warnin.group( 1 ) );
es.total = Integer.parseInt( m_warnin.group( 2 ) );
result.warnings = es;
}
Matcher m_leaks = rx_error_leaks.matcher( summary );
if( m_leaks.find() ) {
logger.debug( "Found leaks!" );
ErrorSummary es = new ErrorSummary();
es.header = "Leaks";
es.unique = Integer.parseInt( m_leaks.group( 1 ) );
es.total = Integer.parseInt( m_leaks.group( 2 ) );
result.leakCount = es;
ErrorSummary es2 = new ErrorSummary();
es2.total = Integer.parseInt( m_leaks.group( 3 ) );
es2.header = "Bytes of Leak";
result.bytesOfLeaks = es2;
}
Matcher m_possib = rx_error_possib.matcher( summary );
if( m_possib.find() ) {
logger.debug( "Found possible leaks!" );
ErrorSummary es = new ErrorSummary();
es.header = "Possible leaks";
es.unique = Integer.parseInt( m_possib.group( 1 ) );
es.total = Integer.parseInt( m_possib.group( 2 ) );
result.possibleLeakCount = es;
ErrorSummary es2 = new ErrorSummary();
- es2.total = Integer.parseInt( m_leaks.group( 3 ) );
+ es2.total = Integer.parseInt( m_possib.group( 3 ) );
es2.header = "Bytes of Possible Leak";
result.bytesOfPossibleLeaks = es2;
}
Matcher m_still_ = rx_error_still_.matcher( summary );
if( m_still_.find() ) {
logger.debug( "Found still-reachable allocations!" );
ErrorSummary es = new ErrorSummary();
es.header = "Still-reachable allocations";
es.total = Integer.parseInt( m_still_.group( 1 ) );
result.stillReachableAllocations = es;
}
}
public static void getDuplicates( DrMemoryResult result, String duplicates ) {
Matcher m = rx_duplicates_finder.matcher( duplicates );
while( m.find() ) {
Integer id = Integer.parseInt( m.group( 1 ) );
int cnt = Integer.parseInt( m.group( 2 ) );
//logger.debug( "Setting " + cnt + " duplicate" + ( cnt == 1 ? "" : "s" ) + " to " + id );
try {
result.getErrors().get( id ).setDuplicates( cnt );
} catch( Exception e ) {
logger.warning( "Unable to set " + cnt + " duplicate" + ( cnt == 1 ? "" : "s" ) + " to " + id );
}
}
}
public static List<String> getElements( File file ) throws IOException {
FileReader fr = new FileReader( file );
BufferedReader br = new BufferedReader( fr );
List<String> list = new ArrayList<String>();
StringBuilder sb = new StringBuilder();
String line;
int cnt = 0;
while( ( line = br.readLine() ) != null ) {
if( cnt > ( __TOP_COUNT ) ) {
if( line.matches( "^\\s*$" ) ) {
list.add( sb.toString() );
sb.setLength( 0 );
} else {
sb.append( line + "\n" );
}
}
cnt++;
}
if( sb.length() > 0 ) {
list.add( sb.toString() );
}
return list;
}
public static String[] getTop( File file ) throws IOException {
FileReader fr = new FileReader( file );
BufferedReader br = new BufferedReader( fr );
String[] buffer = new String[__TOP_COUNT];
for( int i = 0 ; i < __TOP_COUNT ; ++i ) {
buffer[i] = br.readLine();
}
return buffer;
}
}
| true | true | public static void getErrorSummary( DrMemoryResult result, String summary ) {
//logger.debug( summary );
Matcher m_unaddr = rx_error_unaddr.matcher( summary );
if( m_unaddr.find() ) {
logger.debug( "Found unaddressble accesses!" );
ErrorSummary es = new ErrorSummary();
es.header = "Unaddressable accesses";
es.unique = Integer.parseInt( m_unaddr.group( 1 ) );
es.total = Integer.parseInt( m_unaddr.group( 2 ) );
result.unaddressableAccesses = es;
}
Matcher m_uninit = rx_error_uninit.matcher( summary );
if( m_uninit.find() ) {
logger.debug( "Found uninitialized accesses!" );
ErrorSummary es = new ErrorSummary();
es.header = "Uninitialized accesses";
es.unique = Integer.parseInt( m_uninit.group( 1 ) );
es.total = Integer.parseInt( m_uninit.group( 2 ) );
result.uninitializedAccess = es;
}
Matcher m_invali = rx_error_unvali.matcher( summary );
if( m_invali.find() ) {
logger.debug( "Found invalid heap argument!" );
ErrorSummary es = new ErrorSummary();
es.header = "Invalid heap arguments";
es.unique = Integer.parseInt( m_invali.group( 1 ) );
es.total = Integer.parseInt( m_invali.group( 2 ) );
result.invalidHeapArguments = es;
}
Matcher m_warnin = rx_error_warnin.matcher( summary );
if( m_warnin.find() ) {
logger.debug( "Found warning!" );
ErrorSummary es = new ErrorSummary();
es.header = "Warnings";
es.unique = Integer.parseInt( m_warnin.group( 1 ) );
es.total = Integer.parseInt( m_warnin.group( 2 ) );
result.warnings = es;
}
Matcher m_leaks = rx_error_leaks.matcher( summary );
if( m_leaks.find() ) {
logger.debug( "Found leaks!" );
ErrorSummary es = new ErrorSummary();
es.header = "Leaks";
es.unique = Integer.parseInt( m_leaks.group( 1 ) );
es.total = Integer.parseInt( m_leaks.group( 2 ) );
result.leakCount = es;
ErrorSummary es2 = new ErrorSummary();
es2.total = Integer.parseInt( m_leaks.group( 3 ) );
es2.header = "Bytes of Leak";
result.bytesOfLeaks = es2;
}
Matcher m_possib = rx_error_possib.matcher( summary );
if( m_possib.find() ) {
logger.debug( "Found possible leaks!" );
ErrorSummary es = new ErrorSummary();
es.header = "Possible leaks";
es.unique = Integer.parseInt( m_possib.group( 1 ) );
es.total = Integer.parseInt( m_possib.group( 2 ) );
result.possibleLeakCount = es;
ErrorSummary es2 = new ErrorSummary();
es2.total = Integer.parseInt( m_leaks.group( 3 ) );
es2.header = "Bytes of Possible Leak";
result.bytesOfPossibleLeaks = es2;
}
Matcher m_still_ = rx_error_still_.matcher( summary );
if( m_still_.find() ) {
logger.debug( "Found still-reachable allocations!" );
ErrorSummary es = new ErrorSummary();
es.header = "Still-reachable allocations";
es.total = Integer.parseInt( m_still_.group( 1 ) );
result.stillReachableAllocations = es;
}
}
| public static void getErrorSummary( DrMemoryResult result, String summary ) {
//logger.debug( summary );
Matcher m_unaddr = rx_error_unaddr.matcher( summary );
if( m_unaddr.find() ) {
logger.debug( "Found unaddressble accesses!" );
ErrorSummary es = new ErrorSummary();
es.header = "Unaddressable accesses";
es.unique = Integer.parseInt( m_unaddr.group( 1 ) );
es.total = Integer.parseInt( m_unaddr.group( 2 ) );
result.unaddressableAccesses = es;
}
Matcher m_uninit = rx_error_uninit.matcher( summary );
if( m_uninit.find() ) {
logger.debug( "Found uninitialized accesses!" );
ErrorSummary es = new ErrorSummary();
es.header = "Uninitialized accesses";
es.unique = Integer.parseInt( m_uninit.group( 1 ) );
es.total = Integer.parseInt( m_uninit.group( 2 ) );
result.uninitializedAccess = es;
}
Matcher m_invali = rx_error_unvali.matcher( summary );
if( m_invali.find() ) {
logger.debug( "Found invalid heap argument!" );
ErrorSummary es = new ErrorSummary();
es.header = "Invalid heap arguments";
es.unique = Integer.parseInt( m_invali.group( 1 ) );
es.total = Integer.parseInt( m_invali.group( 2 ) );
result.invalidHeapArguments = es;
}
Matcher m_warnin = rx_error_warnin.matcher( summary );
if( m_warnin.find() ) {
logger.debug( "Found warning!" );
ErrorSummary es = new ErrorSummary();
es.header = "Warnings";
es.unique = Integer.parseInt( m_warnin.group( 1 ) );
es.total = Integer.parseInt( m_warnin.group( 2 ) );
result.warnings = es;
}
Matcher m_leaks = rx_error_leaks.matcher( summary );
if( m_leaks.find() ) {
logger.debug( "Found leaks!" );
ErrorSummary es = new ErrorSummary();
es.header = "Leaks";
es.unique = Integer.parseInt( m_leaks.group( 1 ) );
es.total = Integer.parseInt( m_leaks.group( 2 ) );
result.leakCount = es;
ErrorSummary es2 = new ErrorSummary();
es2.total = Integer.parseInt( m_leaks.group( 3 ) );
es2.header = "Bytes of Leak";
result.bytesOfLeaks = es2;
}
Matcher m_possib = rx_error_possib.matcher( summary );
if( m_possib.find() ) {
logger.debug( "Found possible leaks!" );
ErrorSummary es = new ErrorSummary();
es.header = "Possible leaks";
es.unique = Integer.parseInt( m_possib.group( 1 ) );
es.total = Integer.parseInt( m_possib.group( 2 ) );
result.possibleLeakCount = es;
ErrorSummary es2 = new ErrorSummary();
es2.total = Integer.parseInt( m_possib.group( 3 ) );
es2.header = "Bytes of Possible Leak";
result.bytesOfPossibleLeaks = es2;
}
Matcher m_still_ = rx_error_still_.matcher( summary );
if( m_still_.find() ) {
logger.debug( "Found still-reachable allocations!" );
ErrorSummary es = new ErrorSummary();
es.header = "Still-reachable allocations";
es.total = Integer.parseInt( m_still_.group( 1 ) );
result.stillReachableAllocations = es;
}
}
|
diff --git a/ui/isometric/IsoCanvas.java b/ui/isometric/IsoCanvas.java
index c208f62..f6a0b02 100644
--- a/ui/isometric/IsoCanvas.java
+++ b/ui/isometric/IsoCanvas.java
@@ -1,463 +1,465 @@
package ui.isometric;
import game.Location;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Composite;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.swing.JPanel;
import ui.isometric.abstractions.IsoImage;
import ui.isometric.abstractions.IsoSquare;
import ui.isometric.libraries.IsoRendererLibrary;
import util.Direction;
import util.Position;
import util.Resources;
/**
*
* This canvas will render a section of the world, using the given datasource.
*
* @author melby
*
*/
public class IsoCanvas extends JPanel implements MouseMotionListener, MouseListener {
private static final long serialVersionUID = 1L;
public static final int TILE_X = 64;
public static final int TILE_Y = 44;
private IsoDataSource dataSource;
private Direction viewDirection = Direction.NORTH;
private Point mouse;
private Point origin = new Point(0, 0);
private boolean selectionRender = false;
private IsoImage selectedImage;
private Position selectedSquarePosition;
private Point selectionPoint = new Point(0, 0);
private UILayerRenderer selectedRenderer;
public static final double FPS = 20;
private List<UILayerRenderer> extraRenderers = new ArrayList<UILayerRenderer>();
private boolean draggingOk = true;
private BufferedImage backbuffer;
private Graphics2D graphics;
private Image lightMask;
private Point lightPoint;
/**
* An interface for rendering extra content on top of the IsoCanvas
*
* @author melby
*
*/
public static interface UILayerRenderer {
/**
* The level this renderer should renderer at
* @return
*/
public int level();
/**
* Do the rendering into the specified Graphics context
* @param g
* @param into
*/
public void render(Graphics2D g, IsoCanvas into);
/**
* Can use this to figure out what was under the mouse.
* Note don't use this for actions, as this being called is not a guarantee
* that this renderer was not obscured by another renderer. To do that
* wait for a call to wasClicked(), which will be called if this was the topmost
* renderer. This will be called immediately after, so it is safe to store information
* about the click between the two calls.
*
* @param selectionPoint - the point in view coordinates of the selection
* @param isoCanvas - the canvas this is in
* @return whether this renderer would want to intercept the selection
*/
public boolean doSelectionPass(Point selectionPoint, IsoCanvas isoCanvas);
/**
* Called after a call to doSelectionPass if this component was the topmost
* of all the renderers and can act on a mouse down
* @param event - the event that triggered the selection
* @param canvas - the canvas the click was in
*/
public void wasClicked(MouseEvent event, IsoCanvas canvas);
/**
* Set the superview, ok to ignore
* @param canvas
*/
public void setSuperview(IsoCanvas canvas);
}
/**
* An interface for objects that wish to be added to the set of objects to be notified when a selection is made
*
* @author melby
*
*/
public interface SelectionCallback {
/**
* A specific image and location that was selected
* @param image - the image selected
* @param loc - the location under the mouse
* @param event
*/
public void selected(IsoImage image, Location loc, MouseEvent event);
}
private Set<SelectionCallback> selectionCallback = new HashSet<SelectionCallback>();
/**
* Create a new IsoCanvas with a given datasource
* @param dataSource
*/
public IsoCanvas(IsoDataSource dataSource) {
this.dataSource = dataSource;
this.addMouseListener(this);
this.addMouseMotionListener(this);
new Thread(new Runnable() {
@Override
public void run() {
while(true) {
repaint();
try {
Thread.sleep((long) (1000/FPS));
} catch (InterruptedException e) { }
}
}
}).start();
this.setFocusable(true);
backbuffer = new BufferedImage(2560, 2560, BufferedImage.TYPE_INT_ARGB_PRE); // TODO: Max view size
graphics = backbuffer.createGraphics();
try {
graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
}
catch(Exception e) {} // Stupid java bug when not on windows
try {
lightMask = Resources.readImageResourceUnfliped("/resources/test/light_mask.png");
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void paint(Graphics jgraphics) {
dataSource.setViewableRect((int)origin.getX(), (int)origin.getY(), this.getWidth(), this.getHeight(), viewDirection);
dataSource.update();
Point smoothing = dataSource.transform().smoothOrigin(origin);
Composite oc = null;
if(!selectionRender) {
jgraphics.fillRect(0, 0, this.getWidth(), this.getHeight());
+ graphics.setColor(Color.BLACK);
graphics.setBackground(new Color(0, 0, 0, 0));
graphics.clearRect(0, 0, this.getWidth(), this.getHeight());
oc = graphics.getComposite();
if(lightMask != null && lightPoint != null) {
graphics.drawImage(lightMask, lightPoint.x, lightPoint.y, null);
graphics.setComposite(AlphaComposite.SrcAtop);
+ graphics.fillRect(0, 0, this.getWidth(), this.getHeight());
}
}
int rowY = TILE_Y/2;
int tileCountY = this.getHeight()/rowY+5;
int tileCountX = this.getWidth()/TILE_X+2;
int row = 0;
int y = -rowY; // rowY
for(;y<tileCountY*rowY;y+=rowY) {
if(!selectionRender || selectionPoint.y < y+smoothing.getY()) {
int yg = -((row%2 == 0)?row/2-1:row/2);
int xg = (row%2 == 0)?row/2:(row-1)/2;
int x = ((row%2 == 0)?TILE_X/2:0)-TILE_X;
for(;x<tileCountX*TILE_X;x+=TILE_X) {
this.drawSquareAt(graphics, (int)(x+smoothing.getX()), (int)(y+smoothing.getY()), xg, yg);
yg++;
xg++;
}
}
row++;
}
if(!selectionRender) {
graphics.setComposite(oc);
for(UILayerRenderer ren : extraRenderers) {
ren.render(graphics, this);
}
jgraphics.drawImage(backbuffer, 0, 0, null);
}
else {
for(UILayerRenderer ren : extraRenderers) {
if(ren.doSelectionPass(selectionPoint, this)) {
selectedRenderer = ren;
}
}
}
}
/**
* Draw a square at a given location
* @param g
* @param dx
* @param dy
* @param sx
* @param sy
*/
private void drawSquareAt(Graphics2D g, int dx, int dy, int sx, int sy) {
IsoSquare square = dataSource.squareAt(sx, sy);
if(square.numberOfImages() > 0) {
for(IsoImage i : square) {
if(!selectionRender) {
g.drawImage(i.image(), dx-i.width()/2, dy-i.height()-i.yoffset(), i.width(), i.height(), null, this);
}
else {
if(selectionPoint.x > dx-i.width()/2 && selectionPoint.x < dx+i.width()/2) { // Check x
if(selectionPoint.y > dy-i.height() && selectionPoint.y < dy) { // Check y
int x = selectionPoint.x - dx + i.width()/2;
int y = selectionPoint.y - dy + i.height();
int[] pixels = new int[4];
i.image().getAlphaRaster().getPixel(x, y, pixels);
if(pixels[0] > 0) {
selectedImage = i;
}
}
}
}
}
}
if(selectionRender) {
if(selectionPoint.x > dx-TILE_X/2 && selectionPoint.x < dx+TILE_X/2) { // Check x
if(selectionPoint.y > dy-TILE_Y && selectionPoint.y < dy) { // Check y
int x = selectionPoint.x - dx + TILE_X/2;
int y = selectionPoint.y - dy + TILE_Y;
int[] pixels = new int[4];
IsoRendererLibrary.maskTile().getAlphaRaster().getPixel(x, y, pixels);
if(pixels[0] > 0) {
selectedSquarePosition = dataSource.transform().transformViewToMap(new Position(sx, sy));
}
}
}
}
}
@Override
public void mouseDragged(MouseEvent arg0) {
if(draggingOk) {
Point delta = new Point(arg0.getPoint().x-mouse.x, arg0.getPoint().y-mouse.y);
delta = dataSource.transform().transformRelativePoint(delta);
mouse = arg0.getPoint();
origin.setLocation(origin.getX()-delta.getX(), origin.getY()+delta.getY());
this.repaint();
}
}
@Override
public void mouseMoved(MouseEvent arg0) {}
@Override
public void mouseClicked(MouseEvent arg0) {
this.calculateTypesAtAtPoint(arg0.getPoint());
final IsoImage i = this.getCachedSelectedImage();
final Position s = this.getCachedSelectedSquarePosition();
final UILayerRenderer r = this.getCachedSelectedRenderer();
if(r == null) {
for(SelectionCallback c : selectionCallback) {
c.selected(i, dataSource.level().location(s, Direction.NORTH), arg0);
}
}
else {
r.wasClicked(arg0, this);
}
}
/**
* Compute the image/square/renderer at a given point
* Use
* @param point
*/
public void calculateTypesAtAtPoint(Point point) {
selectedImage = null;
selectedSquarePosition = null;
selectedRenderer = null;
selectionRender = true;
selectionPoint = point;
try {
this.paint(null);
}
catch (Exception e) {
System.err.println("Exception renderering for selection");
e.printStackTrace();
}
selectionRender = false;
}
/**
* Get the cached selected image, does no checking to ensure it is not stale,
* should only be called directly after calculateTypesAtAtPoint
* @return
*/
public IsoImage getCachedSelectedImage() {
return selectedImage;
}
/**
* Get the cached selected square location, does no checking to ensure it is not stale,
* should only be called directly after calculateTypesAtAtPoint
* @return
*/
public Position getCachedSelectedSquarePosition() {
return selectedSquarePosition;
}
/**
* Get the cached selected renderer, does no checking to ensure it is not stale,
* should only be called directly after calculateTypesAtAtPoint
* @return
*/
public UILayerRenderer getCachedSelectedRenderer() {
return selectedRenderer;
}
@Override
public void mouseEntered(MouseEvent arg0) {}
@Override
public void mouseExited(MouseEvent arg0) {}
@Override
public void mousePressed(MouseEvent arg0) {
this.calculateTypesAtAtPoint(arg0.getPoint());
final UILayerRenderer r = this.getCachedSelectedRenderer();
draggingOk = r == null;
mouse = arg0.getPoint();
}
@Override
public void mouseReleased(MouseEvent arg0) {}
/**
* Add a SelectionCallback that will be called when an image/square is selected
* @param s
*/
public void addSelectionCallback(SelectionCallback s) {
selectionCallback.add(s);
}
/**
* Remove a given SelectionCallback
* @param s
*/
public void removeSelectionCallback(SelectionCallback s) {
selectionCallback.remove(s);
}
/**
* Get the view direction
* @return
*/
public Direction viewDirection() {
return viewDirection;
}
/**
* Set the view direction
* @param direction
*/
public void setViewDirection(Direction direction) {
viewDirection = direction;
}
/**
* Add a UiLayerRenderer to the correct place in the list of renderers based on the level
* @param renderer
*/
public void addLayerRenderer(UILayerRenderer renderer) { // TODO: log duplicates?
if(extraRenderers.size() == 0) {
extraRenderers.add(renderer);
renderer.setSuperview(this);
}
else {
for(int n = 0; n < extraRenderers.size(); n++) {
if(extraRenderers.get(n).level() < renderer.level()) {
extraRenderers.add(n, renderer);
renderer.setSuperview(this);
return;
}
}
extraRenderers.add(renderer);
renderer.setSuperview(this);
}
}
/**
* Remove a UiLayerRenderer
* @param renderer
*/
public void removeLayerRenderer(UILayerRenderer renderer) {
extraRenderers.remove(renderer);
renderer.setSuperview(null);
}
/**
* Get the light position
* @return
*/
public Point lightPoint() {
return lightPoint;
}
/**
* Set the light position
* @param point
*/
public void setLightPoint(Point point) {
lightPoint = point;
}
}
| false | true | public void paint(Graphics jgraphics) {
dataSource.setViewableRect((int)origin.getX(), (int)origin.getY(), this.getWidth(), this.getHeight(), viewDirection);
dataSource.update();
Point smoothing = dataSource.transform().smoothOrigin(origin);
Composite oc = null;
if(!selectionRender) {
jgraphics.fillRect(0, 0, this.getWidth(), this.getHeight());
graphics.setBackground(new Color(0, 0, 0, 0));
graphics.clearRect(0, 0, this.getWidth(), this.getHeight());
oc = graphics.getComposite();
if(lightMask != null && lightPoint != null) {
graphics.drawImage(lightMask, lightPoint.x, lightPoint.y, null);
graphics.setComposite(AlphaComposite.SrcAtop);
}
}
int rowY = TILE_Y/2;
int tileCountY = this.getHeight()/rowY+5;
int tileCountX = this.getWidth()/TILE_X+2;
int row = 0;
int y = -rowY; // rowY
for(;y<tileCountY*rowY;y+=rowY) {
if(!selectionRender || selectionPoint.y < y+smoothing.getY()) {
int yg = -((row%2 == 0)?row/2-1:row/2);
int xg = (row%2 == 0)?row/2:(row-1)/2;
int x = ((row%2 == 0)?TILE_X/2:0)-TILE_X;
for(;x<tileCountX*TILE_X;x+=TILE_X) {
this.drawSquareAt(graphics, (int)(x+smoothing.getX()), (int)(y+smoothing.getY()), xg, yg);
yg++;
xg++;
}
}
row++;
}
if(!selectionRender) {
graphics.setComposite(oc);
for(UILayerRenderer ren : extraRenderers) {
ren.render(graphics, this);
}
jgraphics.drawImage(backbuffer, 0, 0, null);
}
else {
for(UILayerRenderer ren : extraRenderers) {
if(ren.doSelectionPass(selectionPoint, this)) {
selectedRenderer = ren;
}
}
}
}
| public void paint(Graphics jgraphics) {
dataSource.setViewableRect((int)origin.getX(), (int)origin.getY(), this.getWidth(), this.getHeight(), viewDirection);
dataSource.update();
Point smoothing = dataSource.transform().smoothOrigin(origin);
Composite oc = null;
if(!selectionRender) {
jgraphics.fillRect(0, 0, this.getWidth(), this.getHeight());
graphics.setColor(Color.BLACK);
graphics.setBackground(new Color(0, 0, 0, 0));
graphics.clearRect(0, 0, this.getWidth(), this.getHeight());
oc = graphics.getComposite();
if(lightMask != null && lightPoint != null) {
graphics.drawImage(lightMask, lightPoint.x, lightPoint.y, null);
graphics.setComposite(AlphaComposite.SrcAtop);
graphics.fillRect(0, 0, this.getWidth(), this.getHeight());
}
}
int rowY = TILE_Y/2;
int tileCountY = this.getHeight()/rowY+5;
int tileCountX = this.getWidth()/TILE_X+2;
int row = 0;
int y = -rowY; // rowY
for(;y<tileCountY*rowY;y+=rowY) {
if(!selectionRender || selectionPoint.y < y+smoothing.getY()) {
int yg = -((row%2 == 0)?row/2-1:row/2);
int xg = (row%2 == 0)?row/2:(row-1)/2;
int x = ((row%2 == 0)?TILE_X/2:0)-TILE_X;
for(;x<tileCountX*TILE_X;x+=TILE_X) {
this.drawSquareAt(graphics, (int)(x+smoothing.getX()), (int)(y+smoothing.getY()), xg, yg);
yg++;
xg++;
}
}
row++;
}
if(!selectionRender) {
graphics.setComposite(oc);
for(UILayerRenderer ren : extraRenderers) {
ren.render(graphics, this);
}
jgraphics.drawImage(backbuffer, 0, 0, null);
}
else {
for(UILayerRenderer ren : extraRenderers) {
if(ren.doSelectionPass(selectionPoint, this)) {
selectedRenderer = ren;
}
}
}
}
|
diff --git a/wiki-service/src/main/java/org/exoplatform/wiki/service/impl/WikiSearchServiceConnector.java b/wiki-service/src/main/java/org/exoplatform/wiki/service/impl/WikiSearchServiceConnector.java
index 1d616ad3..45f09049 100644
--- a/wiki-service/src/main/java/org/exoplatform/wiki/service/impl/WikiSearchServiceConnector.java
+++ b/wiki-service/src/main/java/org/exoplatform/wiki/service/impl/WikiSearchServiceConnector.java
@@ -1,147 +1,152 @@
package org.exoplatform.wiki.service.impl;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.List;
import org.exoplatform.commons.api.search.SearchServiceConnector;
import org.exoplatform.commons.api.search.data.SearchResult;
import org.exoplatform.commons.utils.PageList;
import org.exoplatform.container.ExoContainerContext;
import org.exoplatform.container.PortalContainer;
import org.exoplatform.container.xml.InitParams;
import org.exoplatform.portal.config.model.PortalConfig;
import org.exoplatform.services.log.ExoLogger;
import org.exoplatform.services.log.Log;
import org.exoplatform.wiki.mow.api.Wiki;
import org.exoplatform.wiki.mow.api.WikiNodeType;
import org.exoplatform.wiki.mow.core.api.wiki.AttachmentImpl;
import org.exoplatform.wiki.mow.core.api.wiki.PageImpl;
import org.exoplatform.wiki.rendering.RenderingService;
import org.exoplatform.wiki.service.WikiService;
import org.exoplatform.wiki.service.search.WikiSearchData;
import org.exoplatform.wiki.utils.Utils;
import org.xwiki.rendering.syntax.Syntax;
public class WikiSearchServiceConnector extends SearchServiceConnector {
private static final Log LOG = ExoLogger.getLogger("org.exoplatform.wiki.service.impl.WikiSearchServiceConnector");
public static final String WIKI_PAGE_ICON = "/wiki/skin/DefaultSkin/webui/background/PageIcon.png";
public static String DATE_TIME_FORMAT = "EEEEE, MMMMMMMM d, yyyy K:mm a";
private static final int EXCERPT_LENGTH = 140;
private WikiService wikiService;
private RenderingService renderingService;
public WikiSearchServiceConnector(InitParams initParams) {
super(initParams);
wikiService = (WikiService) ExoContainerContext.getCurrentContainer().getComponentInstanceOfType(WikiService.class);
renderingService = (RenderingService) PortalContainer.getInstance().getComponentInstanceOfType(RenderingService.class);
}
@Override
public Collection<SearchResult> search(String query, Collection<String> sites, int offset, int limit, String sort, String order) {
WikiSearchData searchData = new WikiSearchData(query, null, null, null, null, null);
searchData.setOffset(offset);
searchData.setLimit(limit);
searchData.setSort(sort);
searchData.setOrder(order);
List<SearchResult> searchResults = new ArrayList<SearchResult>();
try {
PageList<org.exoplatform.wiki.service.search.SearchResult> wikiSearchPageList = wikiService.search(searchData);
if (wikiSearchPageList != null) {
List<org.exoplatform.wiki.service.search.SearchResult> wikiSearchResults = wikiSearchPageList.getAll();
for (org.exoplatform.wiki.service.search.SearchResult wikiSearchResult : wikiSearchResults) {
SearchResult searchResult = buildResult(wikiSearchResult);
if (searchResult != null) {
searchResults.add(searchResult);
}
}
}
} catch (Exception e) {
LOG.info("Could not execute unified seach on wiki" , e) ;
}
return searchResults;
}
private String getResultIcon(org.exoplatform.wiki.service.search.SearchResult wikiSearchResult) {
return WIKI_PAGE_ICON;
}
private PageImpl getPage(org.exoplatform.wiki.service.search.SearchResult result) throws Exception {
PageImpl page = null;
if (WikiNodeType.WIKI_PAGE_CONTENT.equals(result.getType()) || WikiNodeType.WIKI_ATTACHMENT.equals(result.getType())) {
AttachmentImpl searchContent = (AttachmentImpl) org.exoplatform.wiki.utils.Utils.getObject(result.getPath(), WikiNodeType.WIKI_ATTACHMENT);
page = searchContent.getParentPage();
} else if (WikiNodeType.WIKI_PAGE.equals(result.getType()) || WikiNodeType.WIKI_HOME.equals(result.getType())) {
page = (PageImpl) org.exoplatform.wiki.utils.Utils.getObject(result.getPath(), WikiNodeType.WIKI_PAGE);
}
return page;
}
private String getExcerptOfPage(org.exoplatform.wiki.service.search.SearchResult wikiSearchResult) {
String excerpt = "";
try {
PageImpl page = getPage(wikiSearchResult);
excerpt = renderingService.render(page.getContent().getText(), page.getSyntax(), Syntax.PLAIN_1_0.toIdString(), false);
excerpt = excerpt.split("\n")[0];
if (excerpt.length() > EXCERPT_LENGTH) {
excerpt = excerpt.substring(0, EXCERPT_LENGTH) + "...";
}
} catch (Exception e) {
LOG.info("Can not get page excerpt ", e);
}
return excerpt;
}
private String getPageDetail(org.exoplatform.wiki.service.search.SearchResult wikiSearchResult) {
StringBuffer pageDetail = new StringBuffer();
try {
// Get space name
PageImpl page = getPage(wikiSearchResult);
String spaceName = "";
Wiki wiki = page.getWiki();
if (wiki.getType().equals(PortalConfig.GROUP_TYPE)) {
- spaceName = wikiService.getSpaceNameByGroupId("/spaces/" + wiki.getOwner());
+ String wikiOwner = wiki.getOwner();
+ if (wikiOwner.indexOf('/') == -1) {
+ spaceName = wikiService.getSpaceNameByGroupId("/spaces/" + wiki.getOwner());
+ } else {
+ spaceName = wikiService.getSpaceNameByGroupId(wiki.getOwner());
+ }
} else {
spaceName = wiki.getOwner();
}
// Get update date
Calendar updateDate = wikiSearchResult.getUpdatedDate();
SimpleDateFormat format = new SimpleDateFormat(DATE_TIME_FORMAT);
// Build page detail
pageDetail.append(spaceName);
pageDetail.append(" - ");
pageDetail.append(format.format(updateDate.getTime()));
} catch (Exception e) {
LOG.info("Can not get page detail ", e);
}
return pageDetail.toString();
}
private SearchResult buildResult(org.exoplatform.wiki.service.search.SearchResult wikiSearchResult) {
try {
String title = wikiSearchResult.getTitle();
String url = wikiSearchResult.getUrl();
String excerpt = getExcerptOfPage(wikiSearchResult);
String detail = getPageDetail(wikiSearchResult);
long relevancy = wikiSearchResult.getJcrScore();
long date = wikiSearchResult.getUpdatedDate().getTime().getTime();
String imageUrl = getResultIcon(wikiSearchResult);
return new SearchResult(url, title, excerpt, detail, imageUrl, date, relevancy);
} catch (Exception e) {
LOG.info("Error when getting property from node ", e);
return null;
}
}
}
| true | true | private String getPageDetail(org.exoplatform.wiki.service.search.SearchResult wikiSearchResult) {
StringBuffer pageDetail = new StringBuffer();
try {
// Get space name
PageImpl page = getPage(wikiSearchResult);
String spaceName = "";
Wiki wiki = page.getWiki();
if (wiki.getType().equals(PortalConfig.GROUP_TYPE)) {
spaceName = wikiService.getSpaceNameByGroupId("/spaces/" + wiki.getOwner());
} else {
spaceName = wiki.getOwner();
}
// Get update date
Calendar updateDate = wikiSearchResult.getUpdatedDate();
SimpleDateFormat format = new SimpleDateFormat(DATE_TIME_FORMAT);
// Build page detail
pageDetail.append(spaceName);
pageDetail.append(" - ");
pageDetail.append(format.format(updateDate.getTime()));
} catch (Exception e) {
LOG.info("Can not get page detail ", e);
}
return pageDetail.toString();
}
| private String getPageDetail(org.exoplatform.wiki.service.search.SearchResult wikiSearchResult) {
StringBuffer pageDetail = new StringBuffer();
try {
// Get space name
PageImpl page = getPage(wikiSearchResult);
String spaceName = "";
Wiki wiki = page.getWiki();
if (wiki.getType().equals(PortalConfig.GROUP_TYPE)) {
String wikiOwner = wiki.getOwner();
if (wikiOwner.indexOf('/') == -1) {
spaceName = wikiService.getSpaceNameByGroupId("/spaces/" + wiki.getOwner());
} else {
spaceName = wikiService.getSpaceNameByGroupId(wiki.getOwner());
}
} else {
spaceName = wiki.getOwner();
}
// Get update date
Calendar updateDate = wikiSearchResult.getUpdatedDate();
SimpleDateFormat format = new SimpleDateFormat(DATE_TIME_FORMAT);
// Build page detail
pageDetail.append(spaceName);
pageDetail.append(" - ");
pageDetail.append(format.format(updateDate.getTime()));
} catch (Exception e) {
LOG.info("Can not get page detail ", e);
}
return pageDetail.toString();
}
|
diff --git a/library/src/com/actionbarsherlock/ActionBarSherlock.java b/library/src/com/actionbarsherlock/ActionBarSherlock.java
index ba52627c..d75232a8 100644
--- a/library/src/com/actionbarsherlock/ActionBarSherlock.java
+++ b/library/src/com/actionbarsherlock/ActionBarSherlock.java
@@ -1,789 +1,788 @@
package com.actionbarsherlock;
import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Iterator;
import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.internal.ActionBarSherlockCompat;
import com.actionbarsherlock.internal.ActionBarSherlockNative;
import com.actionbarsherlock.view.ActionMode;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
/**
* <p>Helper for implementing the action bar design pattern across all versions
* of Android.</p>
*
* <p>This class will manage interaction with a custom action bar based on the
* Android 4.0 source code. The exposed API mirrors that of its native
* counterpart and you should refer to its documentation for instruction.</p>
*
* @author Jake Wharton <[email protected]>
* @version 4.0.0
*/
public abstract class ActionBarSherlock {
protected static final String TAG = "ActionBarSherlock";
protected static final boolean DEBUG = true;
private static final Class<?>[] CONSTRUCTOR_ARGS = new Class[] { Activity.class, int.class };
private static final HashMap<Implementation, Class<? extends ActionBarSherlock>> IMPLEMENTATIONS =
new HashMap<Implementation, Class<? extends ActionBarSherlock>>();
static {
//Register our two built-in implementations
registerImplementation(ActionBarSherlockCompat.class);
registerImplementation(ActionBarSherlockNative.class);
}
/**
* <p>Denotes an implementation of ActionBarSherlock which provides an
* action bar-enhanced experience.</p>
*
* <p>The value provided to this annotation should be a
* <a href="http://developer.android.com/guide/topics/resources/providing-resources.html#AlternativeResources">
* configuration qualifier</a> with no resource name prefix (e.g., "v7-desk"
* would provide an implementation on 2.1+ when docked).</p>
*
* <p>Valid qualifiers, in order of precedence, are:</p>
* <ol>
* <li>Screen pixel density (only "tvdpi" supported)</li>
* <li>Platform version level (e.g., "v7", "v14")</li>
* </ol>
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Implementation {
static final int DEFAULT_API = -1;
static final int DEFAULT_DPI = -1;
int api() default DEFAULT_API;
int dpi() default DEFAULT_DPI;
}
/** Activity interface for menu creation callback. */
public interface OnCreatePanelMenuListener {
public boolean onCreatePanelMenu(int featureId, Menu menu);
}
/** Activity interface for menu creation callback. */
public interface OnCreateOptionsMenuListener {
public boolean onCreateOptionsMenu(Menu menu);
}
/** Activity interface for menu item selection callback. */
public interface OnMenuItemSelectedListener {
public boolean onMenuItemSelected(int featureId, MenuItem item);
}
/** Activity interface for menu item selection callback. */
public interface OnOptionsItemSelectedListener {
public boolean onOptionsItemSelected(MenuItem item);
}
/** Activity interface for menu preparation callback. */
public interface OnPreparePanelListener {
public boolean onPreparePanel(int featureId, View view, Menu menu);
}
/** Activity interface for menu preparation callback. */
public interface OnPrepareOptionsMenuListener {
public boolean onPrepareOptionsMenu(Menu menu);
}
/** Activity interface for action mode finished callback. */
public interface OnActionModeFinishedListener {
public void onActionModeFinished(ActionMode mode);
}
/** Activity interface for action mode started callback. */
public interface OnActionModeStartedListener {
public void onActionModeStarted(ActionMode mode);
}
/**
* If set, the logic in these classes will assume that an {@link Activity}
* is dispatching all of the required events to the class. This flag should
* only be used internally or if you are creating your own base activity
* modeled after one of the included types (e.g., {@code SherlockActivity}).
*/
public static final int FLAG_DELEGATE = 1;
/**
* Register an ActionBarSherlock implementation.
*
* @param implementationClass Target implementation class which extends
* {@link ActionBarSherlock}. This class must also be annotated with
* {@link Implementation}.
*/
public static void registerImplementation(Class<? extends ActionBarSherlock> implementationClass) {
if (!implementationClass.isAnnotationPresent(Implementation.class)) {
throw new IllegalArgumentException("Class " + implementationClass.getSimpleName() + " is not annotated with @Implementation");
} else if (IMPLEMENTATIONS.containsValue(implementationClass)) {
if (DEBUG) Log.w(TAG, "Class " + implementationClass.getSimpleName() + " already registered");
return;
}
Implementation impl = implementationClass.getAnnotation(Implementation.class);
if (DEBUG) Log.i(TAG, "Registering " + implementationClass.getSimpleName() + " with qualifier " + impl);
IMPLEMENTATIONS.put(impl, implementationClass);
}
/**
* Unregister an ActionBarSherlock implementation. <strong>This should be
* considered very volatile and you should only use it if you know what
* you are doing.</strong> You have been warned.
*
* @param implementationClass Target implementation class.
* @return Boolean indicating whether the class was removed.
*/
public static boolean unregisterImplementation(Class<? extends ActionBarSherlock> implementationClass) {
return IMPLEMENTATIONS.remove(implementationClass) != null;
}
/**
* Wrap an activity with an action bar abstraction which will enable the
* use of a custom implementation on platforms where a native version does
* not exist.
*
* @param activity Activity to wrap.
* @return Instance to interact with the action bar.
*/
public static ActionBarSherlock wrap(Activity activity) {
return wrap(activity, 0);
}
/**
* Wrap an activity with an action bar abstraction which will enable the
* use of a custom implementation on platforms where a native version does
* not exist.
*
* @param activity Owning activity.
* @param flags Option flags to control behavior.
* @return Instance to interact with the action bar.
*/
public static ActionBarSherlock wrap(Activity activity, int flags) {
//Create a local implementation map we can modify
HashMap<Implementation, Class<? extends ActionBarSherlock>> impls =
new HashMap<Implementation, Class<? extends ActionBarSherlock>>(IMPLEMENTATIONS);
boolean hasQualfier;
- final boolean isTvDpi = activity.getResources().getDisplayMetrics().densityDpi == DisplayMetrics.DENSITY_TV;
/* DPI FILTERING */
hasQualfier = false;
for (Implementation key : impls.keySet()) {
//Only honor TVDPI as a specific qualifier
if (key.dpi() == DisplayMetrics.DENSITY_TV) {
hasQualfier = true;
break;
}
}
if (hasQualfier) {
- //final boolean isTvDpi = activity.getResources().getDisplayMetrics().densityDpi == DisplayMetrics.DENSITY_TV;
+ final boolean isTvDpi = activity.getResources().getDisplayMetrics().densityDpi == DisplayMetrics.DENSITY_TV;
for (Iterator<Implementation> keys = impls.keySet().iterator(); keys.hasNext(); ) {
int keyDpi = keys.next().dpi();
if ((isTvDpi && keyDpi != DisplayMetrics.DENSITY_TV)
|| (!isTvDpi && keyDpi == DisplayMetrics.DENSITY_TV)) {
keys.remove();
}
}
}
/* API FILTERING */
hasQualfier = false;
for (Implementation key : impls.keySet()) {
if (key.api() != Implementation.DEFAULT_API) {
hasQualfier = true;
break;
}
}
if (hasQualfier) {
final int runtimeApi = Build.VERSION.SDK_INT;
int bestApi = 0;
for (Iterator<Implementation> keys = impls.keySet().iterator(); keys.hasNext(); ) {
int keyApi = keys.next().api();
if (keyApi > runtimeApi) {
keys.remove();
} else if (keyApi > bestApi) {
bestApi = keyApi;
}
}
for (Iterator<Implementation> keys = impls.keySet().iterator(); keys.hasNext(); ) {
if (keys.next().api() != bestApi) {
keys.remove();
}
}
}
if (impls.size() > 1) {
throw new IllegalStateException("More than one implementation matches configuration.");
}
if (impls.isEmpty()) {
throw new IllegalStateException("No implementations match configuration.");
}
Class<? extends ActionBarSherlock> impl = impls.values().iterator().next();
try {
Constructor<? extends ActionBarSherlock> ctor = impl.getConstructor(CONSTRUCTOR_ARGS);
return ctor.newInstance(activity, flags);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
} catch (IllegalArgumentException e) {
throw new RuntimeException(e);
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
/** Activity which is displaying the action bar. Also used for context. */
protected final Activity mActivity;
/** Whether delegating actions for the activity or managing ourselves. */
protected final boolean mIsDelegate;
/** Reference to our custom menu inflater which supports action items. */
protected MenuInflater mMenuInflater;
protected ActionBarSherlock(Activity activity, int flags) {
if (DEBUG) Log.d(TAG, "[<ctor>] activity: " + activity + ", flags: " + flags);
mActivity = activity;
mIsDelegate = (flags & FLAG_DELEGATE) != 0;
}
/**
* Get the current action bar instance.
*
* @return Action bar instance.
*/
public abstract ActionBar getActionBar();
///////////////////////////////////////////////////////////////////////////
// Lifecycle and interaction callbacks when delegating
///////////////////////////////////////////////////////////////////////////
/**
* Notify action bar of a configuration change event. Should be dispatched
* after the call to the superclass implementation.
*
* <blockquote><pre>
* @Override
* public void onConfigurationChanged(Configuration newConfig) {
* super.onConfigurationChanged(newConfig);
* mSherlock.dispatchConfigurationChanged(newConfig);
* }
* </pre></blockquote>
*
* @param newConfig The new device configuration.
*/
public void dispatchConfigurationChanged(Configuration newConfig) {}
/**
* Notify the action bar that the activity has finished its resuming. This
* should be dispatched after the call to the superclass implementation.
*
* <blockquote><pre>
* @Override
* protected void onPostResume() {
* super.onPostResume();
* mSherlock.dispatchPostResume();
* }
* </pre></blockquote>
*/
public void dispatchPostResume() {}
/**
* Notify the action bar that the activity is pausing. This should be
* dispatched before the call to the superclass implementation.
*
* <blockquote><pre>
* @Override
* protected void onPause() {
* mSherlock.dispatchPause();
* super.onPause();
* }
* </pre></blockquote>
*/
public void dispatchPause() {}
/**
* Notify the action bar that the activity is stopping. This should be
* called before the superclass implementation.
*
* <blockquote><p>
* @Override
* protected void onStop() {
* mSherlock.dispatchStop();
* super.onStop();
* }
* </p></blockquote>
*/
public void dispatchStop() {}
/**
* Indicate that the menu should be recreated by calling
* {@link OnCreateOptionsMenuListener#onCreateOptionsMenu(com.actionbarsherlock.view.Menu)}.
*/
public abstract void dispatchInvalidateOptionsMenu();
/**
* Notify the action bar that it should display its overflow menu if it is
* appropriate for the device. The implementation should conditionally
* call the superclass method only if this method returns {@code false}.
*
* <blockquote><p>
* @Override
* public void openOptionsMenu() {
* if (!mSherlock.dispatchOpenOptionsMenu()) {
* super.openOptionsMenu();
* }
* }
* </p></blockquote>
*
* @return {@code true} if the opening of the menu was handled internally.
*/
public boolean dispatchOpenOptionsMenu() {
return false;
}
/**
* Notify the action bar that it should close its overflow menu if it is
* appropriate for the device. This implementation should conditionally
* call the superclass method only if this method returns {@code false}.
*
* <blockquote><pre>
* @Override
* public void closeOptionsMenu() {
* if (!mSherlock.dispatchCloseOptionsMenu()) {
* super.closeOptionsMenu();
* }
* }
* </pre></blockquote>
*
* @return {@code true} if the closing of the menu was handled internally.
*/
public boolean dispatchCloseOptionsMenu() {
return false;
}
/**
* Notify the class that the activity has finished its creation. This
* should be called after the superclass implementation.
*
* <blockquote><pre>
* @Override
* protected void onPostCreate(Bundle savedInstanceState) {
* mSherlock.dispatchPostCreate(savedInstanceState);
* super.onPostCreate(savedInstanceState);
* }
* </pre></blockquote>
*
* @param savedInstanceState If the activity is being re-initialized after
* previously being shut down then this Bundle
* contains the data it most recently supplied in
* {@link Activity#}onSaveInstanceState(Bundle)}.
* <strong>Note: Otherwise it is null.</strong>
*/
public void dispatchPostCreate(Bundle savedInstanceState) {}
/**
* Notify the action bar that the title has changed and the action bar
* should be updated to reflect the change. This should be called before
* the superclass implementation.
*
* <blockquote><pre>
* @Override
* protected void onTitleChanged(CharSequence title, int color) {
* mSherlock.dispatchTitleChanged(title, color);
* super.onTitleChanged(title, color);
* }
* </pre></blockquote>
*
* @param title New activity title.
* @param color New activity color.
*/
public void dispatchTitleChanged(CharSequence title, int color) {}
/**
* Notify the action bar the user has created a key event. This is used to
* toggle the display of the overflow action item with the menu key and to
* close the action mode or expanded action item with the back key.
*
* <blockquote><pre>
* @Override
* public boolean dispatchKeyEvent(KeyEvent event) {
* if (mSherlock.dispatchKeyEvent(event)) {
* return true;
* }
* return super.dispatchKeyEvent(event);
* }
* </pre></blockquote>
*
* @param event Description of the key event.
* @return {@code true} if the event was handled.
*/
public boolean dispatchKeyEvent(KeyEvent event) {
return false;
}
/**
* Notify the action bar that the Activity has triggered a menu creation
* which should happen on the conclusion of {@link Activity#onCreate}. This
* will be used to gain a reference to the native menu for native and
* overflow binding as well as to indicate when compatibility create should
* occur for the first time.
*
* @param menu Activity native menu.
* @return {@code true} since we always want to say that we have a native
*/
public abstract boolean dispatchCreateOptionsMenu(android.view.Menu menu);
/**
* Notify the action bar that the Activity has triggered a menu preparation
* which usually means that the user has requested the overflow menu via a
* hardware menu key. You should return the result of this method call and
* not call the superclass implementation.
*
* <blockquote><p>
* @Override
* public final boolean onPrepareOptionsMenu(android.view.Menu menu) {
* return mSherlock.dispatchPrepareOptionsMenu(menu);
* }
* </p></blockquote>
*
* @param menu Activity native menu.
* @return {@code true} if menu display should proceed.
*/
public abstract boolean dispatchPrepareOptionsMenu(android.view.Menu menu);
/**
* Notify the action bar that a native options menu item has been selected.
* The implementation should return the result of this method call.
*
* <blockquote><p>
* @Override
* public final boolean onOptionsItemSelected(android.view.MenuItem item) {
* return mSherlock.dispatchOptionsItemSelected(item);
* }
* </p></blockquote>
*
* @param item Options menu item.
* @return @{code true} if the selection was handled.
*/
public abstract boolean dispatchOptionsItemSelected(android.view.MenuItem item);
/**
* Notify the action bar that the overflow menu has been opened. The
* implementation should conditionally return {@code true} if this method
* returns {@code true}, otherwise return the result of the superclass
* method.
*
* <blockquote><p>
* @Override
* public final boolean onMenuOpened(int featureId, android.view.Menu menu) {
* if (mSherlock.dispatchMenuOpened(featureId, menu)) {
* return true;
* }
* return super.onMenuOpened(featureId, menu);
* }
* </p></blockquote>
*
* @param featureId Window feature which triggered the event.
* @param menu Activity native menu.
* @return {@code true} if the event was handled by this method.
*/
public boolean dispatchMenuOpened(int featureId, android.view.Menu menu) {
return false;
}
/**
* Notify the action bar that the overflow menu has been closed. This
* method should be called before the superclass implementation.
*
* <blockquote><p>
* @Override
* public void onPanelClosed(int featureId, android.view.Menu menu) {
* mSherlock.dispatchPanelClosed(featureId, menu);
* super.onPanelClosed(featureId, menu);
* }
* </p></blockquote>
*
* @param featureId
* @param menu
*/
public void dispatchPanelClosed(int featureId, android.view.Menu menu) {}
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
/**
* Internal method to trigger the menu creation process.
*
* @return {@code true} if menu creation should proceed.
*/
protected final boolean callbackCreateOptionsMenu(Menu menu) {
if (DEBUG) Log.d(TAG, "[callbackCreateOptionsMenu] menu: " + menu);
boolean result = true;
if (mActivity instanceof OnCreatePanelMenuListener) {
OnCreatePanelMenuListener listener = (OnCreatePanelMenuListener)mActivity;
result = listener.onCreatePanelMenu(Window.FEATURE_OPTIONS_PANEL, menu);
} else if (mActivity instanceof OnCreateOptionsMenuListener) {
OnCreateOptionsMenuListener listener = (OnCreateOptionsMenuListener)mActivity;
result = listener.onCreateOptionsMenu(menu);
}
if (DEBUG) Log.d(TAG, "[callbackCreateOptionsMenu] returning " + result);
return result;
}
/**
* Internal method to trigger the menu preparation process.
*
* @return {@code true} if menu preparation should proceed.
*/
protected final boolean callbackPrepareOptionsMenu(Menu menu) {
if (DEBUG) Log.d(TAG, "[callbackPrepareOptionsMenu] menu: " + menu);
boolean result = true;
if (mActivity instanceof OnPreparePanelListener) {
OnPreparePanelListener listener = (OnPreparePanelListener)mActivity;
result = listener.onPreparePanel(Window.FEATURE_OPTIONS_PANEL, null, menu);
} else if (mActivity instanceof OnPrepareOptionsMenuListener) {
OnPrepareOptionsMenuListener listener = (OnPrepareOptionsMenuListener)mActivity;
result = listener.onPrepareOptionsMenu(menu);
}
if (DEBUG) Log.d(TAG, "[callbackPrepareOptionsMenu] returning " + result);
return result;
}
/**
* Internal method for dispatching options menu selection to the owning
* activity callback.
*
* @param item Selected options menu item.
* @return {@code true} if the item selection was handled in the callback.
*/
protected final boolean callbackOptionsItemSelected(MenuItem item) {
if (DEBUG) Log.d(TAG, "[callbackOptionsItemSelected] item: " + item.getTitleCondensed());
boolean result = false;
if (mActivity instanceof OnMenuItemSelectedListener) {
OnMenuItemSelectedListener listener = (OnMenuItemSelectedListener)mActivity;
result = listener.onMenuItemSelected(Window.FEATURE_OPTIONS_PANEL, item);
} else if (mActivity instanceof OnOptionsItemSelectedListener) {
OnOptionsItemSelectedListener listener = (OnOptionsItemSelectedListener)mActivity;
result = listener.onOptionsItemSelected(item);
}
if (DEBUG) Log.d(TAG, "[callbackOptionsItemSelected] returning " + result);
return result;
}
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
/**
* Query for the availability of a certain feature.
*
* @param featureId The feature ID to check.
* @return {@code true} if feature is enabled, {@code false} otherwise.
*/
public abstract boolean hasFeature(int featureId);
/**
* Enable extended screen features. This must be called before
* {@code setContentView()}. May be called as many times as desired as long
* as it is before {@code setContentView()}. If not called, no extended
* features will be available. You can not turn off a feature once it is
* requested.
*
* @param featureId The desired features, defined as constants by Window.
* @return Returns true if the requested feature is supported and now
* enabled.
*/
public abstract boolean requestFeature(int featureId);
/**
* Set extra options that will influence the UI for this window.
*
* @param uiOptions Flags specifying extra options for this window.
*/
public abstract void setUiOptions(int uiOptions);
/**
* Set extra options that will influence the UI for this window. Only the
* bits filtered by mask will be modified.
*
* @param uiOptions Flags specifying extra options for this window.
* @param mask Flags specifying which options should be modified. Others
* will remain unchanged.
*/
public abstract void setUiOptions(int uiOptions, int mask);
/**
* Set the content of the activity inside the action bar.
*
* @param layoutResId Layout resource ID.
*/
public abstract void setContentView(int layoutResId);
/**
* Set the content of the activity inside the action bar.
*
* @param view The desired content to display.
*/
public void setContentView(View view) {
if (DEBUG) Log.d(TAG, "[setContentView] view: " + view);
setContentView(view, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
}
/**
* Set the content of the activity inside the action bar.
*
* @param view The desired content to display.
* @param params Layout parameters to apply to the view.
*/
public abstract void setContentView(View view, ViewGroup.LayoutParams params);
/**
* Variation on {@link #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)}
* to add an additional content view to the screen. Added after any
* existing ones on the screen -- existing views are NOT removed.
*
* @param view The desired content to display.
* @param params Layout parameters for the view.
*/
public abstract void addContentView(View view, ViewGroup.LayoutParams params);
/**
* Change the title associated with this activity.
*/
public abstract void setTitle(CharSequence title);
/**
* Change the title associated with this activity.
*/
public void setTitle(int resId) {
if (DEBUG) Log.d(TAG, "[setTitle] resId: " + resId);
setTitle(mActivity.getString(resId));
}
/**
* Sets the visibility of the progress bar in the title.
* <p>
* In order for the progress bar to be shown, the feature must be requested
* via {@link #requestWindowFeature(int)}.
*
* @param visible Whether to show the progress bars in the title.
*/
public abstract void setProgressBarVisibility(boolean visible);
/**
* Sets the visibility of the indeterminate progress bar in the title.
* <p>
* In order for the progress bar to be shown, the feature must be requested
* via {@link #requestWindowFeature(int)}.
*
* @param visible Whether to show the progress bars in the title.
*/
public abstract void setProgressBarIndeterminateVisibility(boolean visible);
/**
* Sets whether the horizontal progress bar in the title should be indeterminate (the circular
* is always indeterminate).
* <p>
* In order for the progress bar to be shown, the feature must be requested
* via {@link #requestWindowFeature(int)}.
*
* @param indeterminate Whether the horizontal progress bar should be indeterminate.
*/
public abstract void setProgressBarIndeterminate(boolean indeterminate);
/**
* Sets the progress for the progress bars in the title.
* <p>
* In order for the progress bar to be shown, the feature must be requested
* via {@link #requestWindowFeature(int)}.
*
* @param progress The progress for the progress bar. Valid ranges are from
* 0 to 10000 (both inclusive). If 10000 is given, the progress
* bar will be completely filled and will fade out.
*/
public abstract void setProgress(int progress);
/**
* Sets the secondary progress for the progress bar in the title. This
* progress is drawn between the primary progress (set via
* {@link #setProgress(int)} and the background. It can be ideal for media
* scenarios such as showing the buffering progress while the default
* progress shows the play progress.
* <p>
* In order for the progress bar to be shown, the feature must be requested
* via {@link #requestWindowFeature(int)}.
*
* @param secondaryProgress The secondary progress for the progress bar. Valid ranges are from
* 0 to 10000 (both inclusive).
*/
public abstract void setSecondaryProgress(int secondaryProgress);
/**
* Get a menu inflater instance which supports the newer menu attributes.
*
* @return Menu inflater instance.
*/
public MenuInflater getMenuInflater() {
if (DEBUG) Log.d(TAG, "[getMenuInflater]");
// Make sure that action views can get an appropriate theme.
if (mMenuInflater == null) {
if (getActionBar() != null) {
mMenuInflater = new MenuInflater(getThemedContext());
} else {
mMenuInflater = new MenuInflater(mActivity);
}
}
return mMenuInflater;
}
protected abstract Context getThemedContext();
/**
* Start an action mode.
*
* @param callback Callback that will manage lifecycle events for this
* context mode.
* @return The ContextMode that was started, or null if it was canceled.
* @see ActionMode
*/
public abstract ActionMode startActionMode(ActionMode.Callback callback);
}
| false | true | public static ActionBarSherlock wrap(Activity activity, int flags) {
//Create a local implementation map we can modify
HashMap<Implementation, Class<? extends ActionBarSherlock>> impls =
new HashMap<Implementation, Class<? extends ActionBarSherlock>>(IMPLEMENTATIONS);
boolean hasQualfier;
final boolean isTvDpi = activity.getResources().getDisplayMetrics().densityDpi == DisplayMetrics.DENSITY_TV;
/* DPI FILTERING */
hasQualfier = false;
for (Implementation key : impls.keySet()) {
//Only honor TVDPI as a specific qualifier
if (key.dpi() == DisplayMetrics.DENSITY_TV) {
hasQualfier = true;
break;
}
}
if (hasQualfier) {
//final boolean isTvDpi = activity.getResources().getDisplayMetrics().densityDpi == DisplayMetrics.DENSITY_TV;
for (Iterator<Implementation> keys = impls.keySet().iterator(); keys.hasNext(); ) {
int keyDpi = keys.next().dpi();
if ((isTvDpi && keyDpi != DisplayMetrics.DENSITY_TV)
|| (!isTvDpi && keyDpi == DisplayMetrics.DENSITY_TV)) {
keys.remove();
}
}
}
/* API FILTERING */
hasQualfier = false;
for (Implementation key : impls.keySet()) {
if (key.api() != Implementation.DEFAULT_API) {
hasQualfier = true;
break;
}
}
if (hasQualfier) {
final int runtimeApi = Build.VERSION.SDK_INT;
int bestApi = 0;
for (Iterator<Implementation> keys = impls.keySet().iterator(); keys.hasNext(); ) {
int keyApi = keys.next().api();
if (keyApi > runtimeApi) {
keys.remove();
} else if (keyApi > bestApi) {
bestApi = keyApi;
}
}
for (Iterator<Implementation> keys = impls.keySet().iterator(); keys.hasNext(); ) {
if (keys.next().api() != bestApi) {
keys.remove();
}
}
}
if (impls.size() > 1) {
throw new IllegalStateException("More than one implementation matches configuration.");
}
if (impls.isEmpty()) {
throw new IllegalStateException("No implementations match configuration.");
}
Class<? extends ActionBarSherlock> impl = impls.values().iterator().next();
try {
Constructor<? extends ActionBarSherlock> ctor = impl.getConstructor(CONSTRUCTOR_ARGS);
return ctor.newInstance(activity, flags);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
} catch (IllegalArgumentException e) {
throw new RuntimeException(e);
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
| public static ActionBarSherlock wrap(Activity activity, int flags) {
//Create a local implementation map we can modify
HashMap<Implementation, Class<? extends ActionBarSherlock>> impls =
new HashMap<Implementation, Class<? extends ActionBarSherlock>>(IMPLEMENTATIONS);
boolean hasQualfier;
/* DPI FILTERING */
hasQualfier = false;
for (Implementation key : impls.keySet()) {
//Only honor TVDPI as a specific qualifier
if (key.dpi() == DisplayMetrics.DENSITY_TV) {
hasQualfier = true;
break;
}
}
if (hasQualfier) {
final boolean isTvDpi = activity.getResources().getDisplayMetrics().densityDpi == DisplayMetrics.DENSITY_TV;
for (Iterator<Implementation> keys = impls.keySet().iterator(); keys.hasNext(); ) {
int keyDpi = keys.next().dpi();
if ((isTvDpi && keyDpi != DisplayMetrics.DENSITY_TV)
|| (!isTvDpi && keyDpi == DisplayMetrics.DENSITY_TV)) {
keys.remove();
}
}
}
/* API FILTERING */
hasQualfier = false;
for (Implementation key : impls.keySet()) {
if (key.api() != Implementation.DEFAULT_API) {
hasQualfier = true;
break;
}
}
if (hasQualfier) {
final int runtimeApi = Build.VERSION.SDK_INT;
int bestApi = 0;
for (Iterator<Implementation> keys = impls.keySet().iterator(); keys.hasNext(); ) {
int keyApi = keys.next().api();
if (keyApi > runtimeApi) {
keys.remove();
} else if (keyApi > bestApi) {
bestApi = keyApi;
}
}
for (Iterator<Implementation> keys = impls.keySet().iterator(); keys.hasNext(); ) {
if (keys.next().api() != bestApi) {
keys.remove();
}
}
}
if (impls.size() > 1) {
throw new IllegalStateException("More than one implementation matches configuration.");
}
if (impls.isEmpty()) {
throw new IllegalStateException("No implementations match configuration.");
}
Class<? extends ActionBarSherlock> impl = impls.values().iterator().next();
try {
Constructor<? extends ActionBarSherlock> ctor = impl.getConstructor(CONSTRUCTOR_ARGS);
return ctor.newInstance(activity, flags);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
} catch (IllegalArgumentException e) {
throw new RuntimeException(e);
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
|
diff --git a/common-tomcat-maven-plugin/src/main/java/org/apache/tomcat/maven/common/run/DefaultClassLoaderEntriesCalculator.java b/common-tomcat-maven-plugin/src/main/java/org/apache/tomcat/maven/common/run/DefaultClassLoaderEntriesCalculator.java
index ca7bdf4..cbc2d96 100644
--- a/common-tomcat-maven-plugin/src/main/java/org/apache/tomcat/maven/common/run/DefaultClassLoaderEntriesCalculator.java
+++ b/common-tomcat-maven-plugin/src/main/java/org/apache/tomcat/maven/common/run/DefaultClassLoaderEntriesCalculator.java
@@ -1,187 +1,187 @@
package org.apache.tomcat.maven.common.run;
/*
* 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.
*/
import com.google.common.io.Files;
import org.apache.commons.io.FileUtils;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.DependencyResolutionRequiredException;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.archiver.ArchiverException;
import org.codehaus.plexus.archiver.UnArchiver;
import org.codehaus.plexus.archiver.manager.ArchiverManager;
import org.codehaus.plexus.archiver.manager.NoSuchArchiverException;
import org.codehaus.plexus.component.annotations.Component;
import org.codehaus.plexus.component.annotations.Requirement;
import org.codehaus.plexus.components.io.fileselectors.FileInfo;
import org.codehaus.plexus.components.io.fileselectors.FileSelector;
import org.codehaus.plexus.util.StringUtils;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
/**
* @author Olivier Lamy
* @since 2.0
*/
@Component( role = ClassLoaderEntriesCalculator.class )
public class DefaultClassLoaderEntriesCalculator
implements ClassLoaderEntriesCalculator
{
@Requirement
private ArchiverManager archiverManager;
public List<String> calculateClassPathEntries( ClassLoaderEntriesCalculatorRequest request )
throws TomcatRunException
{
List<String> classLoaderEntries = new ArrayList<String>();
// add classes directories to loader
try
{
@SuppressWarnings( "unchecked" ) List<String> classPathElements =
request.getMavenProject().getCompileClasspathElements();
if ( classPathElements != null )
{
for ( String classPathElement : classPathElements )
{
File classPathElementFile = new File( classPathElement );
if ( classPathElementFile.exists() && classPathElementFile.isDirectory() )
{
request.getLog().debug("adding classPathElementFile " + classPathElementFile.toURI().toString());
classLoaderEntries.add( classPathElementFile.toURI().toString() );
}
}
}
}
catch ( DependencyResolutionRequiredException e )
{
throw new TomcatRunException( e.getMessage(), e );
}
// add artifacts to loader
if ( request.getDependencies() != null )
{
for ( Artifact artifact : request.getDependencies() )
{
String scope = artifact.getScope();
// skip provided and test scoped artifacts
if ( !Artifact.SCOPE_PROVIDED.equals( scope ) && !Artifact.SCOPE_TEST.equals( scope ) )
{
request.getLog().debug(
"add dependency to webapploader " + artifact.getGroupId() + ":" + artifact.getArtifactId() + ":"
+ artifact.getVersion() + ":" + artifact.getScope());
if ( !isInProjectReferences( artifact, request.getMavenProject() ) )
{
classLoaderEntries.add( artifact.getFile().toURI().toString() );
}
else
{
request.getLog().debug(
"skip adding artifact " + artifact.getArtifactId() + " as it's in reactors");
}
}
// in case of war dependency we must add /WEB-INF/lib/*.jar in entries and WEB-INF/classes
if ("war".equals(artifact.getType()) && request.isAddWarDependenciesInClassloader() )
{
File tmpDir = null;
try
{
tmpDir = Files.createTempDir();
tmpDir.deleteOnExit();
File warFile = artifact.getFile();
UnArchiver unArchiver = archiverManager.getUnArchiver( "jar" );
unArchiver.setSourceFile( warFile );
unArchiver.setDestDirectory(tmpDir);
unArchiver.extract();
File libsDirectory = new File( tmpDir, "WEB-INF/lib" );
if (libsDirectory.exists())
{
String[] jars = libsDirectory.list( new FilenameFilter()
{
public boolean accept(File file, String s)
{
return s.endsWith( ".jar" );
}
} );
for (String jar : jars)
{
- classLoaderEntries.add( new File( jar ).toURI().toString() );
+ classLoaderEntries.add( new File(libsDirectory, jar ).toURI().toString() );
}
}
File classesDirectory = new File( tmpDir, "WEB-INF/classes" );
if (classesDirectory.exists())
{
classLoaderEntries.add( classesDirectory.toURI().toString() );
}
} catch ( NoSuchArchiverException e)
{
throw new TomcatRunException(e.getMessage(), e);
} catch ( ArchiverException e) {
request.getLog().error(
"fail to extract war file " + artifact.getFile() + ", reason:" + e.getMessage(), e);
throw new TomcatRunException(e.getMessage(), e);
} finally {
deleteDirectory( tmpDir, request.getLog() );
}
}
}
}
return classLoaderEntries;
}
private void deleteDirectory(File directory, Log log) throws TomcatRunException
{
try
{
FileUtils.deleteDirectory(directory);
} catch ( IOException e) {
log.error( "fail to delete directory file " + directory + ", reason:" + e.getMessage(), e );
throw new TomcatRunException(e.getMessage(), e);
}
}
protected boolean isInProjectReferences( Artifact artifact, MavenProject project )
{
if ( project.getProjectReferences() == null || project.getProjectReferences().isEmpty() )
{
return false;
}
@SuppressWarnings( "unchecked" ) Collection<MavenProject> mavenProjects =
project.getProjectReferences().values();
for ( MavenProject mavenProject : mavenProjects )
{
if ( StringUtils.equals( mavenProject.getId(), artifact.getId() ) )
{
return true;
}
}
return false;
}
}
| true | true | public List<String> calculateClassPathEntries( ClassLoaderEntriesCalculatorRequest request )
throws TomcatRunException
{
List<String> classLoaderEntries = new ArrayList<String>();
// add classes directories to loader
try
{
@SuppressWarnings( "unchecked" ) List<String> classPathElements =
request.getMavenProject().getCompileClasspathElements();
if ( classPathElements != null )
{
for ( String classPathElement : classPathElements )
{
File classPathElementFile = new File( classPathElement );
if ( classPathElementFile.exists() && classPathElementFile.isDirectory() )
{
request.getLog().debug("adding classPathElementFile " + classPathElementFile.toURI().toString());
classLoaderEntries.add( classPathElementFile.toURI().toString() );
}
}
}
}
catch ( DependencyResolutionRequiredException e )
{
throw new TomcatRunException( e.getMessage(), e );
}
// add artifacts to loader
if ( request.getDependencies() != null )
{
for ( Artifact artifact : request.getDependencies() )
{
String scope = artifact.getScope();
// skip provided and test scoped artifacts
if ( !Artifact.SCOPE_PROVIDED.equals( scope ) && !Artifact.SCOPE_TEST.equals( scope ) )
{
request.getLog().debug(
"add dependency to webapploader " + artifact.getGroupId() + ":" + artifact.getArtifactId() + ":"
+ artifact.getVersion() + ":" + artifact.getScope());
if ( !isInProjectReferences( artifact, request.getMavenProject() ) )
{
classLoaderEntries.add( artifact.getFile().toURI().toString() );
}
else
{
request.getLog().debug(
"skip adding artifact " + artifact.getArtifactId() + " as it's in reactors");
}
}
// in case of war dependency we must add /WEB-INF/lib/*.jar in entries and WEB-INF/classes
if ("war".equals(artifact.getType()) && request.isAddWarDependenciesInClassloader() )
{
File tmpDir = null;
try
{
tmpDir = Files.createTempDir();
tmpDir.deleteOnExit();
File warFile = artifact.getFile();
UnArchiver unArchiver = archiverManager.getUnArchiver( "jar" );
unArchiver.setSourceFile( warFile );
unArchiver.setDestDirectory(tmpDir);
unArchiver.extract();
File libsDirectory = new File( tmpDir, "WEB-INF/lib" );
if (libsDirectory.exists())
{
String[] jars = libsDirectory.list( new FilenameFilter()
{
public boolean accept(File file, String s)
{
return s.endsWith( ".jar" );
}
} );
for (String jar : jars)
{
classLoaderEntries.add( new File( jar ).toURI().toString() );
}
}
File classesDirectory = new File( tmpDir, "WEB-INF/classes" );
if (classesDirectory.exists())
{
classLoaderEntries.add( classesDirectory.toURI().toString() );
}
} catch ( NoSuchArchiverException e)
{
throw new TomcatRunException(e.getMessage(), e);
} catch ( ArchiverException e) {
request.getLog().error(
"fail to extract war file " + artifact.getFile() + ", reason:" + e.getMessage(), e);
throw new TomcatRunException(e.getMessage(), e);
} finally {
deleteDirectory( tmpDir, request.getLog() );
}
}
}
}
return classLoaderEntries;
}
| public List<String> calculateClassPathEntries( ClassLoaderEntriesCalculatorRequest request )
throws TomcatRunException
{
List<String> classLoaderEntries = new ArrayList<String>();
// add classes directories to loader
try
{
@SuppressWarnings( "unchecked" ) List<String> classPathElements =
request.getMavenProject().getCompileClasspathElements();
if ( classPathElements != null )
{
for ( String classPathElement : classPathElements )
{
File classPathElementFile = new File( classPathElement );
if ( classPathElementFile.exists() && classPathElementFile.isDirectory() )
{
request.getLog().debug("adding classPathElementFile " + classPathElementFile.toURI().toString());
classLoaderEntries.add( classPathElementFile.toURI().toString() );
}
}
}
}
catch ( DependencyResolutionRequiredException e )
{
throw new TomcatRunException( e.getMessage(), e );
}
// add artifacts to loader
if ( request.getDependencies() != null )
{
for ( Artifact artifact : request.getDependencies() )
{
String scope = artifact.getScope();
// skip provided and test scoped artifacts
if ( !Artifact.SCOPE_PROVIDED.equals( scope ) && !Artifact.SCOPE_TEST.equals( scope ) )
{
request.getLog().debug(
"add dependency to webapploader " + artifact.getGroupId() + ":" + artifact.getArtifactId() + ":"
+ artifact.getVersion() + ":" + artifact.getScope());
if ( !isInProjectReferences( artifact, request.getMavenProject() ) )
{
classLoaderEntries.add( artifact.getFile().toURI().toString() );
}
else
{
request.getLog().debug(
"skip adding artifact " + artifact.getArtifactId() + " as it's in reactors");
}
}
// in case of war dependency we must add /WEB-INF/lib/*.jar in entries and WEB-INF/classes
if ("war".equals(artifact.getType()) && request.isAddWarDependenciesInClassloader() )
{
File tmpDir = null;
try
{
tmpDir = Files.createTempDir();
tmpDir.deleteOnExit();
File warFile = artifact.getFile();
UnArchiver unArchiver = archiverManager.getUnArchiver( "jar" );
unArchiver.setSourceFile( warFile );
unArchiver.setDestDirectory(tmpDir);
unArchiver.extract();
File libsDirectory = new File( tmpDir, "WEB-INF/lib" );
if (libsDirectory.exists())
{
String[] jars = libsDirectory.list( new FilenameFilter()
{
public boolean accept(File file, String s)
{
return s.endsWith( ".jar" );
}
} );
for (String jar : jars)
{
classLoaderEntries.add( new File(libsDirectory, jar ).toURI().toString() );
}
}
File classesDirectory = new File( tmpDir, "WEB-INF/classes" );
if (classesDirectory.exists())
{
classLoaderEntries.add( classesDirectory.toURI().toString() );
}
} catch ( NoSuchArchiverException e)
{
throw new TomcatRunException(e.getMessage(), e);
} catch ( ArchiverException e) {
request.getLog().error(
"fail to extract war file " + artifact.getFile() + ", reason:" + e.getMessage(), e);
throw new TomcatRunException(e.getMessage(), e);
} finally {
deleteDirectory( tmpDir, request.getLog() );
}
}
}
}
return classLoaderEntries;
}
|
diff --git a/test/system/CVC4JavaTest.java b/test/system/CVC4JavaTest.java
index a35ee3771..168961b5c 100644
--- a/test/system/CVC4JavaTest.java
+++ b/test/system/CVC4JavaTest.java
@@ -1,54 +1,54 @@
import edu.nyu.acsys.CVC4.CVC4;
import edu.nyu.acsys.CVC4.SmtEngine;
import edu.nyu.acsys.CVC4.ExprManager;
import edu.nyu.acsys.CVC4.Expr;
import edu.nyu.acsys.CVC4.Type;
import edu.nyu.acsys.CVC4.BoolExpr;
import edu.nyu.acsys.CVC4.Kind;
import edu.nyu.acsys.CVC4.Result;
import edu.nyu.acsys.CVC4.Configuration;
//import edu.nyu.acsys.CVC4.Exception;
import edu.nyu.acsys.CVC4.Parser;
import edu.nyu.acsys.CVC4.ParserBuilder;
public class CVC4JavaTest {
public static void main(String[] args) {
try {
- System.loadLibrary("cvc4bindings_java");
+ System.loadLibrary("CVC4");
//CVC4.getDebugChannel().on("current");
System.out.println(Configuration.about());
String[] tags = Configuration.getDebugTags();
System.out.print("available debug tags:");
for(int i = 0; i < tags.length; ++i) {
System.out.print(" " + tags[i]);
}
System.out.println();
ExprManager em = new ExprManager();
SmtEngine smt = new SmtEngine(em);
Type t = em.booleanType();
Expr a = em.mkVar("a", em.booleanType());
Expr b = em.mkVar("b", em.booleanType());
BoolExpr e = new BoolExpr(em.mkExpr(Kind.AND, a, b, new BoolExpr(a).notExpr()));
System.out.println("==> " + e);
Result r = smt.checkSat(e);
boolean correct = r.isSat() == Result.Sat.UNSAT;
System.out.println(smt.getStatisticsRegistry());
System.exit(correct ? 0 : 1);
} catch(Exception e) {
System.err.println(e);
System.exit(1);
}
}
}
| true | true | public static void main(String[] args) {
try {
System.loadLibrary("cvc4bindings_java");
//CVC4.getDebugChannel().on("current");
System.out.println(Configuration.about());
String[] tags = Configuration.getDebugTags();
System.out.print("available debug tags:");
for(int i = 0; i < tags.length; ++i) {
System.out.print(" " + tags[i]);
}
System.out.println();
ExprManager em = new ExprManager();
SmtEngine smt = new SmtEngine(em);
Type t = em.booleanType();
Expr a = em.mkVar("a", em.booleanType());
Expr b = em.mkVar("b", em.booleanType());
BoolExpr e = new BoolExpr(em.mkExpr(Kind.AND, a, b, new BoolExpr(a).notExpr()));
System.out.println("==> " + e);
Result r = smt.checkSat(e);
boolean correct = r.isSat() == Result.Sat.UNSAT;
System.out.println(smt.getStatisticsRegistry());
System.exit(correct ? 0 : 1);
} catch(Exception e) {
System.err.println(e);
System.exit(1);
}
}
| public static void main(String[] args) {
try {
System.loadLibrary("CVC4");
//CVC4.getDebugChannel().on("current");
System.out.println(Configuration.about());
String[] tags = Configuration.getDebugTags();
System.out.print("available debug tags:");
for(int i = 0; i < tags.length; ++i) {
System.out.print(" " + tags[i]);
}
System.out.println();
ExprManager em = new ExprManager();
SmtEngine smt = new SmtEngine(em);
Type t = em.booleanType();
Expr a = em.mkVar("a", em.booleanType());
Expr b = em.mkVar("b", em.booleanType());
BoolExpr e = new BoolExpr(em.mkExpr(Kind.AND, a, b, new BoolExpr(a).notExpr()));
System.out.println("==> " + e);
Result r = smt.checkSat(e);
boolean correct = r.isSat() == Result.Sat.UNSAT;
System.out.println(smt.getStatisticsRegistry());
System.exit(correct ? 0 : 1);
} catch(Exception e) {
System.err.println(e);
System.exit(1);
}
}
|
diff --git a/idv/control/mcidas/McXImageSequenceControl.java b/idv/control/mcidas/McXImageSequenceControl.java
index 7ba772371..448e8aa3a 100644
--- a/idv/control/mcidas/McXImageSequenceControl.java
+++ b/idv/control/mcidas/McXImageSequenceControl.java
@@ -1,375 +1,377 @@
package ucar.unidata.idv.control.mcidas;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.lang.Class;
import java.net.URL;
import java.net.URLConnection;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.StringTokenizer;
import javax.swing.event.*;
import javax.swing.*;
import javax.swing.JCheckBox;
import ucar.unidata.data.DataChoice;
import ucar.unidata.data.DataSourceImpl;
//import ucar.unidata.data.imagery.mcidas.FrameComponentInfo;
import ucar.unidata.data.imagery.mcidas.FrameDirtyInfo;
import ucar.unidata.data.imagery.mcidas.ConduitInfo;
//import ucar.unidata.data.imagery.mcidas.McIDASConstants;
import ucar.unidata.data.imagery.mcidas.McCommandLineDataSource;
import ucar.unidata.data.imagery.mcidas.McCommandLineDataSource.FrameDataInfo;
import ucar.unidata.data.imagery.mcidas.McXFrame;
import ucar.unidata.data.imagery.mcidas.McIDASFrameDescriptor;
import ucar.unidata.idv.ControlContext;
import ucar.unidata.idv.MapViewManager;
import ucar.unidata.idv.control.ImageSequenceControl;
import ucar.unidata.idv.control.WrapperWidget;
import ucar.unidata.idv.IntegratedDataViewer;
import ucar.unidata.ui.TextHistoryPane;
import ucar.unidata.util.GuiUtils;
import ucar.unidata.util.Misc;
import visad.*;
import visad.georef.MapProjection;
/**
* A DisplayControl for handling McIDAS-X image sequences
*/
public class McXImageSequenceControl extends ImageSequenceControl {
private JLabel commandLineLabel;
private JTextField commandLine;
private JPanel commandPanel;
private JButton sendBtn;
private JTextArea textArea;
private JPanel textWrapper;
private String request;
private URLConnection urlc;
private DataInputStream inputStream;
private int nlines, removeIncr,
count = 0;
private int ptSize = 12;
private static DataChoice dc=null;
private static Integer frmI;
/** Holds frame component information */
private FrameComponentInfo frameComponentInfo;
List frameNumbers = new ArrayList();
/**
* Default ctor; sets the attribute flags
*/
public McXImageSequenceControl() {
setAttributeFlags(FLAG_COLORTABLE | FLAG_DISPLAYUNIT);
frameComponentInfo = initFrameComponentInfo();
}
/**
* Override the base class method that creates request properties
* and add in the appropriate frame component request parameters.
* @return table of properties
*/
protected Hashtable getRequestProperties() {
Hashtable props = super.getRequestProperties();
props.put(McIDASComponents.IMAGE, new Boolean(frameComponentInfo.getIsImage()));
props.put(McIDASComponents.GRAPHICS, new Boolean(frameComponentInfo.getIsGraphics()));
props.put(McIDASComponents.COLORTABLE, new Boolean(frameComponentInfo.getIsColorTable()));
return props;
}
/**
* Get control widgets specific to this control.
*
* @param controlWidgets list of control widgets from other places
*
* @throws RemoteException Java RMI error
* @throws VisADException VisAD Error
*/
public void getControlWidgets(List controlWidgets)
throws VisADException, RemoteException {
super.getControlWidgets(controlWidgets);
doMakeCommandField();
getSendButton();
JPanel commandLinePanel =
GuiUtils.hflow(Misc.newList(commandLine, sendBtn), 2, 0);
controlWidgets.add(
new WrapperWidget( this, GuiUtils.rLabel("Command Line:"), commandLinePanel));
final JTextField labelField = new JTextField("" , 20);
ActionListener labelListener = new ActionListener() {
public void actionPerformed(ActionEvent ae) {
setNameFromUser(labelField.getText());
updateLegendLabel();
}
};
labelField.addActionListener(labelListener);
JButton labelBtn = new JButton("Apply");
labelBtn.addActionListener(labelListener);
JPanel labelPanel =
GuiUtils.hflow(Misc.newList(labelField, labelBtn),
2, 0);
controlWidgets.add(
new WrapperWidget(
this, GuiUtils.rLabel("Label:"), labelPanel));
frmI = new Integer(0);
ControlContext controlContext = getControlContext();
List dss = ((IntegratedDataViewer)controlContext).getDataSources();
McCommandLineDataSource mds = null;
List frameI = new ArrayList();
for (int i=0; i<dss.size(); i++) {
DataSourceImpl ds = (DataSourceImpl)dss.get(i);
if (ds instanceof McCommandLineDataSource) {
frameNumbers.clear();
mds = (McCommandLineDataSource)ds;
request = mds.request;
this.dc = getDataChoice();
String choiceStr = this.dc.toString();
if (choiceStr.equals("Frame Sequence")) {
frameI = mds.getFrameNumbers();
ArrayList frmAL = (ArrayList)(frameI.get(0));
for (int indx=0; indx<frmAL.size(); indx++) {
frmI = (Integer)(frmAL.get(indx));
frameNumbers.add(frmI);
}
} else {
StringTokenizer tok = new StringTokenizer(this.dc.toString());
String str = tok.nextToken();
frmI = new Integer(tok.nextToken());
frameNumbers.add(frmI);
}
break;
}
}
setShowNoteText(true);
noteTextArea.setRows(20);
noteTextArea.setLineWrap(true);
noteTextArea.setEditable(false);
noteTextArea.setFont(new Font("Monospaced", Font.PLAIN, ptSize));
}
private void appendLine(String line) {
if (count >= nlines) {
try {
int remove = Math.max(removeIncr, count - nlines); // nlines may have changed
int offset = noteTextArea.getLineEndOffset(remove);
noteTextArea.replaceRange("", 0, offset);
} catch (Exception e) {
System.out.println("BUG in appendLine"); // shouldnt happen
}
count = nlines - removeIncr;
}
noteTextArea.append(line);
noteTextArea.append("\n");
count++;
// scroll to end
noteTextArea.setCaretPosition(noteTextArea.getText().length());
}
private JPanel doMakeTextArea() {
textArea = new JTextArea(50, 30);
textArea.setText("This is only a test.");
JScrollPane sp =
new JScrollPane(
textArea,
ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
JViewport vp = sp.getViewport();
vp.setViewSize(new Dimension(60, 30));
textWrapper = GuiUtils.inset(sp, 4);
return textWrapper;
}
private void doMakeCommandField() {
commandLine = new JTextField("", 30);
/*
commandLine.addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e) {}
public void focusLost(FocusEvent e) {
String saveCommand = (commandLine.getText()).trim();
sendCommandLine(saveCommand);
commandLine.setText(" ");
}
});
*/
commandLine.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String saveCommand = (commandLine.getText()).trim();
commandLine.setText(" ");
sendCommandLine(saveCommand);
}
});
commandLine.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent ke) {
sendBtn.setEnabled(true);
}
});
}
/**
* Creates, if needed, and returns the frameComponentInfo member.
*
* @return The frameComponentInfo
*/
private FrameComponentInfo initFrameComponentInfo() {
if (frameComponentInfo == null) {
frameComponentInfo = new FrameComponentInfo(true, true, true);
}
return frameComponentInfo;
}
protected void getSendButton() {
sendBtn = new JButton("Send");
sendBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String line = (commandLine.getText()).trim();
sendCommandLine(line);
}
});
//sendBtn.setEnabled(false);
return;
}
private void sendCommandLine(String line) {
if (line.length() < 1) return;
line = line.toUpperCase();
String appendLine = line.concat("\n");
noteTextArea.append(appendLine);
line = line.trim();
line = line.replaceAll(" ", "+");
String newRequest = request + "T&text=" + line;
URL url;
try
{
url = new URL(newRequest);
urlc = url.openConnection();
InputStream is = urlc.getInputStream();
inputStream =
new DataInputStream(
new BufferedInputStream(is));
}
catch (Exception e)
{
System.out.println("sendCommandLine exception e=" + e);
return;
}
String responseType = null;
String lineOut = null;
try {
lineOut = inputStream.readLine();
lineOut = inputStream.readLine();
} catch (Exception e) {
System.out.println("readLine exception=" + e);
return;
}
while (lineOut != null) {
StringTokenizer tok = new StringTokenizer(lineOut, " ");
responseType = tok.nextToken();
if (responseType.equals("U")) {
+ String frm = tok.nextToken();
for (int i=0; i<frameNumbers.size(); i++) {
- if (new Integer(tok.nextToken()).equals(frameNumbers.get(i))) {
+ if (new Integer(frm).equals(frameNumbers.get(i))) {
FrameDirtyInfo frameDirtyInfo = new FrameDirtyInfo(false,false,false);
if (lineOut.substring(7,8).equals("1")) {
frameDirtyInfo.setDirtyImage(true);
updateImage();
}
if (lineOut.substring(9,10).equals("1")) {
frameDirtyInfo.setDirtyGraphics(true);
updateGraphics();
}
if (lineOut.substring(11,12).equals("1")) {
frameDirtyInfo.setDirtyColorTable(true);
updateEnhancement();
}
}
+ break;
}
} else if (responseType.equals("V")) {
} else if (responseType.equals("H")) {
} else if (responseType.equals("K")) {
} else if (responseType.equals("T") || responseType.equals("C") ||
responseType.equals("M") || responseType.equals("S") ||
responseType.equals("R")) {
noteTextArea.append(lineOut.substring(6));
noteTextArea.append("\n");
}
try {
lineOut = inputStream.readLine();
} catch (Exception e) {
System.out.println("readLine exception=" + e);
return;
}
}
}
private void updateImage() {
try {
resetData();
} catch (Exception e) {
System.out.println("updateImage failed e=" + e);
}
}
private void updateGraphics() {
}
private void updateEnhancement() {
}
/**
* This gets called when the control has received notification of a
* dataChange event.
*
* @throws RemoteException Java RMI problem
* @throws VisADException VisAD problem
*/
protected void resetData() throws VisADException, RemoteException {
FrameDirtyInfo frameDirtyInfo = new FrameDirtyInfo(false,false,false);
ControlContext controlContext = getControlContext();
List dss = ((IntegratedDataViewer)controlContext).getDataSources();
DataSourceImpl ds = null;
for (int i=0; i<dss.size(); i++) {
ds = (DataSourceImpl)dss.get(i);
if (ds instanceof McCommandLineDataSource) {
frameDirtyInfo = ((McCommandLineDataSource)ds).getFrameDirtyInfo();
break;
}
}
super.resetData();
MapProjection mp = getDataProjection();
if (mp != null) {
MapViewManager mvm = getMapViewManager();
mvm.setMapProjection(mp, false);
}
}
}
| false | true | private void sendCommandLine(String line) {
if (line.length() < 1) return;
line = line.toUpperCase();
String appendLine = line.concat("\n");
noteTextArea.append(appendLine);
line = line.trim();
line = line.replaceAll(" ", "+");
String newRequest = request + "T&text=" + line;
URL url;
try
{
url = new URL(newRequest);
urlc = url.openConnection();
InputStream is = urlc.getInputStream();
inputStream =
new DataInputStream(
new BufferedInputStream(is));
}
catch (Exception e)
{
System.out.println("sendCommandLine exception e=" + e);
return;
}
String responseType = null;
String lineOut = null;
try {
lineOut = inputStream.readLine();
lineOut = inputStream.readLine();
} catch (Exception e) {
System.out.println("readLine exception=" + e);
return;
}
while (lineOut != null) {
StringTokenizer tok = new StringTokenizer(lineOut, " ");
responseType = tok.nextToken();
if (responseType.equals("U")) {
for (int i=0; i<frameNumbers.size(); i++) {
if (new Integer(tok.nextToken()).equals(frameNumbers.get(i))) {
FrameDirtyInfo frameDirtyInfo = new FrameDirtyInfo(false,false,false);
if (lineOut.substring(7,8).equals("1")) {
frameDirtyInfo.setDirtyImage(true);
updateImage();
}
if (lineOut.substring(9,10).equals("1")) {
frameDirtyInfo.setDirtyGraphics(true);
updateGraphics();
}
if (lineOut.substring(11,12).equals("1")) {
frameDirtyInfo.setDirtyColorTable(true);
updateEnhancement();
}
}
}
} else if (responseType.equals("V")) {
} else if (responseType.equals("H")) {
} else if (responseType.equals("K")) {
} else if (responseType.equals("T") || responseType.equals("C") ||
responseType.equals("M") || responseType.equals("S") ||
responseType.equals("R")) {
noteTextArea.append(lineOut.substring(6));
noteTextArea.append("\n");
}
try {
lineOut = inputStream.readLine();
} catch (Exception e) {
System.out.println("readLine exception=" + e);
return;
}
}
}
| private void sendCommandLine(String line) {
if (line.length() < 1) return;
line = line.toUpperCase();
String appendLine = line.concat("\n");
noteTextArea.append(appendLine);
line = line.trim();
line = line.replaceAll(" ", "+");
String newRequest = request + "T&text=" + line;
URL url;
try
{
url = new URL(newRequest);
urlc = url.openConnection();
InputStream is = urlc.getInputStream();
inputStream =
new DataInputStream(
new BufferedInputStream(is));
}
catch (Exception e)
{
System.out.println("sendCommandLine exception e=" + e);
return;
}
String responseType = null;
String lineOut = null;
try {
lineOut = inputStream.readLine();
lineOut = inputStream.readLine();
} catch (Exception e) {
System.out.println("readLine exception=" + e);
return;
}
while (lineOut != null) {
StringTokenizer tok = new StringTokenizer(lineOut, " ");
responseType = tok.nextToken();
if (responseType.equals("U")) {
String frm = tok.nextToken();
for (int i=0; i<frameNumbers.size(); i++) {
if (new Integer(frm).equals(frameNumbers.get(i))) {
FrameDirtyInfo frameDirtyInfo = new FrameDirtyInfo(false,false,false);
if (lineOut.substring(7,8).equals("1")) {
frameDirtyInfo.setDirtyImage(true);
updateImage();
}
if (lineOut.substring(9,10).equals("1")) {
frameDirtyInfo.setDirtyGraphics(true);
updateGraphics();
}
if (lineOut.substring(11,12).equals("1")) {
frameDirtyInfo.setDirtyColorTable(true);
updateEnhancement();
}
}
break;
}
} else if (responseType.equals("V")) {
} else if (responseType.equals("H")) {
} else if (responseType.equals("K")) {
} else if (responseType.equals("T") || responseType.equals("C") ||
responseType.equals("M") || responseType.equals("S") ||
responseType.equals("R")) {
noteTextArea.append(lineOut.substring(6));
noteTextArea.append("\n");
}
try {
lineOut = inputStream.readLine();
} catch (Exception e) {
System.out.println("readLine exception=" + e);
return;
}
}
}
|
diff --git a/P2aktuell/src/ro/inf/p2/uebung03/Pali.java b/P2aktuell/src/ro/inf/p2/uebung03/Pali.java
index 362d46e..d89c892 100644
--- a/P2aktuell/src/ro/inf/p2/uebung03/Pali.java
+++ b/P2aktuell/src/ro/inf/p2/uebung03/Pali.java
@@ -1,23 +1,23 @@
package ro.inf.p2.uebung03;
/**
* Created with IntelliJ IDEA.
* User: felix
* Date: 4/10/13
* Time: 2:14 PM
* Palindrom
*/
public class Pali {
public static String filter(String s) {
s = s.toLowerCase();
- s = s.replaceAll("[^a-z]", "");
+ s = s.replaceAll("[^a-z]+", "");
return s;
}
public static boolean isPalindrome(String s) {
s = filter(s);
return s.equals(new StringBuffer(s).reverse().toString());
}
}
| true | true | public static String filter(String s) {
s = s.toLowerCase();
s = s.replaceAll("[^a-z]", "");
return s;
}
| public static String filter(String s) {
s = s.toLowerCase();
s = s.replaceAll("[^a-z]+", "");
return s;
}
|
diff --git a/modular/inventory/src/main/java/org/wgrus/services/RedisInventoryService.java b/modular/inventory/src/main/java/org/wgrus/services/RedisInventoryService.java
index 08a92c8..8182a16 100644
--- a/modular/inventory/src/main/java/org/wgrus/services/RedisInventoryService.java
+++ b/modular/inventory/src/main/java/org/wgrus/services/RedisInventoryService.java
@@ -1,42 +1,42 @@
package org.wgrus.services;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
public class RedisInventoryService implements InventoryService {
private volatile RedisAtomicLong count;
public RedisInventoryService(String productId, RedisConnectionFactory factory) {
this.count = new RedisAtomicLong(productId, factory);
this.count.compareAndSet(0, 100);
}
public long available() {
return this.count.get();
}
public boolean reserve(long quantity) {
if (quantity == 50) { crash(); }
if (this.count.get() < quantity) {
return false;
}
long remaining = this.count.addAndGet(-quantity);
if (remaining < 0) {
- this.count.addAndGet(quantity - remaining);
+ this.count.addAndGet(remaining + quantity);
return false;
}
return true;
}
private void crash() {
List<Long> list = new ArrayList<Long>();
while (true) {
list.add(new Random().nextLong());
}
}
}
| true | true | public boolean reserve(long quantity) {
if (quantity == 50) { crash(); }
if (this.count.get() < quantity) {
return false;
}
long remaining = this.count.addAndGet(-quantity);
if (remaining < 0) {
this.count.addAndGet(quantity - remaining);
return false;
}
return true;
}
| public boolean reserve(long quantity) {
if (quantity == 50) { crash(); }
if (this.count.get() < quantity) {
return false;
}
long remaining = this.count.addAndGet(-quantity);
if (remaining < 0) {
this.count.addAndGet(remaining + quantity);
return false;
}
return true;
}
|
diff --git a/tests/059-finalizer-throw/src/Main.java b/tests/059-finalizer-throw/src/Main.java
index f000d90a0..42260e434 100644
--- a/tests/059-finalizer-throw/src/Main.java
+++ b/tests/059-finalizer-throw/src/Main.java
@@ -1,56 +1,56 @@
// Copyright 2008 The Android Open Source Project
import java.util.Timer;
import java.util.TimerTask;
/*
* Throw an exception from a finalizer and make sure it's harmless. Under
* Dalvik this may also generate a warning in the log file.
*/
public class Main {
static Object waiter = new Object();
static volatile boolean didFinal = false;
static void createAndForget() {
Main main = new Main();
}
public static void main(String[] args) {
createAndForget();
System.gc();
System.runFinalization();
- new Timer().schedule(new TimerTask() {
+ new Timer(true).schedule(new TimerTask() {
public void run() {
System.out.println("Timed out, exiting");
System.exit(1);
}
}, 30000);
while (!didFinal) {
try {
Thread.sleep(500);
} catch (InterruptedException ie) {
System.err.println(ie);
}
}
/* give it a chance to cause mayhem */
try {
Thread.sleep(750);
} catch (InterruptedException ie) {
System.err.println(ie);
}
System.out.println("done");
}
protected void finalize() throws Throwable {
System.out.println("In finalizer");
didFinal = true;
throw new InterruptedException("whee");
}
}
| true | true | public static void main(String[] args) {
createAndForget();
System.gc();
System.runFinalization();
new Timer().schedule(new TimerTask() {
public void run() {
System.out.println("Timed out, exiting");
System.exit(1);
}
}, 30000);
while (!didFinal) {
try {
Thread.sleep(500);
} catch (InterruptedException ie) {
System.err.println(ie);
}
}
/* give it a chance to cause mayhem */
try {
Thread.sleep(750);
} catch (InterruptedException ie) {
System.err.println(ie);
}
System.out.println("done");
}
| public static void main(String[] args) {
createAndForget();
System.gc();
System.runFinalization();
new Timer(true).schedule(new TimerTask() {
public void run() {
System.out.println("Timed out, exiting");
System.exit(1);
}
}, 30000);
while (!didFinal) {
try {
Thread.sleep(500);
} catch (InterruptedException ie) {
System.err.println(ie);
}
}
/* give it a chance to cause mayhem */
try {
Thread.sleep(750);
} catch (InterruptedException ie) {
System.err.println(ie);
}
System.out.println("done");
}
|
diff --git a/components/patient-data/migrations/src/main/java/edu/toronto/cs/internal/R50290PhenoTips477DataMigration.java b/components/patient-data/migrations/src/main/java/edu/toronto/cs/internal/R50290PhenoTips477DataMigration.java
index 042ce0186..7a64c0efe 100644
--- a/components/patient-data/migrations/src/main/java/edu/toronto/cs/internal/R50290PhenoTips477DataMigration.java
+++ b/components/patient-data/migrations/src/main/java/edu/toronto/cs/internal/R50290PhenoTips477DataMigration.java
@@ -1,202 +1,201 @@
/*
* 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 edu.toronto.cs.internal;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.xwiki.component.annotation.Component;
import org.xwiki.model.reference.DocumentReference;
import org.xwiki.model.reference.DocumentReferenceResolver;
import org.xwiki.model.reference.EntityReferenceSerializer;
import com.xpn.xwiki.XWiki;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.objects.BaseObject;
import com.xpn.xwiki.objects.IntegerProperty;
import com.xpn.xwiki.objects.StringProperty;
import com.xpn.xwiki.objects.classes.BaseClass;
import com.xpn.xwiki.objects.classes.PropertyClass;
import com.xpn.xwiki.store.XWikiHibernateBaseStore.HibernateCallback;
import com.xpn.xwiki.store.XWikiHibernateStore;
import com.xpn.xwiki.store.migration.DataMigrationException;
import com.xpn.xwiki.store.migration.XWikiDBVersion;
import com.xpn.xwiki.store.migration.hibernate.AbstractHibernateDataMigration;
/**
* Migration for PhenoTips issue #477: Automatically migrate existing {@code onset} values to the new
* {@code age_of_onset} field.
*
* @version $Id$
* @since 1.0M7
*/
@Component
@Named("R50290Phenotips#477")
@Singleton
public class R50290PhenoTips477DataMigration extends AbstractHibernateDataMigration
{
/**
* Onsets, as defined in HPO. Not all the terms in HPO are used, just the relevant ones.
*/
private static enum HpoOnsets
{
/** From birth to 28 days (rounded to a month, since the onset has month granularity). */
NEONATAL("HP:0003623", 1),
/** From a month to a year. */
INFANTILE("HP:0003593", 12),
/** One to five years. */
CHILDHOOD("HP:0011463", 60),
/** Five to 15 years. */
JUVENILE("HP:0003621", 180),
/** 15 to 40 years. */
YOUNG_ADULT("HP:0011462", 480),
/** 40 to 60 years. */
MIDDLE_AGE("HP:0003596", 720),
/** After 60 years. */
LATE("HP:0003584", Integer.MAX_VALUE);
/** The identifier of the associated HPO term. */
public String term;
/** The upper age limit of this onset. */
public int upperAgeLimit;
/**
* Simple constructor.
*
* @param term see {@link #term}
* @param upperAgeLimit see {@link #upperAgeLimit}
*/
HpoOnsets(String term, int upperAgeLimit)
{
this.term = term;
this.upperAgeLimit = upperAgeLimit;
}
}
/** Resolves unprefixed document names to the current wiki. */
@Inject
@Named("current")
private DocumentReferenceResolver<String> resolver;
/** Serializes the class name without the wiki prefix, to be used in the database query. */
@Inject
@Named("compactwiki")
private EntityReferenceSerializer<String> serializer;
@Override
public String getDescription()
{
return "Migrate existing onset values to the new age_of_onset field";
}
@Override
public XWikiDBVersion getVersion()
{
return new XWikiDBVersion(50290);
}
@Override
public void hibernateMigrate() throws DataMigrationException, XWikiException
{
getStore().executeWrite(getXWikiContext(), new MigrateOnsetCallback());
}
/**
* Searches for all documents containing values for the {@code onset} property, and for each such document and for
* each such object, updates (or creates) the value for {@code age_of_onset} according to the HPO definitions of
* possible onset. If the object already has a new age of onset, nothing is updated. If the old onset is {@code -1},
* which corresponds to the default "congenital onset", the it is not migrated, since this could indicate both an
* explicit congenital onset, or the fact that the user didn't set an onset and left the default value.
*/
private class MigrateOnsetCallback implements HibernateCallback<Object>
{
/** The name of the old onset property. */
private static final String OLD_ONSET_NAME = "onset";
/** The name of the new onset property. */
private static final String NEW_ONSET_NAME = "age_of_onset";
@Override
public Object doInHibernate(Session session) throws HibernateException, XWikiException
{
XWikiContext context = getXWikiContext();
XWiki xwiki = context.getWiki();
DocumentReference classReference =
new DocumentReference(context.getDatabase(), "PhenoTips", "PatientClass");
BaseClass cls = xwiki.getXClass(classReference, context);
Query q =
session.createQuery("select distinct o.name from BaseObject o, IntegerProperty p where o.className = '"
+ R50290PhenoTips477DataMigration.this.serializer.serialize(classReference)
- + "' and p.id.id = o.id and p.id.name = '" + OLD_ONSET_NAME + "'");
+ + "' and p.id.id = o.id and p.id.name = '" + OLD_ONSET_NAME + "' and p.value IS NOT NULL");
@SuppressWarnings("unchecked")
List<String> documents = q.list();
for (String docName : documents) {
XWikiDocument doc =
xwiki.getDocument(R50290PhenoTips477DataMigration.this.resolver.resolve(docName), context);
BaseObject object = doc.getXObject(classReference);
IntegerProperty oldOnset = (IntegerProperty) object.get(OLD_ONSET_NAME);
StringProperty newOnset = (StringProperty) object.get(NEW_ONSET_NAME);
- if (oldOnset == null || oldOnset.getValue() == null
- || (newOnset != null && StringUtils.isNotBlank(newOnset.getValue()))) {
+ if (oldOnset == null || (newOnset != null && StringUtils.isNotBlank(newOnset.getValue()))) {
continue;
}
object.removeField(OLD_ONSET_NAME);
int value = (Integer) oldOnset.getValue();
if (value == -1) {
// We can't say if this is an actual congenital onset or an unset value... Discard it
continue;
}
if (newOnset == null) {
newOnset = (StringProperty) ((PropertyClass) cls.get(NEW_ONSET_NAME)).newProperty();
object.safeput(NEW_ONSET_NAME, newOnset);
}
for (HpoOnsets onset : HpoOnsets.values()) {
if (value <= onset.upperAgeLimit) {
newOnset.setValue(onset.term);
break;
}
}
doc.setComment("Migrated onset to age_of_onset");
doc.setMinorEdit(true);
try {
// There's a bug in XWiki which prevents saving an object in the same session that it was loaded,
// so we must clear the session cache first.
session.clear();
((XWikiHibernateStore) getStore()).saveXWikiDoc(doc, context, false);
session.flush();
} catch (DataMigrationException e) {
// We're in the middle of a migration, we're not expecting another migration
}
}
return null;
}
}
}
| false | true | public Object doInHibernate(Session session) throws HibernateException, XWikiException
{
XWikiContext context = getXWikiContext();
XWiki xwiki = context.getWiki();
DocumentReference classReference =
new DocumentReference(context.getDatabase(), "PhenoTips", "PatientClass");
BaseClass cls = xwiki.getXClass(classReference, context);
Query q =
session.createQuery("select distinct o.name from BaseObject o, IntegerProperty p where o.className = '"
+ R50290PhenoTips477DataMigration.this.serializer.serialize(classReference)
+ "' and p.id.id = o.id and p.id.name = '" + OLD_ONSET_NAME + "'");
@SuppressWarnings("unchecked")
List<String> documents = q.list();
for (String docName : documents) {
XWikiDocument doc =
xwiki.getDocument(R50290PhenoTips477DataMigration.this.resolver.resolve(docName), context);
BaseObject object = doc.getXObject(classReference);
IntegerProperty oldOnset = (IntegerProperty) object.get(OLD_ONSET_NAME);
StringProperty newOnset = (StringProperty) object.get(NEW_ONSET_NAME);
if (oldOnset == null || oldOnset.getValue() == null
|| (newOnset != null && StringUtils.isNotBlank(newOnset.getValue()))) {
continue;
}
object.removeField(OLD_ONSET_NAME);
int value = (Integer) oldOnset.getValue();
if (value == -1) {
// We can't say if this is an actual congenital onset or an unset value... Discard it
continue;
}
if (newOnset == null) {
newOnset = (StringProperty) ((PropertyClass) cls.get(NEW_ONSET_NAME)).newProperty();
object.safeput(NEW_ONSET_NAME, newOnset);
}
for (HpoOnsets onset : HpoOnsets.values()) {
if (value <= onset.upperAgeLimit) {
newOnset.setValue(onset.term);
break;
}
}
doc.setComment("Migrated onset to age_of_onset");
doc.setMinorEdit(true);
try {
// There's a bug in XWiki which prevents saving an object in the same session that it was loaded,
// so we must clear the session cache first.
session.clear();
((XWikiHibernateStore) getStore()).saveXWikiDoc(doc, context, false);
session.flush();
} catch (DataMigrationException e) {
// We're in the middle of a migration, we're not expecting another migration
}
}
return null;
}
| public Object doInHibernate(Session session) throws HibernateException, XWikiException
{
XWikiContext context = getXWikiContext();
XWiki xwiki = context.getWiki();
DocumentReference classReference =
new DocumentReference(context.getDatabase(), "PhenoTips", "PatientClass");
BaseClass cls = xwiki.getXClass(classReference, context);
Query q =
session.createQuery("select distinct o.name from BaseObject o, IntegerProperty p where o.className = '"
+ R50290PhenoTips477DataMigration.this.serializer.serialize(classReference)
+ "' and p.id.id = o.id and p.id.name = '" + OLD_ONSET_NAME + "' and p.value IS NOT NULL");
@SuppressWarnings("unchecked")
List<String> documents = q.list();
for (String docName : documents) {
XWikiDocument doc =
xwiki.getDocument(R50290PhenoTips477DataMigration.this.resolver.resolve(docName), context);
BaseObject object = doc.getXObject(classReference);
IntegerProperty oldOnset = (IntegerProperty) object.get(OLD_ONSET_NAME);
StringProperty newOnset = (StringProperty) object.get(NEW_ONSET_NAME);
if (oldOnset == null || (newOnset != null && StringUtils.isNotBlank(newOnset.getValue()))) {
continue;
}
object.removeField(OLD_ONSET_NAME);
int value = (Integer) oldOnset.getValue();
if (value == -1) {
// We can't say if this is an actual congenital onset or an unset value... Discard it
continue;
}
if (newOnset == null) {
newOnset = (StringProperty) ((PropertyClass) cls.get(NEW_ONSET_NAME)).newProperty();
object.safeput(NEW_ONSET_NAME, newOnset);
}
for (HpoOnsets onset : HpoOnsets.values()) {
if (value <= onset.upperAgeLimit) {
newOnset.setValue(onset.term);
break;
}
}
doc.setComment("Migrated onset to age_of_onset");
doc.setMinorEdit(true);
try {
// There's a bug in XWiki which prevents saving an object in the same session that it was loaded,
// so we must clear the session cache first.
session.clear();
((XWikiHibernateStore) getStore()).saveXWikiDoc(doc, context, false);
session.flush();
} catch (DataMigrationException e) {
// We're in the middle of a migration, we're not expecting another migration
}
}
return null;
}
|
diff --git a/src/com/noshufou/android/su/InfoFragment.java b/src/com/noshufou/android/su/InfoFragment.java
index 7f5b9fc..d0664eb 100644
--- a/src/com/noshufou/android/su/InfoFragment.java
+++ b/src/com/noshufou/android/su/InfoFragment.java
@@ -1,331 +1,331 @@
package com.noshufou.android.su;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;
import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.noshufou.android.su.preferences.Preferences;
import com.noshufou.android.su.util.Device;
import com.noshufou.android.su.util.Device.FileSystem;
import com.noshufou.android.su.util.Util;
import com.noshufou.android.su.util.Util.MenuId;
import com.noshufou.android.su.util.Util.VersionInfo;
import com.noshufou.android.su.widget.ChangeLog;
public class InfoFragment extends SherlockFragment
implements OnClickListener, OnCheckedChangeListener {
private static final String TAG = "Su.InfoFragment";
private TextView mSuperuserVersion;
private TextView mEliteInstalled;
private TextView mGetEliteLabel;
private TextView mSuVersion;
private View mSuDetailsRow;
private TextView mSuDetailsMode;
private TextView mSuDetailsOwner;
private TextView mSuDetailsFile;
private TextView mSuWarning;
private CheckBox mOutdatedNotification;
private View mSuOptionsRow;
private CheckBox mTempUnroot;
private CheckBox mOtaSurvival;
private View mGetElite;
private View mBinaryUpdater;
private SharedPreferences mPrefs;
private Device mDevice = null;
private boolean mDualPane = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPrefs = PreferenceManager.getDefaultSharedPreferences(getSherlockActivity());
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_info, container, false);
mSuperuserVersion = (TextView) view.findViewById(R.id.superuser_version);
mEliteInstalled = (TextView) view.findViewById(R.id.elite_installed);
mGetEliteLabel = (TextView) view.findViewById(R.id.get_elite_label);
mSuVersion = (TextView) view.findViewById(R.id.su_version);
mSuDetailsRow = view.findViewById(R.id.su_details_row);
mSuDetailsMode = (TextView) view.findViewById(R.id.su_details_mode);
mSuDetailsOwner = (TextView) view.findViewById(R.id.su_details_owner);
mSuDetailsFile = (TextView) view.findViewById(R.id.su_details_file);
mSuWarning = (TextView) view.findViewById(R.id.su_warning);
mOutdatedNotification = (CheckBox) view.findViewById(R.id.outdated_notification);
mOutdatedNotification.setOnCheckedChangeListener(this);
mSuOptionsRow = view.findViewById(R.id.su_options_row);
mTempUnroot = (CheckBox) view.findViewById(R.id.temp_unroot);
mTempUnroot.setOnClickListener(this);
mOtaSurvival = (CheckBox) view.findViewById(R.id.ota_survival);
mOtaSurvival.setOnClickListener(this);
view.findViewById(R.id.display_changelog).setOnClickListener(this);
mGetElite = view.findViewById(R.id.get_elite);
mGetElite.setOnClickListener(this);
mBinaryUpdater = view.findViewById(R.id.binary_updater);
mBinaryUpdater.setOnClickListener(this);
new UpdateInfo().execute();
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mDualPane = ((HomeActivity)getActivity()).isDualPane();
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
if (mDualPane) {
menu.add(Menu.NONE, MenuId.LOG, MenuId.LOG,
R.string.page_label_log)
.setIcon(R.drawable.ic_action_log)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MenuId.LOG:
((HomeActivity)getActivity()).showLog();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.display_changelog:
ChangeLog cl = new ChangeLog(getActivity());
cl.getFullLogDialog().show();
break;
case R.id.get_elite:
final Intent eliteIntent = new Intent(Intent.ACTION_VIEW);
eliteIntent.setData(Uri.parse("market://details?id=com.noshufou.android.su.elite"));
startActivity(eliteIntent);
break;
case R.id.binary_updater:
final Intent updaterIntent = new Intent(getSherlockActivity(), UpdaterActivity.class);
startActivity(updaterIntent);
break;
case R.id.temp_unroot:
new ToggleSuOption(Preferences.TEMP_UNROOT).execute();
break;
case R.id.ota_survival:
new ToggleSuOption(Preferences.OTA_SURVIVE).execute();
break;
}
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
switch (buttonView.getId()) {
case R.id.outdated_notification:
mPrefs.edit().putBoolean(Preferences.OUTDATED_NOTIFICATION, isChecked).commit();
break;
}
}
private class UpdateInfo extends AsyncTask<Void, Object, Void> {
@Override
protected void onPreExecute() {
getSherlockActivity().setSupportProgressBarIndeterminateVisibility(true);
}
@Override
protected Void doInBackground(Void... arg) {
publishProgress(0, Util.getSuperuserVersionInfo(getSherlockActivity()));
publishProgress(1, Util.elitePresent(getSherlockActivity(), false, 0));
String suPath = Util.whichSu();
if (suPath != null) {
publishProgress(2, Util.getSuVersionInfo());
String suTools = Util.ensureSuTools(getSherlockActivity());
try {
Process process = new ProcessBuilder(suTools, "ls", "-l", suPath)
.redirectErrorStream(true).start();
BufferedReader is = new BufferedReader(new InputStreamReader(
process.getInputStream()));
process.waitFor();
String inLine = is.readLine();
String bits[] = inLine.split("\\s+");
publishProgress(3, bits[0], String.format("%s %s", bits[1], bits[2]), suPath);
} catch (IOException e) {
Log.w(TAG, "Binary information could not be read");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
publishProgress(2, null);
}
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getSherlockActivity());
publishProgress(4, prefs.getBoolean(Preferences.OUTDATED_NOTIFICATION, true));
if (mDevice == null) mDevice = new Device(getSherlockActivity());
mDevice.analyzeSu();
boolean supported = mDevice.mFileSystem == FileSystem.EXTFS;
if (!supported) {
publishProgress(5, null);
} else {
publishProgress(5, mDevice.isRooted, mDevice.isSuProtected);
}
return null;
}
@Override
protected void onProgressUpdate(Object... values) {
switch ((Integer) values[0]) {
case 0:
VersionInfo superuserVersion = (VersionInfo) values[1];
mSuperuserVersion.setText(getSherlockActivity().getString(
R.string.info_version,
superuserVersion.version,
superuserVersion.versionCode));
break;
case 1:
boolean eliteInstalled = (Boolean) values[1];
mEliteInstalled.setText(eliteInstalled ?
R.string.info_elite_installed : R.string.info_elite_not_installed);
mGetEliteLabel.setVisibility(eliteInstalled ? View.GONE : View.VISIBLE);
mGetElite.setClickable(!eliteInstalled);
break;
case 2:
VersionInfo suVersion = (VersionInfo) values[1];
if (suVersion != null) {
mSuVersion.setText(getSherlockActivity().getString(
R.string.info_bin_version,
suVersion.version,
suVersion.versionCode));
mSuDetailsRow.setVisibility(View.VISIBLE);
mSuWarning.setVisibility(View.VISIBLE);
mBinaryUpdater.setClickable(true);
} else {
mSuVersion.setText(R.string.info_bin_version_not_found);
mSuDetailsRow.setVisibility(View.GONE);
mBinaryUpdater.setClickable(false);
mSuWarning.setVisibility(View.GONE);
}
break;
case 3:
String mode = (String) values[1];
String owner = (String) values[2];
String file = (String) values[3];
boolean goodMode = mode.equals("-rwsr-sr-x");
boolean goodOwner = owner.equals("root root");
boolean goodFile = !file.equals("/sbin/su");
mSuDetailsMode.setText(mode);
mSuDetailsMode.setTextColor(goodMode ? Color.GREEN : Color.RED);
mSuDetailsOwner.setText(owner);
mSuDetailsOwner.setTextColor(goodOwner ? Color.GREEN : Color.RED);
mSuDetailsFile.setText(file);
mSuDetailsFile.setTextColor(goodFile ? Color.GREEN : Color.RED);
if (!goodFile) {
mBinaryUpdater.setClickable(false);
mSuWarning.setText("note: your su binary cannot be updated due to it's location");
mSuWarning.setVisibility(View.VISIBLE);
}
break;
case 4:
mOutdatedNotification.setChecked((Boolean) values[1]);
break;
case 5:
- if (values[0] == null) {
+ if (values[1] == null) {
mSuOptionsRow.setVisibility(View.GONE);
} else {
boolean rooted = (Boolean) values[1];
boolean backupAvailable = (Boolean) values[2];
mSuOptionsRow.setVisibility(View.VISIBLE);
mTempUnroot.setChecked(!rooted && backupAvailable);
mTempUnroot.setEnabled(rooted || backupAvailable);
mOtaSurvival.setChecked(backupAvailable);
mOtaSurvival.setEnabled(rooted);
}
}
}
@Override
protected void onPostExecute(Void result) {
getSherlockActivity().setSupportProgressBarIndeterminateVisibility(false);
}
}
private class ToggleSuOption extends AsyncTask<Void, Void, Boolean> {
private String mKey;
public ToggleSuOption(String key) {
mKey = key;
}
@Override
protected void onPreExecute() {
getSherlockActivity().setSupportProgressBarIndeterminateVisibility(true);
mTempUnroot.setEnabled(false);
mOtaSurvival.setEnabled(false);
if (mKey.equals(Preferences.TEMP_UNROOT)) mTempUnroot.setText(R.string.info_working);
else mOtaSurvival.setText(R.string.info_working);
}
@Override
protected Boolean doInBackground(Void... params) {
boolean status = false;
mDevice.analyzeSu();
if (mKey.equals(Preferences.TEMP_UNROOT)) {
if (mDevice.isRooted) mDevice.mSuOps.unRoot();
else mDevice.mSuOps.restore();
} else {
if (mDevice.isSuProtected) mDevice.mSuOps.deleteBackup();
else mDevice.mSuOps.backup();
}
return status;
}
@Override
protected void onPostExecute(Boolean result) {
getSherlockActivity().setSupportProgressBarIndeterminateVisibility(false);
mTempUnroot.setText(R.string.info_temp_unroot);
mOtaSurvival.setText(R.string.info_ota_survival);
mTempUnroot.setEnabled(true);
mOtaSurvival.setEnabled(true);
new UpdateInfo().execute();
}
}
}
| true | true | protected void onProgressUpdate(Object... values) {
switch ((Integer) values[0]) {
case 0:
VersionInfo superuserVersion = (VersionInfo) values[1];
mSuperuserVersion.setText(getSherlockActivity().getString(
R.string.info_version,
superuserVersion.version,
superuserVersion.versionCode));
break;
case 1:
boolean eliteInstalled = (Boolean) values[1];
mEliteInstalled.setText(eliteInstalled ?
R.string.info_elite_installed : R.string.info_elite_not_installed);
mGetEliteLabel.setVisibility(eliteInstalled ? View.GONE : View.VISIBLE);
mGetElite.setClickable(!eliteInstalled);
break;
case 2:
VersionInfo suVersion = (VersionInfo) values[1];
if (suVersion != null) {
mSuVersion.setText(getSherlockActivity().getString(
R.string.info_bin_version,
suVersion.version,
suVersion.versionCode));
mSuDetailsRow.setVisibility(View.VISIBLE);
mSuWarning.setVisibility(View.VISIBLE);
mBinaryUpdater.setClickable(true);
} else {
mSuVersion.setText(R.string.info_bin_version_not_found);
mSuDetailsRow.setVisibility(View.GONE);
mBinaryUpdater.setClickable(false);
mSuWarning.setVisibility(View.GONE);
}
break;
case 3:
String mode = (String) values[1];
String owner = (String) values[2];
String file = (String) values[3];
boolean goodMode = mode.equals("-rwsr-sr-x");
boolean goodOwner = owner.equals("root root");
boolean goodFile = !file.equals("/sbin/su");
mSuDetailsMode.setText(mode);
mSuDetailsMode.setTextColor(goodMode ? Color.GREEN : Color.RED);
mSuDetailsOwner.setText(owner);
mSuDetailsOwner.setTextColor(goodOwner ? Color.GREEN : Color.RED);
mSuDetailsFile.setText(file);
mSuDetailsFile.setTextColor(goodFile ? Color.GREEN : Color.RED);
if (!goodFile) {
mBinaryUpdater.setClickable(false);
mSuWarning.setText("note: your su binary cannot be updated due to it's location");
mSuWarning.setVisibility(View.VISIBLE);
}
break;
case 4:
mOutdatedNotification.setChecked((Boolean) values[1]);
break;
case 5:
if (values[0] == null) {
mSuOptionsRow.setVisibility(View.GONE);
} else {
boolean rooted = (Boolean) values[1];
boolean backupAvailable = (Boolean) values[2];
mSuOptionsRow.setVisibility(View.VISIBLE);
mTempUnroot.setChecked(!rooted && backupAvailable);
mTempUnroot.setEnabled(rooted || backupAvailable);
mOtaSurvival.setChecked(backupAvailable);
mOtaSurvival.setEnabled(rooted);
}
}
}
| protected void onProgressUpdate(Object... values) {
switch ((Integer) values[0]) {
case 0:
VersionInfo superuserVersion = (VersionInfo) values[1];
mSuperuserVersion.setText(getSherlockActivity().getString(
R.string.info_version,
superuserVersion.version,
superuserVersion.versionCode));
break;
case 1:
boolean eliteInstalled = (Boolean) values[1];
mEliteInstalled.setText(eliteInstalled ?
R.string.info_elite_installed : R.string.info_elite_not_installed);
mGetEliteLabel.setVisibility(eliteInstalled ? View.GONE : View.VISIBLE);
mGetElite.setClickable(!eliteInstalled);
break;
case 2:
VersionInfo suVersion = (VersionInfo) values[1];
if (suVersion != null) {
mSuVersion.setText(getSherlockActivity().getString(
R.string.info_bin_version,
suVersion.version,
suVersion.versionCode));
mSuDetailsRow.setVisibility(View.VISIBLE);
mSuWarning.setVisibility(View.VISIBLE);
mBinaryUpdater.setClickable(true);
} else {
mSuVersion.setText(R.string.info_bin_version_not_found);
mSuDetailsRow.setVisibility(View.GONE);
mBinaryUpdater.setClickable(false);
mSuWarning.setVisibility(View.GONE);
}
break;
case 3:
String mode = (String) values[1];
String owner = (String) values[2];
String file = (String) values[3];
boolean goodMode = mode.equals("-rwsr-sr-x");
boolean goodOwner = owner.equals("root root");
boolean goodFile = !file.equals("/sbin/su");
mSuDetailsMode.setText(mode);
mSuDetailsMode.setTextColor(goodMode ? Color.GREEN : Color.RED);
mSuDetailsOwner.setText(owner);
mSuDetailsOwner.setTextColor(goodOwner ? Color.GREEN : Color.RED);
mSuDetailsFile.setText(file);
mSuDetailsFile.setTextColor(goodFile ? Color.GREEN : Color.RED);
if (!goodFile) {
mBinaryUpdater.setClickable(false);
mSuWarning.setText("note: your su binary cannot be updated due to it's location");
mSuWarning.setVisibility(View.VISIBLE);
}
break;
case 4:
mOutdatedNotification.setChecked((Boolean) values[1]);
break;
case 5:
if (values[1] == null) {
mSuOptionsRow.setVisibility(View.GONE);
} else {
boolean rooted = (Boolean) values[1];
boolean backupAvailable = (Boolean) values[2];
mSuOptionsRow.setVisibility(View.VISIBLE);
mTempUnroot.setChecked(!rooted && backupAvailable);
mTempUnroot.setEnabled(rooted || backupAvailable);
mOtaSurvival.setChecked(backupAvailable);
mOtaSurvival.setEnabled(rooted);
}
}
}
|
diff --git a/src/main/java/net/betterverse/unclaimed/commands/UnclaimedCommandTeleportTask.java b/src/main/java/net/betterverse/unclaimed/commands/UnclaimedCommandTeleportTask.java
index 30a1e8f..d26aaa7 100644
--- a/src/main/java/net/betterverse/unclaimed/commands/UnclaimedCommandTeleportTask.java
+++ b/src/main/java/net/betterverse/unclaimed/commands/UnclaimedCommandTeleportTask.java
@@ -1,38 +1,38 @@
package net.betterverse.unclaimed.commands;
import java.util.HashMap;
import java.util.Map;
import org.bukkit.entity.Player;
public class UnclaimedCommandTeleportTask implements Runnable {
private static Map<String, Long> cooling = new HashMap<String, Long>();
private String player;
public UnclaimedCommandTeleportTask(Player player, long endTime) {
cooling.put(player.getName(), endTime);
this.player = player.getName();
}
public static long getRemainingTime(Player player) {
Long coolTime = cooling.get(player.getName());
if (coolTime == null) {
return 0;
}
- long diff = System.currentTimeMillis() - coolTime;
+ long diff = coolTime - System.currentTimeMillis();
if (diff < 0) {
cooling.remove(player.getName()); // Just in case the server is lagging
return 0;
}
return diff;
}
public static void reset(Player player) {
cooling.remove(player.getName());
}
@Override
public void run() {
cooling.remove(player);
}
}
| true | true | public static long getRemainingTime(Player player) {
Long coolTime = cooling.get(player.getName());
if (coolTime == null) {
return 0;
}
long diff = System.currentTimeMillis() - coolTime;
if (diff < 0) {
cooling.remove(player.getName()); // Just in case the server is lagging
return 0;
}
return diff;
}
| public static long getRemainingTime(Player player) {
Long coolTime = cooling.get(player.getName());
if (coolTime == null) {
return 0;
}
long diff = coolTime - System.currentTimeMillis();
if (diff < 0) {
cooling.remove(player.getName()); // Just in case the server is lagging
return 0;
}
return diff;
}
|
diff --git a/libraries/javalib/gnu/javax/rmi/CORBA/DelegateFactory.java b/libraries/javalib/gnu/javax/rmi/CORBA/DelegateFactory.java
index c98549b40..bf6f9e64c 100644
--- a/libraries/javalib/gnu/javax/rmi/CORBA/DelegateFactory.java
+++ b/libraries/javalib/gnu/javax/rmi/CORBA/DelegateFactory.java
@@ -1,74 +1,76 @@
/* DelegateFactory.java --
Copyright (C) 2002 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package gnu.javax.rmi.CORBA;
import java.util.HashMap;
import javax.rmi.CORBA.Util;
public class DelegateFactory
{
private static HashMap cache = new HashMap(4);
public static synchronized Object getInstance(String type)
throws GetDelegateInstanceException
{
Object r = cache.get(type);
if (r != null)
return r;
String dcname = System.getProperty("javax.rmi.CORBA." + type + "Class");
if (dcname == null)
{
//throw new DelegateException
// ("no javax.rmi.CORBA.XXXClass property sepcified.");
dcname = "gnu.javax.rmi.CORBA." + type + "DelegateImpl";
}
try
{
- Class dclass = Class.forName(dcname);
+ Class dclass = Class.forName(dcname,
+ true,
+ Thread.currentThread().getContextClassLoader());
r = dclass.newInstance();
cache.put(type, r);
return r;
}
catch(Exception e)
{
throw new GetDelegateInstanceException
("Exception when trying to get delegate instance:" + dcname, e);
}
}
}
| true | true | public static synchronized Object getInstance(String type)
throws GetDelegateInstanceException
{
Object r = cache.get(type);
if (r != null)
return r;
String dcname = System.getProperty("javax.rmi.CORBA." + type + "Class");
if (dcname == null)
{
//throw new DelegateException
// ("no javax.rmi.CORBA.XXXClass property sepcified.");
dcname = "gnu.javax.rmi.CORBA." + type + "DelegateImpl";
}
try
{
Class dclass = Class.forName(dcname);
r = dclass.newInstance();
cache.put(type, r);
return r;
}
catch(Exception e)
{
throw new GetDelegateInstanceException
("Exception when trying to get delegate instance:" + dcname, e);
}
}
| public static synchronized Object getInstance(String type)
throws GetDelegateInstanceException
{
Object r = cache.get(type);
if (r != null)
return r;
String dcname = System.getProperty("javax.rmi.CORBA." + type + "Class");
if (dcname == null)
{
//throw new DelegateException
// ("no javax.rmi.CORBA.XXXClass property sepcified.");
dcname = "gnu.javax.rmi.CORBA." + type + "DelegateImpl";
}
try
{
Class dclass = Class.forName(dcname,
true,
Thread.currentThread().getContextClassLoader());
r = dclass.newInstance();
cache.put(type, r);
return r;
}
catch(Exception e)
{
throw new GetDelegateInstanceException
("Exception when trying to get delegate instance:" + dcname, e);
}
}
|
diff --git a/src/net/lala/CouponCodes/CouponCodes.java b/src/net/lala/CouponCodes/CouponCodes.java
index 99e7823..3e663f5 100644
--- a/src/net/lala/CouponCodes/CouponCodes.java
+++ b/src/net/lala/CouponCodes/CouponCodes.java
@@ -1,472 +1,472 @@
package net.lala.CouponCodes;
import java.io.File;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import net.lala.CouponCodes.api.CouponAPI;
import net.lala.CouponCodes.api.CouponManager;
import net.lala.CouponCodes.api.SQLAPI;
import net.lala.CouponCodes.api.coupon.Coupon;
import net.lala.CouponCodes.api.coupon.EconomyCoupon;
import net.lala.CouponCodes.api.coupon.ItemCoupon;
import net.lala.CouponCodes.api.events.EventHandle;
import net.lala.CouponCodes.api.events.example.CouponCodesMaster;
import net.lala.CouponCodes.api.events.example.CouponMaster;
import net.lala.CouponCodes.api.events.example.DatabaseMaster;
import net.lala.CouponCodes.api.events.plugin.CouponCodesCommandEvent;
import net.lala.CouponCodes.sql.DatabaseOptions;
import net.lala.CouponCodes.sql.SQL;
import net.milkbowl.vault.economy.Economy;
import org.bukkit.ChatColor;
import org.bukkit.Server;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.Event.Priority;
import org.bukkit.event.Event.Type;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.java.JavaPlugin;
/**
* CouponCodes.java - Main class
* @author mike101102
*/
public class CouponCodes extends JavaPlugin {
private static CouponManager cm = null;
private DatabaseOptions dataop = null;
private Config config = null;
private boolean ec = false;
private boolean debug = false;
private SQLType sqltype;
private SQL sql;
public Server server = null;
public Economy econ = null;
@Override
public void onEnable() {
server = getServer();
if (!setupEcon()) {
send("Economy support is disabled.");
ec = false;
} else {
ec = true;
if (!econ.isEnabled())
send("Economy support is disabled.");
ec = false;
}
// This is for this plugin's own events!
server.getPluginManager().registerEvent(Type.CUSTOM_EVENT, new CouponMaster(this), Priority.Monitor, this);
server.getPluginManager().registerEvent(Type.CUSTOM_EVENT, new DatabaseMaster(this), Priority.Monitor, this);
server.getPluginManager().registerEvent(Type.CUSTOM_EVENT, new CouponCodesMaster(this), Priority.Monitor, this);
config = new Config(this);
sqltype = config.getSQLType();
debug = config.getDebug();
if (sqltype.equals(SQLType.MySQL)) {
dataop = new DatabaseOptions(config.getHostname(), config.getPort(), config.getDatabase(), config.getUsername(), config.getPassword());
}
else if (sqltype.equals(SQLType.SQLite)) {
dataop = new DatabaseOptions(new File(this.getDataFolder()+"/coupon_data.db"));
}
else if (sqltype.equals(SQLType.Unknown)) {
sendErr("The SQLType has the unknown value of: "+config.getSQLValue()+" CouponCodes will now disable.");
this.setEnabled(false);
return;
}
sql = new SQL(this, dataop);
try {
sql.open();
sql.createTable("CREATE TABLE IF NOT EXISTS couponcodes (name VARCHAR(24), ctype VARCHAR(10), usetimes INT(10), usedplayers TEXT(1024), ids VARCHAR(255), money INT(10))");
cm = new CouponManager(this, getSQLAPI());
} catch (SQLException e) {
sendErr("SQLException while creating couponcodes table. CouponCodes will now disable.");
e.printStackTrace();
this.setEnabled(false);
return;
}
this.saveConfig();
send("is now enabled! Version: "+this.getDescription().getVersion());
}
@Override
public void onDisable() {
this.saveConfig();
try {
sql.close(true);
} catch (SQLException e) {
sendErr("Could not close SQL connection");
} catch (NullPointerException e) {
sendErr("SQL is null. Connection doesn't exist");
}
send("is now disabled.");
}
private boolean setupEcon() {
try {
RegisteredServiceProvider<Economy> ep = server.getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class);
if (ep == null)
return false;
else
econ = ep.getProvider();
return true;
} catch (NoClassDefFoundError e) {
return false;
}
}
@Override
public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) {
// Event handling
CouponCodesCommandEvent ev = EventHandle.callCouponCodesCommandEvent(sender, command, commandLabel, args);
sender = ev.getSender();
command = ev.getCommand();
commandLabel = ev.getCommandLabel();
args = ev.getArgs();
boolean pl = false;
if (sender instanceof Player) pl = true;
if (args.length == 0 || args[0].equalsIgnoreCase("help")) {
help(sender);
return true;
}
CouponAPI api = CouponCodes.getCouponAPI();
// Add command
if (args[0].equalsIgnoreCase("add")) {
// Fix for being retarded
if (!(args.length == 5)) {
help(sender);
return true;
} // carry on..
if (sender.hasPermission("cc.add")) {
if (args[1].equalsIgnoreCase("item")) {
if (args.length == 5) {
try {
Coupon coupon = api.createNewItemCoupon(args[2], Integer.parseInt(args[4]), this.convertStringToHash(args[3]), new HashMap<String, Boolean>());
if (coupon.isInDatabase()) {
sender.sendMessage(ChatColor.RED+"This coupon already exists!");
return true;
} else {
coupon.addToDatabase();
sender.sendMessage(ChatColor.GREEN+"Coupon "+ChatColor.GOLD+coupon.getName()+ChatColor.GREEN+" has been added!");
return true;
}
} catch (NumberFormatException e) {
sender.sendMessage(ChatColor.DARK_RED+"Expected a number, but got "+ChatColor.YELLOW+args[4]);
return true;
} catch (SQLException e) {
sender.sendMessage(ChatColor.DARK_RED+"Error while adding coupon to database. Please check console for more info.");
sender.sendMessage(ChatColor.DARK_RED+"If this error persists, please report it.");
e.printStackTrace();
return true;
}
} else {
sender.sendMessage(ChatColor.RED+"Invalid syntax length");
sender.sendMessage(ChatColor.YELLOW+"/c add item [name] [item1:amount,item2:amount,...] [usetimes]");
return true;
}
}
else if (args[1].equalsIgnoreCase("econ")) {
if (args.length == 5) {
if (!ec) {
sender.sendMessage(ChatColor.DARK_RED+"Economy support is currently disabled. You cannot add an economy coupon");
return true;
} else {
try {
Coupon coupon = api.createNewEconomyCoupon(args[2], Integer.parseInt(args[4]), new HashMap<String, Boolean>(), Integer.parseInt(args[3]));
if (coupon.isInDatabase()) {
sender.sendMessage(ChatColor.DARK_RED+"This coupon already exists!");
return true;
} else {
coupon.addToDatabase();
sender.sendMessage(ChatColor.GREEN+"Coupon "+ChatColor.GOLD+coupon.getName()+ChatColor.GREEN+" has been added!");
return true;
}
} catch (NumberFormatException e) {
sender.sendMessage(ChatColor.DARK_RED+"Expected a number, but got "+ChatColor.YELLOW+args[3]);
return true;
} catch (SQLException e) {
sender.sendMessage(ChatColor.DARK_RED+"Error while adding coupon to database. Please check console for more info.");
sender.sendMessage(ChatColor.DARK_RED+"If this error persists, please report it.");
e.printStackTrace();
return true;
}
}
} else {
sender.sendMessage(ChatColor.RED+"Invalid syntax length");
sender.sendMessage(ChatColor.YELLOW+"/c add econ [name] [money] [usetimes]");
return true;
}
} else {
help(sender);
return true;
}
} else {
sender.sendMessage(ChatColor.RED+"You do not have permission to use this command");
return true;
}
}
// Remove command
else if (args[0].equalsIgnoreCase("remove")) {
if (sender.hasPermission("cc.remove")) {
if (args.length == 2) {
try {
if (!api.couponExists(args[1])) {
sender.sendMessage(ChatColor.RED+"That coupon doesn't exist!");
return true;
}
api.removeCouponFromDatabase(api.createNewItemCoupon(args[1], 0, null, null));
sender.sendMessage(ChatColor.GREEN+"The coupon "+ChatColor.GOLD+args[1]+ChatColor.GREEN+" has been removed.");
return true;
} catch (SQLException e) {
sender.sendMessage(ChatColor.DARK_RED+"Error while removing coupon from the database. Please check the console for more info.");
sender.sendMessage(ChatColor.DARK_RED+"If this error persists, please report it.");
e.printStackTrace();
return true;
}
} else {
sender.sendMessage(ChatColor.RED+"Invalid syntax length");
sender.sendMessage(ChatColor.YELLOW+"/c remove [name]");
return true;
}
} else {
sender.sendMessage(ChatColor.RED+"You do not have permission to use this command");
return true;
}
}
// Redeem command
else if (args[0].equalsIgnoreCase("redeem")) {
if (!pl) {
sender.sendMessage("You must be a player to redeem a coupon");
return true;
} else {
Player player = (Player) sender;
if (player.hasPermission("cc.redeem")) {
if (args.length == 2) {
try {
if (!api.couponExists(args[1])) {
player.sendMessage(ChatColor.RED+"That coupon doesn't exist!");
return true;
}
Coupon coupon = api.getCoupon(args[1]);
try {
if (!coupon.getUseTimes().equals(null) || !coupon.getUsedPlayers().isEmpty()) {
if (coupon.getUseTimes() <= 0 || coupon.getUsedPlayers().get(player.getName()) == true) {
player.sendMessage(ChatColor.RED+"You cannot use this coupon as it is expired for you.");
return true;
}
}
} catch (NullPointerException e) {}
if (coupon instanceof ItemCoupon) {
ItemCoupon c = (ItemCoupon) coupon;
for (Map.Entry<Integer, Integer> en : c.getIDs().entrySet()) {
player.getInventory().addItem(new ItemStack(en.getKey(), en.getValue()));
}
player.sendMessage(ChatColor.GREEN+"Coupon "+ChatColor.GOLD+c.getName()+ChatColor.GREEN+" has been redeemed, and the items added to your inventory!");
}
else if (coupon instanceof EconomyCoupon) {
if (!econ.isEnabled()) {
player.sendMessage(ChatColor.DARK_RED+"Economy support is currently disabled. You cannot redeem an economy coupon.");
return true;
} else {
EconomyCoupon c = (EconomyCoupon) coupon;
econ.depositPlayer(player.getName(), c.getMoney());
player.sendMessage(ChatColor.GREEN+"Coupon "+ChatColor.GOLD+c.getName()+ChatColor.GREEN+" has been redeemed, and the money added to your account!");
}
}
HashMap<String, Boolean> up = coupon.getUsedPlayers();
up.put(player.getName(), true);
coupon.setUsedPlayers(up);
coupon.setUseTimes(coupon.getUseTimes()-1);
coupon.updateWithDatabase();
return true;
} catch (SQLException e) {
player.sendMessage(ChatColor.DARK_RED+"Error while trying to find "+args[1]+" in the database. Please check the console for more info.");
player.sendMessage(ChatColor.DARK_RED+"If this error persists, please report it.");
e.printStackTrace();
return true;
}
} else {
player.sendMessage(ChatColor.RED+"Invalid syntax length");
player.sendMessage(ChatColor.YELLOW+"/c redeem [name]");
return true;
}
} else {
player.sendMessage(ChatColor.RED+"You do not have permission to use this command");
return true;
}
}
}
// List command
else if (args[0].equalsIgnoreCase("list")) {
if (sender.hasPermission("cc.list")) {
StringBuilder sb = new StringBuilder();
try {
ArrayList<String> c = api.getCoupons();
if (c.isEmpty() || c.size() <= 0 || c.equals(null)) {
sender.sendMessage(ChatColor.RED+"No coupons found.");
return true;
} else {
sb.append(ChatColor.DARK_PURPLE+"Coupon list: "+ChatColor.GOLD);
for (int i = 0; i < c.size(); i++) {
sb.append(c.get(i));
if (!(Integer.valueOf(i+1).equals(c.size()))){
sb.append(", ");
}
}
sender.sendMessage(sb.toString());
return true;
}
} catch (SQLException e) {
sender.sendMessage(ChatColor.DARK_RED+"Error while getting the coupon list from the database. Please check the console for more info.");
sender.sendMessage(ChatColor.DARK_RED+"If this error persists, please report it.");
e.printStackTrace();
return true;
}
} else {
sender.sendMessage(ChatColor.RED+"You do not have permission to use this command");
return true;
}
- } else{
+ } else {
help(sender);
return true;
}
}
private void help(CommandSender sender) {
sender.sendMessage(ChatColor.GOLD+"|---------------------|");
sender.sendMessage(ChatColor.GOLD+"|---"+ChatColor.DARK_RED+"CouponCodes Help"+ChatColor.GOLD+"---|");
sender.sendMessage(ChatColor.GOLD+"|--"+ChatColor.YELLOW+"/c help"+ChatColor.GOLD);
sender.sendMessage(ChatColor.GOLD+"|--"+ChatColor.YELLOW+"/c add item [name] [item1:amount,item2:amount,...] [usetimes]");
sender.sendMessage(ChatColor.GOLD+"|--"+ChatColor.YELLOW+"/c add econ [name] [money] [usetimes]");
sender.sendMessage(ChatColor.GOLD+"|--"+ChatColor.YELLOW+"/c redeem [name]");
sender.sendMessage(ChatColor.GOLD+"|--"+ChatColor.YELLOW+"/c remove [name]");
sender.sendMessage(ChatColor.GOLD+"|--"+ChatColor.YELLOW+"/c list");
sender.sendMessage(ChatColor.GOLD+"|---------------------|");
}
public HashMap<Integer, Integer> convertStringToHash(String args) {
HashMap<Integer, Integer> ids = new HashMap<Integer, Integer>();
String[] sp = args.split(",");
try {
for (int i = 0; i < sp.length; i++) {
int a = Integer.parseInt(sp[i].split(":")[0]);
int b = Integer.parseInt(sp[i].split(":")[1]);
ids.put(a, b);
}
} catch (NumberFormatException e) {
e.printStackTrace();
}
return ids;
}
public String convertHashToString(HashMap<Integer, Integer> hash) {
StringBuilder sb = new StringBuilder();
for (Map.Entry<Integer, Integer> en : hash.entrySet()) {
sb.append(en.getKey()+":"+en.getValue()+",");
}
sb.deleteCharAt(sb.length()-1);
return sb.toString();
}
public HashMap<String, Boolean> convertStringToHash2(String args) {
HashMap<String, Boolean> pl = new HashMap<String, Boolean>();
if (args.equals(null) || args.length() < 1) return pl;
String[] sp = args.split(",");
try {
for (int i = 0; i < sp.length; i++) {
String a = String.valueOf(sp[i].split(":")[0]);
Boolean b = Boolean.valueOf(sp[i].split(":")[1]);
pl.put(a, b);
}
} catch (NumberFormatException e) {
e.printStackTrace();
}
return pl;
}
public String convertHashToString2(HashMap<String, Boolean> hash) {
if (hash.isEmpty() || hash == null || hash.size() < 1) return "";
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, Boolean> en : hash.entrySet()) {
sb.append(en.getKey()+":"+en.getValue()+",");
}
sb.deleteCharAt(sb.length()-1);
return sb.toString();
}
/* Fail code is fail
public ArrayList<String> convertStringToArrayList(String args) {
ArrayList<String> list = new ArrayList<String>();
String[] slist = args.split(",");
for (int i = 0; i < slist.length; i++) {
list.add(slist[i]);
}
send(list.toString());
return list;
}
public String convertArrayListToString(ArrayList<String> args) {
return args.toString().replace(",", "\t");
}*/
public void send(String message) {
System.out.println("[CouponCodes] "+message);
}
public void sendErr(String message) {
System.err.println("[CouponCodes] [Error] "+message);
}
public void debug(String message) {
if (isDebug()) return;
System.out.println("[CouponCodes] [Debug] "+message);
}
public static CouponAPI getCouponAPI() {
return (CouponAPI) cm;
}
public SQLAPI getSQLAPI() {
return (SQLAPI) sql;
}
public DatabaseOptions getDatabaseOptions() {
return dataop;
}
public boolean isEconomyEnabled() {
return ec;
}
public SQLType getSQLType() {
return sqltype;
}
public boolean isDebug() {
return debug;
}
}
| true | true | public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) {
// Event handling
CouponCodesCommandEvent ev = EventHandle.callCouponCodesCommandEvent(sender, command, commandLabel, args);
sender = ev.getSender();
command = ev.getCommand();
commandLabel = ev.getCommandLabel();
args = ev.getArgs();
boolean pl = false;
if (sender instanceof Player) pl = true;
if (args.length == 0 || args[0].equalsIgnoreCase("help")) {
help(sender);
return true;
}
CouponAPI api = CouponCodes.getCouponAPI();
// Add command
if (args[0].equalsIgnoreCase("add")) {
// Fix for being retarded
if (!(args.length == 5)) {
help(sender);
return true;
} // carry on..
if (sender.hasPermission("cc.add")) {
if (args[1].equalsIgnoreCase("item")) {
if (args.length == 5) {
try {
Coupon coupon = api.createNewItemCoupon(args[2], Integer.parseInt(args[4]), this.convertStringToHash(args[3]), new HashMap<String, Boolean>());
if (coupon.isInDatabase()) {
sender.sendMessage(ChatColor.RED+"This coupon already exists!");
return true;
} else {
coupon.addToDatabase();
sender.sendMessage(ChatColor.GREEN+"Coupon "+ChatColor.GOLD+coupon.getName()+ChatColor.GREEN+" has been added!");
return true;
}
} catch (NumberFormatException e) {
sender.sendMessage(ChatColor.DARK_RED+"Expected a number, but got "+ChatColor.YELLOW+args[4]);
return true;
} catch (SQLException e) {
sender.sendMessage(ChatColor.DARK_RED+"Error while adding coupon to database. Please check console for more info.");
sender.sendMessage(ChatColor.DARK_RED+"If this error persists, please report it.");
e.printStackTrace();
return true;
}
} else {
sender.sendMessage(ChatColor.RED+"Invalid syntax length");
sender.sendMessage(ChatColor.YELLOW+"/c add item [name] [item1:amount,item2:amount,...] [usetimes]");
return true;
}
}
else if (args[1].equalsIgnoreCase("econ")) {
if (args.length == 5) {
if (!ec) {
sender.sendMessage(ChatColor.DARK_RED+"Economy support is currently disabled. You cannot add an economy coupon");
return true;
} else {
try {
Coupon coupon = api.createNewEconomyCoupon(args[2], Integer.parseInt(args[4]), new HashMap<String, Boolean>(), Integer.parseInt(args[3]));
if (coupon.isInDatabase()) {
sender.sendMessage(ChatColor.DARK_RED+"This coupon already exists!");
return true;
} else {
coupon.addToDatabase();
sender.sendMessage(ChatColor.GREEN+"Coupon "+ChatColor.GOLD+coupon.getName()+ChatColor.GREEN+" has been added!");
return true;
}
} catch (NumberFormatException e) {
sender.sendMessage(ChatColor.DARK_RED+"Expected a number, but got "+ChatColor.YELLOW+args[3]);
return true;
} catch (SQLException e) {
sender.sendMessage(ChatColor.DARK_RED+"Error while adding coupon to database. Please check console for more info.");
sender.sendMessage(ChatColor.DARK_RED+"If this error persists, please report it.");
e.printStackTrace();
return true;
}
}
} else {
sender.sendMessage(ChatColor.RED+"Invalid syntax length");
sender.sendMessage(ChatColor.YELLOW+"/c add econ [name] [money] [usetimes]");
return true;
}
} else {
help(sender);
return true;
}
} else {
sender.sendMessage(ChatColor.RED+"You do not have permission to use this command");
return true;
}
}
// Remove command
else if (args[0].equalsIgnoreCase("remove")) {
if (sender.hasPermission("cc.remove")) {
if (args.length == 2) {
try {
if (!api.couponExists(args[1])) {
sender.sendMessage(ChatColor.RED+"That coupon doesn't exist!");
return true;
}
api.removeCouponFromDatabase(api.createNewItemCoupon(args[1], 0, null, null));
sender.sendMessage(ChatColor.GREEN+"The coupon "+ChatColor.GOLD+args[1]+ChatColor.GREEN+" has been removed.");
return true;
} catch (SQLException e) {
sender.sendMessage(ChatColor.DARK_RED+"Error while removing coupon from the database. Please check the console for more info.");
sender.sendMessage(ChatColor.DARK_RED+"If this error persists, please report it.");
e.printStackTrace();
return true;
}
} else {
sender.sendMessage(ChatColor.RED+"Invalid syntax length");
sender.sendMessage(ChatColor.YELLOW+"/c remove [name]");
return true;
}
} else {
sender.sendMessage(ChatColor.RED+"You do not have permission to use this command");
return true;
}
}
// Redeem command
else if (args[0].equalsIgnoreCase("redeem")) {
if (!pl) {
sender.sendMessage("You must be a player to redeem a coupon");
return true;
} else {
Player player = (Player) sender;
if (player.hasPermission("cc.redeem")) {
if (args.length == 2) {
try {
if (!api.couponExists(args[1])) {
player.sendMessage(ChatColor.RED+"That coupon doesn't exist!");
return true;
}
Coupon coupon = api.getCoupon(args[1]);
try {
if (!coupon.getUseTimes().equals(null) || !coupon.getUsedPlayers().isEmpty()) {
if (coupon.getUseTimes() <= 0 || coupon.getUsedPlayers().get(player.getName()) == true) {
player.sendMessage(ChatColor.RED+"You cannot use this coupon as it is expired for you.");
return true;
}
}
} catch (NullPointerException e) {}
if (coupon instanceof ItemCoupon) {
ItemCoupon c = (ItemCoupon) coupon;
for (Map.Entry<Integer, Integer> en : c.getIDs().entrySet()) {
player.getInventory().addItem(new ItemStack(en.getKey(), en.getValue()));
}
player.sendMessage(ChatColor.GREEN+"Coupon "+ChatColor.GOLD+c.getName()+ChatColor.GREEN+" has been redeemed, and the items added to your inventory!");
}
else if (coupon instanceof EconomyCoupon) {
if (!econ.isEnabled()) {
player.sendMessage(ChatColor.DARK_RED+"Economy support is currently disabled. You cannot redeem an economy coupon.");
return true;
} else {
EconomyCoupon c = (EconomyCoupon) coupon;
econ.depositPlayer(player.getName(), c.getMoney());
player.sendMessage(ChatColor.GREEN+"Coupon "+ChatColor.GOLD+c.getName()+ChatColor.GREEN+" has been redeemed, and the money added to your account!");
}
}
HashMap<String, Boolean> up = coupon.getUsedPlayers();
up.put(player.getName(), true);
coupon.setUsedPlayers(up);
coupon.setUseTimes(coupon.getUseTimes()-1);
coupon.updateWithDatabase();
return true;
} catch (SQLException e) {
player.sendMessage(ChatColor.DARK_RED+"Error while trying to find "+args[1]+" in the database. Please check the console for more info.");
player.sendMessage(ChatColor.DARK_RED+"If this error persists, please report it.");
e.printStackTrace();
return true;
}
} else {
player.sendMessage(ChatColor.RED+"Invalid syntax length");
player.sendMessage(ChatColor.YELLOW+"/c redeem [name]");
return true;
}
} else {
player.sendMessage(ChatColor.RED+"You do not have permission to use this command");
return true;
}
}
}
// List command
else if (args[0].equalsIgnoreCase("list")) {
if (sender.hasPermission("cc.list")) {
StringBuilder sb = new StringBuilder();
try {
ArrayList<String> c = api.getCoupons();
if (c.isEmpty() || c.size() <= 0 || c.equals(null)) {
sender.sendMessage(ChatColor.RED+"No coupons found.");
return true;
} else {
sb.append(ChatColor.DARK_PURPLE+"Coupon list: "+ChatColor.GOLD);
for (int i = 0; i < c.size(); i++) {
sb.append(c.get(i));
if (!(Integer.valueOf(i+1).equals(c.size()))){
sb.append(", ");
}
}
sender.sendMessage(sb.toString());
return true;
}
} catch (SQLException e) {
sender.sendMessage(ChatColor.DARK_RED+"Error while getting the coupon list from the database. Please check the console for more info.");
sender.sendMessage(ChatColor.DARK_RED+"If this error persists, please report it.");
e.printStackTrace();
return true;
}
} else {
sender.sendMessage(ChatColor.RED+"You do not have permission to use this command");
return true;
}
} else{
help(sender);
return true;
}
}
| public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) {
// Event handling
CouponCodesCommandEvent ev = EventHandle.callCouponCodesCommandEvent(sender, command, commandLabel, args);
sender = ev.getSender();
command = ev.getCommand();
commandLabel = ev.getCommandLabel();
args = ev.getArgs();
boolean pl = false;
if (sender instanceof Player) pl = true;
if (args.length == 0 || args[0].equalsIgnoreCase("help")) {
help(sender);
return true;
}
CouponAPI api = CouponCodes.getCouponAPI();
// Add command
if (args[0].equalsIgnoreCase("add")) {
// Fix for being retarded
if (!(args.length == 5)) {
help(sender);
return true;
} // carry on..
if (sender.hasPermission("cc.add")) {
if (args[1].equalsIgnoreCase("item")) {
if (args.length == 5) {
try {
Coupon coupon = api.createNewItemCoupon(args[2], Integer.parseInt(args[4]), this.convertStringToHash(args[3]), new HashMap<String, Boolean>());
if (coupon.isInDatabase()) {
sender.sendMessage(ChatColor.RED+"This coupon already exists!");
return true;
} else {
coupon.addToDatabase();
sender.sendMessage(ChatColor.GREEN+"Coupon "+ChatColor.GOLD+coupon.getName()+ChatColor.GREEN+" has been added!");
return true;
}
} catch (NumberFormatException e) {
sender.sendMessage(ChatColor.DARK_RED+"Expected a number, but got "+ChatColor.YELLOW+args[4]);
return true;
} catch (SQLException e) {
sender.sendMessage(ChatColor.DARK_RED+"Error while adding coupon to database. Please check console for more info.");
sender.sendMessage(ChatColor.DARK_RED+"If this error persists, please report it.");
e.printStackTrace();
return true;
}
} else {
sender.sendMessage(ChatColor.RED+"Invalid syntax length");
sender.sendMessage(ChatColor.YELLOW+"/c add item [name] [item1:amount,item2:amount,...] [usetimes]");
return true;
}
}
else if (args[1].equalsIgnoreCase("econ")) {
if (args.length == 5) {
if (!ec) {
sender.sendMessage(ChatColor.DARK_RED+"Economy support is currently disabled. You cannot add an economy coupon");
return true;
} else {
try {
Coupon coupon = api.createNewEconomyCoupon(args[2], Integer.parseInt(args[4]), new HashMap<String, Boolean>(), Integer.parseInt(args[3]));
if (coupon.isInDatabase()) {
sender.sendMessage(ChatColor.DARK_RED+"This coupon already exists!");
return true;
} else {
coupon.addToDatabase();
sender.sendMessage(ChatColor.GREEN+"Coupon "+ChatColor.GOLD+coupon.getName()+ChatColor.GREEN+" has been added!");
return true;
}
} catch (NumberFormatException e) {
sender.sendMessage(ChatColor.DARK_RED+"Expected a number, but got "+ChatColor.YELLOW+args[3]);
return true;
} catch (SQLException e) {
sender.sendMessage(ChatColor.DARK_RED+"Error while adding coupon to database. Please check console for more info.");
sender.sendMessage(ChatColor.DARK_RED+"If this error persists, please report it.");
e.printStackTrace();
return true;
}
}
} else {
sender.sendMessage(ChatColor.RED+"Invalid syntax length");
sender.sendMessage(ChatColor.YELLOW+"/c add econ [name] [money] [usetimes]");
return true;
}
} else {
help(sender);
return true;
}
} else {
sender.sendMessage(ChatColor.RED+"You do not have permission to use this command");
return true;
}
}
// Remove command
else if (args[0].equalsIgnoreCase("remove")) {
if (sender.hasPermission("cc.remove")) {
if (args.length == 2) {
try {
if (!api.couponExists(args[1])) {
sender.sendMessage(ChatColor.RED+"That coupon doesn't exist!");
return true;
}
api.removeCouponFromDatabase(api.createNewItemCoupon(args[1], 0, null, null));
sender.sendMessage(ChatColor.GREEN+"The coupon "+ChatColor.GOLD+args[1]+ChatColor.GREEN+" has been removed.");
return true;
} catch (SQLException e) {
sender.sendMessage(ChatColor.DARK_RED+"Error while removing coupon from the database. Please check the console for more info.");
sender.sendMessage(ChatColor.DARK_RED+"If this error persists, please report it.");
e.printStackTrace();
return true;
}
} else {
sender.sendMessage(ChatColor.RED+"Invalid syntax length");
sender.sendMessage(ChatColor.YELLOW+"/c remove [name]");
return true;
}
} else {
sender.sendMessage(ChatColor.RED+"You do not have permission to use this command");
return true;
}
}
// Redeem command
else if (args[0].equalsIgnoreCase("redeem")) {
if (!pl) {
sender.sendMessage("You must be a player to redeem a coupon");
return true;
} else {
Player player = (Player) sender;
if (player.hasPermission("cc.redeem")) {
if (args.length == 2) {
try {
if (!api.couponExists(args[1])) {
player.sendMessage(ChatColor.RED+"That coupon doesn't exist!");
return true;
}
Coupon coupon = api.getCoupon(args[1]);
try {
if (!coupon.getUseTimes().equals(null) || !coupon.getUsedPlayers().isEmpty()) {
if (coupon.getUseTimes() <= 0 || coupon.getUsedPlayers().get(player.getName()) == true) {
player.sendMessage(ChatColor.RED+"You cannot use this coupon as it is expired for you.");
return true;
}
}
} catch (NullPointerException e) {}
if (coupon instanceof ItemCoupon) {
ItemCoupon c = (ItemCoupon) coupon;
for (Map.Entry<Integer, Integer> en : c.getIDs().entrySet()) {
player.getInventory().addItem(new ItemStack(en.getKey(), en.getValue()));
}
player.sendMessage(ChatColor.GREEN+"Coupon "+ChatColor.GOLD+c.getName()+ChatColor.GREEN+" has been redeemed, and the items added to your inventory!");
}
else if (coupon instanceof EconomyCoupon) {
if (!econ.isEnabled()) {
player.sendMessage(ChatColor.DARK_RED+"Economy support is currently disabled. You cannot redeem an economy coupon.");
return true;
} else {
EconomyCoupon c = (EconomyCoupon) coupon;
econ.depositPlayer(player.getName(), c.getMoney());
player.sendMessage(ChatColor.GREEN+"Coupon "+ChatColor.GOLD+c.getName()+ChatColor.GREEN+" has been redeemed, and the money added to your account!");
}
}
HashMap<String, Boolean> up = coupon.getUsedPlayers();
up.put(player.getName(), true);
coupon.setUsedPlayers(up);
coupon.setUseTimes(coupon.getUseTimes()-1);
coupon.updateWithDatabase();
return true;
} catch (SQLException e) {
player.sendMessage(ChatColor.DARK_RED+"Error while trying to find "+args[1]+" in the database. Please check the console for more info.");
player.sendMessage(ChatColor.DARK_RED+"If this error persists, please report it.");
e.printStackTrace();
return true;
}
} else {
player.sendMessage(ChatColor.RED+"Invalid syntax length");
player.sendMessage(ChatColor.YELLOW+"/c redeem [name]");
return true;
}
} else {
player.sendMessage(ChatColor.RED+"You do not have permission to use this command");
return true;
}
}
}
// List command
else if (args[0].equalsIgnoreCase("list")) {
if (sender.hasPermission("cc.list")) {
StringBuilder sb = new StringBuilder();
try {
ArrayList<String> c = api.getCoupons();
if (c.isEmpty() || c.size() <= 0 || c.equals(null)) {
sender.sendMessage(ChatColor.RED+"No coupons found.");
return true;
} else {
sb.append(ChatColor.DARK_PURPLE+"Coupon list: "+ChatColor.GOLD);
for (int i = 0; i < c.size(); i++) {
sb.append(c.get(i));
if (!(Integer.valueOf(i+1).equals(c.size()))){
sb.append(", ");
}
}
sender.sendMessage(sb.toString());
return true;
}
} catch (SQLException e) {
sender.sendMessage(ChatColor.DARK_RED+"Error while getting the coupon list from the database. Please check the console for more info.");
sender.sendMessage(ChatColor.DARK_RED+"If this error persists, please report it.");
e.printStackTrace();
return true;
}
} else {
sender.sendMessage(ChatColor.RED+"You do not have permission to use this command");
return true;
}
} else {
help(sender);
return true;
}
}
|
diff --git a/framework/src/play/mvc/ActionInvoker.java b/framework/src/play/mvc/ActionInvoker.java
index 816f38f4..e9ff9fc7 100644
--- a/framework/src/play/mvc/ActionInvoker.java
+++ b/framework/src/play/mvc/ActionInvoker.java
@@ -1,478 +1,478 @@
package play.mvc;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import play.Logger;
import play.Play;
import play.PlayPlugin;
import play.cache.CacheFor;
import play.classloading.enhancers.ControllersEnhancer.ControllerInstrumentation;
import play.classloading.enhancers.ControllersEnhancer.ControllerSupport;
import play.data.binding.Binder;
import play.data.parsing.UrlEncodedParser;
import play.data.validation.Validation;
import play.exceptions.ActionNotFoundException;
import play.exceptions.JavaExecutionException;
import play.exceptions.PlayException;
import play.exceptions.UnexpectedException;
import play.i18n.Lang;
import play.mvc.Router.Route;
import play.mvc.results.NoResult;
import play.mvc.results.NotFound;
import play.mvc.results.Result;
import play.utils.Java;
import play.utils.Utils;
import com.jamonapi.Monitor;
import com.jamonapi.MonitorFactory;
/**
* Invoke an action after an HTTP request.
*/
public class ActionInvoker {
@SuppressWarnings("unchecked")
public static void invoke(Http.Request request, Http.Response response) {
Monitor monitor = null;
try {
if (!Play.started) {
return;
}
Http.Request.current.set(request);
Http.Response.current.set(response);
Scope.Params.current.set(request.params);
Scope.RenderArgs.current.set(new Scope.RenderArgs());
Scope.RouteArgs.current.set(new Scope.RouteArgs());
Scope.Session.current.set(Scope.Session.restore());
Scope.Flash.current.set(Scope.Flash.restore());
// 1. Route and resolve format if not already done
if (request.action == null) {
for (PlayPlugin plugin : Play.plugins) {
plugin.routeRequest(request);
}
Route route = Router.route(request);
for (PlayPlugin plugin : Play.plugins) {
plugin.onRequestRouting(route);
}
}
request.resolveFormat();
// 2. Find the action method
Method actionMethod = null;
try {
Object[] ca = getActionMethod(request.action);
actionMethod = (Method) ca[1];
request.controller = ((Class) ca[0]).getName().substring(12).replace("$", "");
request.controllerClass = ((Class) ca[0]);
request.actionMethod = actionMethod.getName();
request.action = request.controller + "." + request.actionMethod;
request.invokedMethod = actionMethod;
} catch (ActionNotFoundException e) {
Logger.error(e, "%s action not found", e.getAction());
throw new NotFound(String.format("%s action not found", e.getAction()));
}
Logger.trace("------- %s", actionMethod);
// 3. Prepare request params
Scope.Params.current().__mergeWith(request.routeArgs);
// add parameters from the URI query string
Scope.Params.current()._mergeWith(UrlEncodedParser.parseQueryString(new ByteArrayInputStream(request.querystring.getBytes("utf-8"))));
Lang.resolvefrom(request);
// 4. Easy debugging ...
if (Play.mode == Play.Mode.DEV) {
Controller.class.getDeclaredField("params").set(null, Scope.Params.current());
Controller.class.getDeclaredField("request").set(null, Http.Request.current());
Controller.class.getDeclaredField("response").set(null, Http.Response.current());
Controller.class.getDeclaredField("session").set(null, Scope.Session.current());
Controller.class.getDeclaredField("flash").set(null, Scope.Flash.current());
Controller.class.getDeclaredField("renderArgs").set(null, Scope.RenderArgs.current());
Controller.class.getDeclaredField("routeArgs").set(null, Scope.RouteArgs.current());
Controller.class.getDeclaredField("validation").set(null, Validation.current());
}
ControllerInstrumentation.stopActionCall();
for (PlayPlugin plugin : Play.plugins) {
plugin.beforeActionInvocation(actionMethod);
}
// Monitoring
monitor = MonitorFactory.start(request.action + "()");
// 5. Invoke the action
// There is a difference between a get and a post when binding data. The get does not care about validation while
// the post does.
try {
// @Before
List<Method> befores = Java.findAllAnnotatedMethods(Controller.getControllerClass(), Before.class);
Collections.sort(befores, new Comparator<Method>() {
public int compare(Method m1, Method m2) {
Before before1 = m1.getAnnotation(Before.class);
Before before2 = m2.getAnnotation(Before.class);
return before1.priority() - before2.priority();
}
});
ControllerInstrumentation.stopActionCall();
for (Method before : befores) {
String[] unless = before.getAnnotation(Before.class).unless();
String[] only = before.getAnnotation(Before.class).only();
boolean skip = false;
for (String un : only) {
if (!un.contains(".")) {
un = before.getDeclaringClass().getName().substring(12).replace("$", "") + "." + un;
}
if (un.equals(request.action)) {
skip = false;
break;
} else {
skip = true;
}
}
for (String un : unless) {
if (!un.contains(".")) {
un = before.getDeclaringClass().getName().substring(12).replace("$", "") + "." + un;
}
if (un.equals(request.action)) {
skip = true;
break;
}
}
if (!skip) {
before.setAccessible(true);
inferResult(invokeControllerMethod(before));
}
}
// Action
Result actionResult = null;
String cacheKey = "actioncache:" + request.action + ":" + request.querystring;
// Check the cache (only for GET or HEAD)
if ((request.method.equals("GET") || request.method.equals("HEAD")) && actionMethod.isAnnotationPresent(CacheFor.class)) {
actionResult = (Result) play.cache.Cache.get(cacheKey);
}
if (actionResult == null) {
ControllerInstrumentation.initActionCall();
try {
inferResult(invokeControllerMethod(actionMethod));
} catch (InvocationTargetException ex) {
// It's a Result ? (expected)
if (ex.getTargetException() instanceof Result) {
actionResult = (Result) ex.getTargetException();
// Cache it if needed
if ((request.method.equals("GET") || request.method.equals("HEAD")) && actionMethod.isAnnotationPresent(CacheFor.class)) {
play.cache.Cache.set(cacheKey, actionResult, actionMethod.getAnnotation(CacheFor.class).value());
}
} else {
// @Catch
Object[] args = new Object[]{ex.getTargetException()};
List<Method> catches = Java.findAllAnnotatedMethods(Controller.getControllerClass(), Catch.class);
Collections.sort(catches, new Comparator<Method>() {
public int compare(Method m1, Method m2) {
Catch catch1 = m1.getAnnotation(Catch.class);
Catch catch2 = m2.getAnnotation(Catch.class);
return catch1.priority() - catch2.priority();
}
});
ControllerInstrumentation.stopActionCall();
for (Method mCatch : catches) {
Class[] exceptions = mCatch.getAnnotation(Catch.class).value();
if (exceptions.length == 0) {
exceptions = new Class[]{Exception.class};
}
for (Class exception : exceptions) {
if (exception.isInstance(args[0])) {
mCatch.setAccessible(true);
inferResult(invokeControllerMethod(mCatch, args));
break;
}
}
}
throw ex;
}
}
}
// @After
List<Method> afters = Java.findAllAnnotatedMethods(Controller.getControllerClass(), After.class);
Collections.sort(afters, new Comparator<Method>() {
public int compare(Method m1, Method m2) {
After after1 = m1.getAnnotation(After.class);
After after2 = m2.getAnnotation(After.class);
return after1.priority() - after2.priority();
}
});
ControllerInstrumentation.stopActionCall();
for (Method after : afters) {
String[] unless = after.getAnnotation(After.class).unless();
String[] only = after.getAnnotation(After.class).only();
boolean skip = false;
for (String un : only) {
if (!un.contains(".")) {
un = after.getDeclaringClass().getName().substring(12) + "." + un;
}
if (un.equals(request.action)) {
skip = false;
break;
} else {
skip = true;
}
}
for (String un : unless) {
if (!un.contains(".")) {
un = after.getDeclaringClass().getName().substring(12) + "." + un;
}
if (un.equals(request.action)) {
skip = true;
break;
}
}
if (!skip) {
after.setAccessible(true);
inferResult(invokeControllerMethod(after));
}
}
monitor.stop();
monitor = null;
// OK, re-throw the original action result
if (actionResult != null) {
throw actionResult;
}
throw new NoResult();
} catch (IllegalAccessException ex) {
throw ex;
} catch (IllegalArgumentException ex) {
throw ex;
} catch (InvocationTargetException ex) {
// It's a Result ? (expected)
if (ex.getTargetException() instanceof Result) {
throw (Result) ex.getTargetException();
}
// Re-throw the enclosed exception
if (ex.getTargetException() instanceof PlayException) {
throw (PlayException) ex.getTargetException();
}
StackTraceElement element = PlayException.getInterestingStrackTraceElement(ex.getTargetException());
if (element != null) {
throw new JavaExecutionException(Play.classes.getApplicationClass(element.getClassName()), element.getLineNumber(), ex.getTargetException());
}
throw new JavaExecutionException(Http.Request.current().action, ex);
}
} catch (Result result) {
for (PlayPlugin plugin : Play.plugins) {
plugin.onActionInvocationResult(result);
}
// OK there is a result to apply
// Save session & flash scope now
Scope.Session.current().save();
Scope.Flash.current().save();
result.apply(request, response);
for (PlayPlugin plugin : Play.plugins) {
plugin.afterActionInvocation();
}
// @Finally
if (Controller.getControllerClass() != null) {
try {
List<Method> allFinally = Java.findAllAnnotatedMethods(Controller.getControllerClass(), Finally.class);
Collections.sort(allFinally, new Comparator<Method>() {
public int compare(Method m1, Method m2) {
Finally finally1 = m1.getAnnotation(Finally.class);
Finally finally2 = m2.getAnnotation(Finally.class);
return finally1.priority() - finally2.priority();
}
});
ControllerInstrumentation.stopActionCall();
for (Method aFinally : allFinally) {
String[] unless = aFinally.getAnnotation(Finally.class).unless();
String[] only = aFinally.getAnnotation(Finally.class).only();
boolean skip = false;
for (String un : only) {
if (!un.contains(".")) {
un = aFinally.getDeclaringClass().getName().substring(12) + "." + un;
}
if (un.equals(request.action)) {
skip = false;
break;
} else {
skip = true;
}
}
for (String un : unless) {
if (!un.contains(".")) {
un = aFinally.getDeclaringClass().getName().substring(12) + "." + un;
}
if (un.equals(request.action)) {
skip = true;
break;
}
}
if (!skip) {
aFinally.setAccessible(true);
- invokeControllerMethod(aFinally, new Object[0]);
+ invokeControllerMethod(aFinally, null);
}
}
} catch (InvocationTargetException ex) {
StackTraceElement element = PlayException.getInterestingStrackTraceElement(ex.getTargetException());
if (element != null) {
throw new JavaExecutionException(Play.classes.getApplicationClass(element.getClassName()), element.getLineNumber(), ex.getTargetException());
}
throw new JavaExecutionException(Http.Request.current().action, ex);
} catch (Exception e) {
throw new UnexpectedException("Exception while doing @Finally", e);
}
}
} catch (PlayException e) {
throw e;
} catch (Exception e) {
throw new UnexpectedException(e);
} finally {
if (monitor != null) {
monitor.stop();
}
}
}
@SuppressWarnings("unchecked")
public static void inferResult(Object o) {
// Return type inference
if (o != null) {
if (o instanceof NoResult) {
return;
}
if (o instanceof Result) {
// Of course
throw (Result)o;
}
if (o instanceof InputStream) {
Controller.renderBinary((InputStream) o);
}
if (o instanceof File) {
Controller.renderBinary((File) o);
}
if (o instanceof Map) {
Controller.renderTemplate((Map<String, Object>) o);
}
if (o instanceof Object[]) {
Controller.render(o);
}
Controller.renderHtml(o);
}
}
public static Object invokeControllerMethod(Method method) throws Exception {
return invokeControllerMethod(method, null);
}
public static Object invokeControllerMethod(Method method, Object[] forceArgs) throws Exception {
if (Modifier.isStatic(method.getModifiers()) && !method.getDeclaringClass().getName().matches("^controllers\\..*\\$class$")) {
return method.invoke(null, forceArgs == null ? getActionMethodArgs(method, null) : forceArgs);
} else if (Modifier.isStatic(method.getModifiers())) {
Object[] args = getActionMethodArgs(method, null);
args[0] = Http.Request.current().controllerClass.getDeclaredField("MODULE$").get(null);
return method.invoke(null, args);
} else {
Object instance = null;
try {
instance = method.getDeclaringClass().getDeclaredField("MODULE$").get(null);
} catch (Exception e) {
throw new ActionNotFoundException(Http.Request.current().action, e);
}
return method.invoke(instance, forceArgs == null ? getActionMethodArgs(method, instance) : forceArgs);
}
}
public static Object[] getActionMethod(String fullAction) {
Method actionMethod = null;
Class controllerClass = null;
try {
if (!fullAction.startsWith("controllers.")) {
fullAction = "controllers." + fullAction;
}
String controller = fullAction.substring(0, fullAction.lastIndexOf("."));
String action = fullAction.substring(fullAction.lastIndexOf(".") + 1);
controllerClass = Play.classloader.getClassIgnoreCase(controller);
if (controllerClass == null) {
throw new ActionNotFoundException(fullAction, new Exception("Controller " + controller + " not found"));
}
if (!ControllerSupport.class.isAssignableFrom(controllerClass)) {
// Try the scala way
controllerClass = Play.classloader.getClassIgnoreCase(controller + "$");
if (!ControllerSupport.class.isAssignableFrom(controllerClass)) {
throw new ActionNotFoundException(fullAction, new Exception("class " + controller + " does not extend play.mvc.Controller"));
}
}
actionMethod = Java.findActionMethod(action, controllerClass);
if (actionMethod == null) {
throw new ActionNotFoundException(fullAction, new Exception("No method public static void " + action + "() was found in class " + controller));
}
} catch (PlayException e) {
throw e;
} catch (Exception e) {
throw new ActionNotFoundException(fullAction, e);
}
return new Object[]{controllerClass, actionMethod};
}
public static Object[] getActionMethodArgs(Method method, Object o) throws Exception {
String[] paramsNames = Java.parameterNames(method);
if (paramsNames == null && method.getParameterTypes().length > 0) {
throw new UnexpectedException("Parameter names not found for method " + method);
}
Object[] rArgs = new Object[method.getParameterTypes().length];
for (int i = 0; i < method.getParameterTypes().length; i++) {
Class<?> type = method.getParameterTypes()[i];
Map<String, String[]> params = new HashMap<String, String[]>();
if (type.equals(String.class) || Number.class.isAssignableFrom(type) || type.isPrimitive()) {
params.put(paramsNames[i], Scope.Params.current().getAll(paramsNames[i]));
} else {
params.putAll(Scope.Params.current().all());
}
Logger.trace("getActionMethodArgs name [" + paramsNames[i] + "] annotation [" + Utils.join(method.getParameterAnnotations()[i], " ") + "]");
rArgs[i] = Binder.bind(paramsNames[i], method.getParameterTypes()[i], method.getGenericParameterTypes()[i], method.getParameterAnnotations()[i], params, o, method, i + 1);
}
return rArgs;
}
}
| true | true | public static void invoke(Http.Request request, Http.Response response) {
Monitor monitor = null;
try {
if (!Play.started) {
return;
}
Http.Request.current.set(request);
Http.Response.current.set(response);
Scope.Params.current.set(request.params);
Scope.RenderArgs.current.set(new Scope.RenderArgs());
Scope.RouteArgs.current.set(new Scope.RouteArgs());
Scope.Session.current.set(Scope.Session.restore());
Scope.Flash.current.set(Scope.Flash.restore());
// 1. Route and resolve format if not already done
if (request.action == null) {
for (PlayPlugin plugin : Play.plugins) {
plugin.routeRequest(request);
}
Route route = Router.route(request);
for (PlayPlugin plugin : Play.plugins) {
plugin.onRequestRouting(route);
}
}
request.resolveFormat();
// 2. Find the action method
Method actionMethod = null;
try {
Object[] ca = getActionMethod(request.action);
actionMethod = (Method) ca[1];
request.controller = ((Class) ca[0]).getName().substring(12).replace("$", "");
request.controllerClass = ((Class) ca[0]);
request.actionMethod = actionMethod.getName();
request.action = request.controller + "." + request.actionMethod;
request.invokedMethod = actionMethod;
} catch (ActionNotFoundException e) {
Logger.error(e, "%s action not found", e.getAction());
throw new NotFound(String.format("%s action not found", e.getAction()));
}
Logger.trace("------- %s", actionMethod);
// 3. Prepare request params
Scope.Params.current().__mergeWith(request.routeArgs);
// add parameters from the URI query string
Scope.Params.current()._mergeWith(UrlEncodedParser.parseQueryString(new ByteArrayInputStream(request.querystring.getBytes("utf-8"))));
Lang.resolvefrom(request);
// 4. Easy debugging ...
if (Play.mode == Play.Mode.DEV) {
Controller.class.getDeclaredField("params").set(null, Scope.Params.current());
Controller.class.getDeclaredField("request").set(null, Http.Request.current());
Controller.class.getDeclaredField("response").set(null, Http.Response.current());
Controller.class.getDeclaredField("session").set(null, Scope.Session.current());
Controller.class.getDeclaredField("flash").set(null, Scope.Flash.current());
Controller.class.getDeclaredField("renderArgs").set(null, Scope.RenderArgs.current());
Controller.class.getDeclaredField("routeArgs").set(null, Scope.RouteArgs.current());
Controller.class.getDeclaredField("validation").set(null, Validation.current());
}
ControllerInstrumentation.stopActionCall();
for (PlayPlugin plugin : Play.plugins) {
plugin.beforeActionInvocation(actionMethod);
}
// Monitoring
monitor = MonitorFactory.start(request.action + "()");
// 5. Invoke the action
// There is a difference between a get and a post when binding data. The get does not care about validation while
// the post does.
try {
// @Before
List<Method> befores = Java.findAllAnnotatedMethods(Controller.getControllerClass(), Before.class);
Collections.sort(befores, new Comparator<Method>() {
public int compare(Method m1, Method m2) {
Before before1 = m1.getAnnotation(Before.class);
Before before2 = m2.getAnnotation(Before.class);
return before1.priority() - before2.priority();
}
});
ControllerInstrumentation.stopActionCall();
for (Method before : befores) {
String[] unless = before.getAnnotation(Before.class).unless();
String[] only = before.getAnnotation(Before.class).only();
boolean skip = false;
for (String un : only) {
if (!un.contains(".")) {
un = before.getDeclaringClass().getName().substring(12).replace("$", "") + "." + un;
}
if (un.equals(request.action)) {
skip = false;
break;
} else {
skip = true;
}
}
for (String un : unless) {
if (!un.contains(".")) {
un = before.getDeclaringClass().getName().substring(12).replace("$", "") + "." + un;
}
if (un.equals(request.action)) {
skip = true;
break;
}
}
if (!skip) {
before.setAccessible(true);
inferResult(invokeControllerMethod(before));
}
}
// Action
Result actionResult = null;
String cacheKey = "actioncache:" + request.action + ":" + request.querystring;
// Check the cache (only for GET or HEAD)
if ((request.method.equals("GET") || request.method.equals("HEAD")) && actionMethod.isAnnotationPresent(CacheFor.class)) {
actionResult = (Result) play.cache.Cache.get(cacheKey);
}
if (actionResult == null) {
ControllerInstrumentation.initActionCall();
try {
inferResult(invokeControllerMethod(actionMethod));
} catch (InvocationTargetException ex) {
// It's a Result ? (expected)
if (ex.getTargetException() instanceof Result) {
actionResult = (Result) ex.getTargetException();
// Cache it if needed
if ((request.method.equals("GET") || request.method.equals("HEAD")) && actionMethod.isAnnotationPresent(CacheFor.class)) {
play.cache.Cache.set(cacheKey, actionResult, actionMethod.getAnnotation(CacheFor.class).value());
}
} else {
// @Catch
Object[] args = new Object[]{ex.getTargetException()};
List<Method> catches = Java.findAllAnnotatedMethods(Controller.getControllerClass(), Catch.class);
Collections.sort(catches, new Comparator<Method>() {
public int compare(Method m1, Method m2) {
Catch catch1 = m1.getAnnotation(Catch.class);
Catch catch2 = m2.getAnnotation(Catch.class);
return catch1.priority() - catch2.priority();
}
});
ControllerInstrumentation.stopActionCall();
for (Method mCatch : catches) {
Class[] exceptions = mCatch.getAnnotation(Catch.class).value();
if (exceptions.length == 0) {
exceptions = new Class[]{Exception.class};
}
for (Class exception : exceptions) {
if (exception.isInstance(args[0])) {
mCatch.setAccessible(true);
inferResult(invokeControllerMethod(mCatch, args));
break;
}
}
}
throw ex;
}
}
}
// @After
List<Method> afters = Java.findAllAnnotatedMethods(Controller.getControllerClass(), After.class);
Collections.sort(afters, new Comparator<Method>() {
public int compare(Method m1, Method m2) {
After after1 = m1.getAnnotation(After.class);
After after2 = m2.getAnnotation(After.class);
return after1.priority() - after2.priority();
}
});
ControllerInstrumentation.stopActionCall();
for (Method after : afters) {
String[] unless = after.getAnnotation(After.class).unless();
String[] only = after.getAnnotation(After.class).only();
boolean skip = false;
for (String un : only) {
if (!un.contains(".")) {
un = after.getDeclaringClass().getName().substring(12) + "." + un;
}
if (un.equals(request.action)) {
skip = false;
break;
} else {
skip = true;
}
}
for (String un : unless) {
if (!un.contains(".")) {
un = after.getDeclaringClass().getName().substring(12) + "." + un;
}
if (un.equals(request.action)) {
skip = true;
break;
}
}
if (!skip) {
after.setAccessible(true);
inferResult(invokeControllerMethod(after));
}
}
monitor.stop();
monitor = null;
// OK, re-throw the original action result
if (actionResult != null) {
throw actionResult;
}
throw new NoResult();
} catch (IllegalAccessException ex) {
throw ex;
} catch (IllegalArgumentException ex) {
throw ex;
} catch (InvocationTargetException ex) {
// It's a Result ? (expected)
if (ex.getTargetException() instanceof Result) {
throw (Result) ex.getTargetException();
}
// Re-throw the enclosed exception
if (ex.getTargetException() instanceof PlayException) {
throw (PlayException) ex.getTargetException();
}
StackTraceElement element = PlayException.getInterestingStrackTraceElement(ex.getTargetException());
if (element != null) {
throw new JavaExecutionException(Play.classes.getApplicationClass(element.getClassName()), element.getLineNumber(), ex.getTargetException());
}
throw new JavaExecutionException(Http.Request.current().action, ex);
}
} catch (Result result) {
for (PlayPlugin plugin : Play.plugins) {
plugin.onActionInvocationResult(result);
}
// OK there is a result to apply
// Save session & flash scope now
Scope.Session.current().save();
Scope.Flash.current().save();
result.apply(request, response);
for (PlayPlugin plugin : Play.plugins) {
plugin.afterActionInvocation();
}
// @Finally
if (Controller.getControllerClass() != null) {
try {
List<Method> allFinally = Java.findAllAnnotatedMethods(Controller.getControllerClass(), Finally.class);
Collections.sort(allFinally, new Comparator<Method>() {
public int compare(Method m1, Method m2) {
Finally finally1 = m1.getAnnotation(Finally.class);
Finally finally2 = m2.getAnnotation(Finally.class);
return finally1.priority() - finally2.priority();
}
});
ControllerInstrumentation.stopActionCall();
for (Method aFinally : allFinally) {
String[] unless = aFinally.getAnnotation(Finally.class).unless();
String[] only = aFinally.getAnnotation(Finally.class).only();
boolean skip = false;
for (String un : only) {
if (!un.contains(".")) {
un = aFinally.getDeclaringClass().getName().substring(12) + "." + un;
}
if (un.equals(request.action)) {
skip = false;
break;
} else {
skip = true;
}
}
for (String un : unless) {
if (!un.contains(".")) {
un = aFinally.getDeclaringClass().getName().substring(12) + "." + un;
}
if (un.equals(request.action)) {
skip = true;
break;
}
}
if (!skip) {
aFinally.setAccessible(true);
invokeControllerMethod(aFinally, new Object[0]);
}
}
} catch (InvocationTargetException ex) {
StackTraceElement element = PlayException.getInterestingStrackTraceElement(ex.getTargetException());
if (element != null) {
throw new JavaExecutionException(Play.classes.getApplicationClass(element.getClassName()), element.getLineNumber(), ex.getTargetException());
}
throw new JavaExecutionException(Http.Request.current().action, ex);
} catch (Exception e) {
throw new UnexpectedException("Exception while doing @Finally", e);
}
}
} catch (PlayException e) {
throw e;
} catch (Exception e) {
throw new UnexpectedException(e);
} finally {
if (monitor != null) {
monitor.stop();
}
}
}
| public static void invoke(Http.Request request, Http.Response response) {
Monitor monitor = null;
try {
if (!Play.started) {
return;
}
Http.Request.current.set(request);
Http.Response.current.set(response);
Scope.Params.current.set(request.params);
Scope.RenderArgs.current.set(new Scope.RenderArgs());
Scope.RouteArgs.current.set(new Scope.RouteArgs());
Scope.Session.current.set(Scope.Session.restore());
Scope.Flash.current.set(Scope.Flash.restore());
// 1. Route and resolve format if not already done
if (request.action == null) {
for (PlayPlugin plugin : Play.plugins) {
plugin.routeRequest(request);
}
Route route = Router.route(request);
for (PlayPlugin plugin : Play.plugins) {
plugin.onRequestRouting(route);
}
}
request.resolveFormat();
// 2. Find the action method
Method actionMethod = null;
try {
Object[] ca = getActionMethod(request.action);
actionMethod = (Method) ca[1];
request.controller = ((Class) ca[0]).getName().substring(12).replace("$", "");
request.controllerClass = ((Class) ca[0]);
request.actionMethod = actionMethod.getName();
request.action = request.controller + "." + request.actionMethod;
request.invokedMethod = actionMethod;
} catch (ActionNotFoundException e) {
Logger.error(e, "%s action not found", e.getAction());
throw new NotFound(String.format("%s action not found", e.getAction()));
}
Logger.trace("------- %s", actionMethod);
// 3. Prepare request params
Scope.Params.current().__mergeWith(request.routeArgs);
// add parameters from the URI query string
Scope.Params.current()._mergeWith(UrlEncodedParser.parseQueryString(new ByteArrayInputStream(request.querystring.getBytes("utf-8"))));
Lang.resolvefrom(request);
// 4. Easy debugging ...
if (Play.mode == Play.Mode.DEV) {
Controller.class.getDeclaredField("params").set(null, Scope.Params.current());
Controller.class.getDeclaredField("request").set(null, Http.Request.current());
Controller.class.getDeclaredField("response").set(null, Http.Response.current());
Controller.class.getDeclaredField("session").set(null, Scope.Session.current());
Controller.class.getDeclaredField("flash").set(null, Scope.Flash.current());
Controller.class.getDeclaredField("renderArgs").set(null, Scope.RenderArgs.current());
Controller.class.getDeclaredField("routeArgs").set(null, Scope.RouteArgs.current());
Controller.class.getDeclaredField("validation").set(null, Validation.current());
}
ControllerInstrumentation.stopActionCall();
for (PlayPlugin plugin : Play.plugins) {
plugin.beforeActionInvocation(actionMethod);
}
// Monitoring
monitor = MonitorFactory.start(request.action + "()");
// 5. Invoke the action
// There is a difference between a get and a post when binding data. The get does not care about validation while
// the post does.
try {
// @Before
List<Method> befores = Java.findAllAnnotatedMethods(Controller.getControllerClass(), Before.class);
Collections.sort(befores, new Comparator<Method>() {
public int compare(Method m1, Method m2) {
Before before1 = m1.getAnnotation(Before.class);
Before before2 = m2.getAnnotation(Before.class);
return before1.priority() - before2.priority();
}
});
ControllerInstrumentation.stopActionCall();
for (Method before : befores) {
String[] unless = before.getAnnotation(Before.class).unless();
String[] only = before.getAnnotation(Before.class).only();
boolean skip = false;
for (String un : only) {
if (!un.contains(".")) {
un = before.getDeclaringClass().getName().substring(12).replace("$", "") + "." + un;
}
if (un.equals(request.action)) {
skip = false;
break;
} else {
skip = true;
}
}
for (String un : unless) {
if (!un.contains(".")) {
un = before.getDeclaringClass().getName().substring(12).replace("$", "") + "." + un;
}
if (un.equals(request.action)) {
skip = true;
break;
}
}
if (!skip) {
before.setAccessible(true);
inferResult(invokeControllerMethod(before));
}
}
// Action
Result actionResult = null;
String cacheKey = "actioncache:" + request.action + ":" + request.querystring;
// Check the cache (only for GET or HEAD)
if ((request.method.equals("GET") || request.method.equals("HEAD")) && actionMethod.isAnnotationPresent(CacheFor.class)) {
actionResult = (Result) play.cache.Cache.get(cacheKey);
}
if (actionResult == null) {
ControllerInstrumentation.initActionCall();
try {
inferResult(invokeControllerMethod(actionMethod));
} catch (InvocationTargetException ex) {
// It's a Result ? (expected)
if (ex.getTargetException() instanceof Result) {
actionResult = (Result) ex.getTargetException();
// Cache it if needed
if ((request.method.equals("GET") || request.method.equals("HEAD")) && actionMethod.isAnnotationPresent(CacheFor.class)) {
play.cache.Cache.set(cacheKey, actionResult, actionMethod.getAnnotation(CacheFor.class).value());
}
} else {
// @Catch
Object[] args = new Object[]{ex.getTargetException()};
List<Method> catches = Java.findAllAnnotatedMethods(Controller.getControllerClass(), Catch.class);
Collections.sort(catches, new Comparator<Method>() {
public int compare(Method m1, Method m2) {
Catch catch1 = m1.getAnnotation(Catch.class);
Catch catch2 = m2.getAnnotation(Catch.class);
return catch1.priority() - catch2.priority();
}
});
ControllerInstrumentation.stopActionCall();
for (Method mCatch : catches) {
Class[] exceptions = mCatch.getAnnotation(Catch.class).value();
if (exceptions.length == 0) {
exceptions = new Class[]{Exception.class};
}
for (Class exception : exceptions) {
if (exception.isInstance(args[0])) {
mCatch.setAccessible(true);
inferResult(invokeControllerMethod(mCatch, args));
break;
}
}
}
throw ex;
}
}
}
// @After
List<Method> afters = Java.findAllAnnotatedMethods(Controller.getControllerClass(), After.class);
Collections.sort(afters, new Comparator<Method>() {
public int compare(Method m1, Method m2) {
After after1 = m1.getAnnotation(After.class);
After after2 = m2.getAnnotation(After.class);
return after1.priority() - after2.priority();
}
});
ControllerInstrumentation.stopActionCall();
for (Method after : afters) {
String[] unless = after.getAnnotation(After.class).unless();
String[] only = after.getAnnotation(After.class).only();
boolean skip = false;
for (String un : only) {
if (!un.contains(".")) {
un = after.getDeclaringClass().getName().substring(12) + "." + un;
}
if (un.equals(request.action)) {
skip = false;
break;
} else {
skip = true;
}
}
for (String un : unless) {
if (!un.contains(".")) {
un = after.getDeclaringClass().getName().substring(12) + "." + un;
}
if (un.equals(request.action)) {
skip = true;
break;
}
}
if (!skip) {
after.setAccessible(true);
inferResult(invokeControllerMethod(after));
}
}
monitor.stop();
monitor = null;
// OK, re-throw the original action result
if (actionResult != null) {
throw actionResult;
}
throw new NoResult();
} catch (IllegalAccessException ex) {
throw ex;
} catch (IllegalArgumentException ex) {
throw ex;
} catch (InvocationTargetException ex) {
// It's a Result ? (expected)
if (ex.getTargetException() instanceof Result) {
throw (Result) ex.getTargetException();
}
// Re-throw the enclosed exception
if (ex.getTargetException() instanceof PlayException) {
throw (PlayException) ex.getTargetException();
}
StackTraceElement element = PlayException.getInterestingStrackTraceElement(ex.getTargetException());
if (element != null) {
throw new JavaExecutionException(Play.classes.getApplicationClass(element.getClassName()), element.getLineNumber(), ex.getTargetException());
}
throw new JavaExecutionException(Http.Request.current().action, ex);
}
} catch (Result result) {
for (PlayPlugin plugin : Play.plugins) {
plugin.onActionInvocationResult(result);
}
// OK there is a result to apply
// Save session & flash scope now
Scope.Session.current().save();
Scope.Flash.current().save();
result.apply(request, response);
for (PlayPlugin plugin : Play.plugins) {
plugin.afterActionInvocation();
}
// @Finally
if (Controller.getControllerClass() != null) {
try {
List<Method> allFinally = Java.findAllAnnotatedMethods(Controller.getControllerClass(), Finally.class);
Collections.sort(allFinally, new Comparator<Method>() {
public int compare(Method m1, Method m2) {
Finally finally1 = m1.getAnnotation(Finally.class);
Finally finally2 = m2.getAnnotation(Finally.class);
return finally1.priority() - finally2.priority();
}
});
ControllerInstrumentation.stopActionCall();
for (Method aFinally : allFinally) {
String[] unless = aFinally.getAnnotation(Finally.class).unless();
String[] only = aFinally.getAnnotation(Finally.class).only();
boolean skip = false;
for (String un : only) {
if (!un.contains(".")) {
un = aFinally.getDeclaringClass().getName().substring(12) + "." + un;
}
if (un.equals(request.action)) {
skip = false;
break;
} else {
skip = true;
}
}
for (String un : unless) {
if (!un.contains(".")) {
un = aFinally.getDeclaringClass().getName().substring(12) + "." + un;
}
if (un.equals(request.action)) {
skip = true;
break;
}
}
if (!skip) {
aFinally.setAccessible(true);
invokeControllerMethod(aFinally, null);
}
}
} catch (InvocationTargetException ex) {
StackTraceElement element = PlayException.getInterestingStrackTraceElement(ex.getTargetException());
if (element != null) {
throw new JavaExecutionException(Play.classes.getApplicationClass(element.getClassName()), element.getLineNumber(), ex.getTargetException());
}
throw new JavaExecutionException(Http.Request.current().action, ex);
} catch (Exception e) {
throw new UnexpectedException("Exception while doing @Finally", e);
}
}
} catch (PlayException e) {
throw e;
} catch (Exception e) {
throw new UnexpectedException(e);
} finally {
if (monitor != null) {
monitor.stop();
}
}
}
|
diff --git a/src/com/yahoo/platform/yui/compressor/CssCompressor.java b/src/com/yahoo/platform/yui/compressor/CssCompressor.java
index 170d028..798e689 100644
--- a/src/com/yahoo/platform/yui/compressor/CssCompressor.java
+++ b/src/com/yahoo/platform/yui/compressor/CssCompressor.java
@@ -1,304 +1,309 @@
/*
* YUI Compressor
* http://developer.yahoo.com/yui/compressor/
* Author: Julien Lecomte - http://www.julienlecomte.net/
* Author: Isaac Schlueter - http://foohack.com/
* Author: Stoyan Stefanov - http://phpied.com/
* Copyright (c) 2011 Yahoo! Inc. All rights reserved.
* The copyrights embodied in the content of this file are licensed
* by Yahoo! Inc. under the BSD (revised) open source license.
*/
package com.yahoo.platform.yui.compressor;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.ArrayList;
public class CssCompressor {
private StringBuffer srcsb = new StringBuffer();
public CssCompressor(Reader in) throws IOException {
// Read the stream...
int c;
while ((c = in.read()) != -1) {
srcsb.append((char) c);
}
}
public void compress(Writer out, int linebreakpos)
throws IOException {
Pattern p;
Matcher m;
String css = srcsb.toString();
StringBuffer sb = new StringBuffer(css);
int startIndex = 0;
int endIndex = 0;
int i = 0;
int max = 0;
ArrayList preservedTokens = new ArrayList(0);
ArrayList comments = new ArrayList(0);
String token;
int totallen = css.length();
String placeholder;
// // leave data urls alone to increase parse performance.
// sb = new StringBuffer();
// p = Pattern.compile("url\\(.*data\\:(.*)\\)");
// m = p.matcher(css);
// while (m.find()) {
// token = m.group();
// token = token.substring(1, token.length() - 1);
// preservedTokens.add(token);
// String preserver = "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___";
// m.appendReplacement(sb, preserver);
// }
// m.appendTail(sb);
// css = sb.toString();
// collect all comment blocks...
while ((startIndex = sb.indexOf("/*", startIndex)) >= 0) {
endIndex = sb.indexOf("*/", startIndex + 2);
if (endIndex < 0) {
endIndex = totallen;
}
token = sb.substring(startIndex + 2, endIndex);
comments.add(token);
sb.replace(startIndex + 2, endIndex, "___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + (comments.size() - 1) + "___");
startIndex += 2;
}
css = sb.toString();
// preserve strings so their content doesn't get accidentally minified
sb = new StringBuffer();
p = Pattern.compile("(\"([^\\\\\"]|\\\\.|\\\\)*\")|(\'([^\\\\\']|\\\\.|\\\\)*\')");
m = p.matcher(css);
while (m.find()) {
token = m.group();
char quote = token.charAt(0);
token = token.substring(1, token.length() - 1);
// maybe the string contains a comment-like substring?
// one, maybe more? put'em back then
if (token.indexOf("___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_") >= 0) {
for (i = 0, max = comments.size(); i < max; i += 1) {
token = token.replace("___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + i + "___", comments.get(i).toString());
}
}
// minify alpha opacity in filter strings
token = token.replaceAll("(?i)progid:DXImageTransform.Microsoft.Alpha\\(Opacity=", "alpha(opacity=");
preservedTokens.add(token);
String preserver = quote + "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___" + quote;
m.appendReplacement(sb, preserver);
}
m.appendTail(sb);
css = sb.toString();
// strings are safe, now wrestle the comments
for (i = 0, max = comments.size(); i < max; i += 1) {
token = comments.get(i).toString();
placeholder = "___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + i + "___";
// ! in the first position of the comment means preserve
// so push to the preserved tokens while stripping the !
if (token.startsWith("!")) {
preservedTokens.add(token);
css = css.replace(placeholder, "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___");
continue;
}
// \ in the last position looks like hack for Mac/IE5
// shorten that to /*\*/ and the next one to /**/
if (token.endsWith("\\")) {
preservedTokens.add("\\");
css = css.replace(placeholder, "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___");
i = i + 1; // attn: advancing the loop
preservedTokens.add("");
css = css.replace("___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + i + "___", "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___");
continue;
}
// keep empty comments after child selectors (IE7 hack)
// e.g. html >/**/ body
if (token.length() == 0) {
startIndex = css.indexOf(placeholder);
if (startIndex > 2) {
if (css.charAt(startIndex - 3) == '>') {
preservedTokens.add("");
css = css.replace(placeholder, "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___");
}
}
}
// in all other cases kill the comment
css = css.replace("/*" + placeholder + "*/", "");
}
// Normalize all whitespace strings to single spaces. Easier to work with that way.
css = css.replaceAll("\\s+", " ");
// Remove the spaces before the things that should not have spaces before them.
// But, be careful not to turn "p :link {...}" into "p:link{...}"
// Swap out any pseudo-class colons with the token, and then swap back.
sb = new StringBuffer();
p = Pattern.compile("(^|\\})(([^\\{:])+:)+([^\\{]*\\{)");
m = p.matcher(css);
while (m.find()) {
String s = m.group();
s = s.replaceAll(":", "___YUICSSMIN_PSEUDOCLASSCOLON___");
s = s.replaceAll( "\\\\", "\\\\\\\\" ).replaceAll( "\\$", "\\\\\\$" );
m.appendReplacement(sb, s);
}
m.appendTail(sb);
css = sb.toString();
// Remove spaces before the things that should not have spaces before them.
css = css.replaceAll("\\s+([!{};:>+\\(\\)\\],])", "$1");
// bring back the colon
css = css.replaceAll("___YUICSSMIN_PSEUDOCLASSCOLON___", ":");
// retain space for special IE6 cases
css = css.replaceAll(":first\\-(line|letter)(\\{|,)", ":first-$1 $2");
// no space after the end of a preserved comment
css = css.replaceAll("\\*/ ", "*/");
// If there is a @charset, then only allow one, and push to the top of the file.
css = css.replaceAll("^(.*)(@charset \"[^\"]*\";)", "$2$1");
css = css.replaceAll("^(\\s*@charset [^;]+;\\s*)+", "$1");
// Put the space back in some cases, to support stuff like
// @media screen and (-webkit-min-device-pixel-ratio:0){
css = css.replaceAll("\\band\\(", "and (");
// Remove the spaces after the things that should not have spaces after them.
css = css.replaceAll("([!{}:;>+\\(\\[,])\\s+", "$1");
// remove unnecessary semicolons
css = css.replaceAll(";+}", "}");
// Replace 0(px,em,%) with 0.
css = css.replaceAll("([\\s:])(0)(px|em|%|in|cm|mm|pc|pt|ex)", "$1$2");
// Replace 0 0 0 0; with 0.
css = css.replaceAll(":0 0 0 0(;|})", ":0$1");
css = css.replaceAll(":0 0 0(;|})", ":0$1");
css = css.replaceAll(":0 0(;|})", ":0$1");
// Replace background-position:0; with background-position:0 0;
// same for transform-origin
sb = new StringBuffer();
p = Pattern.compile("(?i)(background-position|transform-origin|webkit-transform-origin|moz-transform-origin|o-transform-origin|ms-transform-origin):0(;|})");
m = p.matcher(css);
while (m.find()) {
m.appendReplacement(sb, m.group(1).toLowerCase() + ":0 0" + m.group(2));
}
m.appendTail(sb);
css = sb.toString();
// Replace 0.6 to .6, but only when preceded by : or a white-space
css = css.replaceAll("(:|\\s)0+\\.(\\d+)", "$1.$2");
// Shorten colors from rgb(51,102,153) to #336699
// This makes it more likely that it'll get further compressed in the next step.
p = Pattern.compile("rgb\\s*\\(\\s*([0-9,\\s]+)\\s*\\)");
m = p.matcher(css);
sb = new StringBuffer();
while (m.find()) {
String[] rgbcolors = m.group(1).split(",");
StringBuffer hexcolor = new StringBuffer("#");
for (i = 0; i < rgbcolors.length; i++) {
int val = Integer.parseInt(rgbcolors[i]);
if (val < 16) {
hexcolor.append("0");
}
hexcolor.append(Integer.toHexString(val));
}
m.appendReplacement(sb, hexcolor.toString());
}
m.appendTail(sb);
css = sb.toString();
// Shorten colors from #AABBCC to #ABC. Note that we want to make sure
// the color is not preceded by either ", " or =. Indeed, the property
// filter: chroma(color="#FFFFFF");
// would become
// filter: chroma(color="#FFF");
// which makes the filter break in IE.
p = Pattern.compile("([^\"'=\\s])(\\s*)#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])");
m = p.matcher(css);
sb = new StringBuffer();
while (m.find()) {
- // Test for AABBCC pattern
- if (m.group(3).equalsIgnoreCase(m.group(4)) &&
+ if (m.group(1).equals("}")) {
+ // Likely an ID selector. Don't touch.
+ // #AABBCC is a valid ID. IDs are case-sensitive.
+ m.appendReplacement(sb, m.group());
+ } else if (m.group(3).equalsIgnoreCase(m.group(4)) &&
m.group(5).equalsIgnoreCase(m.group(6)) &&
m.group(7).equalsIgnoreCase(m.group(8))) {
+ // #AABBCC pattern
m.appendReplacement(sb, (m.group(1) + m.group(2) + "#" + m.group(3) + m.group(5) + m.group(7)).toLowerCase());
} else {
+ // Any other color.
m.appendReplacement(sb, m.group().toLowerCase());
}
}
m.appendTail(sb);
css = sb.toString();
// border: none -> border:0
sb = new StringBuffer();
p = Pattern.compile("(?i)(border|border-top|border-right|border-bottom|border-right|outline|background):none(;|})");
m = p.matcher(css);
while (m.find()) {
m.appendReplacement(sb, m.group(1).toLowerCase() + ":0" + m.group(2));
}
m.appendTail(sb);
css = sb.toString();
// shorter opacity IE filter
css = css.replaceAll("(?i)progid:DXImageTransform.Microsoft.Alpha\\(Opacity=", "alpha(opacity=");
// Remove empty rules.
css = css.replaceAll("[^\\}\\{/;]+\\{\\}", "");
if (linebreakpos >= 0) {
// Some source control tools don't like it when files containing lines longer
// than, say 8000 characters, are checked in. The linebreak option is used in
// that case to split long lines after a specific column.
i = 0;
int linestartpos = 0;
sb = new StringBuffer(css);
while (i < sb.length()) {
char c = sb.charAt(i++);
if (c == '}' && i - linestartpos > linebreakpos) {
sb.insert(i, '\n');
linestartpos = i;
}
}
css = sb.toString();
}
// Replace multiple semi-colons in a row by a single one
// See SF bug #1980989
css = css.replaceAll(";;+", ";");
// restore preserved comments and strings
for(i = 0, max = preservedTokens.size(); i < max; i++) {
css = css.replace("___YUICSSMIN_PRESERVED_TOKEN_" + i + "___", preservedTokens.get(i).toString());
}
// Trim the final string (for any leading or trailing white spaces)
css = css.trim();
// Write the output...
out.write(css);
}
}
| false | true | public void compress(Writer out, int linebreakpos)
throws IOException {
Pattern p;
Matcher m;
String css = srcsb.toString();
StringBuffer sb = new StringBuffer(css);
int startIndex = 0;
int endIndex = 0;
int i = 0;
int max = 0;
ArrayList preservedTokens = new ArrayList(0);
ArrayList comments = new ArrayList(0);
String token;
int totallen = css.length();
String placeholder;
// // leave data urls alone to increase parse performance.
// sb = new StringBuffer();
// p = Pattern.compile("url\\(.*data\\:(.*)\\)");
// m = p.matcher(css);
// while (m.find()) {
// token = m.group();
// token = token.substring(1, token.length() - 1);
// preservedTokens.add(token);
// String preserver = "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___";
// m.appendReplacement(sb, preserver);
// }
// m.appendTail(sb);
// css = sb.toString();
// collect all comment blocks...
while ((startIndex = sb.indexOf("/*", startIndex)) >= 0) {
endIndex = sb.indexOf("*/", startIndex + 2);
if (endIndex < 0) {
endIndex = totallen;
}
token = sb.substring(startIndex + 2, endIndex);
comments.add(token);
sb.replace(startIndex + 2, endIndex, "___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + (comments.size() - 1) + "___");
startIndex += 2;
}
css = sb.toString();
// preserve strings so their content doesn't get accidentally minified
sb = new StringBuffer();
p = Pattern.compile("(\"([^\\\\\"]|\\\\.|\\\\)*\")|(\'([^\\\\\']|\\\\.|\\\\)*\')");
m = p.matcher(css);
while (m.find()) {
token = m.group();
char quote = token.charAt(0);
token = token.substring(1, token.length() - 1);
// maybe the string contains a comment-like substring?
// one, maybe more? put'em back then
if (token.indexOf("___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_") >= 0) {
for (i = 0, max = comments.size(); i < max; i += 1) {
token = token.replace("___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + i + "___", comments.get(i).toString());
}
}
// minify alpha opacity in filter strings
token = token.replaceAll("(?i)progid:DXImageTransform.Microsoft.Alpha\\(Opacity=", "alpha(opacity=");
preservedTokens.add(token);
String preserver = quote + "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___" + quote;
m.appendReplacement(sb, preserver);
}
m.appendTail(sb);
css = sb.toString();
// strings are safe, now wrestle the comments
for (i = 0, max = comments.size(); i < max; i += 1) {
token = comments.get(i).toString();
placeholder = "___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + i + "___";
// ! in the first position of the comment means preserve
// so push to the preserved tokens while stripping the !
if (token.startsWith("!")) {
preservedTokens.add(token);
css = css.replace(placeholder, "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___");
continue;
}
// \ in the last position looks like hack for Mac/IE5
// shorten that to /*\*/ and the next one to /**/
if (token.endsWith("\\")) {
preservedTokens.add("\\");
css = css.replace(placeholder, "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___");
i = i + 1; // attn: advancing the loop
preservedTokens.add("");
css = css.replace("___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + i + "___", "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___");
continue;
}
// keep empty comments after child selectors (IE7 hack)
// e.g. html >/**/ body
if (token.length() == 0) {
startIndex = css.indexOf(placeholder);
if (startIndex > 2) {
if (css.charAt(startIndex - 3) == '>') {
preservedTokens.add("");
css = css.replace(placeholder, "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___");
}
}
}
// in all other cases kill the comment
css = css.replace("/*" + placeholder + "*/", "");
}
// Normalize all whitespace strings to single spaces. Easier to work with that way.
css = css.replaceAll("\\s+", " ");
// Remove the spaces before the things that should not have spaces before them.
// But, be careful not to turn "p :link {...}" into "p:link{...}"
// Swap out any pseudo-class colons with the token, and then swap back.
sb = new StringBuffer();
p = Pattern.compile("(^|\\})(([^\\{:])+:)+([^\\{]*\\{)");
m = p.matcher(css);
while (m.find()) {
String s = m.group();
s = s.replaceAll(":", "___YUICSSMIN_PSEUDOCLASSCOLON___");
s = s.replaceAll( "\\\\", "\\\\\\\\" ).replaceAll( "\\$", "\\\\\\$" );
m.appendReplacement(sb, s);
}
m.appendTail(sb);
css = sb.toString();
// Remove spaces before the things that should not have spaces before them.
css = css.replaceAll("\\s+([!{};:>+\\(\\)\\],])", "$1");
// bring back the colon
css = css.replaceAll("___YUICSSMIN_PSEUDOCLASSCOLON___", ":");
// retain space for special IE6 cases
css = css.replaceAll(":first\\-(line|letter)(\\{|,)", ":first-$1 $2");
// no space after the end of a preserved comment
css = css.replaceAll("\\*/ ", "*/");
// If there is a @charset, then only allow one, and push to the top of the file.
css = css.replaceAll("^(.*)(@charset \"[^\"]*\";)", "$2$1");
css = css.replaceAll("^(\\s*@charset [^;]+;\\s*)+", "$1");
// Put the space back in some cases, to support stuff like
// @media screen and (-webkit-min-device-pixel-ratio:0){
css = css.replaceAll("\\band\\(", "and (");
// Remove the spaces after the things that should not have spaces after them.
css = css.replaceAll("([!{}:;>+\\(\\[,])\\s+", "$1");
// remove unnecessary semicolons
css = css.replaceAll(";+}", "}");
// Replace 0(px,em,%) with 0.
css = css.replaceAll("([\\s:])(0)(px|em|%|in|cm|mm|pc|pt|ex)", "$1$2");
// Replace 0 0 0 0; with 0.
css = css.replaceAll(":0 0 0 0(;|})", ":0$1");
css = css.replaceAll(":0 0 0(;|})", ":0$1");
css = css.replaceAll(":0 0(;|})", ":0$1");
// Replace background-position:0; with background-position:0 0;
// same for transform-origin
sb = new StringBuffer();
p = Pattern.compile("(?i)(background-position|transform-origin|webkit-transform-origin|moz-transform-origin|o-transform-origin|ms-transform-origin):0(;|})");
m = p.matcher(css);
while (m.find()) {
m.appendReplacement(sb, m.group(1).toLowerCase() + ":0 0" + m.group(2));
}
m.appendTail(sb);
css = sb.toString();
// Replace 0.6 to .6, but only when preceded by : or a white-space
css = css.replaceAll("(:|\\s)0+\\.(\\d+)", "$1.$2");
// Shorten colors from rgb(51,102,153) to #336699
// This makes it more likely that it'll get further compressed in the next step.
p = Pattern.compile("rgb\\s*\\(\\s*([0-9,\\s]+)\\s*\\)");
m = p.matcher(css);
sb = new StringBuffer();
while (m.find()) {
String[] rgbcolors = m.group(1).split(",");
StringBuffer hexcolor = new StringBuffer("#");
for (i = 0; i < rgbcolors.length; i++) {
int val = Integer.parseInt(rgbcolors[i]);
if (val < 16) {
hexcolor.append("0");
}
hexcolor.append(Integer.toHexString(val));
}
m.appendReplacement(sb, hexcolor.toString());
}
m.appendTail(sb);
css = sb.toString();
// Shorten colors from #AABBCC to #ABC. Note that we want to make sure
// the color is not preceded by either ", " or =. Indeed, the property
// filter: chroma(color="#FFFFFF");
// would become
// filter: chroma(color="#FFF");
// which makes the filter break in IE.
p = Pattern.compile("([^\"'=\\s])(\\s*)#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])");
m = p.matcher(css);
sb = new StringBuffer();
while (m.find()) {
// Test for AABBCC pattern
if (m.group(3).equalsIgnoreCase(m.group(4)) &&
m.group(5).equalsIgnoreCase(m.group(6)) &&
m.group(7).equalsIgnoreCase(m.group(8))) {
m.appendReplacement(sb, (m.group(1) + m.group(2) + "#" + m.group(3) + m.group(5) + m.group(7)).toLowerCase());
} else {
m.appendReplacement(sb, m.group().toLowerCase());
}
}
m.appendTail(sb);
css = sb.toString();
// border: none -> border:0
sb = new StringBuffer();
p = Pattern.compile("(?i)(border|border-top|border-right|border-bottom|border-right|outline|background):none(;|})");
m = p.matcher(css);
while (m.find()) {
m.appendReplacement(sb, m.group(1).toLowerCase() + ":0" + m.group(2));
}
m.appendTail(sb);
css = sb.toString();
// shorter opacity IE filter
css = css.replaceAll("(?i)progid:DXImageTransform.Microsoft.Alpha\\(Opacity=", "alpha(opacity=");
// Remove empty rules.
css = css.replaceAll("[^\\}\\{/;]+\\{\\}", "");
if (linebreakpos >= 0) {
// Some source control tools don't like it when files containing lines longer
// than, say 8000 characters, are checked in. The linebreak option is used in
// that case to split long lines after a specific column.
i = 0;
int linestartpos = 0;
sb = new StringBuffer(css);
while (i < sb.length()) {
char c = sb.charAt(i++);
if (c == '}' && i - linestartpos > linebreakpos) {
sb.insert(i, '\n');
linestartpos = i;
}
}
css = sb.toString();
}
// Replace multiple semi-colons in a row by a single one
// See SF bug #1980989
css = css.replaceAll(";;+", ";");
// restore preserved comments and strings
for(i = 0, max = preservedTokens.size(); i < max; i++) {
css = css.replace("___YUICSSMIN_PRESERVED_TOKEN_" + i + "___", preservedTokens.get(i).toString());
}
// Trim the final string (for any leading or trailing white spaces)
css = css.trim();
// Write the output...
out.write(css);
}
| public void compress(Writer out, int linebreakpos)
throws IOException {
Pattern p;
Matcher m;
String css = srcsb.toString();
StringBuffer sb = new StringBuffer(css);
int startIndex = 0;
int endIndex = 0;
int i = 0;
int max = 0;
ArrayList preservedTokens = new ArrayList(0);
ArrayList comments = new ArrayList(0);
String token;
int totallen = css.length();
String placeholder;
// // leave data urls alone to increase parse performance.
// sb = new StringBuffer();
// p = Pattern.compile("url\\(.*data\\:(.*)\\)");
// m = p.matcher(css);
// while (m.find()) {
// token = m.group();
// token = token.substring(1, token.length() - 1);
// preservedTokens.add(token);
// String preserver = "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___";
// m.appendReplacement(sb, preserver);
// }
// m.appendTail(sb);
// css = sb.toString();
// collect all comment blocks...
while ((startIndex = sb.indexOf("/*", startIndex)) >= 0) {
endIndex = sb.indexOf("*/", startIndex + 2);
if (endIndex < 0) {
endIndex = totallen;
}
token = sb.substring(startIndex + 2, endIndex);
comments.add(token);
sb.replace(startIndex + 2, endIndex, "___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + (comments.size() - 1) + "___");
startIndex += 2;
}
css = sb.toString();
// preserve strings so their content doesn't get accidentally minified
sb = new StringBuffer();
p = Pattern.compile("(\"([^\\\\\"]|\\\\.|\\\\)*\")|(\'([^\\\\\']|\\\\.|\\\\)*\')");
m = p.matcher(css);
while (m.find()) {
token = m.group();
char quote = token.charAt(0);
token = token.substring(1, token.length() - 1);
// maybe the string contains a comment-like substring?
// one, maybe more? put'em back then
if (token.indexOf("___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_") >= 0) {
for (i = 0, max = comments.size(); i < max; i += 1) {
token = token.replace("___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + i + "___", comments.get(i).toString());
}
}
// minify alpha opacity in filter strings
token = token.replaceAll("(?i)progid:DXImageTransform.Microsoft.Alpha\\(Opacity=", "alpha(opacity=");
preservedTokens.add(token);
String preserver = quote + "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___" + quote;
m.appendReplacement(sb, preserver);
}
m.appendTail(sb);
css = sb.toString();
// strings are safe, now wrestle the comments
for (i = 0, max = comments.size(); i < max; i += 1) {
token = comments.get(i).toString();
placeholder = "___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + i + "___";
// ! in the first position of the comment means preserve
// so push to the preserved tokens while stripping the !
if (token.startsWith("!")) {
preservedTokens.add(token);
css = css.replace(placeholder, "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___");
continue;
}
// \ in the last position looks like hack for Mac/IE5
// shorten that to /*\*/ and the next one to /**/
if (token.endsWith("\\")) {
preservedTokens.add("\\");
css = css.replace(placeholder, "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___");
i = i + 1; // attn: advancing the loop
preservedTokens.add("");
css = css.replace("___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + i + "___", "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___");
continue;
}
// keep empty comments after child selectors (IE7 hack)
// e.g. html >/**/ body
if (token.length() == 0) {
startIndex = css.indexOf(placeholder);
if (startIndex > 2) {
if (css.charAt(startIndex - 3) == '>') {
preservedTokens.add("");
css = css.replace(placeholder, "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___");
}
}
}
// in all other cases kill the comment
css = css.replace("/*" + placeholder + "*/", "");
}
// Normalize all whitespace strings to single spaces. Easier to work with that way.
css = css.replaceAll("\\s+", " ");
// Remove the spaces before the things that should not have spaces before them.
// But, be careful not to turn "p :link {...}" into "p:link{...}"
// Swap out any pseudo-class colons with the token, and then swap back.
sb = new StringBuffer();
p = Pattern.compile("(^|\\})(([^\\{:])+:)+([^\\{]*\\{)");
m = p.matcher(css);
while (m.find()) {
String s = m.group();
s = s.replaceAll(":", "___YUICSSMIN_PSEUDOCLASSCOLON___");
s = s.replaceAll( "\\\\", "\\\\\\\\" ).replaceAll( "\\$", "\\\\\\$" );
m.appendReplacement(sb, s);
}
m.appendTail(sb);
css = sb.toString();
// Remove spaces before the things that should not have spaces before them.
css = css.replaceAll("\\s+([!{};:>+\\(\\)\\],])", "$1");
// bring back the colon
css = css.replaceAll("___YUICSSMIN_PSEUDOCLASSCOLON___", ":");
// retain space for special IE6 cases
css = css.replaceAll(":first\\-(line|letter)(\\{|,)", ":first-$1 $2");
// no space after the end of a preserved comment
css = css.replaceAll("\\*/ ", "*/");
// If there is a @charset, then only allow one, and push to the top of the file.
css = css.replaceAll("^(.*)(@charset \"[^\"]*\";)", "$2$1");
css = css.replaceAll("^(\\s*@charset [^;]+;\\s*)+", "$1");
// Put the space back in some cases, to support stuff like
// @media screen and (-webkit-min-device-pixel-ratio:0){
css = css.replaceAll("\\band\\(", "and (");
// Remove the spaces after the things that should not have spaces after them.
css = css.replaceAll("([!{}:;>+\\(\\[,])\\s+", "$1");
// remove unnecessary semicolons
css = css.replaceAll(";+}", "}");
// Replace 0(px,em,%) with 0.
css = css.replaceAll("([\\s:])(0)(px|em|%|in|cm|mm|pc|pt|ex)", "$1$2");
// Replace 0 0 0 0; with 0.
css = css.replaceAll(":0 0 0 0(;|})", ":0$1");
css = css.replaceAll(":0 0 0(;|})", ":0$1");
css = css.replaceAll(":0 0(;|})", ":0$1");
// Replace background-position:0; with background-position:0 0;
// same for transform-origin
sb = new StringBuffer();
p = Pattern.compile("(?i)(background-position|transform-origin|webkit-transform-origin|moz-transform-origin|o-transform-origin|ms-transform-origin):0(;|})");
m = p.matcher(css);
while (m.find()) {
m.appendReplacement(sb, m.group(1).toLowerCase() + ":0 0" + m.group(2));
}
m.appendTail(sb);
css = sb.toString();
// Replace 0.6 to .6, but only when preceded by : or a white-space
css = css.replaceAll("(:|\\s)0+\\.(\\d+)", "$1.$2");
// Shorten colors from rgb(51,102,153) to #336699
// This makes it more likely that it'll get further compressed in the next step.
p = Pattern.compile("rgb\\s*\\(\\s*([0-9,\\s]+)\\s*\\)");
m = p.matcher(css);
sb = new StringBuffer();
while (m.find()) {
String[] rgbcolors = m.group(1).split(",");
StringBuffer hexcolor = new StringBuffer("#");
for (i = 0; i < rgbcolors.length; i++) {
int val = Integer.parseInt(rgbcolors[i]);
if (val < 16) {
hexcolor.append("0");
}
hexcolor.append(Integer.toHexString(val));
}
m.appendReplacement(sb, hexcolor.toString());
}
m.appendTail(sb);
css = sb.toString();
// Shorten colors from #AABBCC to #ABC. Note that we want to make sure
// the color is not preceded by either ", " or =. Indeed, the property
// filter: chroma(color="#FFFFFF");
// would become
// filter: chroma(color="#FFF");
// which makes the filter break in IE.
p = Pattern.compile("([^\"'=\\s])(\\s*)#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])");
m = p.matcher(css);
sb = new StringBuffer();
while (m.find()) {
if (m.group(1).equals("}")) {
// Likely an ID selector. Don't touch.
// #AABBCC is a valid ID. IDs are case-sensitive.
m.appendReplacement(sb, m.group());
} else if (m.group(3).equalsIgnoreCase(m.group(4)) &&
m.group(5).equalsIgnoreCase(m.group(6)) &&
m.group(7).equalsIgnoreCase(m.group(8))) {
// #AABBCC pattern
m.appendReplacement(sb, (m.group(1) + m.group(2) + "#" + m.group(3) + m.group(5) + m.group(7)).toLowerCase());
} else {
// Any other color.
m.appendReplacement(sb, m.group().toLowerCase());
}
}
m.appendTail(sb);
css = sb.toString();
// border: none -> border:0
sb = new StringBuffer();
p = Pattern.compile("(?i)(border|border-top|border-right|border-bottom|border-right|outline|background):none(;|})");
m = p.matcher(css);
while (m.find()) {
m.appendReplacement(sb, m.group(1).toLowerCase() + ":0" + m.group(2));
}
m.appendTail(sb);
css = sb.toString();
// shorter opacity IE filter
css = css.replaceAll("(?i)progid:DXImageTransform.Microsoft.Alpha\\(Opacity=", "alpha(opacity=");
// Remove empty rules.
css = css.replaceAll("[^\\}\\{/;]+\\{\\}", "");
if (linebreakpos >= 0) {
// Some source control tools don't like it when files containing lines longer
// than, say 8000 characters, are checked in. The linebreak option is used in
// that case to split long lines after a specific column.
i = 0;
int linestartpos = 0;
sb = new StringBuffer(css);
while (i < sb.length()) {
char c = sb.charAt(i++);
if (c == '}' && i - linestartpos > linebreakpos) {
sb.insert(i, '\n');
linestartpos = i;
}
}
css = sb.toString();
}
// Replace multiple semi-colons in a row by a single one
// See SF bug #1980989
css = css.replaceAll(";;+", ";");
// restore preserved comments and strings
for(i = 0, max = preservedTokens.size(); i < max; i++) {
css = css.replace("___YUICSSMIN_PRESERVED_TOKEN_" + i + "___", preservedTokens.get(i).toString());
}
// Trim the final string (for any leading or trailing white spaces)
css = css.trim();
// Write the output...
out.write(css);
}
|
diff --git a/src/uk/co/oliwali/WhoAreYou/WhoAreYou.java b/src/uk/co/oliwali/WhoAreYou/WhoAreYou.java
index 70bf812..2221c0f 100644
--- a/src/uk/co/oliwali/WhoAreYou/WhoAreYou.java
+++ b/src/uk/co/oliwali/WhoAreYou/WhoAreYou.java
@@ -1,101 +1,101 @@
package uk.co.oliwali.WhoAreYou;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.Event.Type;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
public class WhoAreYou extends JavaPlugin {
public static String name;
public static String version;
private Permission permissions;
public Config config;
private WAYPlayerListener playerListener = new WAYPlayerListener(this);
public void onDisable() {
Util.info("Version " + version + " disabled!");
}
public void onEnable() {
name = this.getDescription().getName();
version = this.getDescription().getVersion();
config = new Config(this);
permissions = new Permission(this);
// Register events
PluginManager pm = getServer().getPluginManager();
pm.registerEvent(Type.PLAYER_JOIN, playerListener, Event.Priority.Monitor, this);
Util.info("Version " + version + " enabled!");
}
private void sendPlayerList(Player sender, String message, List<Player> players) {
for (Player player : players.toArray(new Player[0]))
message = message + " " + permissions.getPrefix(player) + player.getName();
Util.sendMessage(sender, message);
}
public void who(Player player) {
List<Player> players = new ArrayList<Player>();
for (World world : getServer().getWorlds().toArray(new World[0]))
players.addAll(world.getPlayers());
sendPlayerList(player, "&aServer player list &7(" + players.size() + "/" + getServer().getMaxPlayers() + ")&a:&f", players);
}
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String args[]) {
String prefix = cmd.getName();
Player player = (Player) sender;
if (prefix.equalsIgnoreCase("who")) {
if (args.length > 0) {
String name = args[0];
if (permissions.world(player)) {
for (World world : getServer().getWorlds().toArray(new World[0])) {
if (name.equalsIgnoreCase(config.getAliasFromWorld(world))) {
sendPlayerList(player, "&aPlayer list for &c" + world.getName() + " &7(" + world.getPlayers().size() + "/" + getServer().getMaxPlayers() + ")&a:&f", world.getPlayers());
return true;
}
}
if (!permissions.player(player))
Util.sendMessage(player, "&cNo worlds found that match &7" + name);
}
if (permissions.player(player)) {
List<Player> matchPlayers = getServer().matchPlayer(name);
if (matchPlayers.size() == 1) {
Player playerInfo = matchPlayers.get(0);
Location loc = Util.getSimpleLocation(playerInfo.getLocation());
- Util.sendMessage(player, "&a------------ &7Who -------------");
+ Util.sendMessage(player, "&a------------ &7Who &a-------------");
Util.sendMessage(player, "&aPlayer: &7" + playerInfo.getName());
Util.sendMessage(player, "&aIP: &7" + playerInfo.getAddress().getAddress().getHostAddress().toString());
Util.sendMessage(player, "&aLocation: &7" + loc.getX() + ", " + loc.getY() + ", " + loc.getZ());
Util.sendMessage(player, "&aWorld: &7" + config.getAliasFromWorld(playerInfo.getWorld()));
Util.sendMessage(player, "&aHealth: &7" + playerInfo.getHealth() + "/20");
Util.sendMessage(player, "&aGroup: &7" + permissions.getPrefix(playerInfo) + permissions.getGroup(playerInfo));
Util.sendMessage(player, "&aOp: &7" + (playerInfo.isOp()?"yes":"no"));
return true;
}
if (!permissions.world(player))
Util.sendMessage(player, "&cNo unique players found that match &7" + name);
else
Util.sendMessage(player, "&cNo unique players or worlds found that match &7" + name);
}
}
else if (permissions.list(player)) {
who(player);
return true;
}
}
return false;
}
}
| true | true | public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String args[]) {
String prefix = cmd.getName();
Player player = (Player) sender;
if (prefix.equalsIgnoreCase("who")) {
if (args.length > 0) {
String name = args[0];
if (permissions.world(player)) {
for (World world : getServer().getWorlds().toArray(new World[0])) {
if (name.equalsIgnoreCase(config.getAliasFromWorld(world))) {
sendPlayerList(player, "&aPlayer list for &c" + world.getName() + " &7(" + world.getPlayers().size() + "/" + getServer().getMaxPlayers() + ")&a:&f", world.getPlayers());
return true;
}
}
if (!permissions.player(player))
Util.sendMessage(player, "&cNo worlds found that match &7" + name);
}
if (permissions.player(player)) {
List<Player> matchPlayers = getServer().matchPlayer(name);
if (matchPlayers.size() == 1) {
Player playerInfo = matchPlayers.get(0);
Location loc = Util.getSimpleLocation(playerInfo.getLocation());
Util.sendMessage(player, "&a------------ &7Who -------------");
Util.sendMessage(player, "&aPlayer: &7" + playerInfo.getName());
Util.sendMessage(player, "&aIP: &7" + playerInfo.getAddress().getAddress().getHostAddress().toString());
Util.sendMessage(player, "&aLocation: &7" + loc.getX() + ", " + loc.getY() + ", " + loc.getZ());
Util.sendMessage(player, "&aWorld: &7" + config.getAliasFromWorld(playerInfo.getWorld()));
Util.sendMessage(player, "&aHealth: &7" + playerInfo.getHealth() + "/20");
Util.sendMessage(player, "&aGroup: &7" + permissions.getPrefix(playerInfo) + permissions.getGroup(playerInfo));
Util.sendMessage(player, "&aOp: &7" + (playerInfo.isOp()?"yes":"no"));
return true;
}
if (!permissions.world(player))
Util.sendMessage(player, "&cNo unique players found that match &7" + name);
else
Util.sendMessage(player, "&cNo unique players or worlds found that match &7" + name);
}
}
else if (permissions.list(player)) {
who(player);
return true;
}
}
return false;
}
| public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String args[]) {
String prefix = cmd.getName();
Player player = (Player) sender;
if (prefix.equalsIgnoreCase("who")) {
if (args.length > 0) {
String name = args[0];
if (permissions.world(player)) {
for (World world : getServer().getWorlds().toArray(new World[0])) {
if (name.equalsIgnoreCase(config.getAliasFromWorld(world))) {
sendPlayerList(player, "&aPlayer list for &c" + world.getName() + " &7(" + world.getPlayers().size() + "/" + getServer().getMaxPlayers() + ")&a:&f", world.getPlayers());
return true;
}
}
if (!permissions.player(player))
Util.sendMessage(player, "&cNo worlds found that match &7" + name);
}
if (permissions.player(player)) {
List<Player> matchPlayers = getServer().matchPlayer(name);
if (matchPlayers.size() == 1) {
Player playerInfo = matchPlayers.get(0);
Location loc = Util.getSimpleLocation(playerInfo.getLocation());
Util.sendMessage(player, "&a------------ &7Who &a-------------");
Util.sendMessage(player, "&aPlayer: &7" + playerInfo.getName());
Util.sendMessage(player, "&aIP: &7" + playerInfo.getAddress().getAddress().getHostAddress().toString());
Util.sendMessage(player, "&aLocation: &7" + loc.getX() + ", " + loc.getY() + ", " + loc.getZ());
Util.sendMessage(player, "&aWorld: &7" + config.getAliasFromWorld(playerInfo.getWorld()));
Util.sendMessage(player, "&aHealth: &7" + playerInfo.getHealth() + "/20");
Util.sendMessage(player, "&aGroup: &7" + permissions.getPrefix(playerInfo) + permissions.getGroup(playerInfo));
Util.sendMessage(player, "&aOp: &7" + (playerInfo.isOp()?"yes":"no"));
return true;
}
if (!permissions.world(player))
Util.sendMessage(player, "&cNo unique players found that match &7" + name);
else
Util.sendMessage(player, "&cNo unique players or worlds found that match &7" + name);
}
}
else if (permissions.list(player)) {
who(player);
return true;
}
}
return false;
}
|
diff --git a/threads/LotteryScheduler.java b/threads/LotteryScheduler.java
index ec60917..c9a4bf5 100755
--- a/threads/LotteryScheduler.java
+++ b/threads/LotteryScheduler.java
@@ -1,193 +1,193 @@
package nachos.threads;
import nachos.machine.*;
import java.util.Random;
import java.util.TreeSet;
import java.util.HashSet;
import java.util.Iterator;
/**
* A scheduler that chooses threads using a lottery.
*
* <p>
* A lottery scheduler associates a number of tickets with each thread. When a
* thread needs to be dequeued, a random lottery is held, among all the tickets
* of all the threads waiting to be dequeued. The thread that holds the winning
* ticket is chosen.
*
* <p>
* Note that a lottery scheduler must be able to handle a lot of tickets
* (sometimes billions), so it is not acceptable to maintain state for every
* ticket.
*
* <p>
* A lottery scheduler must partially solve the priority inversion problem; in
* particular, tickets must be transferred through locks, and through joins.
* Unlike a priority scheduler, these tickets add (as opposed to just taking
* the maximum).
*/
public class LotteryScheduler extends PriorityScheduler {
public static final int priorityMinimum = 1;
public static final int priorityMaximum = Integer.MAX_VALUE;
/**
* Allocate a new lottery scheduler.
*/
public LotteryScheduler() {
}
//DONE!!!!
protected ThreadState getThreadState(KThread thread) {
if (thread.schedulingState == null)
thread.schedulingState = new LotteryThreadState(thread);
return (ThreadState) thread.schedulingState;
}
/**
* Allocate a new lottery thread queue.
*
* @param transferPriority <tt>true</tt> if this queue should
* transfer tickets from waiting threads
* to the owning thread.
* @return a new lottery thread queue.
*/
public ThreadQueue newThreadQueue(boolean transferPriority) {
return new LotteryQueue(transferPriority);
}
protected class LotteryQueue extends PriorityQueue {
//In terms of picking the next thread linear in the number of threads on the queue is fine
LotteryQueue(boolean transferPriority) {
super(transferPriority);
}
public void updateEntry(ThreadState ts, int newEffectivePriority) {
int oldPriority = ts.getEffectivePriority();
ts.effectivePriority = newEffectivePriority;
//propagate
int difference = newEffectivePriority-oldPriority;
if(difference != 0)
ts.propagate(difference);
}
//DONE!!!!!
protected ThreadState pickNextThread() {
//Set up an Iterator and go through it
Random randomGenerator = new Random();
int ticketCount = 0;
Iterator<ThreadState> itr = this.waitQueue.iterator();
while(itr.hasNext()) {
ticketCount += itr.next().getEffectivePriority();
}
if(ticketCount > 0) {
int num = randomGenerator.nextInt(ticketCount);
itr = this.waitQueue.iterator();
ThreadState temp;
while(itr.hasNext()) {
temp = itr.next();
num -= temp.effectivePriority;
if(num <= 0){
return temp;
}
}
}
return null;
}
}
protected class LotteryThreadState extends ThreadState {
public LotteryThreadState(KThread thread) {
super(thread);
}
//DONE!!!!
public void setPriority(int newPriority) {
this.priority = newPriority;
this.updateEffectivePriority();
}
//DONE!!!!
public void propagate(int difference) {
if(pqWant != null) {
if(pqWant.transferPriority == true) {
if(pqWant.holder != null)
pqWant.updateEntry(pqWant.holder, pqWant.holder.effectivePriority+difference);
}
}
}
//DONE!!!!
public void updateEffectivePriority() {
//Calculate new effectivePriority checking possible donations from threads that are waiting for me
int sumPriority = this.priority;
for (PriorityQueue pq: this.pqHave)
if (pq.transferPriority == true) {
Iterator<ThreadState> itr = pq.waitQueue.iterator();
while(itr.hasNext())
sumPriority += itr.next().getEffectivePriority();
}
//If there is a change in priority, update and propagate to other owners
if (sumPriority != this.effectivePriority) {
int difference = sumPriority - this.effectivePriority;
this.effectivePriority = sumPriority;
this.propagate(difference);
}
}
//DONE!!!!
public void waitForAccess(PriorityQueue pq) {
this.pqWant = pq;
//this.time = Machine.timer().getTime();
this.time = TickTimer++;
pq.waitQueue.add(this);
//Propagate this ThreadState's effectivePriority to holder of pq
if (pq.transferPriority == true) {
if(pq.holder != null)
pq.updateEntry(pq.holder, pq.holder.effectivePriority+this.effectivePriority);
}
}
//Added a line to acquire in PriorityScheduler
//updateEffectivePriority() at the very end of acquire
}
public static void selfTest() {
LotteryScheduler ls = new LotteryScheduler();
LotteryQueue[] pq = new LotteryQueue[5];
KThread[] t = new KThread[5];
ThreadState lts[] = new LotteryThreadState[5];
for (int i=0; i < 5; i++)
pq[i] = ls.new LotteryQueue(true);
for (int i=0; i < 5; i++) {
t[i] = new KThread();
t[i].setName("thread" + i);
lts[i] = ls.getThreadState(t[i]);
}
Machine.interrupt().disable();
System.out.println("===========LotteryScheduler Test============");
System.out.println("priority defaults to " + lts[0].priority);
pq[0].acquire(t[0]);
System.out.println("pq[0].acquire(t[0])");
System.out.println("lock holder effective priority is " + pq[0].holder.effectivePriority);
lts[0].setPriority(5);
System.out.println("lts[0].setPriority(5)");
System.out.println("lock holder effective priority is " + lts[0].effectivePriority);
pq[0].waitForAccess(t[1]);
System.out.println("pq[0].waitForAccess(t[1])");
System.out.println("lock holder effective priority is " + lts[0].effectivePriority);
- ThreadState temp = pq[0].pickNextThread();
+ KThread temp = pq[0].pickNextThread().thread;
System.out.println("pq[0].pickNextThread()");
System.out.println("Next Thread Null is: " + (temp == null));
lts[1].setPriority(3);
System.out.println("lts[1].setPriority(3)");
System.out.println("lock holder effective priority is " + lts[0].effectivePriority);
temp = pq[0].nextThread();
System.out.println("pq[0].nextThread()");
System.out.println("Next Thread Null is: " + (temp == null));
- temp = pq[0].pickNextThread();
+ temp = pq[0].pickNextThread().thread;
System.out.println("pq[0].pickNextThread()");
System.out.println("Next Thread Null is: " + (temp == null));
Machine.interrupt().enable();
}
}
| false | true | public static void selfTest() {
LotteryScheduler ls = new LotteryScheduler();
LotteryQueue[] pq = new LotteryQueue[5];
KThread[] t = new KThread[5];
ThreadState lts[] = new LotteryThreadState[5];
for (int i=0; i < 5; i++)
pq[i] = ls.new LotteryQueue(true);
for (int i=0; i < 5; i++) {
t[i] = new KThread();
t[i].setName("thread" + i);
lts[i] = ls.getThreadState(t[i]);
}
Machine.interrupt().disable();
System.out.println("===========LotteryScheduler Test============");
System.out.println("priority defaults to " + lts[0].priority);
pq[0].acquire(t[0]);
System.out.println("pq[0].acquire(t[0])");
System.out.println("lock holder effective priority is " + pq[0].holder.effectivePriority);
lts[0].setPriority(5);
System.out.println("lts[0].setPriority(5)");
System.out.println("lock holder effective priority is " + lts[0].effectivePriority);
pq[0].waitForAccess(t[1]);
System.out.println("pq[0].waitForAccess(t[1])");
System.out.println("lock holder effective priority is " + lts[0].effectivePriority);
ThreadState temp = pq[0].pickNextThread();
System.out.println("pq[0].pickNextThread()");
System.out.println("Next Thread Null is: " + (temp == null));
lts[1].setPriority(3);
System.out.println("lts[1].setPriority(3)");
System.out.println("lock holder effective priority is " + lts[0].effectivePriority);
temp = pq[0].nextThread();
System.out.println("pq[0].nextThread()");
System.out.println("Next Thread Null is: " + (temp == null));
temp = pq[0].pickNextThread();
System.out.println("pq[0].pickNextThread()");
System.out.println("Next Thread Null is: " + (temp == null));
Machine.interrupt().enable();
}
| public static void selfTest() {
LotteryScheduler ls = new LotteryScheduler();
LotteryQueue[] pq = new LotteryQueue[5];
KThread[] t = new KThread[5];
ThreadState lts[] = new LotteryThreadState[5];
for (int i=0; i < 5; i++)
pq[i] = ls.new LotteryQueue(true);
for (int i=0; i < 5; i++) {
t[i] = new KThread();
t[i].setName("thread" + i);
lts[i] = ls.getThreadState(t[i]);
}
Machine.interrupt().disable();
System.out.println("===========LotteryScheduler Test============");
System.out.println("priority defaults to " + lts[0].priority);
pq[0].acquire(t[0]);
System.out.println("pq[0].acquire(t[0])");
System.out.println("lock holder effective priority is " + pq[0].holder.effectivePriority);
lts[0].setPriority(5);
System.out.println("lts[0].setPriority(5)");
System.out.println("lock holder effective priority is " + lts[0].effectivePriority);
pq[0].waitForAccess(t[1]);
System.out.println("pq[0].waitForAccess(t[1])");
System.out.println("lock holder effective priority is " + lts[0].effectivePriority);
KThread temp = pq[0].pickNextThread().thread;
System.out.println("pq[0].pickNextThread()");
System.out.println("Next Thread Null is: " + (temp == null));
lts[1].setPriority(3);
System.out.println("lts[1].setPriority(3)");
System.out.println("lock holder effective priority is " + lts[0].effectivePriority);
temp = pq[0].nextThread();
System.out.println("pq[0].nextThread()");
System.out.println("Next Thread Null is: " + (temp == null));
temp = pq[0].pickNextThread().thread;
System.out.println("pq[0].pickNextThread()");
System.out.println("Next Thread Null is: " + (temp == null));
Machine.interrupt().enable();
}
|
diff --git a/src/com/redhat/ceylon/compiler/java/codegen/ClassTransformer.java b/src/com/redhat/ceylon/compiler/java/codegen/ClassTransformer.java
index 971150e16..aab209bc0 100755
--- a/src/com/redhat/ceylon/compiler/java/codegen/ClassTransformer.java
+++ b/src/com/redhat/ceylon/compiler/java/codegen/ClassTransformer.java
@@ -1,1908 +1,1910 @@
/*
* Copyright Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the authors tag. All rights reserved.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License version 2.
*
* This particular file is subject to the "Classpath" exception as provided in the
* LICENSE file that accompanied this code.
*
* This program is distributed in the hope that it will be useful, but WITHOUT A
* 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 distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package com.redhat.ceylon.compiler.java.codegen;
import static com.redhat.ceylon.compiler.java.codegen.Naming.DeclNameFlag.QUALIFIED;
import static com.sun.tools.javac.code.Flags.ABSTRACT;
import static com.sun.tools.javac.code.Flags.FINAL;
import static com.sun.tools.javac.code.Flags.INTERFACE;
import static com.sun.tools.javac.code.Flags.PRIVATE;
import static com.sun.tools.javac.code.Flags.PROTECTED;
import static com.sun.tools.javac.code.Flags.PUBLIC;
import static com.sun.tools.javac.code.Flags.STATIC;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import com.redhat.ceylon.compiler.java.codegen.Naming.DeclNameFlag;
import com.redhat.ceylon.compiler.loader.model.LazyInterface;
import com.redhat.ceylon.compiler.typechecker.model.Class;
import com.redhat.ceylon.compiler.typechecker.model.ClassOrInterface;
import com.redhat.ceylon.compiler.typechecker.model.Declaration;
import com.redhat.ceylon.compiler.typechecker.model.Functional;
import com.redhat.ceylon.compiler.typechecker.model.FunctionalParameter;
import com.redhat.ceylon.compiler.typechecker.model.Generic;
import com.redhat.ceylon.compiler.typechecker.model.Getter;
import com.redhat.ceylon.compiler.typechecker.model.Interface;
import com.redhat.ceylon.compiler.typechecker.model.Method;
import com.redhat.ceylon.compiler.typechecker.model.MethodOrValue;
import com.redhat.ceylon.compiler.typechecker.model.Package;
import com.redhat.ceylon.compiler.typechecker.model.Parameter;
import com.redhat.ceylon.compiler.typechecker.model.ParameterList;
import com.redhat.ceylon.compiler.typechecker.model.ProducedReference;
import com.redhat.ceylon.compiler.typechecker.model.ProducedType;
import com.redhat.ceylon.compiler.typechecker.model.ProducedTypedReference;
import com.redhat.ceylon.compiler.typechecker.model.Scope;
import com.redhat.ceylon.compiler.typechecker.model.Setter;
import com.redhat.ceylon.compiler.typechecker.model.TypeAlias;
import com.redhat.ceylon.compiler.typechecker.model.TypeDeclaration;
import com.redhat.ceylon.compiler.typechecker.model.TypeParameter;
import com.redhat.ceylon.compiler.typechecker.model.TypedDeclaration;
import com.redhat.ceylon.compiler.typechecker.model.Value;
import com.redhat.ceylon.compiler.typechecker.model.ValueParameter;
import com.redhat.ceylon.compiler.typechecker.tree.Node;
import com.redhat.ceylon.compiler.typechecker.tree.Tree;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.AttributeDeclaration;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.AttributeGetterDefinition;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.AttributeSetterDefinition;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.Block;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.MethodDeclaration;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.MethodDefinition;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.SpecifierExpression;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.SpecifierStatement;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.TypeAliasDeclaration;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.JCAnnotation;
import com.sun.tools.javac.tree.JCTree.JCBinary;
import com.sun.tools.javac.tree.JCTree.JCBlock;
import com.sun.tools.javac.tree.JCTree.JCExpression;
import com.sun.tools.javac.tree.JCTree.JCIdent;
import com.sun.tools.javac.tree.JCTree.JCMethodInvocation;
import com.sun.tools.javac.tree.JCTree.JCNewClass;
import com.sun.tools.javac.tree.JCTree.JCStatement;
import com.sun.tools.javac.tree.JCTree.JCVariableDecl;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.List;
import com.sun.tools.javac.util.ListBuffer;
/**
* This transformer deals with class/interface declarations
*/
public class ClassTransformer extends AbstractTransformer {
public static ClassTransformer getInstance(Context context) {
ClassTransformer trans = context.get(ClassTransformer.class);
if (trans == null) {
trans = new ClassTransformer(context);
context.put(ClassTransformer.class, trans);
}
return trans;
}
private ClassTransformer(Context context) {
super(context);
}
// FIXME: figure out what insertOverloadedClassConstructors does and port it
public List<JCTree> transform(final Tree.ClassOrInterface def) {
final ClassOrInterface model = def.getDeclarationModel();
// we only create types for aliases so they can be imported with the model loader
// and since we can't import local declarations let's just not create those types
// in that case
if(model.isAlias()
&& Decl.isAncestorLocal(def))
return List.nil();
naming.noteDecl(model);
final String javaClassName;
String ceylonClassName = def.getIdentifier().getText();
if (def instanceof Tree.AnyInterface) {
javaClassName = naming.declName(model, QUALIFIED).replaceFirst(".*\\.", "");
} else {
javaClassName = Naming.quoteClassName(def.getIdentifier().getText());
}
ClassDefinitionBuilder instantiatorImplCb;
ClassDefinitionBuilder instantiatorDeclCb;
if (Decl.withinInterface(model)) {
instantiatorImplCb = gen().current().getCompanionBuilder((Interface)model.getContainer());
instantiatorDeclCb = gen().current();
} else {
instantiatorImplCb = gen().current();
instantiatorDeclCb = null;
}
ClassDefinitionBuilder classBuilder = ClassDefinitionBuilder
.klass(this, javaClassName, ceylonClassName)
.forDefinition(def);
if (def instanceof Tree.AnyClass) {
Tree.ParameterList paramList = ((Tree.AnyClass)def).getParameterList();
Class cls = ((Tree.AnyClass)def).getDeclarationModel();
// Member classes need a instantiator method
boolean generateInstantiator = Strategy.generateInstantiator(cls);
if(generateInstantiator){
generateInstantiators(model, classBuilder, paramList, cls, instantiatorDeclCb, instantiatorImplCb);
}
if(def instanceof Tree.ClassDefinition){
transformClass(def, model, classBuilder, paramList, generateInstantiator, cls, instantiatorDeclCb, instantiatorImplCb);
}else{
// class alias
classBuilder.constructorModifiers(PRIVATE);
classBuilder.annotations(makeAtAlias(model.getExtendedType()));
classBuilder.isAlias(true);
}
}
if (def instanceof Tree.AnyInterface) {
if(def instanceof Tree.InterfaceDefinition){
transformInterface(def, model, classBuilder);
}else{
// interface alias
classBuilder.annotations(makeAtAlias(model.getExtendedType()));
classBuilder.isAlias(true);
}
}
// make sure we set the container in case we move it out
addAtContainer(classBuilder, model);
// Transform the class/interface members
List<JCStatement> childDefs = visitClassOrInterfaceDefinition(def, classBuilder);
// If it's a Class without initializer parameters...
if (Strategy.generateMain(def)) {
// ... then add a main() method
classBuilder.method(makeMainForClass(model));
}
return classBuilder
.modelAnnotations(model.getAnnotations())
.modifiers(transformClassDeclFlags(def))
.satisfies(model.getSatisfiedTypes())
.caseTypes(model.getCaseTypes())
.of(model.getSelfType())
.init(childDefs)
.build();
}
private List<JCStatement> visitClassOrInterfaceDefinition(Node def, ClassDefinitionBuilder classBuilder) {
// Transform the class/interface members
CeylonVisitor visitor = gen().visitor;
final ListBuffer<JCTree> prevDefs = visitor.defs;
final boolean prevInInitializer = visitor.inInitializer;
final ClassDefinitionBuilder prevClassBuilder = visitor.classBuilder;
try {
visitor.defs = new ListBuffer<JCTree>();
visitor.inInitializer = true;
visitor.classBuilder = classBuilder;
def.visitChildren(visitor);
return (List<JCStatement>)visitor.getResult().toList();
} finally {
visitor.classBuilder = prevClassBuilder;
visitor.inInitializer = prevInInitializer;
visitor.defs = prevDefs;
}
}
private void generateInstantiators(ClassOrInterface model, ClassDefinitionBuilder classBuilder, Tree.ParameterList paramList,
Class cls, ClassDefinitionBuilder instantiatorDeclCb, ClassDefinitionBuilder instantiatorImplCb) {
// TODO Instantiators on companion classes
classBuilder.constructorModifiers(PROTECTED);
if (Decl.withinInterface(cls)) {
MethodDefinitionBuilder instBuilder = MethodDefinitionBuilder.systemMethod(this, naming.getInstantiatorMethodName(cls));
makeOverloadsForDefaultedParameter(0,
instBuilder,
model, paramList, null);
instantiatorDeclCb.method(instBuilder);
}
if (!Decl.withinInterface(cls)
|| !model.isFormal()) {
MethodDefinitionBuilder instBuilder = MethodDefinitionBuilder.systemMethod(this, naming.getInstantiatorMethodName(cls));
makeOverloadsForDefaultedParameter(!cls.isFormal() ? OL_BODY : 0,
instBuilder,
model, paramList, null);
instantiatorImplCb.method(instBuilder);
}
}
private void transformClass(com.redhat.ceylon.compiler.typechecker.tree.Tree.ClassOrInterface def, ClassOrInterface model, ClassDefinitionBuilder classBuilder,
com.redhat.ceylon.compiler.typechecker.tree.Tree.ParameterList paramList, boolean generateInstantiator,
Class cls, ClassDefinitionBuilder instantiatorDeclCb, ClassDefinitionBuilder instantiatorImplCb) {
for (Tree.Parameter param : paramList.getParameters()) {
// Overloaded instantiators
Parameter paramModel = param.getDeclarationModel();
Parameter refinedParam = (Parameter)CodegenUtil.getTopmostRefinedDeclaration(param.getDeclarationModel());
at(param);
classBuilder.parameter(paramModel);
if (paramModel.isDefaulted()
|| paramModel.isSequenced()
|| (generateInstantiator
&& (refinedParam.isDefaulted()
|| refinedParam.isSequenced()))) {
ClassDefinitionBuilder cbForDevaultValues;
ClassDefinitionBuilder cbForDevaultValuesDecls = null;
switch (Strategy.defaultParameterMethodOwner(model)) {
case STATIC:
cbForDevaultValues = classBuilder;
break;
case OUTER:
cbForDevaultValues = classBuilder.getContainingClassBuilder();
break;
case OUTER_COMPANION:
cbForDevaultValues = classBuilder.getContainingClassBuilder().getCompanionBuilder(Decl.getClassOrInterfaceContainer(model, true));
cbForDevaultValuesDecls = classBuilder.getContainingClassBuilder();
break;
default:
cbForDevaultValues = classBuilder.getCompanionBuilder(model);
}
if (generateInstantiator && refinedParam != paramModel) {}
else {
cbForDevaultValues.method(makeParamDefaultValueMethod(false, def.getDeclarationModel(), paramList, param));
if (cbForDevaultValuesDecls != null) {
cbForDevaultValuesDecls.method(makeParamDefaultValueMethod(true, def.getDeclarationModel(), paramList, param));
}
}
if (generateInstantiator) {
if (Decl.withinInterface(cls)) {
MethodDefinitionBuilder instBuilder = MethodDefinitionBuilder.systemMethod(this, naming.getInstantiatorMethodName(cls));
makeOverloadsForDefaultedParameter(0,
instBuilder,
model, paramList, param);
instantiatorDeclCb.method(instBuilder);
}
MethodDefinitionBuilder instBuilder = MethodDefinitionBuilder.systemMethod(this, naming.getInstantiatorMethodName(cls));
makeOverloadsForDefaultedParameter(OL_BODY,
instBuilder,
model, paramList, param);
instantiatorImplCb.method(instBuilder);
} else {
// Add overloaded constructors for defaulted parameter
MethodDefinitionBuilder overloadBuilder = classBuilder.addConstructor();
makeOverloadsForDefaultedParameter(OL_BODY,
overloadBuilder,
model, paramList, param);
}
}
}
satisfaction((Class)model, classBuilder);
at(def);
// Generate the inner members list for model loading
addAtMembers(classBuilder, model);
}
private void transformInterface(com.redhat.ceylon.compiler.typechecker.tree.Tree.ClassOrInterface def, ClassOrInterface model, ClassDefinitionBuilder classBuilder) {
// Copy all the qualifying type's type parameters into the interface
ProducedType type = model.getType().getQualifyingType();
while (type != null) {
java.util.List<TypeParameter> typeArguments = type.getDeclaration().getTypeParameters();
if (typeArguments == null) {
continue;
}
for (TypeParameter typeArgument : typeArguments) {
classBuilder.typeParameter(typeArgument);
}
type = type.getQualifyingType();
}
classBuilder.method(makeCompanionAccessor((Interface)model, model.getType(), false));
// Build the companion class
buildCompanion(def, (Interface)model, classBuilder);
// Generate the inner members list for model loading
addAtMembers(classBuilder, model);
}
private void addAtMembers(ClassDefinitionBuilder classBuilder, ClassOrInterface model) {
List<JCExpression> members = List.nil();
Package pkg = Decl.getPackageContainer(model);
for(Declaration member : model.getMembers()){
if(member instanceof ClassOrInterface == false
&& member instanceof TypeAlias == false){
continue;
}
TypeDeclaration innerType = (TypeDeclaration) member;
// figure out its java name (strip the leading dot)
String javaClass = naming.declName(innerType, DeclNameFlag.QUALIFIED).substring(1);
String ceylonName = member.getName();
JCAnnotation atMember = makeAtMember(ceylonName, javaClass, pkg.getQualifiedNameString());
members = members.prepend(atMember);
}
classBuilder.annotations(makeAtMembers(members));
}
private void addAtContainer(ClassDefinitionBuilder classBuilder, TypeDeclaration model) {
Package pkg = Decl.getPackageContainer(model);
Scope scope = model.getContainer();
if(scope == null || scope instanceof ClassOrInterface == false)
return;
ClassOrInterface container = (ClassOrInterface) scope;
// figure out its java name (strip the leading dot)
String javaClass = naming.declName(container, DeclNameFlag.QUALIFIED).substring(1);
String ceylonName = container.getName();
List<JCAnnotation> atContainer = makeAtContainer(ceylonName, javaClass, pkg.getQualifiedNameString());
classBuilder.annotations(atContainer);
}
private void satisfaction(final Class model, ClassDefinitionBuilder classBuilder) {
final java.util.List<ProducedType> satisfiedTypes = model.getSatisfiedTypes();
Set<Interface> satisfiedInterfaces = new HashSet<Interface>();
for (ProducedType satisfiedType : satisfiedTypes) {
TypeDeclaration decl = satisfiedType.getDeclaration();
if (!(decl instanceof Interface)) {
continue;
}
concreteMembersFromSuperinterfaces((Class)model, classBuilder, satisfiedType, satisfiedInterfaces);
}
}
/**
* Generates companion fields ($Foo$impl) and methods
*/
private void concreteMembersFromSuperinterfaces(final Class model,
ClassDefinitionBuilder classBuilder,
ProducedType satisfiedType, Set<Interface> satisfiedInterfaces) {
Interface iface = (Interface)satisfiedType.getDeclaration();
if (satisfiedInterfaces.contains(iface)
|| iface.getType().isExactly(typeFact().getIdentifiableDeclaration().getType())) {
return;
}
// If there is no $impl (e.g. implementing a Java interface)
// then don't instantiate it...
if (hasImpl(iface)) {
// ... otherwise for each satisfied interface,
// instantiate an instance of the
// companion class in the constructor and assign it to a
// $Interface$impl field
transformInstantiateCompanions(classBuilder,
model, iface, satisfiedType);
}
if(!Decl.isCeylon(iface)){
// let's not try to implement CMI for Java interfaces
return;
}
// When we implement an interface with union or intersection type arguments
// we have to make method results and parameters raw too
boolean rawifyParametersAndResults = needsRawification(satisfiedType);
// For each super interface
for (Declaration member : iface.getMembers()) {
if (member instanceof Class
&& Strategy.generateInstantiator(member)
&& model.getDirectMember(member.getName(), null, false) == null) {
// instantiator method implementation
Class klass = (Class)member;
generateInstantiatorDelegate(classBuilder, satisfiedType,
iface, rawifyParametersAndResults, klass);
}
if (Strategy.onlyOnCompanion(member)) {
// non-shared interface methods don't need implementing
// (they're just private methods on the $impl)
continue;
}
if (member instanceof Method) {
Method method = (Method)member;
final ProducedTypedReference typedMember = satisfiedType.getTypedMember(method, Collections.<ProducedType>emptyList());
final java.util.List<TypeParameter> typeParameters = method.getTypeParameters();
final java.util.List<Parameter> parameters = method.getParameterLists().get(0).getParameters();
if (!satisfiedInterfaces.contains((Interface)method.getContainer())) {
for (Parameter param : parameters) {
if (param.isDefaulted()
|| param.isSequenced()) {
final ProducedTypedReference typedParameter = typedMember.getTypedParameter(param);
// If that method has a defaulted parameter,
// we need to generate a default value method
// which also delegates to the $impl
final MethodDefinitionBuilder defaultValueDelegate = makeDelegateToCompanion(iface,
typedParameter,
PUBLIC | FINAL,
typeParameters,
typedParameter.getType(),
Naming.getDefaultedParamMethodName(method, param),
parameters.subList(0, parameters.indexOf(param)),
rawifyParametersAndResults);
classBuilder.method(defaultValueDelegate);
final MethodDefinitionBuilder overload = makeDelegateToCompanion(iface,
typedMember,
PUBLIC | FINAL,
typeParameters,
typedMember.getType(),
naming.selector(method),
parameters.subList(0, parameters.indexOf(param)),
rawifyParametersAndResults);
classBuilder.method(overload);
}
}
}
// if it has the *most refined* default concrete member,
// then generate a method on the class
// delegating to the $impl instance
if (needsCompanionDelegate(model, member)) {
final MethodDefinitionBuilder concreteMemberDelegate = makeDelegateToCompanion(iface,
typedMember,
PUBLIC | (method.isDefault() ? 0 : FINAL),
method.getTypeParameters(),
method.getType(),
naming.selector(method),
method.getParameterLists().get(0).getParameters(),
rawifyParametersAndResults);
classBuilder.method(concreteMemberDelegate);
}
} else if (member instanceof Getter
|| member instanceof Setter
|| member instanceof Value) {
TypedDeclaration attr = (TypedDeclaration)member;
final ProducedTypedReference typedMember = satisfiedType.getTypedMember(attr, null);
if (needsCompanionDelegate(model, member)) {
if (member instanceof Value
|| member instanceof Getter) {
final MethodDefinitionBuilder getterDelegate = makeDelegateToCompanion(iface,
typedMember,
PUBLIC | (attr.isDefault() ? 0 : FINAL),
Collections.<TypeParameter>emptyList(),
typedMember.getType(),
Naming.getGetterName(attr),
Collections.<Parameter>emptyList(),
rawifyParametersAndResults);
classBuilder.method(getterDelegate);
}
if (member instanceof Setter) {
final MethodDefinitionBuilder setterDelegate = makeDelegateToCompanion(iface,
typedMember,
PUBLIC | (((Setter)member).getGetter().isDefault() ? 0 : FINAL),
Collections.<TypeParameter>emptyList(),
typeFact().getVoidDeclaration().getType(),
Naming.getSetterName(attr),
Collections.<Parameter>singletonList(((Setter)member).getParameter()),
rawifyParametersAndResults);
classBuilder.method(setterDelegate);
}
if (member instanceof Value
&& ((Value)attr).isVariable()) {
// I don't *think* this can happen because although a
// variable Value can be declared on an interface it
// will need to we refined as a Getter+Setter on a
// subinterface in order for there to be a method in a
// $impl to delegate to
throw new RuntimeException();
}
}
} else if (needsCompanionDelegate(model, member)) {
log.error("ceylon", "Unhandled concrete interface member " + member.getQualifiedNameString() + " " + member.getClass());
}
}
// Add $impl instances for the whole interface hierarchy
satisfiedInterfaces.add(iface);
for (ProducedType sat : iface.getSatisfiedTypes()) {
sat = satisfiedType.getSupertype(sat.getDeclaration());
concreteMembersFromSuperinterfaces(model, classBuilder, sat, satisfiedInterfaces);
}
}
private void generateInstantiatorDelegate(
ClassDefinitionBuilder classBuilder, ProducedType satisfiedType,
Interface iface, boolean rawifyParametersAndResults, Class klass) {
ProducedType typeMember = satisfiedType.getTypeMember(klass, Collections.<ProducedType>emptyList());
java.util.List<TypeParameter> typeParameters = klass.getTypeParameters();
java.util.List<Parameter> parameters = klass.getParameterLists().get(0).getParameters();
String instantiatorMethodName = naming.getInstantiatorMethodName(klass);
for (Parameter param : parameters) {
if (param.isDefaulted()
|| param.isSequenced()) {
final ProducedTypedReference typedParameter = typeMember.getTypedParameter(param);
// If that method has a defaulted parameter,
// we need to generate a default value method
// which also delegates to the $impl
final MethodDefinitionBuilder defaultValueDelegate = makeDelegateToCompanion(iface,
typedParameter,
PUBLIC | FINAL,
typeParameters,
typedParameter.getType(),
Naming.getDefaultedParamMethodName(klass, param),
parameters.subList(0, parameters.indexOf(param)),
rawifyParametersAndResults);
classBuilder.method(defaultValueDelegate);
final MethodDefinitionBuilder overload = makeDelegateToCompanion(iface,
typeMember,
PUBLIC | FINAL,
typeParameters,
typeMember.getType(),
instantiatorMethodName,
parameters.subList(0, parameters.indexOf(param)),
rawifyParametersAndResults);
classBuilder.method(overload);
}
}
final MethodDefinitionBuilder overload = makeDelegateToCompanion(iface,
typeMember,
PUBLIC | FINAL,
typeParameters,
typeMember.getType(),
instantiatorMethodName,
parameters,
rawifyParametersAndResults);
classBuilder.method(overload);
}
private boolean needsRawification(ProducedType type) {
final Iterator<TypeParameter> refinedTypeParameters = type.getDeclaration().getTypeParameters().iterator();
boolean rawifyParametersAndResults = false;
for (ProducedType typeArg : type.getTypeArgumentList()) {
final TypeParameter typeParam = refinedTypeParameters.next();
if (typeParam.getSatisfiedTypes().isEmpty()
&& (typeFact().isIntersection(typeArg) || typeFact().isUnion(typeArg))) {
// Use the same hack that makeJavaType() does when handling iterables
if (typeFact().getNonemptyIterableType(typeFact().getDefiniteType(typeArg)) == null) {
rawifyParametersAndResults = true;
break;
}
}
}
return rawifyParametersAndResults;
}
private boolean needsCompanionDelegate(final Class model, Declaration member) {
final boolean mostRefined;
Declaration m = model.getMember(member.getName(), null, false);
if (member instanceof Setter && m instanceof Getter) {
mostRefined = member.equals(((Getter)m).getSetter());
} else {
mostRefined = member.equals(m);
}
return mostRefined
&& (member.isDefault() || !member.isFormal());
}
/**
* Generates a method which delegates to the companion instance $Foo$impl
*/
private MethodDefinitionBuilder makeDelegateToCompanion(Interface iface,
ProducedReference typedMember, final long mods,
final java.util.List<TypeParameter> typeParameters,
final ProducedType methodType,
final String methodName, final java.util.List<Parameter> parameters,
boolean rawifyParametersAndResults) {
final MethodDefinitionBuilder concreteWrapper = MethodDefinitionBuilder.systemMethod(gen(), methodName);
concreteWrapper.modifiers(mods);
concreteWrapper.ignoreAnnotations();
concreteWrapper.isOverride(true);
if (!rawifyParametersAndResults) {
for (TypeParameter tp : typeParameters) {
concreteWrapper.typeParameter(tp);
}
}
boolean explicitReturn = false;
Declaration member = typedMember.getDeclaration();
if (!isVoid(methodType)
|| ((member instanceof Method || member instanceof Getter || member instanceof Value) && !Decl.isUnboxedVoid(member))
|| (member instanceof Method && Strategy.useBoxedVoid((Method)member))) {
explicitReturn = true;
if (typedMember instanceof ProducedTypedReference) {
concreteWrapper.resultTypeNonWidening((ProducedTypedReference)typedMember, typedMember.getType(),
rawifyParametersAndResults ? JT_RAW_TP_BOUND : 0);
} else {
concreteWrapper.resultType(null, makeJavaType((ProducedType)typedMember));
}
}
ListBuffer<JCExpression> arguments = ListBuffer.<JCExpression>lb();
for (Parameter param : parameters) {
final ProducedTypedReference typedParameter = typedMember.getTypedParameter(param);
concreteWrapper.parameter(param, typedParameter.getType(), FINAL, rawifyParametersAndResults ? JT_RAW_TP_BOUND : 0);
arguments.add(naming.makeName(param, Naming.NA_MEMBER));
}
JCExpression expr = make().Apply(
null, // TODO Type args
makeSelect(getCompanionFieldName(iface), methodName),
arguments.toList());
if (!explicitReturn) {
concreteWrapper.body(gen().make().Exec(expr));
} else {
concreteWrapper.body(gen().make().Return(expr));
}
return concreteWrapper;
}
private Boolean hasImpl(Interface iface) {
if (gen().willEraseToObject(iface.getType())) {
return false;
}
if (iface instanceof LazyInterface) {
return ((LazyInterface)iface).isCeylon();
}
return true;
}
private void transformInstantiateCompanions(
ClassDefinitionBuilder classBuilder,
Class model, Interface iface, ProducedType satisfiedType) {
at(null);
final List<JCExpression> state = List.<JCExpression>of(
expressionGen().applyErasureAndBoxing(naming.makeThis(),
model.getType(), false, true, BoxingStrategy.BOXED,
satisfiedType, ExpressionTransformer.EXPR_FOR_COMPANION));
JCExpression containerInstance = null;
JCExpression ifaceImplType = null;
if(!Decl.isToplevel(iface)){
// if it's a member type we need to qualify the new instance with its $impl container
ClassOrInterface interfaceContainer = Decl.getClassOrInterfaceContainer(iface, false);
if(interfaceContainer instanceof Interface){
ClassOrInterface modelContainer = model;
while((modelContainer = Decl.getClassOrInterfaceContainer(modelContainer, false)) != null
&& modelContainer.getType().getSupertype(interfaceContainer) == null){
// keep searching
}
Assert.that(modelContainer != null, "Could not find container that satisfies interface "
+ iface.getQualifiedNameString() + " to find qualifying instance for companion instance for "
+ model.getQualifiedNameString());
// find the right field used for the interface container impl
String containerFieldName = getCompanionFieldName((Interface)interfaceContainer);
JCExpression containerType = makeJavaType(modelContainer.getType(), JT_SATISFIES);
containerInstance = makeSelect(makeSelect(containerType, "this"), containerFieldName);
ifaceImplType = makeJavaType(satisfiedType, JT_COMPANION | JT_SATISFIES | JT_NON_QUALIFIED);
}
}
if(ifaceImplType == null){
ifaceImplType = makeJavaType(satisfiedType, JT_COMPANION | JT_SATISFIES);
}
JCExpression newInstance = make().NewClass(containerInstance,
null,
ifaceImplType,
state,
null);
final String fieldName = getCompanionFieldName(iface);
classBuilder.init(make().Exec(make().Assign(
makeSelect("this", fieldName),// TODO Use qualified name for quoting?
newInstance)));
classBuilder.field(PRIVATE | FINAL, fieldName,
makeJavaType(satisfiedType, AbstractTransformer.JT_COMPANION | JT_SATISFIES), null, false);
classBuilder.method(makeCompanionAccessor(iface, satisfiedType, true));
}
private MethodDefinitionBuilder makeCompanionAccessor(Interface iface, ProducedType satisfiedType, boolean forImplementor) {
// Doing this only for interfaces with inner classes breaks BC for implementors
// when an inner class is added to the interface. OTOH it means we
// don't have to have an access on every Ceylon interface when it
// isn't used on most of them.
boolean hasInnerClasses = false;
for (Declaration member : iface.getMembers()) {
if (member instanceof Class) {
hasInnerClasses = true;
break;
}
}
if (hasInnerClasses) {
MethodDefinitionBuilder thisMethod = MethodDefinitionBuilder.systemMethod(
this, getCompanionAccessorName(iface));
thisMethod.noAnnotations();
if (!forImplementor && Decl.isAncestorLocal(iface)) {
// For a local interface the return type cannot be a local
// companion class, because that won't be visible at the
// top level, so use Object instead
thisMethod.resultType(null, make().Type(syms().objectType));
} else {
thisMethod.resultType(null, makeJavaType(satisfiedType, JT_COMPANION));
}
if (forImplementor) {
thisMethod.isOverride(true);
} else {
thisMethod.ignoreAnnotations();
}
thisMethod.modifiers(PUBLIC);
if (forImplementor) {
thisMethod.body(make().Return(naming.makeCompanionFieldName(iface)));
} else {
thisMethod.noBody();
}
return thisMethod;
}
return null;
}
private void buildCompanion(final Tree.ClassOrInterface def,
final Interface model, ClassDefinitionBuilder classBuilder) {
at(def);
// Give the $impl companion a $this field...
ClassDefinitionBuilder companionBuilder = classBuilder.getCompanionBuilder(model);
ProducedType thisType = model.getType();
companionBuilder.field(PRIVATE | FINAL,
"$this",
makeJavaType(thisType),
null, false);
MethodDefinitionBuilder ctor = companionBuilder.addConstructor();
ctor.modifiers(model.isShared() ? PUBLIC : 0);
ParameterDefinitionBuilder pdb = ParameterDefinitionBuilder.instance(this, "$this");
pdb.type(makeJavaType(thisType), null);
// ...initialize the $this field from a ctor parameter...
ctor.parameter(pdb);
ListBuffer<JCStatement> bodyStatements = ListBuffer.<JCStatement>of(
make().Exec(
make().Assign(
makeSelect(naming.makeThis(), "$this"),
naming.makeQuotedThis())));
ctor.body(bodyStatements.toList());
}
public List<JCStatement> transformRefinementSpecifierStatement(SpecifierStatement op, ClassDefinitionBuilder classBuilder) {
List<JCStatement> result = List.<JCStatement>nil();
// Check if this is a shortcut form of formal attribute refinement
if (op.getRefinement()) {
Tree.BaseMemberExpression expr = (Tree.BaseMemberExpression)op.getBaseMemberExpression();
Declaration decl = expr.getDeclaration();
if (decl instanceof Value) {
// Now build a "fake" declaration for the attribute
Tree.AttributeDeclaration attrDecl = new Tree.AttributeDeclaration(null);
attrDecl.setDeclarationModel((Value)decl);
attrDecl.setIdentifier(expr.getIdentifier());
attrDecl.setScope(op.getScope());
// Make sure the boxing information is set correctly
BoxingDeclarationVisitor v = new CompilerBoxingDeclarationVisitor(this);
v.visit(attrDecl);
// Generate the attribute
transform(attrDecl, classBuilder);
// Generate the specifier statement
result = result.append(expressionGen().transform(op));
} else if (decl instanceof Method) {
// Now build a "fake" declaration for the method
Tree.MethodDeclaration methDecl = new Tree.MethodDeclaration(null);
Method m = (Method)decl;
methDecl.setDeclarationModel(m);
methDecl.setIdentifier(expr.getIdentifier());
methDecl.setScope(op.getScope());
methDecl.setSpecifierExpression(op.getSpecifierExpression());
for (ParameterList pl : m.getParameterLists()) {
Tree.ParameterList tpl = new Tree.ParameterList(null);
for (Parameter p : pl.getParameters()) {
Tree.Parameter tp = null;
if (p instanceof ValueParameter) {
Tree.ValueParameterDeclaration tvpd = new Tree.ValueParameterDeclaration(null);
tvpd.setDeclarationModel((ValueParameter)p);
tp = tvpd;
} else if (p instanceof FunctionalParameter) {
Tree.FunctionalParameterDeclaration tfpd = new Tree.FunctionalParameterDeclaration(null);
tfpd.setDeclarationModel((FunctionalParameter)p);
tp = tfpd;
}
tp.setScope(p.getContainer());
tp.setIdentifier(makeIdentifier(p.getName()));
tpl.addParameter(tp);
}
methDecl.addParameterList(tpl);
}
// Make sure the boxing information is set correctly
BoxingDeclarationVisitor v = new CompilerBoxingDeclarationVisitor(this);
v.visit(methDecl);
// Generate the attribute
classBuilder.method(methDecl);
}
} else {
// Normal case, just generate the specifier statement
result = result.append(expressionGen().transform(op));
}
return result;
}
private Tree.Identifier makeIdentifier(String name) {
Tree.Identifier id = new Tree.Identifier(null);
id.setText(name);
return id;
}
public void transform(AttributeDeclaration decl, ClassDefinitionBuilder classBuilder) {
final Value model = decl.getDeclarationModel();
boolean useField = Strategy.useField(model);
String attrName = decl.getIdentifier().getText();
// Only a non-formal attribute has a corresponding field
// and if a captured class parameter exists with the same name we skip this part as well
Parameter parameter = CodegenUtil.findParamForDecl(decl);
boolean createField = Strategy.createField(parameter, model);
boolean concrete = Decl.withinInterface(decl)
&& decl.getSpecifierOrInitializerExpression() != null;
if (concrete ||
(!Decl.isFormal(decl)
&& createField)) {
JCExpression initialValue = null;
if (decl.getSpecifierOrInitializerExpression() != null) {
Value declarationModel = model;
initialValue = expressionGen().transformExpression(decl.getSpecifierOrInitializerExpression().getExpression(),
CodegenUtil.getBoxingStrategy(declarationModel),
declarationModel.getType());
}
int flags = 0;
ProducedTypedReference typedRef = getTypedReference(model);
ProducedTypedReference nonWideningTypedRef = nonWideningTypeDecl(typedRef);
ProducedType nonWideningType = nonWideningType(typedRef, nonWideningTypedRef);
if (!CodegenUtil.isUnBoxed(nonWideningTypedRef.getDeclaration())) {
flags |= JT_NO_PRIMITIVES;
}
JCExpression type = makeJavaType(nonWideningType, flags);
int modifiers = (useField) ? transformAttributeFieldDeclFlags(decl) : transformLocalDeclFlags(decl);
// If the attribute is really from a parameter then don't generate a field
// (The ClassDefinitionBuilder does it in that case)
if (parameter == null
|| ((parameter instanceof ValueParameter)
&& ((ValueParameter)parameter).isHidden())) {
if (concrete) {
classBuilder.getCompanionBuilder((TypeDeclaration)model.getContainer()).field(modifiers, attrName, type, initialValue, !useField);
} else {
classBuilder.field(modifiers, attrName, type, initialValue, !useField);
}
}
}
if (useField) {
classBuilder.attribute(makeGetter(decl, false));
if (Decl.withinInterface(decl)) {
classBuilder.getCompanionBuilder((Interface)decl.getDeclarationModel().getContainer()).attribute(makeGetter(decl, true));
}
if (Decl.isMutable(decl)) {
classBuilder.attribute(makeSetter(decl, false));
if (Decl.withinInterface(decl)) {
classBuilder.getCompanionBuilder((Interface)decl.getDeclarationModel().getContainer()).attribute(makeSetter(decl, true));
}
}
}
}
public AttributeDefinitionBuilder transform(AttributeSetterDefinition decl, boolean forCompanion) {
if (Strategy.onlyOnCompanion(decl.getDeclarationModel()) && !forCompanion) {
return null;
}
String name = decl.getIdentifier().getText();
final AttributeDefinitionBuilder builder = AttributeDefinitionBuilder
/*
* We use the getter as TypedDeclaration here because this is the same type but has a refined
* declaration we can use to make sure we're not widening the attribute type.
*/
.setter(this, name, decl.getDeclarationModel().getGetter())
.modifiers(transformAttributeGetSetDeclFlags(decl.getDeclarationModel(), false));
// companion class members are never actual no matter what the Declaration says
if(forCompanion)
builder.notActual();
if (Decl.withinClass(decl) || forCompanion) {
JCBlock body = statementGen().transform(decl.getBlock());
builder.setterBlock(body);
} else {
builder.isFormal(true);
}
return builder;
}
public AttributeDefinitionBuilder transform(AttributeGetterDefinition decl, boolean forCompanion) {
if (Strategy.onlyOnCompanion(decl.getDeclarationModel()) && !forCompanion) {
return null;
}
String name = decl.getIdentifier().getText();
final AttributeDefinitionBuilder builder = AttributeDefinitionBuilder
.getter(this, name, decl.getDeclarationModel())
.modifiers(transformAttributeGetSetDeclFlags(decl.getDeclarationModel(), forCompanion));
// companion class members are never actual no matter what the Declaration says
if(forCompanion)
builder.notActual();
if (Decl.withinClass(decl) || forCompanion) {
JCBlock body = statementGen().transform(decl.getBlock());
builder.getterBlock(body);
} else {
builder.isFormal(true);
}
return builder;
}
private int transformDeclarationSharedFlags(Declaration decl){
return Decl.isShared(decl) && !Decl.isAncestorLocal(decl) ? PUBLIC : 0;
}
private int transformClassDeclFlags(ClassOrInterface cdecl) {
int result = 0;
result |= transformDeclarationSharedFlags(cdecl);
result |= (cdecl.isAbstract() || cdecl.isFormal()) && (cdecl instanceof Class) ? ABSTRACT : 0;
result |= (cdecl instanceof Interface) ? INTERFACE : 0;
result |= cdecl.isAlias() && (cdecl instanceof Class) ? FINAL : 0;
return result;
}
private int transformTypeAliasDeclFlags(TypeAlias decl) {
int result = 0;
result |= transformDeclarationSharedFlags(decl);
result |= FINAL;
return result;
}
private int transformClassDeclFlags(Tree.ClassOrInterface cdecl) {
return transformClassDeclFlags(cdecl.getDeclarationModel());
}
private int transformOverloadCtorFlags(Class typeDecl) {
return transformClassDeclFlags(typeDecl) & (PUBLIC | PRIVATE | PROTECTED);
}
private int transformMethodDeclFlags(Method def) {
int result = 0;
if (def.isToplevel()) {
result |= def.isShared() ? PUBLIC : 0;
result |= STATIC;
} else if (Decl.isLocal(def)) {
result |= def.isShared() ? PUBLIC : 0;
} else {
result |= def.isShared() ? PUBLIC : PRIVATE;
result |= def.isFormal() && !def.isDefault() ? ABSTRACT : 0;
result |= !(def.isFormal() || def.isDefault() || def.getContainer() instanceof Interface) ? FINAL : 0;
}
return result;
}
private int transformOverloadMethodDeclFlags(final Method model) {
int mods = transformMethodDeclFlags(model);
if (!Decl.withinInterface((model))) {
mods |= FINAL;
}
return mods;
}
private int transformAttributeFieldDeclFlags(Tree.AttributeDeclaration cdecl) {
int result = 0;
result |= Decl.isMutable(cdecl) ? 0 : FINAL;
result |= PRIVATE;
return result;
}
private int transformLocalDeclFlags(Tree.AttributeDeclaration cdecl) {
int result = 0;
result |= Decl.isMutable(cdecl) ? 0 : FINAL;
return result;
}
private int transformAttributeGetSetDeclFlags(TypedDeclaration tdecl, boolean forCompanion) {
if (tdecl instanceof Setter) {
// Spec says: A setter may not be annotated shared, default or
// actual. The visibility and refinement modifiers of an attribute
// with a setter are specified by annotating the matching getter.
tdecl = ((Setter)tdecl).getGetter();
}
int result = 0;
result |= tdecl.isShared() ? PUBLIC : PRIVATE;
result |= (tdecl.isFormal() && !tdecl.isDefault() && !forCompanion) ? ABSTRACT : 0;
result |= !(tdecl.isFormal() || tdecl.isDefault() || tdecl.getContainer() instanceof Interface) || forCompanion ? FINAL : 0;
return result;
}
private int transformObjectDeclFlags(Value cdecl) {
int result = 0;
result |= FINAL;
result |= !Decl.isAncestorLocal(cdecl) && Decl.isShared(cdecl) ? PUBLIC : 0;
return result;
}
private AttributeDefinitionBuilder makeGetterOrSetter(Tree.AttributeDeclaration decl, boolean forCompanion, AttributeDefinitionBuilder builder, boolean isGetter) {
at(decl);
if (forCompanion) {
if (decl.getSpecifierOrInitializerExpression() != null) {
builder.getterBlock(make().Block(0, List.<JCStatement>of(make().Return(makeErroneous()))));
} else {
JCExpression accessor = naming.makeQualifiedName(
naming.makeQuotedThis(),
decl.getDeclarationModel(),
Naming.NA_MEMBER | (isGetter ? Naming.NA_GETTER : Naming.NA_SETTER));
if (isGetter) {
builder.getterBlock(make().Block(0, List.<JCStatement>of(make().Return(
make().Apply(
null,
accessor,
List.<JCExpression>nil())))));
} else {
List<JCExpression> args = List.<JCExpression>of(naming.makeName(decl.getDeclarationModel(), Naming.NA_MEMBER | Naming.NA_IDENT));
builder.setterBlock(make().Block(0, List.<JCStatement>of(make().Exec(
make().Apply(
null,
accessor,
args)))));
}
}
}
if(forCompanion)
builder.notActual();
return builder
.modifiers(transformAttributeGetSetDeclFlags(decl.getDeclarationModel(), forCompanion))
.isFormal(Decl.isFormal(decl) && !forCompanion);
}
private AttributeDefinitionBuilder makeGetter(Tree.AttributeDeclaration decl, boolean forCompanion) {
at(decl);
String attrName = decl.getIdentifier().getText();
AttributeDefinitionBuilder getter = AttributeDefinitionBuilder
.getter(this, attrName, decl.getDeclarationModel());
return makeGetterOrSetter(decl, forCompanion, getter, true);
}
private AttributeDefinitionBuilder makeSetter(Tree.AttributeDeclaration decl, boolean forCompanion) {
at(decl);
String attrName = decl.getIdentifier().getText();
AttributeDefinitionBuilder setter = AttributeDefinitionBuilder.setter(this, attrName, decl.getDeclarationModel());
return makeGetterOrSetter(decl, forCompanion, setter, false);
}
public List<JCTree> transformWrappedMethod(Tree.AnyMethod def) {
final Method model = def.getDeclarationModel();
naming.noteDecl(model);
// Generate a wrapper class for the method
String name = def.getIdentifier().getText();
ClassDefinitionBuilder builder = ClassDefinitionBuilder.methodWrapper(this, name, Decl.isShared(def));
builder.methods(classGen().transform(def, builder));
// Toplevel method
if (Strategy.generateMain(def)) {
// Add a main() method
builder.method(makeMainForFunction(model));
}
List<JCTree> result = builder.build();
if (Decl.isLocal(def)) {
// Inner method
JCVariableDecl call = at(def).VarDef(
make().Modifiers(FINAL),
naming.getSyntheticInstanceName(model),
naming.makeSyntheticClassname(model),
makeSyntheticInstance(model));
result = result.append(call);
}
return result;
}
public List<MethodDefinitionBuilder> transform(Tree.AnyMethod def, ClassDefinitionBuilder classBuilder) {
// Transform the method body of the 'inner-most method'
List<JCStatement> body = transformMethodBody(def);
return transform(def, classBuilder, body);
}
List<MethodDefinitionBuilder> transform(Tree.AnyMethod def,
ClassDefinitionBuilder classBuilder, List<JCStatement> body) {
final Method model = def.getDeclarationModel();
final String methodName = naming.selector(model);
if (Decl.withinInterface(model)) {
// Transform it for the companion
final Block block;
final SpecifierExpression specifier;
if (def instanceof MethodDeclaration) {
block = null;
specifier = ((MethodDeclaration) def).getSpecifierExpression();
} else if (def instanceof MethodDefinition) {
block = ((MethodDefinition) def).getBlock();
specifier = null;
} else {
throw new RuntimeException();
}
boolean transformMethod = specifier != null || block != null;
boolean actualAndAnnotations = def instanceof MethodDeclaration;
List<JCStatement> cbody = specifier != null ? transformMplBody(model, body)
: block != null ? transformMethodBlock(model, block)
: null;
boolean transformOverloads = def instanceof MethodDeclaration || block != null;
int overloadsDelegator = OL_BODY | OL_IMPLEMENTOR | (def instanceof MethodDeclaration ? OL_DELEGATOR : 0);
boolean transformDefaultValues = def instanceof MethodDeclaration || block != null;
List<MethodDefinitionBuilder> companionDefs = transformMethod(def, model, methodName,
transformMethod,
actualAndAnnotations,
cbody,
transformOverloads,
overloadsDelegator,
transformDefaultValues,
false);
classBuilder.getCompanionBuilder((TypeDeclaration)model.getContainer()).methods(companionDefs);
}
List<MethodDefinitionBuilder> result = List.<MethodDefinitionBuilder>nil();
if (!Strategy.onlyOnCompanion(model)) {
// Transform it for the interface/class
List<JCStatement> cbody = !model.isInterfaceMember() ? transformMplBody(model, body) : null;
result = transformMethod(def, model, methodName, true, true,
cbody,
true,
Decl.withinInterface(model) ? 0 : OL_BODY,
true,
!Strategy.defaultParameterMethodOnSelf(model));
}
return result;
}
/**
* Transforms a method, optionally generating overloads and
* default value methods
* @param def The method
* @param model The method model
* @param methodName The method name
* @param transformMethod Whether the method itself should be transformed.
* @param actualAndAnnotations Whether the method itself is actual and has
* model annotations
* @param body The body of the method (or null for an abstract method)
* @param transformOverloads Whether to generate overload methods
* @param overloadsFlags The overload flags
* @param transformDefaultValues Whether to generate default value methods
* @param defaultValuesBody Whether the default value methods should have a body
*/
private List<MethodDefinitionBuilder> transformMethod(Tree.AnyMethod def,
final Method model, final String methodName,
boolean transformMethod, boolean actualAndAnnotations, List<JCStatement> body,
boolean transformOverloads, int overloadsFlags,
boolean transformDefaultValues, boolean defaultValuesBody) {
ListBuffer<MethodDefinitionBuilder> lb = ListBuffer.<MethodDefinitionBuilder>lb();
boolean needsRaw = false;
if (Decl.withinClassOrInterface(model)) {
final Scope refinedFrom = model.getRefinedDeclaration().getContainer();
final ProducedType inheritedFrom = ((ClassOrInterface)model.getContainer()).getType().getSupertype((TypeDeclaration)refinedFrom);
needsRaw = needsRawification(inheritedFrom);
}
final MethodDefinitionBuilder methodBuilder = MethodDefinitionBuilder.method(
this, model.isClassOrInterfaceMember(),
methodName);
final ParameterList parameterList = model.getParameterLists().get(0);
Tree.ParameterList paramList = def.getParameterLists().get(0);
for (Tree.Parameter param : paramList.getParameters()) {
Parameter parameter = param.getDeclarationModel();
methodBuilder.parameter(parameter, needsRaw ? JT_RAW_TP_BOUND : 0);
if (parameter.isDefaulted()
|| parameter.isSequenced()) {
if (model.getRefinedDeclaration() == model) {
if (transformOverloads) {
MethodDefinitionBuilder overloadBuilder = MethodDefinitionBuilder.method(this, model.isClassOrInterfaceMember(),
methodName);
MethodDefinitionBuilder overloadedMethod = makeOverloadsForDefaultedParameter(
overloadsFlags,
overloadBuilder,
model, parameterList.getParameters(), parameter);
lb.append(overloadedMethod);
}
if (transformDefaultValues) {
lb.append(makeParamDefaultValueMethod(defaultValuesBody, model, paramList, param));
}
}
}
}
if (transformMethod) {
methodBuilder.resultType(model, needsRaw ? JT_RAW_TP_BOUND : 0);
if (!needsRaw) {
copyTypeParameters(model, methodBuilder);
}
if (body != null) {
// Construct the outermost method using the body we've built so far
methodBuilder.body(body);
} else {
methodBuilder.noBody();
}
methodBuilder
.modifiers(transformMethodDeclFlags(model));
if (actualAndAnnotations) {
methodBuilder.isOverride(model.isActual())
.modelAnnotations(model.getAnnotations());
}
if (CodegenUtil.hasCompilerAnnotation(def, "test")){
methodBuilder.annotations(List.of(make().Annotation(naming.makeFQIdent("org", "junit", "Test"), List.<JCTree.JCExpression>nil())));
}
lb.append(methodBuilder);
}
return lb.toList();
}
/**
* Constructs all but the outer-most method of a {@code Method} with
* multiple parameter lists
* @param model The {@code Method} model
* @param body The inner-most body
*/
List<JCStatement> transformMplBody(Method model,
List<JCStatement> body) {
ProducedType resultType = model.getType();
for (int index = model.getParameterLists().size() - 1; index > 0; index--) {
resultType = gen().typeFact().getCallableType(resultType);
CallableBuilder cb = CallableBuilder.mpl(gen(), resultType, model.getParameterLists().get(index), body);
body = List.<JCStatement>of(make().Return(cb.build()));
}
return body;
}
private List<JCStatement> transformMethodBody(Tree.AnyMethod def) {
List<JCStatement> body = null;
final Method model = def.getDeclarationModel();
if (Decl.isDeferredOrParamInitialized(def)) {
// Uninitialized or deferred initialized method => Make a Callable field
final Parameter initializingParameter = CodegenUtil.findParamForDecl(def);
int mods = PRIVATE;
JCExpression initialValue;
if (initializingParameter != null) {
mods |= FINAL;
int namingOptions = Naming.NA_MEMBER;
if (initializingParameter.getContainer() instanceof Method) {
// We're initializing a local method, which will have a
// class wrapper of the same name as the param, so
// the param gets renamed
namingOptions |= Naming.NA_ALIASED;
}
initialValue = naming.makeName(initializingParameter, namingOptions);
} else {
// The field isn't initialized by a parameter, but later in the block
initialValue = makeNull();
}
current().field(mods, model.getName(), makeJavaType(typeFact().getCallableType(model.getType())), initialValue, false);
ListBuffer<JCExpression> args = ListBuffer.<JCExpression>lb();
for (Parameter param : model.getParameterLists().get(0).getParameters()) {
args.append(naming.makeName(param, Naming.NA_MEMBER));
}
JCExpression call = make().Apply(null, makeSelect(
model.getName(), "$call"), args.toList());
call = gen().expressionGen().applyErasureAndBoxing(call, model.getType(),
true, BoxingStrategy.UNBOXED, model.getType());
JCStatement stmt;
if (isVoid(def)) {
stmt = make().Exec(call);
} else {
stmt = make().Return(call);
}
JCStatement result;
if (initializingParameter == null) {
// If the field isn't initialized by a parameter we have to
// cope with the possibility that it's never initialized
final JCBinary cond = make().Binary(JCTree.EQ, naming.makeName(model, Naming.NA_MEMBER), makeNull());
final JCStatement throw_ = make().Throw(make().NewClass(null, null,
make().Type(syms().ceylonUninitializedMethodErrorType),
List.<JCExpression>nil(),
null));
result = make().If(cond, throw_, stmt);
} else {
result = stmt;
}
return List.<JCStatement>of(result);
} else if (def instanceof Tree.MethodDefinition) {
Scope container = model.getContainer();
boolean isInterface = container instanceof com.redhat.ceylon.compiler.typechecker.model.Interface;
if(!isInterface){
final Block block = ((Tree.MethodDefinition) def).getBlock();
body = transformMethodBlock(model, block);
}
} else if (def instanceof MethodDeclaration
&& ((MethodDeclaration) def).getSpecifierExpression() != null) {
body = transformSpecifiedMethodBody((MethodDeclaration)def, ((MethodDeclaration) def).getSpecifierExpression());
}
return body;
}
private List<JCStatement> transformMethodBlock(final Method model,
final Block block) {
List<JCStatement> body;
boolean prevNoExpressionlessReturn = statementGen().noExpressionlessReturn;
try {
statementGen().noExpressionlessReturn = Decl.isMpl(model) || Strategy.useBoxedVoid(model);
body = statementGen().transform(block).getStatements();
} finally {
statementGen().noExpressionlessReturn = prevNoExpressionlessReturn;
}
// We void methods need to have their Callables return null
// so adjust here.
if ((Decl.isMpl(model) || Strategy.useBoxedVoid(model))
&& !block.getDefinitelyReturns()) {
if (Decl.isUnboxedVoid(model)) {
body = body.append(make().Return(makeNull()));
} else {
body = body.append(make().Return(makeErroneous(block, "non-void method doesn't definitely return")));
}
}
return body;
}
List<JCStatement> transformSpecifiedMethodBody(Tree.MethodDeclaration def, SpecifierExpression specifierExpression) {
final Method model = def.getDeclarationModel();
List<JCStatement> body;
MethodDeclaration methodDecl = (MethodDeclaration)def;
boolean returnNull = false;
JCExpression bodyExpr;
Tree.Term term = null;
if (specifierExpression != null
&& specifierExpression.getExpression() != null) {
term = specifierExpression.getExpression().getTerm();
}
if (term instanceof Tree.FunctionArgument) {
// Method specified with lambda: Don't bother generating a
// Callable, just transform the expr to use as the method body.
Tree.FunctionArgument fa = (Tree.FunctionArgument)term;
ProducedType resultType = model.getType();
returnNull = isVoid(resultType) && fa.getExpression().getUnboxed();
final java.util.List<com.redhat.ceylon.compiler.typechecker.tree.Tree.Parameter> lambdaParams = fa.getParameterLists().get(0).getParameters();
final java.util.List<com.redhat.ceylon.compiler.typechecker.tree.Tree.Parameter> defParams = def.getParameterLists().get(0).getParameters();
for (int ii = 0; ii < lambdaParams.size(); ii++) {
naming.addVariableSubst(lambdaParams.get(ii).getIdentifier().getText(),
defParams.get(ii).getIdentifier().getText());
}
bodyExpr = gen().expressionGen().transformExpression(fa.getExpression(), BoxingStrategy.UNBOXED, null);
bodyExpr = gen().expressionGen().applyErasureAndBoxing(bodyExpr, resultType,
true,
model.getUnboxed() ? BoxingStrategy.UNBOXED : BoxingStrategy.BOXED,
resultType);
for (int ii = 0; ii < lambdaParams.size(); ii++) {
naming.removeVariableSubst(lambdaParams.get(ii).getIdentifier().getText(),
null);
}
} else {
returnNull = isVoid(getReturnTypeOfCallable(term.getTypeModel())) && term.getUnboxed();
InvocationBuilder specifierBuilder = InvocationBuilder.forSpecifierInvocation(gen(), specifierExpression, methodDecl.getDeclarationModel());
bodyExpr = specifierBuilder.build();
}
if (!Decl.isUnboxedVoid(model) || Strategy.useBoxedVoid(model)) {
if (returnNull) {
body = List.<JCStatement>of(make().Exec(bodyExpr), make().Return(makeNull()));
} else {
body = List.<JCStatement>of(make().Return(bodyExpr));
}
} else {
body = List.<JCStatement>of(make().Exec(bodyExpr));
}
return body;
}
private boolean isVoid(Tree.Declaration def) {
if (def instanceof Tree.AnyMethod) {
return gen().isVoid(((Tree.AnyMethod)def).getType().getTypeModel());
} else if (def instanceof Tree.AnyClass) {
// Consider classes void since ctors don't require a return statement
return true;
}
throw new RuntimeException();
}
private boolean isVoid(Declaration def) {
if (def instanceof Method) {
return gen().isVoid(((Method)def).getType());
} else if (def instanceof Class) {
// Consider classes void since ctors don't require a return statement
return true;
}
throw new RuntimeException();
}
private static int OL_BODY = 1<<0;
private static int OL_IMPLEMENTOR = 1<<1;
private static int OL_DELEGATOR = 1<<2;
/**
* Generates an overloaded method where all the defaulted parameters after
* and including the given {@code currentParam} are given their default
* values. Using Java-side overloading ensures positional invocations
* are binary compatible when new defaulted parameters are appended to a
* parameter list.
*/
private MethodDefinitionBuilder makeOverloadsForDefaultedParameter(
int flags,
MethodDefinitionBuilder overloadBuilder,
Declaration model,
Tree.ParameterList paramList,
Tree.Parameter currentParam) {
at(currentParam);
java.util.List<Parameter> parameters = new java.util.ArrayList<Parameter>(paramList.getParameters().size());
for (Tree.Parameter param : paramList.getParameters()) {
parameters.add(param.getDeclarationModel());
}
return makeOverloadsForDefaultedParameter(flags,
overloadBuilder, model,
parameters, currentParam != null ? currentParam.getDeclarationModel() : null);
}
/**
* Generates an overloaded method where all the defaulted parameters after
* and including the given {@code currentParam} are given their default
* values. Using Java-side overloading ensures positional invocations
* are binary compatible when new defaulted parameters are appended to a
* parameter list.
*/
private MethodDefinitionBuilder makeOverloadsForDefaultedParameter(
int flags, MethodDefinitionBuilder overloadBuilder,
final Declaration model, java.util.List<Parameter> parameters,
final Parameter currentParam) {
// need annotations for BC, but the method isn't really there
overloadBuilder.ignoreAnnotations();
final JCExpression methName;
if (model instanceof Method) {
long mods = transformOverloadMethodDeclFlags((Method)model);
if ((flags & OL_BODY) != 0) {
mods &= ~ABSTRACT;
}
if ((flags & OL_IMPLEMENTOR) != 0 || (flags & OL_DELEGATOR) != 0) {
mods |= FINAL;
}
overloadBuilder.modifiers(mods);
JCExpression qualifier;
if ((flags & OL_DELEGATOR) != 0) {
qualifier = naming.makeQuotedThis();
} else {
qualifier = null;
}
methName = naming.makeQualifiedName(qualifier, (Method)model, Naming.NA_MEMBER);
overloadBuilder.resultType((Method)model, 0);
} else if (model instanceof Class) {
Class klass = (Class)model;
if (Strategy.generateInstantiator(model)) {
overloadBuilder.ignoreAnnotations();
- if (!klass.isAlias() && Strategy.generateInstantiator(klass.getExtendedTypeDeclaration())){
+ if (!klass.isAlias()
+ && Strategy.generateInstantiator(klass.getExtendedTypeDeclaration())
+ && klass.isActual()){
//&& ((Class)model).getExtendedTypeDeclaration().getContainer() instanceof Class) {
overloadBuilder.isOverride(true);
}
// remove the FINAL bit in case it gets set, because that is valid for a class decl, but
// not for a method if in an interface
overloadBuilder.modifiers(transformClassDeclFlags(klass) & ~FINAL);
methName = naming.makeInstantiatorMethodName(null, klass);
JCExpression resultType;
ProducedType type = klass.isAlias() ? klass.getExtendedType() : klass.getType();
if (Decl.isAncestorLocal(model)) {
// We can't expose a local type name to a place it's not visible
resultType = make().Type(syms().objectType);
} else {
resultType = makeJavaType(type);
}
overloadBuilder.resultType(null, resultType);
} else {
overloadBuilder.modifiers(transformOverloadCtorFlags(klass));
methName = naming.makeThis();
}
} else {
throw new RuntimeException();
}
// TODO MPL
if (model instanceof Method) {
copyTypeParameters((Functional)model, overloadBuilder);
} else if (Strategy.generateInstantiator(model)) {
for (TypeParameter tp : typeParametersForInstantiator((Class)model)) {
overloadBuilder.typeParameter(tp);
}
}
// TODO Some simple default expressions (e.g. literals, null and
// base expressions it might be worth inlining the expression rather
// than calling the default value method.
// TODO This really belongs in the invocation builder
ListBuffer<JCExpression> args = ListBuffer.<JCExpression>lb();
ListBuffer<JCStatement> vars = ListBuffer.<JCStatement>lb();
final Naming.SyntheticName companionInstanceName = naming.temp("$impl$");
if (model instanceof Class
&& !Strategy.defaultParameterMethodStatic(model)
&& !Strategy.defaultParameterMethodOnOuter(model)
&& currentParam != null) {
Class classModel = (Class)model;
vars.append(makeVar(companionInstanceName,
makeJavaType(classModel.getType(), AbstractTransformer.JT_COMPANION),
make().NewClass(null,
null,
makeJavaType(classModel.getType(), AbstractTransformer.JT_COMPANION),
List.<JCExpression>nil(), null)));
}
boolean useDefault = false;
for (Parameter param2 : parameters) {
if (param2 == currentParam) {
useDefault = true;
}
if (useDefault) {
List<JCExpression> typeArguments = List.<JCExpression>nil();
JCIdent dpmQualifier;
if (Strategy.defaultParameterMethodOnSelf(model)
|| Strategy.defaultParameterMethodOnOuter(model)
|| (flags & OL_IMPLEMENTOR) != 0) {
dpmQualifier = null;
} else if (Strategy.defaultParameterMethodStatic(model)){
dpmQualifier = null;
if (model instanceof Class) {
typeArguments = typeArguments((Class)model);
} else if (model instanceof Method) {
typeArguments = typeArguments((Method)model);
}
} else {
dpmQualifier = companionInstanceName.makeIdent();
}
JCExpression defaultValueMethodName = naming.makeDefaultedParamMethod(dpmQualifier, param2);
Naming.SyntheticName varName = naming.temp("$"+param2.getName()+"$");
final ProducedType paramType;
if (param2 instanceof FunctionalParameter) {
paramType = typeFact().getCallableType(param2.getType());
} else {
paramType = param2.getType();
}
vars.append(makeVar(varName,
makeJavaType(paramType),
make().Apply(typeArguments,
defaultValueMethodName,
ListBuffer.<JCExpression>lb().appendList(args).toList())));
args.add(varName.makeIdent());
} else {
overloadBuilder.parameter(param2, 0);
args.add(naming.makeName(param2, Naming.NA_MEMBER | Naming.NA_ALIASED));
}
}
// TODO Type args on method call
if ((flags & OL_BODY) != 0) {
JCExpression invocation;
if (Strategy.generateInstantiator(model)) {
Class klass = (Class) model;
ProducedType type = klass.isAlias() ? klass.getExtendedType() : klass.getType();
invocation = make().NewClass(null,
null,
makeJavaType(type, JT_CLASS_NEW | JT_NON_QUALIFIED),
args.toList(),
null);
} else {
invocation = make().Apply(List.<JCExpression>nil(),
methName, args.toList());
}
if (!isVoid(model)
|| (model instanceof Method && Strategy.useBoxedVoid((Method)model))
|| Strategy.generateInstantiator(model)) {
if (!vars.isEmpty()) {
invocation = make().LetExpr(vars.toList(), invocation);
}
overloadBuilder.body(make().Return(invocation));
} else {
vars.append(make().Exec(invocation));
invocation = make().LetExpr(vars.toList(), makeNull());
overloadBuilder.body(make().Exec(invocation));
}
} else {
overloadBuilder.noBody();
}
return overloadBuilder;
}
/**
* When generating an instantiator method if the inner class has a type
* parameter with the same name as a type parameter of an outer type, then the
* instantiator method shouldn't declare its own type parameter of that
* name -- it should use the captured one. This method filters out the
* type parameters of the inner class which are the same as type parameters
* of the outer class so that they can be captured.
*/
private java.util.List<TypeParameter> typeParametersForInstantiator(final Class model) {
Assert.that(Strategy.generateInstantiator(model));
java.util.List<TypeParameter> filtered = new ArrayList<TypeParameter>();
java.util.List<TypeParameter> tps = model.getTypeParameters();
if (tps != null) {
for (TypeParameter tp : tps) {
boolean omit = false;
Scope s = model.getContainer();
while (!(s instanceof Package)) {
if (s instanceof Generic) {
for (TypeParameter outerTp : ((Generic)s).getTypeParameters()) {
if (tp.getName().equals(outerTp.getName())) {
omit = true;
}
}
}
s = s.getContainer();
}
if (!omit) {
filtered.add(tp);
}
}
}
return filtered;
}
/**
* Creates a (possibly abstract) method for retrieving the value for a
* defaulted parameter
*/
private MethodDefinitionBuilder makeParamDefaultValueMethod(boolean noBody, Declaration container,
Tree.ParameterList params, Tree.Parameter currentParam) {
at(currentParam);
Parameter parameter = currentParam.getDeclarationModel();
String name = Naming.getDefaultedParamMethodName(container, parameter );
MethodDefinitionBuilder methodBuilder = MethodDefinitionBuilder.systemMethod(this, name);
methodBuilder.ignoreAnnotations();
int modifiers = 0;
if (noBody) {
modifiers |= PUBLIC | ABSTRACT;
} else if (!(container instanceof Class
&& Strategy.defaultParameterMethodStatic(container))) {
// initializers can override parameter defaults
modifiers |= FINAL;
}
if (container.isShared()) {
modifiers |= PUBLIC;
} else if (!container.isToplevel()
&& !noBody){
modifiers |= PRIVATE;
}
if (Strategy.defaultParameterMethodStatic(container)) {
modifiers |= STATIC;
}
methodBuilder.modifiers(modifiers);
if (container instanceof Method) {
copyTypeParameters((Method)container, methodBuilder);
} else if (Decl.isToplevel(container)
&& container instanceof Class) {
copyTypeParameters((Class)container, methodBuilder);
}
// Add any of the preceding parameters as parameters to the method
for (Tree.Parameter p : params.getParameters()) {
if (p == currentParam) {
break;
}
at(p);
methodBuilder.parameter(p.getDeclarationModel(), 0);
}
// The method's return type is the same as the parameter's type
methodBuilder.resultType(parameter, parameter.getType(), 0);
// The implementation of the method
if (noBody) {
methodBuilder.noBody();
} else {
JCExpression expr = expressionGen().transform(currentParam);
JCBlock body = at(currentParam).Block(0, List.<JCStatement> of(at(currentParam).Return(expr)));
methodBuilder.block(body);
}
return methodBuilder;
}
public List<JCTree> transformObjectDefinition(Tree.ObjectDefinition def, ClassDefinitionBuilder containingClassBuilder) {
return transformObject(def, def.getDeclarationModel(),
def.getAnonymousClass(), containingClassBuilder, Decl.isLocal(def));
}
public List<JCTree> transformObjectArgument(Tree.ObjectArgument def) {
return transformObject(def, def.getDeclarationModel(),
def.getAnonymousClass(), null, false);
}
private List<JCTree> transformObject(Tree.StatementOrArgument def, Value model,
Class klass,
ClassDefinitionBuilder containingClassBuilder,
boolean makeLocalInstance) {
naming.noteDecl(model);
String name = model.getName();
ClassDefinitionBuilder objectClassBuilder = ClassDefinitionBuilder.object(
this, name);
CeylonVisitor visitor = gen().visitor;
final ListBuffer<JCTree> prevDefs = visitor.defs;
final boolean prevInInitializer = visitor.inInitializer;
final ClassDefinitionBuilder prevClassBuilder = visitor.classBuilder;
List<JCStatement> childDefs;
try {
visitor.defs = new ListBuffer<JCTree>();
visitor.inInitializer = true;
visitor.classBuilder = objectClassBuilder;
def.visitChildren(visitor);
childDefs = (List<JCStatement>)visitor.getResult().toList();
} finally {
visitor.classBuilder = prevClassBuilder;
visitor.inInitializer = prevInInitializer;
visitor.defs = prevDefs;
}
satisfaction(klass, objectClassBuilder);
TypeDeclaration decl = model.getType().getDeclaration();
if (Decl.isToplevel(model)
&& def instanceof Tree.ObjectDefinition) {
// generate a field and getter
AttributeDefinitionBuilder builder = AttributeDefinitionBuilder
// TODO attr build take a JCExpression className
.wrapped(this, null, model.getName(), model, true)
.immutable()
.initialValue(makeNewClass(naming.makeName(model, Naming.NA_FQ | Naming.NA_WRAPPER)))
.is(PUBLIC, Decl.isShared(decl))
.is(STATIC, true);
objectClassBuilder.defs(builder.build());
}
List<JCTree> result = objectClassBuilder
.annotations(makeAtObject())
.modelAnnotations(model.getAnnotations())
.modifiers(transformObjectDeclFlags(model))
.constructorModifiers(PRIVATE)
.satisfies(decl.getSatisfiedTypes())
.init(childDefs)
.build();
if (makeLocalInstance) {
result = result.append(makeLocalIdentityInstance(name, objectClassBuilder.getClassName(), false));
} else if (Decl.withinClassOrInterface(model)) {
boolean visible = Decl.isCaptured(model);
int modifiers = FINAL | ((visible) ? PRIVATE : 0);
JCExpression type = makeJavaType(klass.getType());
JCExpression initialValue = makeNewClass(makeJavaType(klass.getType()), null);
containingClassBuilder.field(modifiers, name, type, initialValue, !visible);
if (visible) {
result = result.appendList(AttributeDefinitionBuilder
.getter(this, name, model)
.modifiers(transformAttributeGetSetDeclFlags(model, false))
.build());
}
}
return result;
}
/**
* Makes a {@code main()} method which calls the given top-level method
* @param def
*/
private MethodDefinitionBuilder makeMainForClass(ClassOrInterface model) {
at(null);
if(model.isAlias())
model = model.getExtendedTypeDeclaration();
JCExpression nameId = makeJavaType(model.getType(), JT_RAW);
JCNewClass expr = make().NewClass(null, null, nameId, List.<JCTree.JCExpression>nil(), null);
return makeMainMethod(model, expr);
}
/**
* Makes a {@code main()} method which calls the given top-level method
* @param method
*/
private MethodDefinitionBuilder makeMainForFunction(Method method) {
at(null);
JCExpression qualifiedName = naming.makeName(method, Naming.NA_FQ | Naming.NA_WRAPPER | Naming.NA_MEMBER);
MethodDefinitionBuilder mainMethod = makeMainMethod(method, make().Apply(null, qualifiedName, List.<JCTree.JCExpression>nil()));
return mainMethod;
}
/**
* Makes a {@code main()} method which calls the given callee
* (a no-args method or class)
* @param decl
* @param callee
*/
private MethodDefinitionBuilder makeMainMethod(Declaration decl, JCExpression callee) {
// Add a main() method
MethodDefinitionBuilder methbuilder = MethodDefinitionBuilder
.main(this)
.ignoreAnnotations();
// Add call to process.setupArguments
JCExpression argsId = makeUnquotedIdent("args");
JCMethodInvocation processExpr = make().Apply(null, naming.makeLanguageValue("process"), List.<JCTree.JCExpression>nil());
methbuilder.body(make().Exec(make().Apply(null, makeSelect(processExpr, "setupArguments"), List.<JCTree.JCExpression>of(argsId))));
// Add call to toplevel method
methbuilder.body(make().Exec(callee));
return methbuilder;
}
void copyTypeParameters(Functional def, MethodDefinitionBuilder methodBuilder) {
if (def.getTypeParameters() != null) {
for (TypeParameter t : def.getTypeParameters()) {
methodBuilder.typeParameter(t);
}
}
}
public List<JCTree> transform(final Tree.TypeAliasDeclaration def) {
final TypeAlias model = def.getDeclarationModel();
// we only create types for aliases so they can be imported with the model loader
// and since we can't import local declarations let's just not create those types
// in that case
if(Decl.isAncestorLocal(def))
return List.nil();
naming.noteDecl(model);
String ceylonClassName = def.getIdentifier().getText();
final String javaClassName = Naming.quoteClassName(def.getIdentifier().getText());
ClassDefinitionBuilder classBuilder = ClassDefinitionBuilder
.klass(this, javaClassName, ceylonClassName);
// class alias
classBuilder.constructorModifiers(PRIVATE);
classBuilder.annotations(makeAtTypeAlias(model.getExtendedType()));
classBuilder.isAlias(true);
// make sure we set the container in case we move it out
addAtContainer(classBuilder, model);
visitClassOrInterfaceDefinition(def, classBuilder);
return classBuilder
.modelAnnotations(model.getAnnotations())
.modifiers(transformTypeAliasDeclFlags(model))
.satisfies(model.getSatisfiedTypes())
.build();
}
}
| true | true | private MethodDefinitionBuilder makeOverloadsForDefaultedParameter(
int flags, MethodDefinitionBuilder overloadBuilder,
final Declaration model, java.util.List<Parameter> parameters,
final Parameter currentParam) {
// need annotations for BC, but the method isn't really there
overloadBuilder.ignoreAnnotations();
final JCExpression methName;
if (model instanceof Method) {
long mods = transformOverloadMethodDeclFlags((Method)model);
if ((flags & OL_BODY) != 0) {
mods &= ~ABSTRACT;
}
if ((flags & OL_IMPLEMENTOR) != 0 || (flags & OL_DELEGATOR) != 0) {
mods |= FINAL;
}
overloadBuilder.modifiers(mods);
JCExpression qualifier;
if ((flags & OL_DELEGATOR) != 0) {
qualifier = naming.makeQuotedThis();
} else {
qualifier = null;
}
methName = naming.makeQualifiedName(qualifier, (Method)model, Naming.NA_MEMBER);
overloadBuilder.resultType((Method)model, 0);
} else if (model instanceof Class) {
Class klass = (Class)model;
if (Strategy.generateInstantiator(model)) {
overloadBuilder.ignoreAnnotations();
if (!klass.isAlias() && Strategy.generateInstantiator(klass.getExtendedTypeDeclaration())){
//&& ((Class)model).getExtendedTypeDeclaration().getContainer() instanceof Class) {
overloadBuilder.isOverride(true);
}
// remove the FINAL bit in case it gets set, because that is valid for a class decl, but
// not for a method if in an interface
overloadBuilder.modifiers(transformClassDeclFlags(klass) & ~FINAL);
methName = naming.makeInstantiatorMethodName(null, klass);
JCExpression resultType;
ProducedType type = klass.isAlias() ? klass.getExtendedType() : klass.getType();
if (Decl.isAncestorLocal(model)) {
// We can't expose a local type name to a place it's not visible
resultType = make().Type(syms().objectType);
} else {
resultType = makeJavaType(type);
}
overloadBuilder.resultType(null, resultType);
} else {
overloadBuilder.modifiers(transformOverloadCtorFlags(klass));
methName = naming.makeThis();
}
} else {
throw new RuntimeException();
}
// TODO MPL
if (model instanceof Method) {
copyTypeParameters((Functional)model, overloadBuilder);
} else if (Strategy.generateInstantiator(model)) {
for (TypeParameter tp : typeParametersForInstantiator((Class)model)) {
overloadBuilder.typeParameter(tp);
}
}
// TODO Some simple default expressions (e.g. literals, null and
// base expressions it might be worth inlining the expression rather
// than calling the default value method.
// TODO This really belongs in the invocation builder
ListBuffer<JCExpression> args = ListBuffer.<JCExpression>lb();
ListBuffer<JCStatement> vars = ListBuffer.<JCStatement>lb();
final Naming.SyntheticName companionInstanceName = naming.temp("$impl$");
if (model instanceof Class
&& !Strategy.defaultParameterMethodStatic(model)
&& !Strategy.defaultParameterMethodOnOuter(model)
&& currentParam != null) {
Class classModel = (Class)model;
vars.append(makeVar(companionInstanceName,
makeJavaType(classModel.getType(), AbstractTransformer.JT_COMPANION),
make().NewClass(null,
null,
makeJavaType(classModel.getType(), AbstractTransformer.JT_COMPANION),
List.<JCExpression>nil(), null)));
}
boolean useDefault = false;
for (Parameter param2 : parameters) {
if (param2 == currentParam) {
useDefault = true;
}
if (useDefault) {
List<JCExpression> typeArguments = List.<JCExpression>nil();
JCIdent dpmQualifier;
if (Strategy.defaultParameterMethodOnSelf(model)
|| Strategy.defaultParameterMethodOnOuter(model)
|| (flags & OL_IMPLEMENTOR) != 0) {
dpmQualifier = null;
} else if (Strategy.defaultParameterMethodStatic(model)){
dpmQualifier = null;
if (model instanceof Class) {
typeArguments = typeArguments((Class)model);
} else if (model instanceof Method) {
typeArguments = typeArguments((Method)model);
}
} else {
dpmQualifier = companionInstanceName.makeIdent();
}
JCExpression defaultValueMethodName = naming.makeDefaultedParamMethod(dpmQualifier, param2);
Naming.SyntheticName varName = naming.temp("$"+param2.getName()+"$");
final ProducedType paramType;
if (param2 instanceof FunctionalParameter) {
paramType = typeFact().getCallableType(param2.getType());
} else {
paramType = param2.getType();
}
vars.append(makeVar(varName,
makeJavaType(paramType),
make().Apply(typeArguments,
defaultValueMethodName,
ListBuffer.<JCExpression>lb().appendList(args).toList())));
args.add(varName.makeIdent());
} else {
overloadBuilder.parameter(param2, 0);
args.add(naming.makeName(param2, Naming.NA_MEMBER | Naming.NA_ALIASED));
}
}
// TODO Type args on method call
if ((flags & OL_BODY) != 0) {
JCExpression invocation;
if (Strategy.generateInstantiator(model)) {
Class klass = (Class) model;
ProducedType type = klass.isAlias() ? klass.getExtendedType() : klass.getType();
invocation = make().NewClass(null,
null,
makeJavaType(type, JT_CLASS_NEW | JT_NON_QUALIFIED),
args.toList(),
null);
} else {
invocation = make().Apply(List.<JCExpression>nil(),
methName, args.toList());
}
if (!isVoid(model)
|| (model instanceof Method && Strategy.useBoxedVoid((Method)model))
|| Strategy.generateInstantiator(model)) {
if (!vars.isEmpty()) {
invocation = make().LetExpr(vars.toList(), invocation);
}
overloadBuilder.body(make().Return(invocation));
} else {
vars.append(make().Exec(invocation));
invocation = make().LetExpr(vars.toList(), makeNull());
overloadBuilder.body(make().Exec(invocation));
}
} else {
overloadBuilder.noBody();
}
return overloadBuilder;
}
| private MethodDefinitionBuilder makeOverloadsForDefaultedParameter(
int flags, MethodDefinitionBuilder overloadBuilder,
final Declaration model, java.util.List<Parameter> parameters,
final Parameter currentParam) {
// need annotations for BC, but the method isn't really there
overloadBuilder.ignoreAnnotations();
final JCExpression methName;
if (model instanceof Method) {
long mods = transformOverloadMethodDeclFlags((Method)model);
if ((flags & OL_BODY) != 0) {
mods &= ~ABSTRACT;
}
if ((flags & OL_IMPLEMENTOR) != 0 || (flags & OL_DELEGATOR) != 0) {
mods |= FINAL;
}
overloadBuilder.modifiers(mods);
JCExpression qualifier;
if ((flags & OL_DELEGATOR) != 0) {
qualifier = naming.makeQuotedThis();
} else {
qualifier = null;
}
methName = naming.makeQualifiedName(qualifier, (Method)model, Naming.NA_MEMBER);
overloadBuilder.resultType((Method)model, 0);
} else if (model instanceof Class) {
Class klass = (Class)model;
if (Strategy.generateInstantiator(model)) {
overloadBuilder.ignoreAnnotations();
if (!klass.isAlias()
&& Strategy.generateInstantiator(klass.getExtendedTypeDeclaration())
&& klass.isActual()){
//&& ((Class)model).getExtendedTypeDeclaration().getContainer() instanceof Class) {
overloadBuilder.isOverride(true);
}
// remove the FINAL bit in case it gets set, because that is valid for a class decl, but
// not for a method if in an interface
overloadBuilder.modifiers(transformClassDeclFlags(klass) & ~FINAL);
methName = naming.makeInstantiatorMethodName(null, klass);
JCExpression resultType;
ProducedType type = klass.isAlias() ? klass.getExtendedType() : klass.getType();
if (Decl.isAncestorLocal(model)) {
// We can't expose a local type name to a place it's not visible
resultType = make().Type(syms().objectType);
} else {
resultType = makeJavaType(type);
}
overloadBuilder.resultType(null, resultType);
} else {
overloadBuilder.modifiers(transformOverloadCtorFlags(klass));
methName = naming.makeThis();
}
} else {
throw new RuntimeException();
}
// TODO MPL
if (model instanceof Method) {
copyTypeParameters((Functional)model, overloadBuilder);
} else if (Strategy.generateInstantiator(model)) {
for (TypeParameter tp : typeParametersForInstantiator((Class)model)) {
overloadBuilder.typeParameter(tp);
}
}
// TODO Some simple default expressions (e.g. literals, null and
// base expressions it might be worth inlining the expression rather
// than calling the default value method.
// TODO This really belongs in the invocation builder
ListBuffer<JCExpression> args = ListBuffer.<JCExpression>lb();
ListBuffer<JCStatement> vars = ListBuffer.<JCStatement>lb();
final Naming.SyntheticName companionInstanceName = naming.temp("$impl$");
if (model instanceof Class
&& !Strategy.defaultParameterMethodStatic(model)
&& !Strategy.defaultParameterMethodOnOuter(model)
&& currentParam != null) {
Class classModel = (Class)model;
vars.append(makeVar(companionInstanceName,
makeJavaType(classModel.getType(), AbstractTransformer.JT_COMPANION),
make().NewClass(null,
null,
makeJavaType(classModel.getType(), AbstractTransformer.JT_COMPANION),
List.<JCExpression>nil(), null)));
}
boolean useDefault = false;
for (Parameter param2 : parameters) {
if (param2 == currentParam) {
useDefault = true;
}
if (useDefault) {
List<JCExpression> typeArguments = List.<JCExpression>nil();
JCIdent dpmQualifier;
if (Strategy.defaultParameterMethodOnSelf(model)
|| Strategy.defaultParameterMethodOnOuter(model)
|| (flags & OL_IMPLEMENTOR) != 0) {
dpmQualifier = null;
} else if (Strategy.defaultParameterMethodStatic(model)){
dpmQualifier = null;
if (model instanceof Class) {
typeArguments = typeArguments((Class)model);
} else if (model instanceof Method) {
typeArguments = typeArguments((Method)model);
}
} else {
dpmQualifier = companionInstanceName.makeIdent();
}
JCExpression defaultValueMethodName = naming.makeDefaultedParamMethod(dpmQualifier, param2);
Naming.SyntheticName varName = naming.temp("$"+param2.getName()+"$");
final ProducedType paramType;
if (param2 instanceof FunctionalParameter) {
paramType = typeFact().getCallableType(param2.getType());
} else {
paramType = param2.getType();
}
vars.append(makeVar(varName,
makeJavaType(paramType),
make().Apply(typeArguments,
defaultValueMethodName,
ListBuffer.<JCExpression>lb().appendList(args).toList())));
args.add(varName.makeIdent());
} else {
overloadBuilder.parameter(param2, 0);
args.add(naming.makeName(param2, Naming.NA_MEMBER | Naming.NA_ALIASED));
}
}
// TODO Type args on method call
if ((flags & OL_BODY) != 0) {
JCExpression invocation;
if (Strategy.generateInstantiator(model)) {
Class klass = (Class) model;
ProducedType type = klass.isAlias() ? klass.getExtendedType() : klass.getType();
invocation = make().NewClass(null,
null,
makeJavaType(type, JT_CLASS_NEW | JT_NON_QUALIFIED),
args.toList(),
null);
} else {
invocation = make().Apply(List.<JCExpression>nil(),
methName, args.toList());
}
if (!isVoid(model)
|| (model instanceof Method && Strategy.useBoxedVoid((Method)model))
|| Strategy.generateInstantiator(model)) {
if (!vars.isEmpty()) {
invocation = make().LetExpr(vars.toList(), invocation);
}
overloadBuilder.body(make().Return(invocation));
} else {
vars.append(make().Exec(invocation));
invocation = make().LetExpr(vars.toList(), makeNull());
overloadBuilder.body(make().Exec(invocation));
}
} else {
overloadBuilder.noBody();
}
return overloadBuilder;
}
|
diff --git a/src/org/concord/energy3d/scene/SceneManager.java b/src/org/concord/energy3d/scene/SceneManager.java
index 6952d92a..0616d04e 100644
--- a/src/org/concord/energy3d/scene/SceneManager.java
+++ b/src/org/concord/energy3d/scene/SceneManager.java
@@ -1,1075 +1,1080 @@
package org.concord.energy3d.scene;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.nio.FloatBuffer;
import java.util.concurrent.Callable;
import org.concord.energy3d.gui.MainFrame;
import org.concord.energy3d.model.Door;
import org.concord.energy3d.model.Floor;
import org.concord.energy3d.model.Foundation;
import org.concord.energy3d.model.HipRoof;
import org.concord.energy3d.model.HousePart;
import org.concord.energy3d.model.PyramidRoof;
import org.concord.energy3d.model.Wall;
import org.concord.energy3d.model.Window;
import org.concord.energy3d.scene.CameraControl.ButtonAction;
import org.concord.energy3d.util.Blinker;
import org.concord.energy3d.util.FontManager;
import org.concord.energy3d.util.SelectUtil;
import org.concord.energy3d.util.Util;
import org.poly2tri.Poly2Tri;
import org.poly2tri.geometry.polygon.Polygon;
import org.poly2tri.geometry.polygon.PolygonPoint;
import org.poly2tri.triangulation.tools.ardor3d.ArdorMeshMapper;
import com.ardor3d.annotation.MainThread;
import com.ardor3d.bounding.BoundingVolume;
import com.ardor3d.extension.effect.bloom.BloomRenderPass;
import com.ardor3d.extension.model.collada.jdom.ColladaImporter;
import com.ardor3d.extension.model.collada.jdom.data.ColladaStorage;
import com.ardor3d.extension.shadow.map.ParallelSplitShadowMapPass;
import com.ardor3d.framework.Canvas;
import com.ardor3d.framework.DisplaySettings;
import com.ardor3d.framework.FrameHandler;
import com.ardor3d.framework.Updater;
import com.ardor3d.framework.jogl.JoglAwtCanvas;
import com.ardor3d.framework.jogl.JoglCanvasRenderer;
import com.ardor3d.image.Texture;
import com.ardor3d.image.TextureStoreFormat;
import com.ardor3d.image.util.AWTImageLoader;
import com.ardor3d.input.ButtonState;
import com.ardor3d.input.Key;
import com.ardor3d.input.MouseButton;
import com.ardor3d.input.MouseState;
import com.ardor3d.input.PhysicalLayer;
import com.ardor3d.input.awt.AwtFocusWrapper;
import com.ardor3d.input.awt.AwtKeyboardWrapper;
import com.ardor3d.input.awt.AwtMouseManager;
import com.ardor3d.input.awt.AwtMouseWrapper;
import com.ardor3d.input.logical.InputTrigger;
import com.ardor3d.input.logical.KeyHeldCondition;
import com.ardor3d.input.logical.KeyPressedCondition;
import com.ardor3d.input.logical.KeyReleasedCondition;
import com.ardor3d.input.logical.LogicalLayer;
import com.ardor3d.input.logical.MouseButtonPressedCondition;
import com.ardor3d.input.logical.MouseButtonReleasedCondition;
import com.ardor3d.input.logical.MouseMovedCondition;
import com.ardor3d.input.logical.MouseWheelMovedCondition;
import com.ardor3d.input.logical.TriggerAction;
import com.ardor3d.input.logical.TwoInputStates;
import com.ardor3d.intersection.PickResults;
import com.ardor3d.light.DirectionalLight;
import com.ardor3d.math.ColorRGBA;
import com.ardor3d.math.MathUtils;
import com.ardor3d.math.Matrix3;
import com.ardor3d.math.Ray3;
import com.ardor3d.math.Transform;
import com.ardor3d.math.Vector3;
import com.ardor3d.renderer.Camera;
import com.ardor3d.renderer.Camera.ProjectionMode;
import com.ardor3d.renderer.Renderer;
import com.ardor3d.renderer.TextureRendererFactory;
import com.ardor3d.renderer.jogl.JoglTextureRendererProvider;
import com.ardor3d.renderer.pass.BasicPassManager;
import com.ardor3d.renderer.pass.RenderPass;
import com.ardor3d.renderer.queue.RenderBucketType;
import com.ardor3d.renderer.state.BlendState;
import com.ardor3d.renderer.state.ClipState;
import com.ardor3d.renderer.state.LightState;
import com.ardor3d.renderer.state.MaterialState;
import com.ardor3d.renderer.state.MaterialState.ColorMaterial;
import com.ardor3d.renderer.state.TextureState;
import com.ardor3d.renderer.state.ZBufferState;
import com.ardor3d.scenegraph.Line;
import com.ardor3d.scenegraph.Mesh;
import com.ardor3d.scenegraph.Node;
import com.ardor3d.scenegraph.Spatial;
import com.ardor3d.scenegraph.controller.SpatialController;
import com.ardor3d.scenegraph.extension.CameraNode;
import com.ardor3d.scenegraph.hint.CullHint;
import com.ardor3d.scenegraph.hint.LightCombineMode;
import com.ardor3d.scenegraph.shape.Cylinder;
import com.ardor3d.scenegraph.shape.Dome;
import com.ardor3d.scenegraph.shape.Quad;
import com.ardor3d.scenegraph.shape.Sphere;
import com.ardor3d.ui.text.BMText;
import com.ardor3d.util.ContextGarbageCollector;
import com.ardor3d.util.GameTaskQueue;
import com.ardor3d.util.GameTaskQueueManager;
import com.ardor3d.util.ReadOnlyTimer;
import com.ardor3d.util.TextureManager;
import com.ardor3d.util.Timer;
import com.ardor3d.util.geom.BufferUtils;
import com.ardor3d.util.resource.ResourceLocatorTool;
import com.ardor3d.util.resource.ResourceSource;
import com.ardor3d.util.resource.SimpleResourceLocator;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
public class SceneManager implements com.ardor3d.framework.Scene, Runnable, Updater {
public enum Operation {
SELECT, RESIZE, DRAW_WALL, DRAW_DOOR, DRAW_ROOF, DRAW_ROOF_HIP, DRAW_WINDOW, DRAW_FOUNDATION, DRAW_FLOOR
}
public enum CameraMode {
ORBIT, FIRST_PERSON
}
public enum ViewMode {
NORMAL, TOP_VIEW, PRINT_PREVIEW, PRINT
}
private static final double MOVE_SPEED = 5;
static public final GameTaskQueueManager taskManager = GameTaskQueueManager.getManager("Task Manager");
static private final SceneManager instance = new SceneManager(MainFrame.getInstance().getContentPane());
static private final boolean JOGL = true;
private final Canvas canvas;
private final FrameHandler frameHandler;
private final LogicalLayer logicalLayer;
private final Node root = new Node("Root");
private final Node backgroundRoot = new Node("Scenary Root");
private final BasicPassManager passManager = new BasicPassManager();
private final Mesh floor = new Quad("Floor", 200, 200);
private final LightState lightState = new LightState();
private boolean exit = false;
private boolean rotAnim = false;
private HousePart drawn = null;
private Operation operation = Operation.SELECT;
private double sunAngle = 45, sunBaseAngle = 135;
private CameraControl control;
private ParallelSplitShadowMapPass shadowPass;
private Sphere sun;
private Node sunHeliodon;
private Node sunRot;
private boolean sunControl;
private boolean sunAnim;
private BloomRenderPass bloomRenderPass;
private ViewMode viewMode = ViewMode.NORMAL;
private boolean operationFlag = false;
private CameraNode cameraNode;
private boolean operationStick = false;
private TwoInputStates moveState;
private boolean drawBounds = false;
private long lastRenderTime;
public static SceneManager getInstance() {
return instance;
}
private SceneManager(final Container panel) {// throws LWJGLException {
System.out.print("Initializing scene manager...");
// instance = this;
// root.attachChild(Scene.getRoot());
// final DisplaySettings settings = new DisplaySettings(800, 600, 32, 60, 0, 8, 0, 0, false, false);
final DisplaySettings settings = new DisplaySettings(800, 600, 32, 60, 0, 8, 0, 8, false, false);
if (JOGL)
canvas = new JoglAwtCanvas(settings, new JoglCanvasRenderer(this));
// else
// canvas = new LwjglAwtCanvas(settings, new LwjglCanvasRenderer(this));
frameHandler = new FrameHandler(new Timer());
frameHandler.addCanvas(canvas);
logicalLayer = new LogicalLayer();
final AwtMouseWrapper mouseWrapper = new AwtMouseWrapper((Component) canvas, new AwtMouseManager((Component) canvas));
final AwtKeyboardWrapper keyboardWrapper = new AwtKeyboardWrapper((Component) canvas);
final AwtFocusWrapper focusWrapper = new AwtFocusWrapper((Component) canvas);
final PhysicalLayer physicalLayer = new PhysicalLayer(keyboardWrapper, mouseWrapper, focusWrapper);
logicalLayer.registerInput(canvas, physicalLayer);
frameHandler.addUpdater(this);
frameHandler.addUpdater(PrintController.getInstance());
frameHandler.addUpdater(Blinker.getInstance());
if (JOGL)
TextureRendererFactory.INSTANCE.setProvider(new JoglTextureRendererProvider());
// else
// TextureRendererFactory.INSTANCE.setProvider(new LwjglTextureRendererProvider());
panel.addComponentListener(new java.awt.event.ComponentAdapter() {
public void componentResized(java.awt.event.ComponentEvent e) {
resizeCamera();
}
});
panel.add((Component) canvas, "Center");
System.out.println("done");
}
@MainThread
public void init() {
System.out.print("Initializing scene manager models...");
AWTImageLoader.registerLoader();
try {
ResourceLocatorTool.addResourceLocator(ResourceLocatorTool.TYPE_TEXTURE, new SimpleResourceLocator(SceneManager.class.getClassLoader().getResource("org/concord/energy3d/resources/images/")));
ResourceLocatorTool.addResourceLocator(ResourceLocatorTool.TYPE_TEXTURE, new SimpleResourceLocator(SceneManager.class.getClassLoader().getResource("org/concord/energy3d/resources/")));
ResourceLocatorTool.addResourceLocator(ResourceLocatorTool.TYPE_MODEL, new SimpleResourceLocator(SceneManager.class.getClassLoader().getResource("org/concord/energy3d/resources/")));
} catch (final Exception ex) {
ex.printStackTrace();
}
cameraNode = new CameraNode("Camera Node", canvas.getCanvasRenderer().getCamera());
root.attachChild(cameraNode);
cameraNode.updateFromCamera();
setCameraControl(CameraMode.ORBIT);
resetCamera(ViewMode.NORMAL);
// enable depth test
final ZBufferState zbuf = new ZBufferState();
zbuf.setEnabled(true);
zbuf.setFunction(ZBufferState.TestFunction.LessThanOrEqualTo);
root.setRenderState(zbuf);
final DirectionalLight light = new DirectionalLight();
light.setDirection(new Vector3(0, 0, -1));
light.setAmbient(new ColorRGBA(1, 1, 1, 1));
light.setEnabled(true);
lightState.setEnabled(false);
lightState.attach(light);
root.setRenderState(lightState);
backgroundRoot.attachChild(createSky());
backgroundRoot.attachChild(createFloor());
backgroundRoot.attachChild(createAxis());
root.attachChild(backgroundRoot);
root.attachChild(Scene.getRoot());
final RenderPass rootPass = new RenderPass();
rootPass.add(root);
passManager.add(rootPass);
// shadowPass = new ParallelSplitShadowMapPass(light, 512, 3);
shadowPass = new ParallelSplitShadowMapPass(light, 3072, 3);
shadowPass.setUseObjectCullFace(true);
shadowPass.add(floor);
shadowPass.add(Scene.getRoot());
shadowPass.addOccluder(Scene.getRoot());
createSunHeliodon();
updateSunHeliodon();
Scene.getInstance();
SelectUtil.init(floor, Scene.getRoot());
registerInputTriggers();
taskManager.update(new Callable<Object>() {
public Object call() throws Exception {
final Spatial compass = loadCompassModel();
compass.setScale(0.1);
compass.setTranslation(-1, -0.7, 2);
cameraNode.attachChild(compass);
return null;
}
});
root.updateGeometricState(0, true);
System.out.println("done");
}
protected void test() {
PolygonPoint p[] = new PolygonPoint[4];
p[0] = new PolygonPoint(-1.0292539544430312, 0.09999999999999999, 1.362032135164121);
p[1] = new PolygonPoint(0.8537302277848444, 0.09999999999999991, 1.362032135164121);
p[2] = new PolygonPoint(0.8537302277848444, 1.1, 1.362032135164121);
p[3] = new PolygonPoint(-1.0292539544430312, 1.1, 1.362032135164121);
Polygon polygon = new Polygon(p);
double data[] = new double[] { -0.8409555362202437, 0.8999999999999999, 1.362032135164121, -0.5114333043303654, 0.8999999999999999, 1.362032135164121, -0.5114333043303654, 0.6, 1.362032135164121, -0.8409555362202437, 0.6, 1.362032135164121, -0.3702094906632748, 0.8999999999999999, 1.362032135164121, -0.08776186332909341, 0.8999999999999999, 1.362032135164121, -0.08776186332909341, 0.6, 1.362032135164121, -0.3702094906632748, 0.6, 1.362032135164121, 0.053461950337997166, 0.8999999999999999, 1.362032135164121, 0.33590957767217855, 0.8999999999999999, 1.362032135164121, 0.33590957767217855, 0.6, 1.362032135164121, 0.053461950337997166, 0.6, 1.362032135164121, 0.47713339133926946, 0.8999999999999999, 1.362032135164121, 0.6654318095620568, 0.8999999999999999, 1.362032135164121, 0.6654318095620568, 0.5999999999999999, 1.362032135164121, 0.47713339133926946, 0.5999999999999999, 1.362032135164121, -0.7938809316645468, 0.44999999999999996, 1.362032135164121, -0.5114333043303654,
0.44999999999999996, 1.362032135164121, -0.5114333043303654, 0.14999999999999997, 1.362032135164121, -0.7938809316645468, 0.14999999999999997, 1.362032135164121, -0.3702094906632748, 0.44999999999999996, 1.362032135164121, -0.08776186332909341, 0.44999999999999996, 1.362032135164121, -0.08776186332909341, 0.14999999999999994, 1.362032135164121, -0.3702094906632748, 0.14999999999999997, 1.362032135164121, 0.053461950337997166, 0.44999999999999996, 1.362032135164121, 0.33590957767217855, 0.4499999999999999, 1.362032135164121, 0.33590957767217855, 0.1499999999999999, 1.362032135164121, 0.053461950337997166, 0.14999999999999994, 1.362032135164121, 0.47713339133926946, 0.4499999999999999, 1.362032135164121, 0.6654318095620568, 0.4499999999999999, 1.362032135164121, 0.6654318095620568, 0.1499999999999999, 1.362032135164121, 0.47713339133926946, 0.1499999999999999, 1.362032135164121 };
for (int i = 0; i < data.length; i += 12) {
p = new PolygonPoint[] { new PolygonPoint(data[i], data[i + 1], data[i + 2]), new PolygonPoint(data[i + 3], data[i + 4], data[i + 5]), new PolygonPoint(data[i + 6], data[i + 7], data[i + 8]), new PolygonPoint(data[i + 9], data[i + 10], data[i + 11]) };
Polygon hole = new Polygon(p);
polygon.addHole(hole);
}
Mesh mesh = new Mesh();
mesh.setDefaultColor(ColorRGBA.BLUE);
root.attachChild(mesh);
Poly2Tri.triangulate(polygon);
ArdorMeshMapper.updateTriangleMesh(mesh, polygon);
}
public void run() {
frameHandler.init();
while (!exit) {
frameHandler.updateFrame();
final double syncNS = 1000000000.0 / 60;
long sinceLast = System.nanoTime() - lastRenderTime;
if (sinceLast < syncNS) {
try {
Thread.sleep(Math.round((syncNS - sinceLast) / 1000000L));
} catch (Exception e) {
e.printStackTrace();
}
}
lastRenderTime = System.nanoTime();
}
}
public void update(final ReadOnlyTimer timer) {
final double tpf = timer.getTimePerFrame();
HousePart.clearDrawFlags();
passManager.updatePasses(tpf);
logicalLayer.checkTriggers(tpf);
taskManager.getQueue(GameTaskQueue.UPDATE).execute(canvas.getCanvasRenderer().getRenderer());
Scene.getInstance().update();
if (rotAnim && viewMode == ViewMode.NORMAL) {
final Matrix3 rotate = new Matrix3();
rotate.fromAngleNormalAxis(1 * MathUtils.DEG_TO_RAD, Vector3.UNIT_Z);
final Camera camera = canvas.getCanvasRenderer().getCamera();
camera.setLocation(rotate.applyPre(camera.getLocation(), null));
camera.lookAt(0, 0, 1, Vector3.UNIT_Z);
getCameraNode().updateFromCamera();
}
if (sunAnim) {
sunAngle++;
updateSunHeliodon();
}
root.updateGeometricState(tpf);
}
public boolean renderUnto(Renderer renderer) {
// try {
// final boolean doRender = moveState != null;
if (moveState != null)
executeMouseMove();
// else
// return false;
if (operationFlag)
executeOperation();
// if (!Scene.getInstance().getParts().isEmpty())
// Scene.getInstance().renderTexture(renderer);
// Scene.getInstance().init();
if (drawBounds && drawn != null)
com.ardor3d.util.geom.Debugger.drawBounds(drawn.getRoot(), renderer, true);
// com.ardor3d.util.geom.Debugger.drawBounds(Scene.getInstance().getOriginalHouseRoot(), renderer, true);
// if (doRender)
passManager.renderPasses(renderer);
// } catch (Exception e) {
// e.printStackTrace();
// }
return true;
}
private Spatial createSunHeliodon() {
sunHeliodon = new Node();
Cylinder cyl = new Cylinder("Sun Curve", 10, 50, 5, 0.3);
Transform trans = new Transform();
trans.setMatrix(new Matrix3().fromAngleAxis(Math.PI / 2, Vector3.UNIT_X));
cyl.setDefaultColor(ColorRGBA.YELLOW);
cyl.setTransform(trans);
sunHeliodon.attachChild(cyl);
final ClipState cs = new ClipState();
cs.setEnableClipPlane(0, true);
cs.setClipPlaneEquation(0, 0, 0, 1, -0.19);
cyl.setRenderState(cs);
Cylinder baseCyl = new Cylinder("Sun Curve", 10, 50, 5, 0.2);
baseCyl.setTranslation(0, 0, 0.1);
sunHeliodon.attachChild(baseCyl);
sun = new Sphere("Sun", 20, 20, 0.3);
sun.setTranslation(0, 0, 5);
sunRot = new Node("Sun Root");
sunRot.attachChild(sun);
sunHeliodon.attachChild(sunRot);
reverseNormals(sun.getMeshData().getNormalBuffer());
MaterialState material = new MaterialState();
material.setEmissive(ColorRGBA.WHITE);
sun.setRenderState(material);
return sunHeliodon;
}
private void reverseNormals(FloatBuffer normalBuffer) {
normalBuffer.rewind();
int i = 0;
while (normalBuffer.hasRemaining()) {
float f = normalBuffer.get();
normalBuffer.position(i);
normalBuffer.put(-f);
i++;
}
}
private void updateSunHeliodon() {
if (sunAnim)
sunAngle %= 180;
else {
sunAngle = Math.max(sunAngle, 1);
sunAngle = Math.min(sunAngle, 179);
}
final Matrix3 m = new Matrix3().fromAngleAxis((-90 + sunAngle) * Math.PI / 180, Vector3.UNIT_Y);
sunRot.setRotation(m);
sunBaseAngle = sunBaseAngle % 360;
sunHeliodon.setRotation(new Matrix3().fromAngleAxis(sunBaseAngle * Math.PI / 180, Vector3.UNIT_Z));
DirectionalLight light = (DirectionalLight) lightState.get(0);
sunHeliodon.updateWorldTransform(true);
light.setDirection(sun.getWorldTranslation().negate(null));
sunHeliodon.updateGeometricState(0);
}
public PickResults doPick(Ray3 pickRay) {
return null;
}
public Canvas getCanvas() {
return canvas;
}
private Mesh createFloor() {
// floor = new Quad("Floor", 200, 200);
floor.setDefaultColor(new ColorRGBA(0, 1, 0, 0.5f));
final BlendState blendState = new BlendState();
blendState.setBlendEnabled(true);
blendState.setTestEnabled(true);
floor.setRenderState(blendState);
floor.getSceneHints().setRenderBucketType(RenderBucketType.Transparent);
floor.getSceneHints().setLightCombineMode(LightCombineMode.Off);
final MaterialState ms = new MaterialState();
ms.setColorMaterial(ColorMaterial.Diffuse);
floor.setRenderState(ms);
floor.updateModelBound();
return floor;
}
private Mesh createSky() {
final Dome sky = new Dome("Sky", 100, 100, 100);
sky.setRotation(new Matrix3().fromAngles(Math.PI / 2, 0, 0));
final TextureState ts = new TextureState();
ts.setTexture(TextureManager.load("sky.jpg", Texture.MinificationFilter.Trilinear, TextureStoreFormat.GuessNoCompressedFormat, true));
sky.setRenderState(ts);
sky.getSceneHints().setLightCombineMode(LightCombineMode.Off);
return sky;
}
private Spatial createAxis() {
final int axisLen = 100;
final FloatBuffer verts = BufferUtils.createVector3Buffer(12);
verts.put(0).put(0).put(0);
verts.put(-axisLen).put(0).put(0);
verts.put(0).put(0).put(0);
verts.put(axisLen).put(0).put(0);
verts.put(0).put(0).put(0);
verts.put(0).put(-axisLen).put(0);
verts.put(0).put(0).put(0);
verts.put(0).put(axisLen).put(0);
verts.put(0).put(0).put(0);
verts.put(0).put(0).put(-axisLen);
verts.put(0).put(0).put(0);
verts.put(0).put(0).put(axisLen);
final FloatBuffer colors = BufferUtils.createColorBuffer(12);
colors.put(1).put(0).put(0).put(0);
colors.put(1).put(0).put(0).put(0);
colors.put(1).put(0).put(0).put(0);
colors.put(1).put(0).put(0).put(0);
colors.put(0).put(1).put(0).put(0);
colors.put(0).put(1).put(0).put(0);
colors.put(0).put(1).put(0).put(0);
colors.put(0).put(1).put(0).put(0);
colors.put(0).put(0).put(1).put(0);
colors.put(0).put(0).put(1).put(0);
colors.put(0).put(0).put(1).put(0);
colors.put(0).put(0).put(1).put(0);
final Line axis = new Line("Axis", verts, null, colors, null);
axis.getSceneHints().setLightCombineMode(LightCombineMode.Off);
return axis;
}
private void registerInputTriggers() {
logicalLayer.registerTrigger(new InputTrigger(new MouseButtonPressedCondition(MouseButton.LEFT), new TriggerAction() {
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
taskManager.update(new Callable<Object>() {
public Object call() throws Exception {
MouseState mouseState = inputStates.getCurrent().getMouseState();
if (operation == Operation.SELECT || operation == Operation.RESIZE) {
if (drawn == null || drawn.isDrawCompleted()) {
if (drawn != null)
drawn.hidePoints();
drawn = SelectUtil.selectHousePart(mouseState.getX(), mouseState.getY(), true);
System.out.println("Clicked on: " + drawn);
SelectUtil.nextPickLayer();
}
} else
drawn.addPoint(mouseState.getX(), mouseState.getY());
enableDisableRotationControl();
return null;
}
});
}
}));
logicalLayer.registerTrigger(new InputTrigger(new MouseButtonReleasedCondition(MouseButton.LEFT), new TriggerAction() {
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
taskManager.update(new Callable<Object>() {
public Object call() throws Exception {
MouseState mouseState = inputStates.getCurrent().getMouseState();
if (operation == Operation.SELECT || operation == Operation.RESIZE) {
if (drawn != null && !drawn.isDrawCompleted())
drawn.complete();
} else {
if (!drawn.isDrawCompleted())
drawn.addPoint(mouseState.getX(), mouseState.getY());
if (drawn.isDrawCompleted()) {
drawn.hidePoints();
drawn = null;
if (operationStick)
operationFlag = true;
else {
MainFrame.getInstance().deselect();
}
}
}
enableDisableRotationControl();
updateHeliodonSize();
return null;
}
});
}
}));
logicalLayer.registerTrigger(new InputTrigger(new MouseMovedCondition(), new TriggerAction() {
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
// mouseMoveFlag = true;
moveState = inputStates;
}
}));
final KeyHeldCondition cond1 = new KeyHeldCondition(Key.LCONTROL);
final MouseMovedCondition cond2 = new MouseMovedCondition();
final Predicate<TwoInputStates> condition = Predicates.and(cond1, cond2);
logicalLayer.registerTrigger(new InputTrigger(condition, new TriggerAction() {
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
int dy = inputStates.getCurrent().getMouseState().getDy();
if (dy < -4)
dy = -4;
if (dy > 4)
dy = 4;
zoom(canvas, tpf, dy / 5.0);
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.LSHIFT), new TriggerAction() {
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
SelectUtil.setPickLayer(0);
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyReleasedCondition(Key.LSHIFT), new TriggerAction() {
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
SelectUtil.setPickLayer(-1);
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.DELETE), new TriggerAction() {
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
- Scene.getInstance().remove(drawn);
- drawn = null;
+ taskManager.update(new Callable<Object>() {
+ public Object call() throws Exception {
+ Scene.getInstance().remove(drawn);
+ drawn = null;
+ return null;
+ }
+ });
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyHeldCondition(Key.ESCAPE), new TriggerAction() {
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
hideAllEditPoints();
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyHeldCondition(Key.Q), new TriggerAction() {
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
moveUpDown(source, tpf, true);
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyHeldCondition(Key.Z), new TriggerAction() {
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
moveUpDown(source, tpf, false);
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyHeldCondition(Key.W), new TriggerAction() {
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
if (viewMode == ViewMode.TOP_VIEW)
moveUpDown(source, tpf, true);
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyHeldCondition(Key.S), new TriggerAction() {
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
if (viewMode == ViewMode.TOP_VIEW)
moveUpDown(source, tpf, false);
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.R), new TriggerAction() {
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
toggleRotation();
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.ZERO), new TriggerAction() {
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
resetCamera(viewMode);
}
}));
logicalLayer.registerTrigger(new InputTrigger(new MouseWheelMovedCondition(), new TriggerAction() {
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
zoom(source, tpf, inputStates.getCurrent().getMouseState().getDwheel());
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyHeldCondition(Key.UP), new TriggerAction() {
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
if (!sunControl)
return;
sunAngle--;
updateSunHeliodon();
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyHeldCondition(Key.DOWN), new TriggerAction() {
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
if (!sunControl)
return;
sunAngle++;
updateSunHeliodon();
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyHeldCondition(Key.RIGHT), new TriggerAction() {
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
if (!sunControl)
return;
sunBaseAngle++;
updateSunHeliodon();
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyHeldCondition(Key.LEFT), new TriggerAction() {
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
if (!sunControl)
return;
sunBaseAngle--;
updateSunHeliodon();
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.B), new TriggerAction() {
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
drawBounds = !drawBounds;
if (drawBounds)
System.out.println("Enabling draw bounds...");
else
System.out.println("Disabling draw bounds...");
}
}));
}
public void setCameraControl(CameraMode type) {
// this.cameraMode = type;
if (control != null)
control.removeTriggers(logicalLayer);
if (type == CameraMode.ORBIT)
control = new OrbitControl(Vector3.UNIT_Z);
else if (type == CameraMode.FIRST_PERSON)
control = new FirstPersonControl(Vector3.UNIT_Z);
control.setupKeyboardTriggers(logicalLayer);
control.setupMouseTriggers(logicalLayer, true);
control.setMoveSpeed(MOVE_SPEED);
control.setKeyRotateSpeed(1);
}
private void hideAllEditPoints() {
for (HousePart part : Scene.getInstance().getParts())
part.hidePoints();
}
public void resetCamera(final ViewMode viewMode) {
this.viewMode = viewMode;
final Camera camera = canvas.getCanvasRenderer().getCamera();
// setCameraControl(cameraMode);
control.setMouseButtonActions(ButtonAction.ROTATE, ButtonAction.MOVE);
control.setMoveSpeed(MOVE_SPEED);
Vector3 loc = new Vector3(1.0f, -8.0f, 1.0f);
Vector3 left = new Vector3(-1.0f, 0.0f, 0.0f);
Vector3 up = new Vector3(0.0f, 0.0f, 1.0f);
Vector3 dir = new Vector3(0.0f, 1.0f, 0.0f);
setCompassVisible(viewMode == ViewMode.NORMAL);
if (viewMode == ViewMode.NORMAL) {
camera.setProjectionMode(ProjectionMode.Perspective);
resizeCamera();
} else if (viewMode == ViewMode.TOP_VIEW) {
camera.setProjectionMode(ProjectionMode.Parallel);
control.setMouseButtonActions(ButtonAction.MOVE, ButtonAction.NONE);
control.setMoveSpeed(5 * MOVE_SPEED);
loc = new Vector3(0, 0, 10);
up = new Vector3(0.0f, -1.0f, 0.0f);
dir = new Vector3(0.0f, 0.0f, -1.0f);
resizeCamera(2);
} else if (viewMode == ViewMode.PRINT) {
control.setMouseButtonActions(ButtonAction.MOVE, ButtonAction.MOVE);
camera.setProjectionMode(ProjectionMode.Parallel);
loc = new Vector3(0, -1, 0);
final double pageWidth = PrintController.getInstance().getPageWidth();
final double pageHeight = PrintController.getInstance().getPageHeight();
final double ratio = (double) camera.getWidth() / camera.getHeight();
if (ratio > pageWidth / pageHeight)
resizeCamera(pageHeight * ratio);
else
resizeCamera(pageWidth);
} else if (viewMode == ViewMode.PRINT_PREVIEW) {
control.setMouseButtonActions(ButtonAction.MOVE, ButtonAction.MOVE);
camera.setProjectionMode(ProjectionMode.Perspective);
final int rows = PrintController.getInstance().getRows();
final double pageHeight = PrintController.getInstance().getPageHeight() + PrintController.getMargin();
final double w = PrintController.getInstance().getCols() * (PrintController.getInstance().getPageWidth() + PrintController.getMargin());
final double h = rows * pageHeight;
loc = new Vector3(0, -Math.max(w, h), rows % 2 != 0 ? 0 : pageHeight / 2);
resizeCamera(PrintController.getInstance().getPageWidth());
}
camera.setFrame(loc, left, up, dir);
cameraNode.updateFromCamera();
}
private void resizeCamera() {
resizeCamera(2);
}
private void resizeCamera(final double orthoWidth) {
final Camera camera = canvas.getCanvasRenderer().getCamera();
if (camera == null)
return;
final Dimension size = ((Component) canvas).getSize();
camera.resize(size.width, size.height);
final double ratio = (double) size.width / size.height;
if (camera.getProjectionMode() == ProjectionMode.Parallel)
camera.setFrustum(0.01, 200, -orthoWidth / 2, orthoWidth / 2, -orthoWidth / ratio / 2, orthoWidth / ratio / 2);
else
camera.setFrustumPerspective(45.0, ratio, 0.01, 200);
}
public void toggleRotation() {
rotAnim = !rotAnim;
}
private void zoom(final Canvas canvas, final double tpf, double val) {
if (Camera.getCurrentCamera().getProjectionMode() == ProjectionMode.Parallel) {
final double fac = val > 0 ? 1.1 : 0.9;
final Camera camera = canvas.getCanvasRenderer().getCamera();
camera.setFrustumTop(camera.getFrustumTop() * fac);
camera.setFrustumBottom(camera.getFrustumBottom() * fac);
camera.setFrustumLeft(camera.getFrustumLeft() * fac);
camera.setFrustumRight(camera.getFrustumRight() * fac);
camera.update();
control.setMoveSpeed(2 * camera.getFrustumTop() * camera.getFrustumTop());
} else {
final Camera camera = canvas.getCanvasRenderer().getCamera();
final Vector3 loc = new Vector3(camera.getDirection()).multiplyLocal(-val * MOVE_SPEED * 10 * tpf).addLocal(camera.getLocation());
camera.setLocation(loc);
if (control instanceof OrbitControl)
((OrbitControl) control).computeNewFrontDistance();
}
getCameraNode().updateFromCamera();
}
private void moveUpDown(final Canvas canvas, final double tpf, boolean up) {
final Camera camera = canvas.getCanvasRenderer().getCamera();
final Vector3 loc = new Vector3(camera.getUp());
if (viewMode == ViewMode.TOP_VIEW)
up = !up;
loc.multiplyLocal((up ? 1 : -1) * MOVE_SPEED * tpf).addLocal(camera.getLocation());
camera.setLocation(loc);
}
public void setOperation(Operation operation) {
this.operationStick = false;
this.operation = operation;
this.operationFlag = true;
}
public void setOperationStick(boolean stick) {
this.operationStick = stick;
}
public void executeOperation() {
System.out.println("executeOperation()");
this.operationFlag = false;
if (drawn != null && !drawn.isDrawCompleted())
Scene.getInstance().remove(drawn);
for (HousePart part : Scene.getInstance().getParts())
if (part instanceof Foundation) {
((Foundation) part).setResizeHouseMode(operation == Operation.RESIZE);
}
if (viewMode != ViewMode.PRINT_PREVIEW)
Scene.getInstance().drawResizeBounds();
drawn = newHousePart();
enableDisableRotationControl();
}
private HousePart newHousePart() {
HousePart drawn = null;
if (operation == Operation.DRAW_WALL)
drawn = new Wall();
else if (operation == Operation.DRAW_DOOR)
drawn = new Door();
else if (operation == Operation.DRAW_WINDOW)
drawn = new Window();
else if (operation == Operation.DRAW_ROOF)
drawn = new PyramidRoof();
else if (operation == Operation.DRAW_ROOF_HIP)
drawn = new HipRoof();
else if (operation == Operation.DRAW_FLOOR)
drawn = new Floor();
else if (operation == Operation.DRAW_FOUNDATION)
drawn = new Foundation();
if (drawn != null)
Scene.getInstance().add(drawn);
return drawn;
}
public Operation getOperation() {
return operation;
}
public void setLighting(final boolean enable) {
taskManager.update(new Callable<Object>() {
public Object call() throws Exception {
lightState.setEnabled(enable);
root.updateWorldRenderStates(true);
return null;
}
});
}
public void setSunControl(boolean selected) {
this.sunControl = selected;
taskManager.update(new Callable<Object>() {
public Object call() throws Exception {
if (sunControl) {
updateHeliodonSize();
root.attachChild(sunHeliodon);
} else
root.detachChild(sunHeliodon);
if (bloomRenderPass != null)
passManager.remove(bloomRenderPass);
if (sunControl) {
bloomRenderPass = new BloomRenderPass(canvas.getCanvasRenderer().getCamera(), 4);
if (!bloomRenderPass.isSupported()) {
System.out.println("Bloom not supported!");
} else {
bloomRenderPass.add(sun);
}
passManager.add(bloomRenderPass);
}
enableDisableRotationControl();
return null;
}
});
}
public void setSunAnim(boolean selected) {
this.sunAnim = selected;
}
public void enableDisableRotationControl() {
if ((operation == Operation.SELECT || operation == Operation.RESIZE) && (drawn == null || drawn.isDrawCompleted())) // && viewMode != ViewMode.TOP_VIEW) // && viewMode != ViewMode.PRINT_PREVIEW)
control.setMouseEnabled(true);
else
control.setMouseEnabled(false);
if (sunControl)
control.setKeyRotateSpeed(0);
else
control.setKeyRotateSpeed(1);
}
public HousePart getSelectedPart() {
return drawn;
}
public boolean isTopView() {
return viewMode == ViewMode.TOP_VIEW;
}
public void exit() {
System.out.print("exiting...");
this.exit = true;
canvas.getCanvasRenderer().makeCurrentContext();
ContextGarbageCollector.doFinalCleanup(canvas.getCanvasRenderer().getRenderer());
System.out.println("done");
System.exit(0);
}
public void updatePrintPreviewScene(boolean printPreview) {
// if (printPreview) {
// resetCamera(ViewMode.PRINT_PREVIEW);
// root.detachChild(floor);
// root.detachChild(axis);
// root.detachChild(sky);
// } else {
// resetCamera(ViewMode.NORMAL);
// root.attachChild(floor);
// root.attachChild(axis);
// root.attachChild(sky);
// }
resetCamera(printPreview ? ViewMode.PRINT_PREVIEW : ViewMode.NORMAL);
backgroundRoot.getSceneHints().setCullHint(printPreview ? CullHint.Always : CullHint.Inherit);
}
public void setShadow(boolean shadow) {
if (shadow)
passManager.add(shadowPass);
else
passManager.remove(shadowPass);
}
public CameraNode getCameraNode() {
return cameraNode;
}
private Node loadCompassModel() {
System.out.print("Loading compass...");
final ResourceSource source = ResourceLocatorTool.locateResource(ResourceLocatorTool.TYPE_MODEL, "compass.dae");
final ColladaImporter colladaImporter = new ColladaImporter();
// Load the collada scene
final ColladaStorage storage = colladaImporter.load(source);
final Node compass = storage.getScene();
BMText txt;
final double Z = 0.2;
txt = new BMText("N", "N", FontManager.getInstance().getAnnotationFont());
txt.setAutoRotate(false);
txt.setTranslation(3, -0.3, Z);
txt.setRotation(new Matrix3().fromAngleAxis(-Math.PI / 2, Vector3.UNIT_Y).multiplyLocal(new Matrix3().fromAngleAxis(Math.PI / 2, Vector3.UNIT_Z)));
compass.attachChild(txt);
txt = new BMText("S", "S", FontManager.getInstance().getAnnotationFont());
txt.setAutoRotate(false);
txt.setTranslation(-2, -0.2, Z);
txt.setRotation(new Matrix3().fromAngleAxis(-Math.PI / 2, Vector3.UNIT_Y).multiplyLocal(new Matrix3().fromAngleAxis(Math.PI / 2, Vector3.UNIT_Z)));
compass.attachChild(txt);
txt = new BMText("E", "E", FontManager.getInstance().getAnnotationFont());
txt.setAutoRotate(false);
txt.setTranslation(-0.2, 2.1, Z);
txt.setRotation(new Matrix3().fromAngleAxis(-Math.PI / 2, Vector3.UNIT_X));
compass.attachChild(txt);
txt = new BMText("W", "W", FontManager.getInstance().getAnnotationFont());
txt.setAutoRotate(false);
txt.setTranslation(-0.4, -2, Z);
txt.setRotation(new Matrix3().fromAngleAxis(Math.PI / 2, Vector3.UNIT_X));
compass.attachChild(txt);
final DirectionalLight light = new DirectionalLight();
light.setDirection(new Vector3(0, 0, -1));
// light.setAmbient(new ColorRGBA(1, 1, 1, 1));
light.setEnabled(true);
final LightState lightState = new LightState();
lightState.attach(light);
compass.setRenderState(lightState);
compass.updateWorldRenderStates(true);
compass.addController(new SpatialController<Spatial>() {
public void update(double time, Spatial caller) {
final Vector3 direction = Camera.getCurrentCamera().getDirection().normalize(null);
direction.setZ(0);
direction.normalizeLocal();
double angle = -direction.smallestAngleBetween(Vector3.UNIT_Y);
if (direction.dot(Vector3.UNIT_X) > 0)
angle = -angle;
angle -= Math.PI / 2;
compass.setRotation(new Matrix3().fromAngleAxis(angle, Vector3.UNIT_Z));
}
});
final Node compassNode1 = new Node();
compassNode1.setRotation(new Matrix3().fromAngleAxis(-Math.PI / 2, Vector3.UNIT_X));
compassNode1.attachChild(compass);
final Node compassNode2 = new Node();
compassNode2.attachChild(compassNode1);
System.out.println("done");
return compassNode2;
}
public void setCompassVisible(boolean visible) {
cameraNode.getSceneHints().setCullHint(visible ? CullHint.Inherit : CullHint.Always);
}
public void updateHeliodonSize() {
if (sunControl)
taskManager.update(new Callable<Object>() {
public Object call() throws Exception {
Scene.getRoot().updateWorldBound(true);
final BoundingVolume bounds = Scene.getRoot().getWorldBound();
if (bounds == null)
sunHeliodon.setScale(1);
else {
final double scale = (Util.findBoundLength(bounds) / 2.0 + bounds.getCenter().length()) / 5.0;
sunHeliodon.setScale(scale);
}
return null;
}
});
}
public void executeMouseMove() {
// this.mouseMoveFlag = false;
final MouseState mouseState = moveState.getCurrent().getMouseState();
moveState = null;
int x = mouseState.getX();
int y = mouseState.getY();
if (drawn != null && !drawn.isDrawCompleted()) {
drawn.setPreviewPoint(x, y);
} else if (operation == Operation.SELECT && mouseState.getButtonState(MouseButton.LEFT) == ButtonState.UP && mouseState.getButtonState(MouseButton.MIDDLE) == ButtonState.UP && mouseState.getButtonState(MouseButton.RIGHT) == ButtonState.UP) {
drawn = SelectUtil.selectHousePart(x, y, false);
}
}
public ViewMode getViewMode() {
return viewMode;
}
public boolean isRotationAnimationOn() {
return rotAnim;
}
}
| true | true | private SceneManager(final Container panel) {// throws LWJGLException {
System.out.print("Initializing scene manager...");
// instance = this;
// root.attachChild(Scene.getRoot());
// final DisplaySettings settings = new DisplaySettings(800, 600, 32, 60, 0, 8, 0, 0, false, false);
final DisplaySettings settings = new DisplaySettings(800, 600, 32, 60, 0, 8, 0, 8, false, false);
if (JOGL)
canvas = new JoglAwtCanvas(settings, new JoglCanvasRenderer(this));
// else
// canvas = new LwjglAwtCanvas(settings, new LwjglCanvasRenderer(this));
frameHandler = new FrameHandler(new Timer());
frameHandler.addCanvas(canvas);
logicalLayer = new LogicalLayer();
final AwtMouseWrapper mouseWrapper = new AwtMouseWrapper((Component) canvas, new AwtMouseManager((Component) canvas));
final AwtKeyboardWrapper keyboardWrapper = new AwtKeyboardWrapper((Component) canvas);
final AwtFocusWrapper focusWrapper = new AwtFocusWrapper((Component) canvas);
final PhysicalLayer physicalLayer = new PhysicalLayer(keyboardWrapper, mouseWrapper, focusWrapper);
logicalLayer.registerInput(canvas, physicalLayer);
frameHandler.addUpdater(this);
frameHandler.addUpdater(PrintController.getInstance());
frameHandler.addUpdater(Blinker.getInstance());
if (JOGL)
TextureRendererFactory.INSTANCE.setProvider(new JoglTextureRendererProvider());
// else
// TextureRendererFactory.INSTANCE.setProvider(new LwjglTextureRendererProvider());
panel.addComponentListener(new java.awt.event.ComponentAdapter() {
public void componentResized(java.awt.event.ComponentEvent e) {
resizeCamera();
}
});
panel.add((Component) canvas, "Center");
System.out.println("done");
}
@MainThread
public void init() {
System.out.print("Initializing scene manager models...");
AWTImageLoader.registerLoader();
try {
ResourceLocatorTool.addResourceLocator(ResourceLocatorTool.TYPE_TEXTURE, new SimpleResourceLocator(SceneManager.class.getClassLoader().getResource("org/concord/energy3d/resources/images/")));
ResourceLocatorTool.addResourceLocator(ResourceLocatorTool.TYPE_TEXTURE, new SimpleResourceLocator(SceneManager.class.getClassLoader().getResource("org/concord/energy3d/resources/")));
ResourceLocatorTool.addResourceLocator(ResourceLocatorTool.TYPE_MODEL, new SimpleResourceLocator(SceneManager.class.getClassLoader().getResource("org/concord/energy3d/resources/")));
} catch (final Exception ex) {
ex.printStackTrace();
}
cameraNode = new CameraNode("Camera Node", canvas.getCanvasRenderer().getCamera());
root.attachChild(cameraNode);
cameraNode.updateFromCamera();
setCameraControl(CameraMode.ORBIT);
resetCamera(ViewMode.NORMAL);
// enable depth test
final ZBufferState zbuf = new ZBufferState();
zbuf.setEnabled(true);
zbuf.setFunction(ZBufferState.TestFunction.LessThanOrEqualTo);
root.setRenderState(zbuf);
final DirectionalLight light = new DirectionalLight();
light.setDirection(new Vector3(0, 0, -1));
light.setAmbient(new ColorRGBA(1, 1, 1, 1));
light.setEnabled(true);
lightState.setEnabled(false);
lightState.attach(light);
root.setRenderState(lightState);
backgroundRoot.attachChild(createSky());
backgroundRoot.attachChild(createFloor());
backgroundRoot.attachChild(createAxis());
root.attachChild(backgroundRoot);
root.attachChild(Scene.getRoot());
final RenderPass rootPass = new RenderPass();
rootPass.add(root);
passManager.add(rootPass);
// shadowPass = new ParallelSplitShadowMapPass(light, 512, 3);
shadowPass = new ParallelSplitShadowMapPass(light, 3072, 3);
shadowPass.setUseObjectCullFace(true);
shadowPass.add(floor);
shadowPass.add(Scene.getRoot());
shadowPass.addOccluder(Scene.getRoot());
createSunHeliodon();
updateSunHeliodon();
Scene.getInstance();
SelectUtil.init(floor, Scene.getRoot());
registerInputTriggers();
taskManager.update(new Callable<Object>() {
public Object call() throws Exception {
final Spatial compass = loadCompassModel();
compass.setScale(0.1);
compass.setTranslation(-1, -0.7, 2);
cameraNode.attachChild(compass);
return null;
}
});
root.updateGeometricState(0, true);
System.out.println("done");
}
protected void test() {
PolygonPoint p[] = new PolygonPoint[4];
p[0] = new PolygonPoint(-1.0292539544430312, 0.09999999999999999, 1.362032135164121);
p[1] = new PolygonPoint(0.8537302277848444, 0.09999999999999991, 1.362032135164121);
p[2] = new PolygonPoint(0.8537302277848444, 1.1, 1.362032135164121);
p[3] = new PolygonPoint(-1.0292539544430312, 1.1, 1.362032135164121);
Polygon polygon = new Polygon(p);
double data[] = new double[] { -0.8409555362202437, 0.8999999999999999, 1.362032135164121, -0.5114333043303654, 0.8999999999999999, 1.362032135164121, -0.5114333043303654, 0.6, 1.362032135164121, -0.8409555362202437, 0.6, 1.362032135164121, -0.3702094906632748, 0.8999999999999999, 1.362032135164121, -0.08776186332909341, 0.8999999999999999, 1.362032135164121, -0.08776186332909341, 0.6, 1.362032135164121, -0.3702094906632748, 0.6, 1.362032135164121, 0.053461950337997166, 0.8999999999999999, 1.362032135164121, 0.33590957767217855, 0.8999999999999999, 1.362032135164121, 0.33590957767217855, 0.6, 1.362032135164121, 0.053461950337997166, 0.6, 1.362032135164121, 0.47713339133926946, 0.8999999999999999, 1.362032135164121, 0.6654318095620568, 0.8999999999999999, 1.362032135164121, 0.6654318095620568, 0.5999999999999999, 1.362032135164121, 0.47713339133926946, 0.5999999999999999, 1.362032135164121, -0.7938809316645468, 0.44999999999999996, 1.362032135164121, -0.5114333043303654,
0.44999999999999996, 1.362032135164121, -0.5114333043303654, 0.14999999999999997, 1.362032135164121, -0.7938809316645468, 0.14999999999999997, 1.362032135164121, -0.3702094906632748, 0.44999999999999996, 1.362032135164121, -0.08776186332909341, 0.44999999999999996, 1.362032135164121, -0.08776186332909341, 0.14999999999999994, 1.362032135164121, -0.3702094906632748, 0.14999999999999997, 1.362032135164121, 0.053461950337997166, 0.44999999999999996, 1.362032135164121, 0.33590957767217855, 0.4499999999999999, 1.362032135164121, 0.33590957767217855, 0.1499999999999999, 1.362032135164121, 0.053461950337997166, 0.14999999999999994, 1.362032135164121, 0.47713339133926946, 0.4499999999999999, 1.362032135164121, 0.6654318095620568, 0.4499999999999999, 1.362032135164121, 0.6654318095620568, 0.1499999999999999, 1.362032135164121, 0.47713339133926946, 0.1499999999999999, 1.362032135164121 };
for (int i = 0; i < data.length; i += 12) {
p = new PolygonPoint[] { new PolygonPoint(data[i], data[i + 1], data[i + 2]), new PolygonPoint(data[i + 3], data[i + 4], data[i + 5]), new PolygonPoint(data[i + 6], data[i + 7], data[i + 8]), new PolygonPoint(data[i + 9], data[i + 10], data[i + 11]) };
Polygon hole = new Polygon(p);
polygon.addHole(hole);
}
Mesh mesh = new Mesh();
mesh.setDefaultColor(ColorRGBA.BLUE);
root.attachChild(mesh);
Poly2Tri.triangulate(polygon);
ArdorMeshMapper.updateTriangleMesh(mesh, polygon);
}
public void run() {
frameHandler.init();
while (!exit) {
frameHandler.updateFrame();
final double syncNS = 1000000000.0 / 60;
long sinceLast = System.nanoTime() - lastRenderTime;
if (sinceLast < syncNS) {
try {
Thread.sleep(Math.round((syncNS - sinceLast) / 1000000L));
} catch (Exception e) {
e.printStackTrace();
}
}
lastRenderTime = System.nanoTime();
}
}
public void update(final ReadOnlyTimer timer) {
final double tpf = timer.getTimePerFrame();
HousePart.clearDrawFlags();
passManager.updatePasses(tpf);
logicalLayer.checkTriggers(tpf);
taskManager.getQueue(GameTaskQueue.UPDATE).execute(canvas.getCanvasRenderer().getRenderer());
Scene.getInstance().update();
if (rotAnim && viewMode == ViewMode.NORMAL) {
final Matrix3 rotate = new Matrix3();
rotate.fromAngleNormalAxis(1 * MathUtils.DEG_TO_RAD, Vector3.UNIT_Z);
final Camera camera = canvas.getCanvasRenderer().getCamera();
camera.setLocation(rotate.applyPre(camera.getLocation(), null));
camera.lookAt(0, 0, 1, Vector3.UNIT_Z);
getCameraNode().updateFromCamera();
}
if (sunAnim) {
sunAngle++;
updateSunHeliodon();
}
root.updateGeometricState(tpf);
}
public boolean renderUnto(Renderer renderer) {
// try {
// final boolean doRender = moveState != null;
if (moveState != null)
executeMouseMove();
// else
// return false;
if (operationFlag)
executeOperation();
// if (!Scene.getInstance().getParts().isEmpty())
// Scene.getInstance().renderTexture(renderer);
// Scene.getInstance().init();
if (drawBounds && drawn != null)
com.ardor3d.util.geom.Debugger.drawBounds(drawn.getRoot(), renderer, true);
// com.ardor3d.util.geom.Debugger.drawBounds(Scene.getInstance().getOriginalHouseRoot(), renderer, true);
// if (doRender)
passManager.renderPasses(renderer);
// } catch (Exception e) {
// e.printStackTrace();
// }
return true;
}
private Spatial createSunHeliodon() {
sunHeliodon = new Node();
Cylinder cyl = new Cylinder("Sun Curve", 10, 50, 5, 0.3);
Transform trans = new Transform();
trans.setMatrix(new Matrix3().fromAngleAxis(Math.PI / 2, Vector3.UNIT_X));
cyl.setDefaultColor(ColorRGBA.YELLOW);
cyl.setTransform(trans);
sunHeliodon.attachChild(cyl);
final ClipState cs = new ClipState();
cs.setEnableClipPlane(0, true);
cs.setClipPlaneEquation(0, 0, 0, 1, -0.19);
cyl.setRenderState(cs);
Cylinder baseCyl = new Cylinder("Sun Curve", 10, 50, 5, 0.2);
baseCyl.setTranslation(0, 0, 0.1);
sunHeliodon.attachChild(baseCyl);
sun = new Sphere("Sun", 20, 20, 0.3);
sun.setTranslation(0, 0, 5);
sunRot = new Node("Sun Root");
sunRot.attachChild(sun);
sunHeliodon.attachChild(sunRot);
reverseNormals(sun.getMeshData().getNormalBuffer());
MaterialState material = new MaterialState();
material.setEmissive(ColorRGBA.WHITE);
sun.setRenderState(material);
return sunHeliodon;
}
private void reverseNormals(FloatBuffer normalBuffer) {
normalBuffer.rewind();
int i = 0;
while (normalBuffer.hasRemaining()) {
float f = normalBuffer.get();
normalBuffer.position(i);
normalBuffer.put(-f);
i++;
}
}
private void updateSunHeliodon() {
if (sunAnim)
sunAngle %= 180;
else {
sunAngle = Math.max(sunAngle, 1);
sunAngle = Math.min(sunAngle, 179);
}
final Matrix3 m = new Matrix3().fromAngleAxis((-90 + sunAngle) * Math.PI / 180, Vector3.UNIT_Y);
sunRot.setRotation(m);
sunBaseAngle = sunBaseAngle % 360;
sunHeliodon.setRotation(new Matrix3().fromAngleAxis(sunBaseAngle * Math.PI / 180, Vector3.UNIT_Z));
DirectionalLight light = (DirectionalLight) lightState.get(0);
sunHeliodon.updateWorldTransform(true);
light.setDirection(sun.getWorldTranslation().negate(null));
sunHeliodon.updateGeometricState(0);
}
public PickResults doPick(Ray3 pickRay) {
return null;
}
public Canvas getCanvas() {
return canvas;
}
private Mesh createFloor() {
// floor = new Quad("Floor", 200, 200);
floor.setDefaultColor(new ColorRGBA(0, 1, 0, 0.5f));
final BlendState blendState = new BlendState();
blendState.setBlendEnabled(true);
blendState.setTestEnabled(true);
floor.setRenderState(blendState);
floor.getSceneHints().setRenderBucketType(RenderBucketType.Transparent);
floor.getSceneHints().setLightCombineMode(LightCombineMode.Off);
final MaterialState ms = new MaterialState();
ms.setColorMaterial(ColorMaterial.Diffuse);
floor.setRenderState(ms);
floor.updateModelBound();
return floor;
}
private Mesh createSky() {
final Dome sky = new Dome("Sky", 100, 100, 100);
sky.setRotation(new Matrix3().fromAngles(Math.PI / 2, 0, 0));
final TextureState ts = new TextureState();
ts.setTexture(TextureManager.load("sky.jpg", Texture.MinificationFilter.Trilinear, TextureStoreFormat.GuessNoCompressedFormat, true));
sky.setRenderState(ts);
sky.getSceneHints().setLightCombineMode(LightCombineMode.Off);
return sky;
}
private Spatial createAxis() {
final int axisLen = 100;
final FloatBuffer verts = BufferUtils.createVector3Buffer(12);
verts.put(0).put(0).put(0);
verts.put(-axisLen).put(0).put(0);
verts.put(0).put(0).put(0);
verts.put(axisLen).put(0).put(0);
verts.put(0).put(0).put(0);
verts.put(0).put(-axisLen).put(0);
verts.put(0).put(0).put(0);
verts.put(0).put(axisLen).put(0);
verts.put(0).put(0).put(0);
verts.put(0).put(0).put(-axisLen);
verts.put(0).put(0).put(0);
verts.put(0).put(0).put(axisLen);
final FloatBuffer colors = BufferUtils.createColorBuffer(12);
colors.put(1).put(0).put(0).put(0);
colors.put(1).put(0).put(0).put(0);
colors.put(1).put(0).put(0).put(0);
colors.put(1).put(0).put(0).put(0);
colors.put(0).put(1).put(0).put(0);
colors.put(0).put(1).put(0).put(0);
colors.put(0).put(1).put(0).put(0);
colors.put(0).put(1).put(0).put(0);
colors.put(0).put(0).put(1).put(0);
colors.put(0).put(0).put(1).put(0);
colors.put(0).put(0).put(1).put(0);
colors.put(0).put(0).put(1).put(0);
final Line axis = new Line("Axis", verts, null, colors, null);
axis.getSceneHints().setLightCombineMode(LightCombineMode.Off);
return axis;
}
private void registerInputTriggers() {
logicalLayer.registerTrigger(new InputTrigger(new MouseButtonPressedCondition(MouseButton.LEFT), new TriggerAction() {
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
taskManager.update(new Callable<Object>() {
public Object call() throws Exception {
MouseState mouseState = inputStates.getCurrent().getMouseState();
if (operation == Operation.SELECT || operation == Operation.RESIZE) {
if (drawn == null || drawn.isDrawCompleted()) {
if (drawn != null)
drawn.hidePoints();
drawn = SelectUtil.selectHousePart(mouseState.getX(), mouseState.getY(), true);
System.out.println("Clicked on: " + drawn);
SelectUtil.nextPickLayer();
}
} else
drawn.addPoint(mouseState.getX(), mouseState.getY());
enableDisableRotationControl();
return null;
}
});
}
}));
logicalLayer.registerTrigger(new InputTrigger(new MouseButtonReleasedCondition(MouseButton.LEFT), new TriggerAction() {
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
taskManager.update(new Callable<Object>() {
public Object call() throws Exception {
MouseState mouseState = inputStates.getCurrent().getMouseState();
if (operation == Operation.SELECT || operation == Operation.RESIZE) {
if (drawn != null && !drawn.isDrawCompleted())
drawn.complete();
} else {
if (!drawn.isDrawCompleted())
drawn.addPoint(mouseState.getX(), mouseState.getY());
if (drawn.isDrawCompleted()) {
drawn.hidePoints();
drawn = null;
if (operationStick)
operationFlag = true;
else {
MainFrame.getInstance().deselect();
}
}
}
enableDisableRotationControl();
updateHeliodonSize();
return null;
}
});
}
}));
logicalLayer.registerTrigger(new InputTrigger(new MouseMovedCondition(), new TriggerAction() {
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
// mouseMoveFlag = true;
moveState = inputStates;
}
}));
final KeyHeldCondition cond1 = new KeyHeldCondition(Key.LCONTROL);
final MouseMovedCondition cond2 = new MouseMovedCondition();
final Predicate<TwoInputStates> condition = Predicates.and(cond1, cond2);
logicalLayer.registerTrigger(new InputTrigger(condition, new TriggerAction() {
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
int dy = inputStates.getCurrent().getMouseState().getDy();
if (dy < -4)
dy = -4;
if (dy > 4)
dy = 4;
zoom(canvas, tpf, dy / 5.0);
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.LSHIFT), new TriggerAction() {
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
SelectUtil.setPickLayer(0);
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyReleasedCondition(Key.LSHIFT), new TriggerAction() {
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
SelectUtil.setPickLayer(-1);
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.DELETE), new TriggerAction() {
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
Scene.getInstance().remove(drawn);
drawn = null;
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyHeldCondition(Key.ESCAPE), new TriggerAction() {
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
hideAllEditPoints();
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyHeldCondition(Key.Q), new TriggerAction() {
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
moveUpDown(source, tpf, true);
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyHeldCondition(Key.Z), new TriggerAction() {
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
moveUpDown(source, tpf, false);
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyHeldCondition(Key.W), new TriggerAction() {
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
if (viewMode == ViewMode.TOP_VIEW)
moveUpDown(source, tpf, true);
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyHeldCondition(Key.S), new TriggerAction() {
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
if (viewMode == ViewMode.TOP_VIEW)
moveUpDown(source, tpf, false);
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.R), new TriggerAction() {
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
toggleRotation();
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.ZERO), new TriggerAction() {
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
resetCamera(viewMode);
}
}));
logicalLayer.registerTrigger(new InputTrigger(new MouseWheelMovedCondition(), new TriggerAction() {
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
zoom(source, tpf, inputStates.getCurrent().getMouseState().getDwheel());
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyHeldCondition(Key.UP), new TriggerAction() {
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
if (!sunControl)
return;
sunAngle--;
updateSunHeliodon();
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyHeldCondition(Key.DOWN), new TriggerAction() {
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
if (!sunControl)
return;
sunAngle++;
updateSunHeliodon();
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyHeldCondition(Key.RIGHT), new TriggerAction() {
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
if (!sunControl)
return;
sunBaseAngle++;
updateSunHeliodon();
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyHeldCondition(Key.LEFT), new TriggerAction() {
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
if (!sunControl)
return;
sunBaseAngle--;
updateSunHeliodon();
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.B), new TriggerAction() {
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
drawBounds = !drawBounds;
if (drawBounds)
System.out.println("Enabling draw bounds...");
else
System.out.println("Disabling draw bounds...");
}
}));
}
public void setCameraControl(CameraMode type) {
// this.cameraMode = type;
if (control != null)
control.removeTriggers(logicalLayer);
if (type == CameraMode.ORBIT)
control = new OrbitControl(Vector3.UNIT_Z);
else if (type == CameraMode.FIRST_PERSON)
control = new FirstPersonControl(Vector3.UNIT_Z);
control.setupKeyboardTriggers(logicalLayer);
control.setupMouseTriggers(logicalLayer, true);
control.setMoveSpeed(MOVE_SPEED);
control.setKeyRotateSpeed(1);
}
private void hideAllEditPoints() {
for (HousePart part : Scene.getInstance().getParts())
part.hidePoints();
}
public void resetCamera(final ViewMode viewMode) {
this.viewMode = viewMode;
final Camera camera = canvas.getCanvasRenderer().getCamera();
// setCameraControl(cameraMode);
control.setMouseButtonActions(ButtonAction.ROTATE, ButtonAction.MOVE);
control.setMoveSpeed(MOVE_SPEED);
Vector3 loc = new Vector3(1.0f, -8.0f, 1.0f);
Vector3 left = new Vector3(-1.0f, 0.0f, 0.0f);
Vector3 up = new Vector3(0.0f, 0.0f, 1.0f);
Vector3 dir = new Vector3(0.0f, 1.0f, 0.0f);
setCompassVisible(viewMode == ViewMode.NORMAL);
if (viewMode == ViewMode.NORMAL) {
camera.setProjectionMode(ProjectionMode.Perspective);
resizeCamera();
} else if (viewMode == ViewMode.TOP_VIEW) {
camera.setProjectionMode(ProjectionMode.Parallel);
control.setMouseButtonActions(ButtonAction.MOVE, ButtonAction.NONE);
control.setMoveSpeed(5 * MOVE_SPEED);
loc = new Vector3(0, 0, 10);
up = new Vector3(0.0f, -1.0f, 0.0f);
dir = new Vector3(0.0f, 0.0f, -1.0f);
resizeCamera(2);
} else if (viewMode == ViewMode.PRINT) {
control.setMouseButtonActions(ButtonAction.MOVE, ButtonAction.MOVE);
camera.setProjectionMode(ProjectionMode.Parallel);
loc = new Vector3(0, -1, 0);
final double pageWidth = PrintController.getInstance().getPageWidth();
final double pageHeight = PrintController.getInstance().getPageHeight();
final double ratio = (double) camera.getWidth() / camera.getHeight();
if (ratio > pageWidth / pageHeight)
resizeCamera(pageHeight * ratio);
else
resizeCamera(pageWidth);
} else if (viewMode == ViewMode.PRINT_PREVIEW) {
control.setMouseButtonActions(ButtonAction.MOVE, ButtonAction.MOVE);
camera.setProjectionMode(ProjectionMode.Perspective);
final int rows = PrintController.getInstance().getRows();
final double pageHeight = PrintController.getInstance().getPageHeight() + PrintController.getMargin();
final double w = PrintController.getInstance().getCols() * (PrintController.getInstance().getPageWidth() + PrintController.getMargin());
final double h = rows * pageHeight;
loc = new Vector3(0, -Math.max(w, h), rows % 2 != 0 ? 0 : pageHeight / 2);
resizeCamera(PrintController.getInstance().getPageWidth());
}
camera.setFrame(loc, left, up, dir);
cameraNode.updateFromCamera();
}
private void resizeCamera() {
resizeCamera(2);
}
private void resizeCamera(final double orthoWidth) {
final Camera camera = canvas.getCanvasRenderer().getCamera();
if (camera == null)
return;
final Dimension size = ((Component) canvas).getSize();
camera.resize(size.width, size.height);
final double ratio = (double) size.width / size.height;
if (camera.getProjectionMode() == ProjectionMode.Parallel)
camera.setFrustum(0.01, 200, -orthoWidth / 2, orthoWidth / 2, -orthoWidth / ratio / 2, orthoWidth / ratio / 2);
else
camera.setFrustumPerspective(45.0, ratio, 0.01, 200);
}
public void toggleRotation() {
rotAnim = !rotAnim;
}
private void zoom(final Canvas canvas, final double tpf, double val) {
if (Camera.getCurrentCamera().getProjectionMode() == ProjectionMode.Parallel) {
final double fac = val > 0 ? 1.1 : 0.9;
final Camera camera = canvas.getCanvasRenderer().getCamera();
camera.setFrustumTop(camera.getFrustumTop() * fac);
camera.setFrustumBottom(camera.getFrustumBottom() * fac);
camera.setFrustumLeft(camera.getFrustumLeft() * fac);
camera.setFrustumRight(camera.getFrustumRight() * fac);
camera.update();
control.setMoveSpeed(2 * camera.getFrustumTop() * camera.getFrustumTop());
} else {
final Camera camera = canvas.getCanvasRenderer().getCamera();
final Vector3 loc = new Vector3(camera.getDirection()).multiplyLocal(-val * MOVE_SPEED * 10 * tpf).addLocal(camera.getLocation());
camera.setLocation(loc);
if (control instanceof OrbitControl)
((OrbitControl) control).computeNewFrontDistance();
}
getCameraNode().updateFromCamera();
}
private void moveUpDown(final Canvas canvas, final double tpf, boolean up) {
final Camera camera = canvas.getCanvasRenderer().getCamera();
final Vector3 loc = new Vector3(camera.getUp());
if (viewMode == ViewMode.TOP_VIEW)
up = !up;
loc.multiplyLocal((up ? 1 : -1) * MOVE_SPEED * tpf).addLocal(camera.getLocation());
camera.setLocation(loc);
}
public void setOperation(Operation operation) {
this.operationStick = false;
this.operation = operation;
this.operationFlag = true;
}
public void setOperationStick(boolean stick) {
this.operationStick = stick;
}
public void executeOperation() {
System.out.println("executeOperation()");
this.operationFlag = false;
if (drawn != null && !drawn.isDrawCompleted())
Scene.getInstance().remove(drawn);
for (HousePart part : Scene.getInstance().getParts())
if (part instanceof Foundation) {
((Foundation) part).setResizeHouseMode(operation == Operation.RESIZE);
}
if (viewMode != ViewMode.PRINT_PREVIEW)
Scene.getInstance().drawResizeBounds();
drawn = newHousePart();
enableDisableRotationControl();
}
private HousePart newHousePart() {
HousePart drawn = null;
if (operation == Operation.DRAW_WALL)
drawn = new Wall();
else if (operation == Operation.DRAW_DOOR)
drawn = new Door();
else if (operation == Operation.DRAW_WINDOW)
drawn = new Window();
else if (operation == Operation.DRAW_ROOF)
drawn = new PyramidRoof();
else if (operation == Operation.DRAW_ROOF_HIP)
drawn = new HipRoof();
else if (operation == Operation.DRAW_FLOOR)
drawn = new Floor();
else if (operation == Operation.DRAW_FOUNDATION)
drawn = new Foundation();
if (drawn != null)
Scene.getInstance().add(drawn);
return drawn;
}
public Operation getOperation() {
return operation;
}
public void setLighting(final boolean enable) {
taskManager.update(new Callable<Object>() {
public Object call() throws Exception {
lightState.setEnabled(enable);
root.updateWorldRenderStates(true);
return null;
}
});
}
public void setSunControl(boolean selected) {
this.sunControl = selected;
taskManager.update(new Callable<Object>() {
public Object call() throws Exception {
if (sunControl) {
updateHeliodonSize();
root.attachChild(sunHeliodon);
} else
root.detachChild(sunHeliodon);
if (bloomRenderPass != null)
passManager.remove(bloomRenderPass);
if (sunControl) {
bloomRenderPass = new BloomRenderPass(canvas.getCanvasRenderer().getCamera(), 4);
if (!bloomRenderPass.isSupported()) {
System.out.println("Bloom not supported!");
} else {
bloomRenderPass.add(sun);
}
passManager.add(bloomRenderPass);
}
enableDisableRotationControl();
return null;
}
});
}
public void setSunAnim(boolean selected) {
this.sunAnim = selected;
}
public void enableDisableRotationControl() {
if ((operation == Operation.SELECT || operation == Operation.RESIZE) && (drawn == null || drawn.isDrawCompleted())) // && viewMode != ViewMode.TOP_VIEW) // && viewMode != ViewMode.PRINT_PREVIEW)
control.setMouseEnabled(true);
else
control.setMouseEnabled(false);
if (sunControl)
control.setKeyRotateSpeed(0);
else
control.setKeyRotateSpeed(1);
}
public HousePart getSelectedPart() {
return drawn;
}
public boolean isTopView() {
return viewMode == ViewMode.TOP_VIEW;
}
public void exit() {
System.out.print("exiting...");
this.exit = true;
canvas.getCanvasRenderer().makeCurrentContext();
ContextGarbageCollector.doFinalCleanup(canvas.getCanvasRenderer().getRenderer());
System.out.println("done");
System.exit(0);
}
public void updatePrintPreviewScene(boolean printPreview) {
// if (printPreview) {
// resetCamera(ViewMode.PRINT_PREVIEW);
// root.detachChild(floor);
// root.detachChild(axis);
// root.detachChild(sky);
// } else {
// resetCamera(ViewMode.NORMAL);
// root.attachChild(floor);
// root.attachChild(axis);
// root.attachChild(sky);
// }
resetCamera(printPreview ? ViewMode.PRINT_PREVIEW : ViewMode.NORMAL);
backgroundRoot.getSceneHints().setCullHint(printPreview ? CullHint.Always : CullHint.Inherit);
}
public void setShadow(boolean shadow) {
if (shadow)
passManager.add(shadowPass);
else
passManager.remove(shadowPass);
}
public CameraNode getCameraNode() {
return cameraNode;
}
private Node loadCompassModel() {
System.out.print("Loading compass...");
final ResourceSource source = ResourceLocatorTool.locateResource(ResourceLocatorTool.TYPE_MODEL, "compass.dae");
final ColladaImporter colladaImporter = new ColladaImporter();
// Load the collada scene
final ColladaStorage storage = colladaImporter.load(source);
final Node compass = storage.getScene();
BMText txt;
final double Z = 0.2;
txt = new BMText("N", "N", FontManager.getInstance().getAnnotationFont());
txt.setAutoRotate(false);
txt.setTranslation(3, -0.3, Z);
txt.setRotation(new Matrix3().fromAngleAxis(-Math.PI / 2, Vector3.UNIT_Y).multiplyLocal(new Matrix3().fromAngleAxis(Math.PI / 2, Vector3.UNIT_Z)));
compass.attachChild(txt);
txt = new BMText("S", "S", FontManager.getInstance().getAnnotationFont());
txt.setAutoRotate(false);
txt.setTranslation(-2, -0.2, Z);
txt.setRotation(new Matrix3().fromAngleAxis(-Math.PI / 2, Vector3.UNIT_Y).multiplyLocal(new Matrix3().fromAngleAxis(Math.PI / 2, Vector3.UNIT_Z)));
compass.attachChild(txt);
txt = new BMText("E", "E", FontManager.getInstance().getAnnotationFont());
txt.setAutoRotate(false);
txt.setTranslation(-0.2, 2.1, Z);
txt.setRotation(new Matrix3().fromAngleAxis(-Math.PI / 2, Vector3.UNIT_X));
compass.attachChild(txt);
txt = new BMText("W", "W", FontManager.getInstance().getAnnotationFont());
txt.setAutoRotate(false);
txt.setTranslation(-0.4, -2, Z);
txt.setRotation(new Matrix3().fromAngleAxis(Math.PI / 2, Vector3.UNIT_X));
compass.attachChild(txt);
final DirectionalLight light = new DirectionalLight();
light.setDirection(new Vector3(0, 0, -1));
// light.setAmbient(new ColorRGBA(1, 1, 1, 1));
light.setEnabled(true);
final LightState lightState = new LightState();
lightState.attach(light);
compass.setRenderState(lightState);
compass.updateWorldRenderStates(true);
compass.addController(new SpatialController<Spatial>() {
public void update(double time, Spatial caller) {
final Vector3 direction = Camera.getCurrentCamera().getDirection().normalize(null);
direction.setZ(0);
direction.normalizeLocal();
double angle = -direction.smallestAngleBetween(Vector3.UNIT_Y);
if (direction.dot(Vector3.UNIT_X) > 0)
angle = -angle;
angle -= Math.PI / 2;
compass.setRotation(new Matrix3().fromAngleAxis(angle, Vector3.UNIT_Z));
}
});
final Node compassNode1 = new Node();
compassNode1.setRotation(new Matrix3().fromAngleAxis(-Math.PI / 2, Vector3.UNIT_X));
compassNode1.attachChild(compass);
final Node compassNode2 = new Node();
compassNode2.attachChild(compassNode1);
System.out.println("done");
return compassNode2;
}
public void setCompassVisible(boolean visible) {
cameraNode.getSceneHints().setCullHint(visible ? CullHint.Inherit : CullHint.Always);
}
public void updateHeliodonSize() {
if (sunControl)
taskManager.update(new Callable<Object>() {
public Object call() throws Exception {
Scene.getRoot().updateWorldBound(true);
final BoundingVolume bounds = Scene.getRoot().getWorldBound();
if (bounds == null)
sunHeliodon.setScale(1);
else {
final double scale = (Util.findBoundLength(bounds) / 2.0 + bounds.getCenter().length()) / 5.0;
sunHeliodon.setScale(scale);
}
return null;
}
});
}
public void executeMouseMove() {
// this.mouseMoveFlag = false;
final MouseState mouseState = moveState.getCurrent().getMouseState();
moveState = null;
int x = mouseState.getX();
int y = mouseState.getY();
if (drawn != null && !drawn.isDrawCompleted()) {
drawn.setPreviewPoint(x, y);
} else if (operation == Operation.SELECT && mouseState.getButtonState(MouseButton.LEFT) == ButtonState.UP && mouseState.getButtonState(MouseButton.MIDDLE) == ButtonState.UP && mouseState.getButtonState(MouseButton.RIGHT) == ButtonState.UP) {
drawn = SelectUtil.selectHousePart(x, y, false);
}
}
public ViewMode getViewMode() {
return viewMode;
}
public boolean isRotationAnimationOn() {
return rotAnim;
}
}
| private SceneManager(final Container panel) {// throws LWJGLException {
System.out.print("Initializing scene manager...");
// instance = this;
// root.attachChild(Scene.getRoot());
// final DisplaySettings settings = new DisplaySettings(800, 600, 32, 60, 0, 8, 0, 0, false, false);
final DisplaySettings settings = new DisplaySettings(800, 600, 32, 60, 0, 8, 0, 8, false, false);
if (JOGL)
canvas = new JoglAwtCanvas(settings, new JoglCanvasRenderer(this));
// else
// canvas = new LwjglAwtCanvas(settings, new LwjglCanvasRenderer(this));
frameHandler = new FrameHandler(new Timer());
frameHandler.addCanvas(canvas);
logicalLayer = new LogicalLayer();
final AwtMouseWrapper mouseWrapper = new AwtMouseWrapper((Component) canvas, new AwtMouseManager((Component) canvas));
final AwtKeyboardWrapper keyboardWrapper = new AwtKeyboardWrapper((Component) canvas);
final AwtFocusWrapper focusWrapper = new AwtFocusWrapper((Component) canvas);
final PhysicalLayer physicalLayer = new PhysicalLayer(keyboardWrapper, mouseWrapper, focusWrapper);
logicalLayer.registerInput(canvas, physicalLayer);
frameHandler.addUpdater(this);
frameHandler.addUpdater(PrintController.getInstance());
frameHandler.addUpdater(Blinker.getInstance());
if (JOGL)
TextureRendererFactory.INSTANCE.setProvider(new JoglTextureRendererProvider());
// else
// TextureRendererFactory.INSTANCE.setProvider(new LwjglTextureRendererProvider());
panel.addComponentListener(new java.awt.event.ComponentAdapter() {
public void componentResized(java.awt.event.ComponentEvent e) {
resizeCamera();
}
});
panel.add((Component) canvas, "Center");
System.out.println("done");
}
@MainThread
public void init() {
System.out.print("Initializing scene manager models...");
AWTImageLoader.registerLoader();
try {
ResourceLocatorTool.addResourceLocator(ResourceLocatorTool.TYPE_TEXTURE, new SimpleResourceLocator(SceneManager.class.getClassLoader().getResource("org/concord/energy3d/resources/images/")));
ResourceLocatorTool.addResourceLocator(ResourceLocatorTool.TYPE_TEXTURE, new SimpleResourceLocator(SceneManager.class.getClassLoader().getResource("org/concord/energy3d/resources/")));
ResourceLocatorTool.addResourceLocator(ResourceLocatorTool.TYPE_MODEL, new SimpleResourceLocator(SceneManager.class.getClassLoader().getResource("org/concord/energy3d/resources/")));
} catch (final Exception ex) {
ex.printStackTrace();
}
cameraNode = new CameraNode("Camera Node", canvas.getCanvasRenderer().getCamera());
root.attachChild(cameraNode);
cameraNode.updateFromCamera();
setCameraControl(CameraMode.ORBIT);
resetCamera(ViewMode.NORMAL);
// enable depth test
final ZBufferState zbuf = new ZBufferState();
zbuf.setEnabled(true);
zbuf.setFunction(ZBufferState.TestFunction.LessThanOrEqualTo);
root.setRenderState(zbuf);
final DirectionalLight light = new DirectionalLight();
light.setDirection(new Vector3(0, 0, -1));
light.setAmbient(new ColorRGBA(1, 1, 1, 1));
light.setEnabled(true);
lightState.setEnabled(false);
lightState.attach(light);
root.setRenderState(lightState);
backgroundRoot.attachChild(createSky());
backgroundRoot.attachChild(createFloor());
backgroundRoot.attachChild(createAxis());
root.attachChild(backgroundRoot);
root.attachChild(Scene.getRoot());
final RenderPass rootPass = new RenderPass();
rootPass.add(root);
passManager.add(rootPass);
// shadowPass = new ParallelSplitShadowMapPass(light, 512, 3);
shadowPass = new ParallelSplitShadowMapPass(light, 3072, 3);
shadowPass.setUseObjectCullFace(true);
shadowPass.add(floor);
shadowPass.add(Scene.getRoot());
shadowPass.addOccluder(Scene.getRoot());
createSunHeliodon();
updateSunHeliodon();
Scene.getInstance();
SelectUtil.init(floor, Scene.getRoot());
registerInputTriggers();
taskManager.update(new Callable<Object>() {
public Object call() throws Exception {
final Spatial compass = loadCompassModel();
compass.setScale(0.1);
compass.setTranslation(-1, -0.7, 2);
cameraNode.attachChild(compass);
return null;
}
});
root.updateGeometricState(0, true);
System.out.println("done");
}
protected void test() {
PolygonPoint p[] = new PolygonPoint[4];
p[0] = new PolygonPoint(-1.0292539544430312, 0.09999999999999999, 1.362032135164121);
p[1] = new PolygonPoint(0.8537302277848444, 0.09999999999999991, 1.362032135164121);
p[2] = new PolygonPoint(0.8537302277848444, 1.1, 1.362032135164121);
p[3] = new PolygonPoint(-1.0292539544430312, 1.1, 1.362032135164121);
Polygon polygon = new Polygon(p);
double data[] = new double[] { -0.8409555362202437, 0.8999999999999999, 1.362032135164121, -0.5114333043303654, 0.8999999999999999, 1.362032135164121, -0.5114333043303654, 0.6, 1.362032135164121, -0.8409555362202437, 0.6, 1.362032135164121, -0.3702094906632748, 0.8999999999999999, 1.362032135164121, -0.08776186332909341, 0.8999999999999999, 1.362032135164121, -0.08776186332909341, 0.6, 1.362032135164121, -0.3702094906632748, 0.6, 1.362032135164121, 0.053461950337997166, 0.8999999999999999, 1.362032135164121, 0.33590957767217855, 0.8999999999999999, 1.362032135164121, 0.33590957767217855, 0.6, 1.362032135164121, 0.053461950337997166, 0.6, 1.362032135164121, 0.47713339133926946, 0.8999999999999999, 1.362032135164121, 0.6654318095620568, 0.8999999999999999, 1.362032135164121, 0.6654318095620568, 0.5999999999999999, 1.362032135164121, 0.47713339133926946, 0.5999999999999999, 1.362032135164121, -0.7938809316645468, 0.44999999999999996, 1.362032135164121, -0.5114333043303654,
0.44999999999999996, 1.362032135164121, -0.5114333043303654, 0.14999999999999997, 1.362032135164121, -0.7938809316645468, 0.14999999999999997, 1.362032135164121, -0.3702094906632748, 0.44999999999999996, 1.362032135164121, -0.08776186332909341, 0.44999999999999996, 1.362032135164121, -0.08776186332909341, 0.14999999999999994, 1.362032135164121, -0.3702094906632748, 0.14999999999999997, 1.362032135164121, 0.053461950337997166, 0.44999999999999996, 1.362032135164121, 0.33590957767217855, 0.4499999999999999, 1.362032135164121, 0.33590957767217855, 0.1499999999999999, 1.362032135164121, 0.053461950337997166, 0.14999999999999994, 1.362032135164121, 0.47713339133926946, 0.4499999999999999, 1.362032135164121, 0.6654318095620568, 0.4499999999999999, 1.362032135164121, 0.6654318095620568, 0.1499999999999999, 1.362032135164121, 0.47713339133926946, 0.1499999999999999, 1.362032135164121 };
for (int i = 0; i < data.length; i += 12) {
p = new PolygonPoint[] { new PolygonPoint(data[i], data[i + 1], data[i + 2]), new PolygonPoint(data[i + 3], data[i + 4], data[i + 5]), new PolygonPoint(data[i + 6], data[i + 7], data[i + 8]), new PolygonPoint(data[i + 9], data[i + 10], data[i + 11]) };
Polygon hole = new Polygon(p);
polygon.addHole(hole);
}
Mesh mesh = new Mesh();
mesh.setDefaultColor(ColorRGBA.BLUE);
root.attachChild(mesh);
Poly2Tri.triangulate(polygon);
ArdorMeshMapper.updateTriangleMesh(mesh, polygon);
}
public void run() {
frameHandler.init();
while (!exit) {
frameHandler.updateFrame();
final double syncNS = 1000000000.0 / 60;
long sinceLast = System.nanoTime() - lastRenderTime;
if (sinceLast < syncNS) {
try {
Thread.sleep(Math.round((syncNS - sinceLast) / 1000000L));
} catch (Exception e) {
e.printStackTrace();
}
}
lastRenderTime = System.nanoTime();
}
}
public void update(final ReadOnlyTimer timer) {
final double tpf = timer.getTimePerFrame();
HousePart.clearDrawFlags();
passManager.updatePasses(tpf);
logicalLayer.checkTriggers(tpf);
taskManager.getQueue(GameTaskQueue.UPDATE).execute(canvas.getCanvasRenderer().getRenderer());
Scene.getInstance().update();
if (rotAnim && viewMode == ViewMode.NORMAL) {
final Matrix3 rotate = new Matrix3();
rotate.fromAngleNormalAxis(1 * MathUtils.DEG_TO_RAD, Vector3.UNIT_Z);
final Camera camera = canvas.getCanvasRenderer().getCamera();
camera.setLocation(rotate.applyPre(camera.getLocation(), null));
camera.lookAt(0, 0, 1, Vector3.UNIT_Z);
getCameraNode().updateFromCamera();
}
if (sunAnim) {
sunAngle++;
updateSunHeliodon();
}
root.updateGeometricState(tpf);
}
public boolean renderUnto(Renderer renderer) {
// try {
// final boolean doRender = moveState != null;
if (moveState != null)
executeMouseMove();
// else
// return false;
if (operationFlag)
executeOperation();
// if (!Scene.getInstance().getParts().isEmpty())
// Scene.getInstance().renderTexture(renderer);
// Scene.getInstance().init();
if (drawBounds && drawn != null)
com.ardor3d.util.geom.Debugger.drawBounds(drawn.getRoot(), renderer, true);
// com.ardor3d.util.geom.Debugger.drawBounds(Scene.getInstance().getOriginalHouseRoot(), renderer, true);
// if (doRender)
passManager.renderPasses(renderer);
// } catch (Exception e) {
// e.printStackTrace();
// }
return true;
}
private Spatial createSunHeliodon() {
sunHeliodon = new Node();
Cylinder cyl = new Cylinder("Sun Curve", 10, 50, 5, 0.3);
Transform trans = new Transform();
trans.setMatrix(new Matrix3().fromAngleAxis(Math.PI / 2, Vector3.UNIT_X));
cyl.setDefaultColor(ColorRGBA.YELLOW);
cyl.setTransform(trans);
sunHeliodon.attachChild(cyl);
final ClipState cs = new ClipState();
cs.setEnableClipPlane(0, true);
cs.setClipPlaneEquation(0, 0, 0, 1, -0.19);
cyl.setRenderState(cs);
Cylinder baseCyl = new Cylinder("Sun Curve", 10, 50, 5, 0.2);
baseCyl.setTranslation(0, 0, 0.1);
sunHeliodon.attachChild(baseCyl);
sun = new Sphere("Sun", 20, 20, 0.3);
sun.setTranslation(0, 0, 5);
sunRot = new Node("Sun Root");
sunRot.attachChild(sun);
sunHeliodon.attachChild(sunRot);
reverseNormals(sun.getMeshData().getNormalBuffer());
MaterialState material = new MaterialState();
material.setEmissive(ColorRGBA.WHITE);
sun.setRenderState(material);
return sunHeliodon;
}
private void reverseNormals(FloatBuffer normalBuffer) {
normalBuffer.rewind();
int i = 0;
while (normalBuffer.hasRemaining()) {
float f = normalBuffer.get();
normalBuffer.position(i);
normalBuffer.put(-f);
i++;
}
}
private void updateSunHeliodon() {
if (sunAnim)
sunAngle %= 180;
else {
sunAngle = Math.max(sunAngle, 1);
sunAngle = Math.min(sunAngle, 179);
}
final Matrix3 m = new Matrix3().fromAngleAxis((-90 + sunAngle) * Math.PI / 180, Vector3.UNIT_Y);
sunRot.setRotation(m);
sunBaseAngle = sunBaseAngle % 360;
sunHeliodon.setRotation(new Matrix3().fromAngleAxis(sunBaseAngle * Math.PI / 180, Vector3.UNIT_Z));
DirectionalLight light = (DirectionalLight) lightState.get(0);
sunHeliodon.updateWorldTransform(true);
light.setDirection(sun.getWorldTranslation().negate(null));
sunHeliodon.updateGeometricState(0);
}
public PickResults doPick(Ray3 pickRay) {
return null;
}
public Canvas getCanvas() {
return canvas;
}
private Mesh createFloor() {
// floor = new Quad("Floor", 200, 200);
floor.setDefaultColor(new ColorRGBA(0, 1, 0, 0.5f));
final BlendState blendState = new BlendState();
blendState.setBlendEnabled(true);
blendState.setTestEnabled(true);
floor.setRenderState(blendState);
floor.getSceneHints().setRenderBucketType(RenderBucketType.Transparent);
floor.getSceneHints().setLightCombineMode(LightCombineMode.Off);
final MaterialState ms = new MaterialState();
ms.setColorMaterial(ColorMaterial.Diffuse);
floor.setRenderState(ms);
floor.updateModelBound();
return floor;
}
private Mesh createSky() {
final Dome sky = new Dome("Sky", 100, 100, 100);
sky.setRotation(new Matrix3().fromAngles(Math.PI / 2, 0, 0));
final TextureState ts = new TextureState();
ts.setTexture(TextureManager.load("sky.jpg", Texture.MinificationFilter.Trilinear, TextureStoreFormat.GuessNoCompressedFormat, true));
sky.setRenderState(ts);
sky.getSceneHints().setLightCombineMode(LightCombineMode.Off);
return sky;
}
private Spatial createAxis() {
final int axisLen = 100;
final FloatBuffer verts = BufferUtils.createVector3Buffer(12);
verts.put(0).put(0).put(0);
verts.put(-axisLen).put(0).put(0);
verts.put(0).put(0).put(0);
verts.put(axisLen).put(0).put(0);
verts.put(0).put(0).put(0);
verts.put(0).put(-axisLen).put(0);
verts.put(0).put(0).put(0);
verts.put(0).put(axisLen).put(0);
verts.put(0).put(0).put(0);
verts.put(0).put(0).put(-axisLen);
verts.put(0).put(0).put(0);
verts.put(0).put(0).put(axisLen);
final FloatBuffer colors = BufferUtils.createColorBuffer(12);
colors.put(1).put(0).put(0).put(0);
colors.put(1).put(0).put(0).put(0);
colors.put(1).put(0).put(0).put(0);
colors.put(1).put(0).put(0).put(0);
colors.put(0).put(1).put(0).put(0);
colors.put(0).put(1).put(0).put(0);
colors.put(0).put(1).put(0).put(0);
colors.put(0).put(1).put(0).put(0);
colors.put(0).put(0).put(1).put(0);
colors.put(0).put(0).put(1).put(0);
colors.put(0).put(0).put(1).put(0);
colors.put(0).put(0).put(1).put(0);
final Line axis = new Line("Axis", verts, null, colors, null);
axis.getSceneHints().setLightCombineMode(LightCombineMode.Off);
return axis;
}
private void registerInputTriggers() {
logicalLayer.registerTrigger(new InputTrigger(new MouseButtonPressedCondition(MouseButton.LEFT), new TriggerAction() {
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
taskManager.update(new Callable<Object>() {
public Object call() throws Exception {
MouseState mouseState = inputStates.getCurrent().getMouseState();
if (operation == Operation.SELECT || operation == Operation.RESIZE) {
if (drawn == null || drawn.isDrawCompleted()) {
if (drawn != null)
drawn.hidePoints();
drawn = SelectUtil.selectHousePart(mouseState.getX(), mouseState.getY(), true);
System.out.println("Clicked on: " + drawn);
SelectUtil.nextPickLayer();
}
} else
drawn.addPoint(mouseState.getX(), mouseState.getY());
enableDisableRotationControl();
return null;
}
});
}
}));
logicalLayer.registerTrigger(new InputTrigger(new MouseButtonReleasedCondition(MouseButton.LEFT), new TriggerAction() {
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
taskManager.update(new Callable<Object>() {
public Object call() throws Exception {
MouseState mouseState = inputStates.getCurrent().getMouseState();
if (operation == Operation.SELECT || operation == Operation.RESIZE) {
if (drawn != null && !drawn.isDrawCompleted())
drawn.complete();
} else {
if (!drawn.isDrawCompleted())
drawn.addPoint(mouseState.getX(), mouseState.getY());
if (drawn.isDrawCompleted()) {
drawn.hidePoints();
drawn = null;
if (operationStick)
operationFlag = true;
else {
MainFrame.getInstance().deselect();
}
}
}
enableDisableRotationControl();
updateHeliodonSize();
return null;
}
});
}
}));
logicalLayer.registerTrigger(new InputTrigger(new MouseMovedCondition(), new TriggerAction() {
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
// mouseMoveFlag = true;
moveState = inputStates;
}
}));
final KeyHeldCondition cond1 = new KeyHeldCondition(Key.LCONTROL);
final MouseMovedCondition cond2 = new MouseMovedCondition();
final Predicate<TwoInputStates> condition = Predicates.and(cond1, cond2);
logicalLayer.registerTrigger(new InputTrigger(condition, new TriggerAction() {
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
int dy = inputStates.getCurrent().getMouseState().getDy();
if (dy < -4)
dy = -4;
if (dy > 4)
dy = 4;
zoom(canvas, tpf, dy / 5.0);
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.LSHIFT), new TriggerAction() {
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
SelectUtil.setPickLayer(0);
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyReleasedCondition(Key.LSHIFT), new TriggerAction() {
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
SelectUtil.setPickLayer(-1);
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.DELETE), new TriggerAction() {
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
taskManager.update(new Callable<Object>() {
public Object call() throws Exception {
Scene.getInstance().remove(drawn);
drawn = null;
return null;
}
});
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyHeldCondition(Key.ESCAPE), new TriggerAction() {
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
hideAllEditPoints();
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyHeldCondition(Key.Q), new TriggerAction() {
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
moveUpDown(source, tpf, true);
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyHeldCondition(Key.Z), new TriggerAction() {
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
moveUpDown(source, tpf, false);
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyHeldCondition(Key.W), new TriggerAction() {
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
if (viewMode == ViewMode.TOP_VIEW)
moveUpDown(source, tpf, true);
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyHeldCondition(Key.S), new TriggerAction() {
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
if (viewMode == ViewMode.TOP_VIEW)
moveUpDown(source, tpf, false);
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.R), new TriggerAction() {
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
toggleRotation();
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.ZERO), new TriggerAction() {
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
resetCamera(viewMode);
}
}));
logicalLayer.registerTrigger(new InputTrigger(new MouseWheelMovedCondition(), new TriggerAction() {
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
zoom(source, tpf, inputStates.getCurrent().getMouseState().getDwheel());
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyHeldCondition(Key.UP), new TriggerAction() {
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
if (!sunControl)
return;
sunAngle--;
updateSunHeliodon();
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyHeldCondition(Key.DOWN), new TriggerAction() {
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
if (!sunControl)
return;
sunAngle++;
updateSunHeliodon();
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyHeldCondition(Key.RIGHT), new TriggerAction() {
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
if (!sunControl)
return;
sunBaseAngle++;
updateSunHeliodon();
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyHeldCondition(Key.LEFT), new TriggerAction() {
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
if (!sunControl)
return;
sunBaseAngle--;
updateSunHeliodon();
}
}));
logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.B), new TriggerAction() {
public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
drawBounds = !drawBounds;
if (drawBounds)
System.out.println("Enabling draw bounds...");
else
System.out.println("Disabling draw bounds...");
}
}));
}
public void setCameraControl(CameraMode type) {
// this.cameraMode = type;
if (control != null)
control.removeTriggers(logicalLayer);
if (type == CameraMode.ORBIT)
control = new OrbitControl(Vector3.UNIT_Z);
else if (type == CameraMode.FIRST_PERSON)
control = new FirstPersonControl(Vector3.UNIT_Z);
control.setupKeyboardTriggers(logicalLayer);
control.setupMouseTriggers(logicalLayer, true);
control.setMoveSpeed(MOVE_SPEED);
control.setKeyRotateSpeed(1);
}
private void hideAllEditPoints() {
for (HousePart part : Scene.getInstance().getParts())
part.hidePoints();
}
public void resetCamera(final ViewMode viewMode) {
this.viewMode = viewMode;
final Camera camera = canvas.getCanvasRenderer().getCamera();
// setCameraControl(cameraMode);
control.setMouseButtonActions(ButtonAction.ROTATE, ButtonAction.MOVE);
control.setMoveSpeed(MOVE_SPEED);
Vector3 loc = new Vector3(1.0f, -8.0f, 1.0f);
Vector3 left = new Vector3(-1.0f, 0.0f, 0.0f);
Vector3 up = new Vector3(0.0f, 0.0f, 1.0f);
Vector3 dir = new Vector3(0.0f, 1.0f, 0.0f);
setCompassVisible(viewMode == ViewMode.NORMAL);
if (viewMode == ViewMode.NORMAL) {
camera.setProjectionMode(ProjectionMode.Perspective);
resizeCamera();
} else if (viewMode == ViewMode.TOP_VIEW) {
camera.setProjectionMode(ProjectionMode.Parallel);
control.setMouseButtonActions(ButtonAction.MOVE, ButtonAction.NONE);
control.setMoveSpeed(5 * MOVE_SPEED);
loc = new Vector3(0, 0, 10);
up = new Vector3(0.0f, -1.0f, 0.0f);
dir = new Vector3(0.0f, 0.0f, -1.0f);
resizeCamera(2);
} else if (viewMode == ViewMode.PRINT) {
control.setMouseButtonActions(ButtonAction.MOVE, ButtonAction.MOVE);
camera.setProjectionMode(ProjectionMode.Parallel);
loc = new Vector3(0, -1, 0);
final double pageWidth = PrintController.getInstance().getPageWidth();
final double pageHeight = PrintController.getInstance().getPageHeight();
final double ratio = (double) camera.getWidth() / camera.getHeight();
if (ratio > pageWidth / pageHeight)
resizeCamera(pageHeight * ratio);
else
resizeCamera(pageWidth);
} else if (viewMode == ViewMode.PRINT_PREVIEW) {
control.setMouseButtonActions(ButtonAction.MOVE, ButtonAction.MOVE);
camera.setProjectionMode(ProjectionMode.Perspective);
final int rows = PrintController.getInstance().getRows();
final double pageHeight = PrintController.getInstance().getPageHeight() + PrintController.getMargin();
final double w = PrintController.getInstance().getCols() * (PrintController.getInstance().getPageWidth() + PrintController.getMargin());
final double h = rows * pageHeight;
loc = new Vector3(0, -Math.max(w, h), rows % 2 != 0 ? 0 : pageHeight / 2);
resizeCamera(PrintController.getInstance().getPageWidth());
}
camera.setFrame(loc, left, up, dir);
cameraNode.updateFromCamera();
}
private void resizeCamera() {
resizeCamera(2);
}
private void resizeCamera(final double orthoWidth) {
final Camera camera = canvas.getCanvasRenderer().getCamera();
if (camera == null)
return;
final Dimension size = ((Component) canvas).getSize();
camera.resize(size.width, size.height);
final double ratio = (double) size.width / size.height;
if (camera.getProjectionMode() == ProjectionMode.Parallel)
camera.setFrustum(0.01, 200, -orthoWidth / 2, orthoWidth / 2, -orthoWidth / ratio / 2, orthoWidth / ratio / 2);
else
camera.setFrustumPerspective(45.0, ratio, 0.01, 200);
}
public void toggleRotation() {
rotAnim = !rotAnim;
}
private void zoom(final Canvas canvas, final double tpf, double val) {
if (Camera.getCurrentCamera().getProjectionMode() == ProjectionMode.Parallel) {
final double fac = val > 0 ? 1.1 : 0.9;
final Camera camera = canvas.getCanvasRenderer().getCamera();
camera.setFrustumTop(camera.getFrustumTop() * fac);
camera.setFrustumBottom(camera.getFrustumBottom() * fac);
camera.setFrustumLeft(camera.getFrustumLeft() * fac);
camera.setFrustumRight(camera.getFrustumRight() * fac);
camera.update();
control.setMoveSpeed(2 * camera.getFrustumTop() * camera.getFrustumTop());
} else {
final Camera camera = canvas.getCanvasRenderer().getCamera();
final Vector3 loc = new Vector3(camera.getDirection()).multiplyLocal(-val * MOVE_SPEED * 10 * tpf).addLocal(camera.getLocation());
camera.setLocation(loc);
if (control instanceof OrbitControl)
((OrbitControl) control).computeNewFrontDistance();
}
getCameraNode().updateFromCamera();
}
private void moveUpDown(final Canvas canvas, final double tpf, boolean up) {
final Camera camera = canvas.getCanvasRenderer().getCamera();
final Vector3 loc = new Vector3(camera.getUp());
if (viewMode == ViewMode.TOP_VIEW)
up = !up;
loc.multiplyLocal((up ? 1 : -1) * MOVE_SPEED * tpf).addLocal(camera.getLocation());
camera.setLocation(loc);
}
public void setOperation(Operation operation) {
this.operationStick = false;
this.operation = operation;
this.operationFlag = true;
}
public void setOperationStick(boolean stick) {
this.operationStick = stick;
}
public void executeOperation() {
System.out.println("executeOperation()");
this.operationFlag = false;
if (drawn != null && !drawn.isDrawCompleted())
Scene.getInstance().remove(drawn);
for (HousePart part : Scene.getInstance().getParts())
if (part instanceof Foundation) {
((Foundation) part).setResizeHouseMode(operation == Operation.RESIZE);
}
if (viewMode != ViewMode.PRINT_PREVIEW)
Scene.getInstance().drawResizeBounds();
drawn = newHousePart();
enableDisableRotationControl();
}
private HousePart newHousePart() {
HousePart drawn = null;
if (operation == Operation.DRAW_WALL)
drawn = new Wall();
else if (operation == Operation.DRAW_DOOR)
drawn = new Door();
else if (operation == Operation.DRAW_WINDOW)
drawn = new Window();
else if (operation == Operation.DRAW_ROOF)
drawn = new PyramidRoof();
else if (operation == Operation.DRAW_ROOF_HIP)
drawn = new HipRoof();
else if (operation == Operation.DRAW_FLOOR)
drawn = new Floor();
else if (operation == Operation.DRAW_FOUNDATION)
drawn = new Foundation();
if (drawn != null)
Scene.getInstance().add(drawn);
return drawn;
}
public Operation getOperation() {
return operation;
}
public void setLighting(final boolean enable) {
taskManager.update(new Callable<Object>() {
public Object call() throws Exception {
lightState.setEnabled(enable);
root.updateWorldRenderStates(true);
return null;
}
});
}
public void setSunControl(boolean selected) {
this.sunControl = selected;
taskManager.update(new Callable<Object>() {
public Object call() throws Exception {
if (sunControl) {
updateHeliodonSize();
root.attachChild(sunHeliodon);
} else
root.detachChild(sunHeliodon);
if (bloomRenderPass != null)
passManager.remove(bloomRenderPass);
if (sunControl) {
bloomRenderPass = new BloomRenderPass(canvas.getCanvasRenderer().getCamera(), 4);
if (!bloomRenderPass.isSupported()) {
System.out.println("Bloom not supported!");
} else {
bloomRenderPass.add(sun);
}
passManager.add(bloomRenderPass);
}
enableDisableRotationControl();
return null;
}
});
}
public void setSunAnim(boolean selected) {
this.sunAnim = selected;
}
public void enableDisableRotationControl() {
if ((operation == Operation.SELECT || operation == Operation.RESIZE) && (drawn == null || drawn.isDrawCompleted())) // && viewMode != ViewMode.TOP_VIEW) // && viewMode != ViewMode.PRINT_PREVIEW)
control.setMouseEnabled(true);
else
control.setMouseEnabled(false);
if (sunControl)
control.setKeyRotateSpeed(0);
else
control.setKeyRotateSpeed(1);
}
public HousePart getSelectedPart() {
return drawn;
}
public boolean isTopView() {
return viewMode == ViewMode.TOP_VIEW;
}
public void exit() {
System.out.print("exiting...");
this.exit = true;
canvas.getCanvasRenderer().makeCurrentContext();
ContextGarbageCollector.doFinalCleanup(canvas.getCanvasRenderer().getRenderer());
System.out.println("done");
System.exit(0);
}
public void updatePrintPreviewScene(boolean printPreview) {
// if (printPreview) {
// resetCamera(ViewMode.PRINT_PREVIEW);
// root.detachChild(floor);
// root.detachChild(axis);
// root.detachChild(sky);
// } else {
// resetCamera(ViewMode.NORMAL);
// root.attachChild(floor);
// root.attachChild(axis);
// root.attachChild(sky);
// }
resetCamera(printPreview ? ViewMode.PRINT_PREVIEW : ViewMode.NORMAL);
backgroundRoot.getSceneHints().setCullHint(printPreview ? CullHint.Always : CullHint.Inherit);
}
public void setShadow(boolean shadow) {
if (shadow)
passManager.add(shadowPass);
else
passManager.remove(shadowPass);
}
public CameraNode getCameraNode() {
return cameraNode;
}
private Node loadCompassModel() {
System.out.print("Loading compass...");
final ResourceSource source = ResourceLocatorTool.locateResource(ResourceLocatorTool.TYPE_MODEL, "compass.dae");
final ColladaImporter colladaImporter = new ColladaImporter();
// Load the collada scene
final ColladaStorage storage = colladaImporter.load(source);
final Node compass = storage.getScene();
BMText txt;
final double Z = 0.2;
txt = new BMText("N", "N", FontManager.getInstance().getAnnotationFont());
txt.setAutoRotate(false);
txt.setTranslation(3, -0.3, Z);
txt.setRotation(new Matrix3().fromAngleAxis(-Math.PI / 2, Vector3.UNIT_Y).multiplyLocal(new Matrix3().fromAngleAxis(Math.PI / 2, Vector3.UNIT_Z)));
compass.attachChild(txt);
txt = new BMText("S", "S", FontManager.getInstance().getAnnotationFont());
txt.setAutoRotate(false);
txt.setTranslation(-2, -0.2, Z);
txt.setRotation(new Matrix3().fromAngleAxis(-Math.PI / 2, Vector3.UNIT_Y).multiplyLocal(new Matrix3().fromAngleAxis(Math.PI / 2, Vector3.UNIT_Z)));
compass.attachChild(txt);
txt = new BMText("E", "E", FontManager.getInstance().getAnnotationFont());
txt.setAutoRotate(false);
txt.setTranslation(-0.2, 2.1, Z);
txt.setRotation(new Matrix3().fromAngleAxis(-Math.PI / 2, Vector3.UNIT_X));
compass.attachChild(txt);
txt = new BMText("W", "W", FontManager.getInstance().getAnnotationFont());
txt.setAutoRotate(false);
txt.setTranslation(-0.4, -2, Z);
txt.setRotation(new Matrix3().fromAngleAxis(Math.PI / 2, Vector3.UNIT_X));
compass.attachChild(txt);
final DirectionalLight light = new DirectionalLight();
light.setDirection(new Vector3(0, 0, -1));
// light.setAmbient(new ColorRGBA(1, 1, 1, 1));
light.setEnabled(true);
final LightState lightState = new LightState();
lightState.attach(light);
compass.setRenderState(lightState);
compass.updateWorldRenderStates(true);
compass.addController(new SpatialController<Spatial>() {
public void update(double time, Spatial caller) {
final Vector3 direction = Camera.getCurrentCamera().getDirection().normalize(null);
direction.setZ(0);
direction.normalizeLocal();
double angle = -direction.smallestAngleBetween(Vector3.UNIT_Y);
if (direction.dot(Vector3.UNIT_X) > 0)
angle = -angle;
angle -= Math.PI / 2;
compass.setRotation(new Matrix3().fromAngleAxis(angle, Vector3.UNIT_Z));
}
});
final Node compassNode1 = new Node();
compassNode1.setRotation(new Matrix3().fromAngleAxis(-Math.PI / 2, Vector3.UNIT_X));
compassNode1.attachChild(compass);
final Node compassNode2 = new Node();
compassNode2.attachChild(compassNode1);
System.out.println("done");
return compassNode2;
}
public void setCompassVisible(boolean visible) {
cameraNode.getSceneHints().setCullHint(visible ? CullHint.Inherit : CullHint.Always);
}
public void updateHeliodonSize() {
if (sunControl)
taskManager.update(new Callable<Object>() {
public Object call() throws Exception {
Scene.getRoot().updateWorldBound(true);
final BoundingVolume bounds = Scene.getRoot().getWorldBound();
if (bounds == null)
sunHeliodon.setScale(1);
else {
final double scale = (Util.findBoundLength(bounds) / 2.0 + bounds.getCenter().length()) / 5.0;
sunHeliodon.setScale(scale);
}
return null;
}
});
}
public void executeMouseMove() {
// this.mouseMoveFlag = false;
final MouseState mouseState = moveState.getCurrent().getMouseState();
moveState = null;
int x = mouseState.getX();
int y = mouseState.getY();
if (drawn != null && !drawn.isDrawCompleted()) {
drawn.setPreviewPoint(x, y);
} else if (operation == Operation.SELECT && mouseState.getButtonState(MouseButton.LEFT) == ButtonState.UP && mouseState.getButtonState(MouseButton.MIDDLE) == ButtonState.UP && mouseState.getButtonState(MouseButton.RIGHT) == ButtonState.UP) {
drawn = SelectUtil.selectHousePart(x, y, false);
}
}
public ViewMode getViewMode() {
return viewMode;
}
public boolean isRotationAnimationOn() {
return rotAnim;
}
}
|
diff --git a/ios/src/playn/ios/IOSGLProgram.java b/ios/src/playn/ios/IOSGLProgram.java
index c480ce2d..484e0ef1 100644
--- a/ios/src/playn/ios/IOSGLProgram.java
+++ b/ios/src/playn/ios/IOSGLProgram.java
@@ -1,193 +1,193 @@
/**
* Copyright 2012 The PlayN 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 playn.ios;
import cli.System.IntPtr;
import cli.OpenTK.Graphics.ES20.All;
import cli.OpenTK.Graphics.ES20.GL;
import playn.core.gl.GLBuffer;
import playn.core.gl.GLProgram;
import playn.core.gl.GLShader;
import static playn.core.PlayN.log;
public class IOSGLProgram implements GLProgram {
private final int program, vertexShader, fragmentShader;
public IOSGLProgram(IOSGLContext ctx, String vertexSource, String fragmentSource) {
int program = 0, vertexShader = 0, fragmentShader = 0;
try {
program = GL.CreateProgram();
if (program == 0)
throw new RuntimeException("Failed to create program: " + GL.GetError());
vertexShader = compileShader(All.wrap(All.VertexShader), vertexSource);
GL.AttachShader(program, vertexShader);
ctx.checkGLError("Attached vertex shader");
fragmentShader = compileShader(All.wrap(All.FragmentShader), fragmentSource);
GL.AttachShader(program, fragmentShader);
ctx.checkGLError("Attached fragment shader");
GL.LinkProgram(program);
int[] linkStatus = new int[1];
GL.GetProgram(program, All.wrap(All.LinkStatus), linkStatus);
if (linkStatus[0] != All.True) {
int[] llength = new int[1];
GL.GetProgram(program, All.wrap(All.InfoLogLength), llength);
cli.System.Text.StringBuilder log = new cli.System.Text.StringBuilder(llength[0]);
GL.GetProgramInfoLog(program, llength[0], llength, log);
throw new RuntimeException("Failed to link program: " + log.ToString());
}
this.program = program;
this.vertexShader = vertexShader;
this.fragmentShader = fragmentShader;
program = vertexShader = fragmentShader = 0;
} finally {
if (program != 0)
GL.DeleteProgram(program);
if (vertexShader != 0)
GL.DeleteShader(vertexShader);
if (fragmentShader != 0)
- GL.DeleteShader(program);
+ GL.DeleteShader(fragmentShader);
}
}
@Override
public GLShader.Uniform1f getUniform1f(String name) {
final int loc = GL.GetUniformLocation(program, name);
return (loc < 0) ? null : new GLShader.Uniform1f() {
public void bind(float a) {
GL.Uniform1(loc, a);
}
};
}
@Override
public GLShader.Uniform2f getUniform2f(String name) {
final int loc = GL.GetUniformLocation(program, name);
return (loc < 0) ? null : new GLShader.Uniform2f() {
public void bind(float a, float b) {
GL.Uniform2(loc, a, b);
}
};
}
@Override
public GLShader.Uniform3f getUniform3f(String name) {
final int loc = GL.GetUniformLocation(program, name);
return (loc < 0) ? null : new GLShader.Uniform3f() {
public void bind(float a, float b, float c) {
GL.Uniform3(loc, a, b, c);
}
};
}
@Override
public GLShader.Uniform4f getUniform4f(String name) {
final int loc = GL.GetUniformLocation(program, name);
return (loc < 0) ? null : new GLShader.Uniform4f() {
public void bind(float a, float b, float c, float d) {
GL.Uniform4(loc, a, b, c, d);
}
};
}
@Override
public GLShader.Uniform1i getUniform1i(String name) {
final int loc = GL.GetUniformLocation(program, name);
return (loc < 0) ? null : new GLShader.Uniform1i() {
public void bind(int a) {
GL.Uniform1(loc, a);
}
};
}
@Override
public GLShader.Uniform2i getUniform2i(String name) {
final int loc = GL.GetUniformLocation(program, name);
return (loc < 0) ? null : new GLShader.Uniform2i() {
public void bind(int a, int b) {
GL.Uniform2(loc, a, b);
}
};
}
@Override
public GLShader.Uniform2fv getUniform2fv(String name) {
final int loc = GL.GetUniformLocation(program, name);
return (loc < 0) ? null : new GLShader.Uniform2fv() {
public void bind(GLBuffer.Float data, int count) {
IOSGLBuffer.FloatImpl idata = (IOSGLBuffer.FloatImpl) data;
idata.position = 0;
GL.Uniform2(loc, count, idata.data);
}
};
}
@Override
public GLShader.UniformMatrix4fv getUniformMatrix4fv(String name) {
final int loc = GL.GetUniformLocation(program, name);
return (loc < 0) ? null : new GLShader.UniformMatrix4fv() {
public void bind(GLBuffer.Float data, int count) {
IOSGLBuffer.FloatImpl idata = (IOSGLBuffer.FloatImpl) data;
idata.position = 0;
GL.UniformMatrix4(loc, count, false, idata.data);
}
};
}
@Override
public GLShader.Attrib getAttrib(String name, final int size, final int type) {
final int loc = GL.GetAttribLocation(program, name);
return (loc < 0) ? null : new GLShader.Attrib() {
public void bind(int stride, int offset) {
GL.EnableVertexAttribArray(loc);
GL.VertexAttribPointer(loc, size, All.wrap(type), false, stride, new IntPtr(offset));
}
};
}
@Override
public void bind() {
GL.UseProgram(program);
}
@Override
public void destroy() {
GL.DeleteShader(vertexShader);
GL.DeleteShader(fragmentShader);
GL.DeleteProgram(program);
}
private int compileShader(All type, final String shaderSource) {
int shader = GL.CreateShader(type);
if (shader == 0)
throw new RuntimeException("Failed to create shader: " + GL.GetError());
GL.ShaderSource(shader, 1, new String[] { shaderSource }, null);
GL.CompileShader(shader);
int[] compiled = new int[1];
GL.GetShader(shader, All.wrap(All.CompileStatus), compiled);
if (compiled[0] == All.False) {
int[] llength = new int[1];
GL.GetShader(shader, All.wrap(All.InfoLogLength), llength);
cli.System.Text.StringBuilder log = new cli.System.Text.StringBuilder(llength[0]);
GL.GetShaderInfoLog(shader, llength[0], llength, log);
GL.DeleteShader(shader);
throw new RuntimeException("Failed to compile shader (" + type + "): " + log.ToString());
}
return shader;
}
}
| true | true | public IOSGLProgram(IOSGLContext ctx, String vertexSource, String fragmentSource) {
int program = 0, vertexShader = 0, fragmentShader = 0;
try {
program = GL.CreateProgram();
if (program == 0)
throw new RuntimeException("Failed to create program: " + GL.GetError());
vertexShader = compileShader(All.wrap(All.VertexShader), vertexSource);
GL.AttachShader(program, vertexShader);
ctx.checkGLError("Attached vertex shader");
fragmentShader = compileShader(All.wrap(All.FragmentShader), fragmentSource);
GL.AttachShader(program, fragmentShader);
ctx.checkGLError("Attached fragment shader");
GL.LinkProgram(program);
int[] linkStatus = new int[1];
GL.GetProgram(program, All.wrap(All.LinkStatus), linkStatus);
if (linkStatus[0] != All.True) {
int[] llength = new int[1];
GL.GetProgram(program, All.wrap(All.InfoLogLength), llength);
cli.System.Text.StringBuilder log = new cli.System.Text.StringBuilder(llength[0]);
GL.GetProgramInfoLog(program, llength[0], llength, log);
throw new RuntimeException("Failed to link program: " + log.ToString());
}
this.program = program;
this.vertexShader = vertexShader;
this.fragmentShader = fragmentShader;
program = vertexShader = fragmentShader = 0;
} finally {
if (program != 0)
GL.DeleteProgram(program);
if (vertexShader != 0)
GL.DeleteShader(vertexShader);
if (fragmentShader != 0)
GL.DeleteShader(program);
}
}
| public IOSGLProgram(IOSGLContext ctx, String vertexSource, String fragmentSource) {
int program = 0, vertexShader = 0, fragmentShader = 0;
try {
program = GL.CreateProgram();
if (program == 0)
throw new RuntimeException("Failed to create program: " + GL.GetError());
vertexShader = compileShader(All.wrap(All.VertexShader), vertexSource);
GL.AttachShader(program, vertexShader);
ctx.checkGLError("Attached vertex shader");
fragmentShader = compileShader(All.wrap(All.FragmentShader), fragmentSource);
GL.AttachShader(program, fragmentShader);
ctx.checkGLError("Attached fragment shader");
GL.LinkProgram(program);
int[] linkStatus = new int[1];
GL.GetProgram(program, All.wrap(All.LinkStatus), linkStatus);
if (linkStatus[0] != All.True) {
int[] llength = new int[1];
GL.GetProgram(program, All.wrap(All.InfoLogLength), llength);
cli.System.Text.StringBuilder log = new cli.System.Text.StringBuilder(llength[0]);
GL.GetProgramInfoLog(program, llength[0], llength, log);
throw new RuntimeException("Failed to link program: " + log.ToString());
}
this.program = program;
this.vertexShader = vertexShader;
this.fragmentShader = fragmentShader;
program = vertexShader = fragmentShader = 0;
} finally {
if (program != 0)
GL.DeleteProgram(program);
if (vertexShader != 0)
GL.DeleteShader(vertexShader);
if (fragmentShader != 0)
GL.DeleteShader(fragmentShader);
}
}
|
diff --git a/Screen/Tools/SBS/src/main/java/screen/tools/sbs/Main.java b/Screen/Tools/SBS/src/main/java/screen/tools/sbs/Main.java
index 9fb6670..8652983 100644
--- a/Screen/Tools/SBS/src/main/java/screen/tools/sbs/Main.java
+++ b/Screen/Tools/SBS/src/main/java/screen/tools/sbs/Main.java
@@ -1,106 +1,109 @@
/*****************************************************************************
* This source file is part of SBS (Screen Build System), *
* which is a component of Screen Framework *
* *
* Copyright (c) 2008-2010 Ratouit Thomas *
* *
* This program is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Lesser General Public License as published by *
* the Free Software Foundation; either version 3 of the License, or (at *
* your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser *
* General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this program; if not, write to the Free Software Foundation, *
* Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA, or go to *
* http://www.gnu.org/copyleft/lesser.txt. *
*****************************************************************************/
package screen.tools.sbs;
import screen.tools.sbs.actions.ActionManager;
import screen.tools.sbs.objects.ErrorList;
import screen.tools.sbs.objects.GlobalSettings;
import screen.tools.sbs.targets.Parameters;
import screen.tools.sbs.targets.TargetManager;
import screen.tools.sbs.utils.Logger;
/**
* Main class, entry point for sbs commands
*
* @author Ratouit Thomas
*
*/
public class Main {
/**
* Logs registered errors and warnings.
*
* @return has error during the process
*
*/
private static boolean checkErrors(){
ErrorList err = GlobalSettings.getGlobalSettings().getErrorList();
if(err.hasErrors()){
Logger.info("errors detected");
Logger.info("Logged errors (" + err.getErrors().size() + ") :");
err.displayErrors();
if(err.hasWarnings()){
Logger.info("Logged warnings (" + err.getWarnings().size() + ")");
err.displayWarnings();
}
Logger.info("============== STOP ===============");
return false;
}else if(err.hasWarnings()){
Logger.info("warnings detected");
Logger.info("Logged warnings (" + err.getWarnings().size() + ")");
err.displayWarnings();
}
return true;
}
/**
* Software entry / Main method.
*
* @param args
* @throws Exception
*
*/
public static void main(String[] args) throws Exception {
Logger.info("------------ begin SBS ------------");
String root = System.getProperty("SBS_ROOT");
GlobalSettings.getGlobalSettings().getEnvironmentVariables().put("SBS_ROOT", root);
ActionManager actionManager = new ActionManager();
TargetManager targetManager = new TargetManager(actionManager);
Parameters parameters = new Parameters(args);
//register actions for a given target
targetManager.call(parameters.getTargetCall(), parameters);
//verify that there is no error to resume the process
- checkErrors();
+ boolean hasNoError = checkErrors();
if(GlobalSettings.getGlobalSettings().isPrintUsage()){
//print help
targetManager.callUsage(GlobalSettings.getGlobalSettings().getTargetUsage());
}
else{
//process registered actions
actionManager.processActions();
//verify that there is no error to resume the process
- checkErrors();
+ hasNoError = checkErrors();
if(GlobalSettings.getGlobalSettings().isPrintUsage())
//print help
targetManager.callUsage(GlobalSettings.getGlobalSettings().getTargetUsage());
}
Logger.info("------------- end SBS -------------");
Logger.info("");
Logger.info("-----------------------------------");
- Logger.info(" COMMAND SUCCESSFUL ");
+ if(hasNoError)
+ Logger.info(" COMMAND SUCCESSFUL ");
+ else
+ Logger.info(" COMMAND FAILED ");
Logger.info("-----------------------------------");
}
}
| false | true | public static void main(String[] args) throws Exception {
Logger.info("------------ begin SBS ------------");
String root = System.getProperty("SBS_ROOT");
GlobalSettings.getGlobalSettings().getEnvironmentVariables().put("SBS_ROOT", root);
ActionManager actionManager = new ActionManager();
TargetManager targetManager = new TargetManager(actionManager);
Parameters parameters = new Parameters(args);
//register actions for a given target
targetManager.call(parameters.getTargetCall(), parameters);
//verify that there is no error to resume the process
checkErrors();
if(GlobalSettings.getGlobalSettings().isPrintUsage()){
//print help
targetManager.callUsage(GlobalSettings.getGlobalSettings().getTargetUsage());
}
else{
//process registered actions
actionManager.processActions();
//verify that there is no error to resume the process
checkErrors();
if(GlobalSettings.getGlobalSettings().isPrintUsage())
//print help
targetManager.callUsage(GlobalSettings.getGlobalSettings().getTargetUsage());
}
Logger.info("------------- end SBS -------------");
Logger.info("");
Logger.info("-----------------------------------");
Logger.info(" COMMAND SUCCESSFUL ");
Logger.info("-----------------------------------");
}
| public static void main(String[] args) throws Exception {
Logger.info("------------ begin SBS ------------");
String root = System.getProperty("SBS_ROOT");
GlobalSettings.getGlobalSettings().getEnvironmentVariables().put("SBS_ROOT", root);
ActionManager actionManager = new ActionManager();
TargetManager targetManager = new TargetManager(actionManager);
Parameters parameters = new Parameters(args);
//register actions for a given target
targetManager.call(parameters.getTargetCall(), parameters);
//verify that there is no error to resume the process
boolean hasNoError = checkErrors();
if(GlobalSettings.getGlobalSettings().isPrintUsage()){
//print help
targetManager.callUsage(GlobalSettings.getGlobalSettings().getTargetUsage());
}
else{
//process registered actions
actionManager.processActions();
//verify that there is no error to resume the process
hasNoError = checkErrors();
if(GlobalSettings.getGlobalSettings().isPrintUsage())
//print help
targetManager.callUsage(GlobalSettings.getGlobalSettings().getTargetUsage());
}
Logger.info("------------- end SBS -------------");
Logger.info("");
Logger.info("-----------------------------------");
if(hasNoError)
Logger.info(" COMMAND SUCCESSFUL ");
else
Logger.info(" COMMAND FAILED ");
Logger.info("-----------------------------------");
}
|
diff --git a/jython/src/org/python/modules/_threading/_threading.java b/jython/src/org/python/modules/_threading/_threading.java
index 1a9c11bc..04838dad 100644
--- a/jython/src/org/python/modules/_threading/_threading.java
+++ b/jython/src/org/python/modules/_threading/_threading.java
@@ -1,15 +1,17 @@
package org.python.modules._threading;
import org.python.core.ClassDictInit;
import org.python.core.Py;
import org.python.core.PyObject;
public class _threading implements ClassDictInit {
public static void classDictInit(PyObject dict) {
dict.__setitem__("__name__", Py.newString("_threading"));
dict.__setitem__("Lock", Lock.TYPE);
dict.__setitem__("RLock", Lock.TYPE);
+ dict.__setitem__("_Lock", Lock.TYPE);
+ dict.__setitem__("_RLock", Lock.TYPE);
dict.__setitem__("Condition", Condition.TYPE);
}
}
| true | true | public static void classDictInit(PyObject dict) {
dict.__setitem__("__name__", Py.newString("_threading"));
dict.__setitem__("Lock", Lock.TYPE);
dict.__setitem__("RLock", Lock.TYPE);
dict.__setitem__("Condition", Condition.TYPE);
}
| public static void classDictInit(PyObject dict) {
dict.__setitem__("__name__", Py.newString("_threading"));
dict.__setitem__("Lock", Lock.TYPE);
dict.__setitem__("RLock", Lock.TYPE);
dict.__setitem__("_Lock", Lock.TYPE);
dict.__setitem__("_RLock", Lock.TYPE);
dict.__setitem__("Condition", Condition.TYPE);
}
|
diff --git a/src/com/android/exchange/adapter/CalendarSyncAdapter.java b/src/com/android/exchange/adapter/CalendarSyncAdapter.java
index aa38e05..1d1059f 100644
--- a/src/com/android/exchange/adapter/CalendarSyncAdapter.java
+++ b/src/com/android/exchange/adapter/CalendarSyncAdapter.java
@@ -1,2169 +1,2172 @@
/*
* Copyright (C) 2008-2009 Marc Blank
* Licensed to 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.exchange.adapter;
import android.content.ContentProviderClient;
import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Entity;
import android.content.Entity.NamedContentValues;
import android.content.EntityIterator;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.net.Uri;
import android.os.RemoteException;
import android.provider.CalendarContract;
import android.provider.CalendarContract.Attendees;
import android.provider.CalendarContract.Calendars;
import android.provider.CalendarContract.Events;
import android.provider.CalendarContract.EventsEntity;
import android.provider.CalendarContract.ExtendedProperties;
import android.provider.CalendarContract.Reminders;
import android.provider.CalendarContract.SyncState;
import android.provider.ContactsContract.RawContacts;
import android.provider.SyncStateContract;
import android.text.TextUtils;
import android.util.Log;
import com.android.emailcommon.AccountManagerTypes;
import com.android.emailcommon.provider.EmailContent;
import com.android.emailcommon.provider.EmailContent.Message;
import com.android.emailcommon.utility.Utility;
import com.android.exchange.CommandStatusException;
import com.android.exchange.Eas;
import com.android.exchange.EasOutboxService;
import com.android.exchange.EasSyncService;
import com.android.exchange.ExchangeService;
import com.android.exchange.utility.CalendarUtilities;
import com.android.exchange.utility.Duration;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.Map.Entry;
import java.util.StringTokenizer;
import java.util.TimeZone;
import java.util.UUID;
/**
* Sync adapter class for EAS calendars
*
*/
public class CalendarSyncAdapter extends AbstractSyncAdapter {
private static final String TAG = "EasCalendarSyncAdapter";
private static final String EVENT_SAVED_TIMEZONE_COLUMN = Events.SYNC_DATA1;
/**
* Used to keep track of exception vs parent event dirtiness.
*/
private static final String EVENT_SYNC_MARK = Events.SYNC_DATA8;
private static final String EVENT_SYNC_VERSION = Events.SYNC_DATA4;
// Since exceptions will have the same _SYNC_ID as the original event we have to check that
// there's no original event when finding an item by _SYNC_ID
private static final String SERVER_ID_AND_CALENDAR_ID = Events._SYNC_ID + "=? AND " +
Events.ORIGINAL_SYNC_ID + " ISNULL AND " + Events.CALENDAR_ID + "=?";
private static final String EVENT_ID_AND_CALENDAR_ID = Events._ID + "=? AND " +
Events.ORIGINAL_SYNC_ID + " ISNULL AND " + Events.CALENDAR_ID + "=?";
private static final String DIRTY_OR_MARKED_TOP_LEVEL_IN_CALENDAR = "(" + Events.DIRTY
+ "=1 OR " + EVENT_SYNC_MARK + "= 1) AND " +
Events.ORIGINAL_ID + " ISNULL AND " + Events.CALENDAR_ID + "=?";
private static final String DIRTY_EXCEPTION_IN_CALENDAR =
Events.DIRTY + "=1 AND " + Events.ORIGINAL_ID + " NOTNULL AND " +
Events.CALENDAR_ID + "=?";
private static final String CLIENT_ID_SELECTION = Events.SYNC_DATA2 + "=?";
private static final String ORIGINAL_EVENT_AND_CALENDAR =
Events.ORIGINAL_SYNC_ID + "=? AND " + Events.CALENDAR_ID + "=?";
private static final String ATTENDEES_EXCEPT_ORGANIZER = Attendees.EVENT_ID + "=? AND " +
Attendees.ATTENDEE_RELATIONSHIP + "!=" + Attendees.RELATIONSHIP_ORGANIZER;
private static final String[] ID_PROJECTION = new String[] {Events._ID};
private static final String[] ORIGINAL_EVENT_PROJECTION =
new String[] {Events.ORIGINAL_ID, Events._ID};
private static final String EVENT_ID_AND_NAME =
ExtendedProperties.EVENT_ID + "=? AND " + ExtendedProperties.NAME + "=?";
// Note that we use LIKE below for its case insensitivity
private static final String EVENT_AND_EMAIL =
Attendees.EVENT_ID + "=? AND "+ Attendees.ATTENDEE_EMAIL + " LIKE ?";
private static final int ATTENDEE_STATUS_COLUMN_STATUS = 0;
private static final String[] ATTENDEE_STATUS_PROJECTION =
new String[] {Attendees.ATTENDEE_STATUS};
public static final String CALENDAR_SELECTION =
Calendars.ACCOUNT_NAME + "=? AND " + Calendars.ACCOUNT_TYPE + "=?";
private static final int CALENDAR_SELECTION_ID = 0;
private static final String[] EXTENDED_PROPERTY_PROJECTION =
new String[] {ExtendedProperties._ID};
private static final int EXTENDED_PROPERTY_ID = 0;
private static final String CATEGORY_TOKENIZER_DELIMITER = "\\";
private static final String ATTENDEE_TOKENIZER_DELIMITER = CATEGORY_TOKENIZER_DELIMITER;
private static final String EXTENDED_PROPERTY_USER_ATTENDEE_STATUS = "userAttendeeStatus";
private static final String EXTENDED_PROPERTY_ATTENDEES = "attendees";
private static final String EXTENDED_PROPERTY_DTSTAMP = "dtstamp";
private static final String EXTENDED_PROPERTY_MEETING_STATUS = "meeting_status";
private static final String EXTENDED_PROPERTY_CATEGORIES = "categories";
// Used to indicate that we removed the attendee list because it was too large
private static final String EXTENDED_PROPERTY_ATTENDEES_REDACTED = "attendeesRedacted";
// Used to indicate that upsyncs aren't allowed (we catch this in sendLocalChanges)
private static final String EXTENDED_PROPERTY_UPSYNC_PROHIBITED = "upsyncProhibited";
private static final ContentProviderOperation PLACEHOLDER_OPERATION =
ContentProviderOperation.newInsert(Uri.EMPTY).build();
private static final Object sSyncKeyLock = new Object();
private static final TimeZone UTC_TIMEZONE = TimeZone.getTimeZone("UTC");
private final TimeZone mLocalTimeZone = TimeZone.getDefault();
// Maximum number of allowed attendees; above this number, we mark the Event with the
// attendeesRedacted extended property and don't allow the event to be upsynced to the server
private static final int MAX_SYNCED_ATTENDEES = 50;
// We set the organizer to this when the user is the organizer and we've redacted the
// attendee list. By making the meeting organizer OTHER than the user, we cause the UI to
// prevent edits to this event (except local changes like reminder).
private static final String BOGUS_ORGANIZER_EMAIL = "[email protected]";
// Maximum number of CPO's before we start redacting attendees in exceptions
// The number 500 has been determined empirically; 1500 CPOs appears to be the limit before
// binder failures occur, but we need room at any point for additional events/exceptions so
// we set our limit at 1/3 of the apparent maximum for extra safety
// TODO Find a better solution to this workaround
private static final int MAX_OPS_BEFORE_EXCEPTION_ATTENDEE_REDACTION = 500;
private long mCalendarId = -1;
private String mCalendarIdString;
private String[] mCalendarIdArgument;
/*package*/ String mEmailAddress;
private ArrayList<Long> mDeletedIdList = new ArrayList<Long>();
private ArrayList<Long> mUploadedIdList = new ArrayList<Long>();
private ArrayList<Long> mSendCancelIdList = new ArrayList<Long>();
private ArrayList<Message> mOutgoingMailList = new ArrayList<Message>();
public CalendarSyncAdapter(EasSyncService service) {
super(service);
mEmailAddress = mAccount.mEmailAddress;
Cursor c = mService.mContentResolver.query(Calendars.CONTENT_URI,
new String[] {Calendars._ID}, CALENDAR_SELECTION,
new String[] {mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE}, null);
if (c == null) return;
try {
if (c.moveToFirst()) {
mCalendarId = c.getLong(CALENDAR_SELECTION_ID);
} else {
mCalendarId = CalendarUtilities.createCalendar(mService, mAccount, mMailbox);
}
mCalendarIdString = Long.toString(mCalendarId);
mCalendarIdArgument = new String[] {mCalendarIdString};
} finally {
c.close();
}
}
@Override
public String getCollectionName() {
return "Calendar";
}
@Override
public void cleanup() {
}
@Override
public void wipe() {
// Delete the calendar associated with this account
// CalendarProvider2 does NOT handle selection arguments in deletions
mContentResolver.delete(
asSyncAdapter(Calendars.CONTENT_URI, mEmailAddress,
Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE),
Calendars.ACCOUNT_NAME + "=" + DatabaseUtils.sqlEscapeString(mEmailAddress)
+ " AND " + Calendars.ACCOUNT_TYPE + "="
+ DatabaseUtils.sqlEscapeString(AccountManagerTypes.TYPE_EXCHANGE), null);
// Invalidate our calendar observers
ExchangeService.unregisterCalendarObservers();
}
@Override
public void sendSyncOptions(Double protocolVersion, Serializer s) throws IOException {
setPimSyncOptions(protocolVersion, Eas.FILTER_2_WEEKS, s);
}
@Override
public boolean isSyncable() {
return ContentResolver.getSyncAutomatically(mAccountManagerAccount,
CalendarContract.AUTHORITY);
}
@Override
public boolean parse(InputStream is) throws IOException, CommandStatusException {
EasCalendarSyncParser p = new EasCalendarSyncParser(is, this);
return p.parse();
}
public static Uri asSyncAdapter(Uri uri, String account, String accountType) {
return uri.buildUpon().appendQueryParameter(CalendarContract.CALLER_IS_SYNCADAPTER, "true")
.appendQueryParameter(Calendars.ACCOUNT_NAME, account)
.appendQueryParameter(Calendars.ACCOUNT_TYPE, accountType).build();
}
/**
* Generate the uri for the data row associated with this NamedContentValues object
* @param ncv the NamedContentValues object
* @return a uri that can be used to refer to this row
*/
public Uri dataUriFromNamedContentValues(NamedContentValues ncv) {
long id = ncv.values.getAsLong(RawContacts._ID);
Uri dataUri = ContentUris.withAppendedId(ncv.uri, id);
return dataUri;
}
/**
* We get our SyncKey from CalendarProvider. If there's not one, we set it to "0" (the reset
* state) and save that away.
*/
@Override
public String getSyncKey() throws IOException {
synchronized (sSyncKeyLock) {
ContentProviderClient client = mService.mContentResolver
.acquireContentProviderClient(CalendarContract.CONTENT_URI);
try {
byte[] data = SyncStateContract.Helpers.get(
client,
asSyncAdapter(SyncState.CONTENT_URI, mEmailAddress,
Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), mAccountManagerAccount);
if (data == null || data.length == 0) {
// Initialize the SyncKey
setSyncKey("0", false);
return "0";
} else {
String syncKey = new String(data);
userLog("SyncKey retrieved as ", syncKey, " from CalendarProvider");
return syncKey;
}
} catch (RemoteException e) {
throw new IOException("Can't get SyncKey from CalendarProvider");
}
}
}
/**
* We only need to set this when we're forced to make the SyncKey "0" (a reset). In all other
* cases, the SyncKey is set within Calendar
*/
@Override
public void setSyncKey(String syncKey, boolean inCommands) throws IOException {
synchronized (sSyncKeyLock) {
if ("0".equals(syncKey) || !inCommands) {
ContentProviderClient client = mService.mContentResolver
.acquireContentProviderClient(CalendarContract.CONTENT_URI);
try {
SyncStateContract.Helpers.set(
client,
asSyncAdapter(SyncState.CONTENT_URI, mEmailAddress,
Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), mAccountManagerAccount,
syncKey.getBytes());
userLog("SyncKey set to ", syncKey, " in CalendarProvider");
} catch (RemoteException e) {
throw new IOException("Can't set SyncKey in CalendarProvider");
}
}
mMailbox.mSyncKey = syncKey;
}
}
public class EasCalendarSyncParser extends AbstractSyncParser {
String[] mBindArgument = new String[1];
Uri mAccountUri;
CalendarOperations mOps = new CalendarOperations();
public EasCalendarSyncParser(InputStream in, CalendarSyncAdapter adapter)
throws IOException {
super(in, adapter);
setLoggingTag("CalendarParser");
mAccountUri = Events.CONTENT_URI;
}
private void addOrganizerToAttendees(CalendarOperations ops, long eventId,
String organizerName, String organizerEmail) {
// Handle the organizer (who IS an attendee on device, but NOT in EAS)
if (organizerName != null || organizerEmail != null) {
ContentValues attendeeCv = new ContentValues();
if (organizerName != null) {
attendeeCv.put(Attendees.ATTENDEE_NAME, organizerName);
}
if (organizerEmail != null) {
attendeeCv.put(Attendees.ATTENDEE_EMAIL, organizerEmail);
}
attendeeCv.put(Attendees.ATTENDEE_RELATIONSHIP, Attendees.RELATIONSHIP_ORGANIZER);
attendeeCv.put(Attendees.ATTENDEE_TYPE, Attendees.TYPE_REQUIRED);
attendeeCv.put(Attendees.ATTENDEE_STATUS, Attendees.ATTENDEE_STATUS_ACCEPTED);
if (eventId < 0) {
ops.newAttendee(attendeeCv);
} else {
ops.updatedAttendee(attendeeCv, eventId);
}
}
}
/**
* Set DTSTART, DTEND, DURATION and EVENT_TIMEZONE as appropriate for the given Event
* The follow rules are enforced by CalendarProvider2:
* Events that aren't exceptions MUST have either 1) a DTEND or 2) a DURATION
* Recurring events (i.e. events with RRULE) must have a DURATION
* All-day recurring events MUST have a DURATION that is in the form P<n>D
* Other events MAY have a DURATION in any valid form (we use P<n>M)
* All-day events MUST have hour, minute, and second = 0; in addition, they must have
* the EVENT_TIMEZONE set to UTC
* Also, exceptions to all-day events need to have an ORIGINAL_INSTANCE_TIME that has
* hour, minute, and second = 0 and be set in UTC
* @param cv the ContentValues for the Event
* @param startTime the start time for the Event
* @param endTime the end time for the Event
* @param allDayEvent whether this is an all day event (1) or not (0)
*/
/*package*/ void setTimeRelatedValues(ContentValues cv, long startTime, long endTime,
int allDayEvent) {
// If there's no startTime, the event will be found to be invalid, so return
if (startTime < 0) return;
// EAS events can arrive without an end time, but CalendarProvider requires them
// so we'll default to 30 minutes; this will be superceded if this is an all-day event
if (endTime < 0) endTime = startTime + (30*MINUTES);
// If this is an all-day event, set hour, minute, and second to zero, and use UTC
if (allDayEvent != 0) {
startTime = CalendarUtilities.getUtcAllDayCalendarTime(startTime, mLocalTimeZone);
endTime = CalendarUtilities.getUtcAllDayCalendarTime(endTime, mLocalTimeZone);
String originalTimeZone = cv.getAsString(Events.EVENT_TIMEZONE);
cv.put(EVENT_SAVED_TIMEZONE_COLUMN, originalTimeZone);
cv.put(Events.EVENT_TIMEZONE, UTC_TIMEZONE.getID());
}
// If this is an exception, and the original was an all-day event, make sure the
// original instance time has hour, minute, and second set to zero, and is in UTC
if (cv.containsKey(Events.ORIGINAL_INSTANCE_TIME) &&
cv.containsKey(Events.ORIGINAL_ALL_DAY)) {
Integer ade = cv.getAsInteger(Events.ORIGINAL_ALL_DAY);
if (ade != null && ade != 0) {
long exceptionTime = cv.getAsLong(Events.ORIGINAL_INSTANCE_TIME);
GregorianCalendar cal = new GregorianCalendar(UTC_TIMEZONE);
cal.setTimeInMillis(exceptionTime);
cal.set(GregorianCalendar.HOUR_OF_DAY, 0);
cal.set(GregorianCalendar.MINUTE, 0);
cal.set(GregorianCalendar.SECOND, 0);
cv.put(Events.ORIGINAL_INSTANCE_TIME, cal.getTimeInMillis());
}
}
// Always set DTSTART
cv.put(Events.DTSTART, startTime);
// For recurring events, set DURATION. Use P<n>D format for all day events
if (cv.containsKey(Events.RRULE)) {
if (allDayEvent != 0) {
cv.put(Events.DURATION, "P" + ((endTime - startTime) / DAYS) + "D");
}
else {
cv.put(Events.DURATION, "P" + ((endTime - startTime) / MINUTES) + "M");
}
// For other events, set DTEND and LAST_DATE
} else {
cv.put(Events.DTEND, endTime);
cv.put(Events.LAST_DATE, endTime);
}
}
public void addEvent(CalendarOperations ops, String serverId, boolean update)
throws IOException {
ContentValues cv = new ContentValues();
cv.put(Events.CALENDAR_ID, mCalendarId);
cv.put(Events._SYNC_ID, serverId);
cv.put(Events.HAS_ATTENDEE_DATA, 1);
cv.put(Events.SYNC_DATA2, "0");
int allDayEvent = 0;
String organizerName = null;
String organizerEmail = null;
int eventOffset = -1;
int deleteOffset = -1;
int busyStatus = CalendarUtilities.BUSY_STATUS_TENTATIVE;
int responseType = CalendarUtilities.RESPONSE_TYPE_NONE;
boolean firstTag = true;
long eventId = -1;
long startTime = -1;
long endTime = -1;
TimeZone timeZone = null;
// Keep track of the attendees; exceptions will need them
ArrayList<ContentValues> attendeeValues = new ArrayList<ContentValues>();
int reminderMins = -1;
String dtStamp = null;
boolean organizerAdded = false;
while (nextTag(Tags.SYNC_APPLICATION_DATA) != END) {
if (update && firstTag) {
// Find the event that's being updated
Cursor c = getServerIdCursor(serverId);
long id = -1;
try {
if (c != null && c.moveToFirst()) {
id = c.getLong(0);
}
} finally {
if (c != null) c.close();
}
if (id > 0) {
// DTSTAMP can come first, and we simply need to track it
if (tag == Tags.CALENDAR_DTSTAMP) {
dtStamp = getValue();
continue;
} else if (tag == Tags.CALENDAR_ATTENDEES) {
// This is an attendees-only update; just
// delete/re-add attendees
mBindArgument[0] = Long.toString(id);
ops.add(ContentProviderOperation
.newDelete(
asSyncAdapter(Attendees.CONTENT_URI, mEmailAddress,
Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE))
.withSelection(ATTENDEES_EXCEPT_ORGANIZER, mBindArgument)
.build());
eventId = id;
} else {
// Otherwise, delete the original event and recreate it
userLog("Changing (delete/add) event ", serverId);
deleteOffset = ops.newDelete(id, serverId);
// Add a placeholder event so that associated tables can reference
// this as a back reference. We add the event at the end of the method
eventOffset = ops.newEvent(PLACEHOLDER_OPERATION);
}
} else {
// The changed item isn't found. We'll treat this as a new item
eventOffset = ops.newEvent(PLACEHOLDER_OPERATION);
userLog(TAG, "Changed item not found; treating as new.");
}
} else if (firstTag) {
// Add a placeholder event so that associated tables can reference
// this as a back reference. We add the event at the end of the method
eventOffset = ops.newEvent(PLACEHOLDER_OPERATION);
}
firstTag = false;
switch (tag) {
case Tags.CALENDAR_ALL_DAY_EVENT:
allDayEvent = getValueInt();
if (allDayEvent != 0 && timeZone != null) {
// If the event doesn't start at midnight local time, we won't consider
// this an all-day event in the local time zone (this is what OWA does)
GregorianCalendar cal = new GregorianCalendar(mLocalTimeZone);
cal.setTimeInMillis(startTime);
userLog("All-day event arrived in: " + timeZone.getID());
if (cal.get(GregorianCalendar.HOUR_OF_DAY) != 0 ||
cal.get(GregorianCalendar.MINUTE) != 0) {
allDayEvent = 0;
userLog("Not an all-day event locally: " + mLocalTimeZone.getID());
}
}
cv.put(Events.ALL_DAY, allDayEvent);
break;
case Tags.CALENDAR_ATTACHMENTS:
attachmentsParser();
break;
case Tags.CALENDAR_ATTENDEES:
// If eventId >= 0, this is an update; otherwise, a new Event
attendeeValues = attendeesParser(ops, eventId);
break;
case Tags.BASE_BODY:
cv.put(Events.DESCRIPTION, bodyParser());
break;
case Tags.CALENDAR_BODY:
cv.put(Events.DESCRIPTION, getValue());
break;
case Tags.CALENDAR_TIME_ZONE:
timeZone = CalendarUtilities.tziStringToTimeZone(getValue());
if (timeZone == null) {
timeZone = mLocalTimeZone;
}
cv.put(Events.EVENT_TIMEZONE, timeZone.getID());
break;
case Tags.CALENDAR_START_TIME:
startTime = Utility.parseDateTimeToMillis(getValue());
break;
case Tags.CALENDAR_END_TIME:
endTime = Utility.parseDateTimeToMillis(getValue());
break;
case Tags.CALENDAR_EXCEPTIONS:
// For exceptions to show the organizer, the organizer must be added before
// we call exceptionsParser
addOrganizerToAttendees(ops, eventId, organizerName, organizerEmail);
organizerAdded = true;
exceptionsParser(ops, cv, attendeeValues, reminderMins, busyStatus,
startTime, endTime);
break;
case Tags.CALENDAR_LOCATION:
cv.put(Events.EVENT_LOCATION, getValue());
break;
case Tags.CALENDAR_RECURRENCE:
String rrule = recurrenceParser();
if (rrule != null) {
cv.put(Events.RRULE, rrule);
}
break;
case Tags.CALENDAR_ORGANIZER_EMAIL:
organizerEmail = getValue();
cv.put(Events.ORGANIZER, organizerEmail);
break;
case Tags.CALENDAR_SUBJECT:
cv.put(Events.TITLE, getValue());
break;
case Tags.CALENDAR_SENSITIVITY:
cv.put(Events.ACCESS_LEVEL, encodeVisibility(getValueInt()));
break;
case Tags.CALENDAR_ORGANIZER_NAME:
organizerName = getValue();
break;
case Tags.CALENDAR_REMINDER_MINS_BEFORE:
reminderMins = getValueInt();
ops.newReminder(reminderMins);
cv.put(Events.HAS_ALARM, 1);
break;
// The following are fields we should save (for changes), though they don't
// relate to data used by CalendarProvider at this point
case Tags.CALENDAR_UID:
cv.put(Events.SYNC_DATA2, getValue());
break;
case Tags.CALENDAR_DTSTAMP:
dtStamp = getValue();
break;
case Tags.CALENDAR_MEETING_STATUS:
ops.newExtendedProperty(EXTENDED_PROPERTY_MEETING_STATUS, getValue());
break;
case Tags.CALENDAR_BUSY_STATUS:
// We'll set the user's status in the Attendees table below
// Don't set selfAttendeeStatus or CalendarProvider will create a duplicate
// attendee!
busyStatus = getValueInt();
break;
case Tags.CALENDAR_RESPONSE_TYPE:
// EAS 14+ uses this for the user's response status; we'll use this instead
// of busy status, if it appears
responseType = getValueInt();
break;
case Tags.CALENDAR_CATEGORIES:
String categories = categoriesParser(ops);
if (categories.length() > 0) {
ops.newExtendedProperty(EXTENDED_PROPERTY_CATEGORIES, categories);
}
break;
default:
skipTag();
}
}
// Enforce CalendarProvider required properties
setTimeRelatedValues(cv, startTime, endTime, allDayEvent);
// If we haven't added the organizer to attendees, do it now
if (!organizerAdded) {
addOrganizerToAttendees(ops, eventId, organizerName, organizerEmail);
}
// Note that organizerEmail can be null with a DTSTAMP only change from the server
boolean selfOrganizer = (mEmailAddress.equals(organizerEmail));
// Store email addresses of attendees (in a tokenizable string) in ExtendedProperties
// If the user is an attendee, set the attendee status using busyStatus (note that the
// busyStatus is inherited from the parent unless it's specified in the exception)
// Add the insert/update operation for each attendee (based on whether it's add/change)
int numAttendees = attendeeValues.size();
if (numAttendees > MAX_SYNCED_ATTENDEES) {
// Indicate that we've redacted attendees. If we're the organizer, disable edit
// by setting organizerEmail to a bogus value and by setting the upsync prohibited
// extended properly.
// Note that we don't set ANY attendees if we're in this branch; however, the
// organizer has already been included above, and WILL show up (which is good)
if (eventId < 0) {
ops.newExtendedProperty(EXTENDED_PROPERTY_ATTENDEES_REDACTED, "1");
if (selfOrganizer) {
ops.newExtendedProperty(EXTENDED_PROPERTY_UPSYNC_PROHIBITED, "1");
}
} else {
ops.updatedExtendedProperty(EXTENDED_PROPERTY_ATTENDEES_REDACTED, "1", eventId);
if (selfOrganizer) {
ops.updatedExtendedProperty(EXTENDED_PROPERTY_UPSYNC_PROHIBITED, "1",
eventId);
}
}
if (selfOrganizer) {
organizerEmail = BOGUS_ORGANIZER_EMAIL;
cv.put(Events.ORGANIZER, organizerEmail);
}
// Tell UI that we don't have any attendees
cv.put(Events.HAS_ATTENDEE_DATA, "0");
mService.userLog("Maximum number of attendees exceeded; redacting");
} else if (numAttendees > 0) {
StringBuilder sb = new StringBuilder();
for (ContentValues attendee: attendeeValues) {
String attendeeEmail = attendee.getAsString(Attendees.ATTENDEE_EMAIL);
sb.append(attendeeEmail);
sb.append(ATTENDEE_TOKENIZER_DELIMITER);
if (mEmailAddress.equalsIgnoreCase(attendeeEmail)) {
int attendeeStatus;
// We'll use the response type (EAS 14), if we've got one; otherwise, we'll
// try to infer it from busy status
if (responseType != CalendarUtilities.RESPONSE_TYPE_NONE) {
attendeeStatus =
CalendarUtilities.attendeeStatusFromResponseType(responseType);
} else if (!update) {
// For new events in EAS < 14, we have no idea what the busy status
// means, so we show "none", allowing the user to select an option.
attendeeStatus = Attendees.ATTENDEE_STATUS_NONE;
} else {
// For updated events, we'll try to infer the attendee status from the
// busy status
attendeeStatus =
CalendarUtilities.attendeeStatusFromBusyStatus(busyStatus);
}
attendee.put(Attendees.ATTENDEE_STATUS, attendeeStatus);
// If we're an attendee, save away our initial attendee status in the
// event's ExtendedProperties (we look for differences between this and
// the user's current attendee status to determine whether an email needs
// to be sent to the organizer)
// organizerEmail will be null in the case that this is an attendees-only
// change from the server
if (organizerEmail == null ||
!organizerEmail.equalsIgnoreCase(attendeeEmail)) {
if (eventId < 0) {
ops.newExtendedProperty(EXTENDED_PROPERTY_USER_ATTENDEE_STATUS,
Integer.toString(attendeeStatus));
} else {
ops.updatedExtendedProperty(EXTENDED_PROPERTY_USER_ATTENDEE_STATUS,
Integer.toString(attendeeStatus), eventId);
}
}
}
if (eventId < 0) {
ops.newAttendee(attendee);
} else {
ops.updatedAttendee(attendee, eventId);
}
}
if (eventId < 0) {
ops.newExtendedProperty(EXTENDED_PROPERTY_ATTENDEES, sb.toString());
ops.newExtendedProperty(EXTENDED_PROPERTY_ATTENDEES_REDACTED, "0");
ops.newExtendedProperty(EXTENDED_PROPERTY_UPSYNC_PROHIBITED, "0");
} else {
ops.updatedExtendedProperty(EXTENDED_PROPERTY_ATTENDEES, sb.toString(),
eventId);
ops.updatedExtendedProperty(EXTENDED_PROPERTY_ATTENDEES_REDACTED, "0", eventId);
ops.updatedExtendedProperty(EXTENDED_PROPERTY_UPSYNC_PROHIBITED, "0", eventId);
}
}
// Put the real event in the proper place in the ops ArrayList
if (eventOffset >= 0) {
// Store away the DTSTAMP here
if (dtStamp != null) {
ops.newExtendedProperty(EXTENDED_PROPERTY_DTSTAMP, dtStamp);
}
if (isValidEventValues(cv)) {
ops.set(eventOffset,
ContentProviderOperation
.newInsert(
asSyncAdapter(Events.CONTENT_URI, mEmailAddress,
Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE))
.withValues(cv).build());
} else {
// If we can't add this event (it's invalid), remove all of the inserts
// we've built for it
int cnt = ops.mCount - eventOffset;
userLog(TAG, "Removing " + cnt + " inserts from mOps");
for (int i = 0; i < cnt; i++) {
ops.remove(eventOffset);
}
ops.mCount = eventOffset;
// If this is a change, we need to also remove the deletion that comes
// before the addition
if (deleteOffset >= 0) {
// Remove the deletion
ops.remove(deleteOffset);
// And the deletion of exceptions
ops.remove(deleteOffset);
userLog(TAG, "Removing deletion ops from mOps");
ops.mCount = deleteOffset;
}
}
}
}
private void logEventColumns(ContentValues cv, String reason) {
if (Eas.USER_LOG) {
StringBuilder sb =
new StringBuilder("Event invalid, " + reason + ", skipping: Columns = ");
for (Entry<String, Object> entry: cv.valueSet()) {
sb.append(entry.getKey());
sb.append('/');
}
userLog(TAG, sb.toString());
}
}
/*package*/ boolean isValidEventValues(ContentValues cv) {
boolean isException = cv.containsKey(Events.ORIGINAL_INSTANCE_TIME);
// All events require DTSTART
if (!cv.containsKey(Events.DTSTART)) {
logEventColumns(cv, "DTSTART missing");
return false;
// If we're a top-level event, we must have _SYNC_DATA (uid)
} else if (!isException && !cv.containsKey(Events.SYNC_DATA2)) {
logEventColumns(cv, "_SYNC_DATA missing");
return false;
// We must also have DTEND or DURATION if we're not an exception
} else if (!isException && !cv.containsKey(Events.DTEND) &&
!cv.containsKey(Events.DURATION)) {
logEventColumns(cv, "DTEND/DURATION missing");
return false;
// Exceptions require DTEND
} else if (isException && !cv.containsKey(Events.DTEND)) {
logEventColumns(cv, "Exception missing DTEND");
return false;
// If this is a recurrence, we need a DURATION (in days if an all-day event)
} else if (cv.containsKey(Events.RRULE)) {
String duration = cv.getAsString(Events.DURATION);
if (duration == null) return false;
if (cv.containsKey(Events.ALL_DAY)) {
Integer ade = cv.getAsInteger(Events.ALL_DAY);
if (ade != null && ade != 0 && !duration.endsWith("D")) {
return false;
}
}
}
return true;
}
public String recurrenceParser() throws IOException {
// Turn this information into an RRULE
int type = -1;
int occurrences = -1;
int interval = -1;
int dow = -1;
int dom = -1;
int wom = -1;
int moy = -1;
String until = null;
while (nextTag(Tags.CALENDAR_RECURRENCE) != END) {
switch (tag) {
case Tags.CALENDAR_RECURRENCE_TYPE:
type = getValueInt();
break;
case Tags.CALENDAR_RECURRENCE_INTERVAL:
interval = getValueInt();
break;
case Tags.CALENDAR_RECURRENCE_OCCURRENCES:
occurrences = getValueInt();
break;
case Tags.CALENDAR_RECURRENCE_DAYOFWEEK:
dow = getValueInt();
break;
case Tags.CALENDAR_RECURRENCE_DAYOFMONTH:
dom = getValueInt();
break;
case Tags.CALENDAR_RECURRENCE_WEEKOFMONTH:
wom = getValueInt();
break;
case Tags.CALENDAR_RECURRENCE_MONTHOFYEAR:
moy = getValueInt();
break;
case Tags.CALENDAR_RECURRENCE_UNTIL:
until = getValue();
break;
default:
skipTag();
}
}
return CalendarUtilities.rruleFromRecurrence(type, occurrences, interval,
dow, dom, wom, moy, until);
}
private void exceptionParser(CalendarOperations ops, ContentValues parentCv,
ArrayList<ContentValues> attendeeValues, int reminderMins, int busyStatus,
long startTime, long endTime) throws IOException {
ContentValues cv = new ContentValues();
cv.put(Events.CALENDAR_ID, mCalendarId);
// It appears that these values have to be copied from the parent if they are to appear
// Note that they can be overridden below
cv.put(Events.ORGANIZER, parentCv.getAsString(Events.ORGANIZER));
cv.put(Events.TITLE, parentCv.getAsString(Events.TITLE));
cv.put(Events.DESCRIPTION, parentCv.getAsString(Events.DESCRIPTION));
cv.put(Events.ORIGINAL_ALL_DAY, parentCv.getAsInteger(Events.ALL_DAY));
cv.put(Events.EVENT_LOCATION, parentCv.getAsString(Events.EVENT_LOCATION));
cv.put(Events.ACCESS_LEVEL, parentCv.getAsString(Events.ACCESS_LEVEL));
cv.put(Events.EVENT_TIMEZONE, parentCv.getAsString(Events.EVENT_TIMEZONE));
// Exceptions should always have this set to zero, since EAS has no concept of
// separate attendee lists for exceptions; if we fail to do this, then the UI will
// allow the user to change attendee data, and this change would never get reflected
// on the server.
cv.put(Events.HAS_ATTENDEE_DATA, 0);
int allDayEvent = 0;
// This column is the key that links the exception to the serverId
cv.put(Events.ORIGINAL_SYNC_ID, parentCv.getAsString(Events._SYNC_ID));
String exceptionStartTime = "_noStartTime";
while (nextTag(Tags.SYNC_APPLICATION_DATA) != END) {
switch (tag) {
case Tags.CALENDAR_ATTACHMENTS:
attachmentsParser();
break;
case Tags.CALENDAR_EXCEPTION_START_TIME:
exceptionStartTime = getValue();
cv.put(Events.ORIGINAL_INSTANCE_TIME,
Utility.parseDateTimeToMillis(exceptionStartTime));
break;
case Tags.CALENDAR_EXCEPTION_IS_DELETED:
if (getValueInt() == 1) {
cv.put(Events.STATUS, Events.STATUS_CANCELED);
}
break;
case Tags.CALENDAR_ALL_DAY_EVENT:
allDayEvent = getValueInt();
cv.put(Events.ALL_DAY, allDayEvent);
break;
case Tags.BASE_BODY:
cv.put(Events.DESCRIPTION, bodyParser());
break;
case Tags.CALENDAR_BODY:
cv.put(Events.DESCRIPTION, getValue());
break;
case Tags.CALENDAR_START_TIME:
startTime = Utility.parseDateTimeToMillis(getValue());
break;
case Tags.CALENDAR_END_TIME:
endTime = Utility.parseDateTimeToMillis(getValue());
break;
case Tags.CALENDAR_LOCATION:
cv.put(Events.EVENT_LOCATION, getValue());
break;
case Tags.CALENDAR_RECURRENCE:
String rrule = recurrenceParser();
if (rrule != null) {
cv.put(Events.RRULE, rrule);
}
break;
case Tags.CALENDAR_SUBJECT:
cv.put(Events.TITLE, getValue());
break;
case Tags.CALENDAR_SENSITIVITY:
cv.put(Events.ACCESS_LEVEL, encodeVisibility(getValueInt()));
break;
case Tags.CALENDAR_BUSY_STATUS:
busyStatus = getValueInt();
// Don't set selfAttendeeStatus or CalendarProvider will create a duplicate
// attendee!
break;
// TODO How to handle these items that are linked to event id!
// case Tags.CALENDAR_DTSTAMP:
// ops.newExtendedProperty("dtstamp", getValue());
// break;
// case Tags.CALENDAR_REMINDER_MINS_BEFORE:
// ops.newReminder(getValueInt());
// break;
default:
skipTag();
}
}
// We need a _sync_id, but it can't be the parent's id, so we generate one
cv.put(Events._SYNC_ID, parentCv.getAsString(Events._SYNC_ID) + '_' +
exceptionStartTime);
// Enforce CalendarProvider required properties
setTimeRelatedValues(cv, startTime, endTime, allDayEvent);
// Don't insert an invalid exception event
if (!isValidEventValues(cv)) return;
// Add the exception insert
int exceptionStart = ops.mCount;
ops.newException(cv);
// Also add the attendees, because they need to be copied over from the parent event
boolean attendeesRedacted = false;
if (attendeeValues != null) {
for (ContentValues attValues: attendeeValues) {
// If this is the user, use his busy status for attendee status
String attendeeEmail = attValues.getAsString(Attendees.ATTENDEE_EMAIL);
// Note that the exception at which we surpass the redaction limit might have
// any number of attendees shown; since this is an edge case and a workaround,
// it seems to be an acceptable implementation
if (mEmailAddress.equalsIgnoreCase(attendeeEmail)) {
attValues.put(Attendees.ATTENDEE_STATUS,
CalendarUtilities.attendeeStatusFromBusyStatus(busyStatus));
ops.newAttendee(attValues, exceptionStart);
} else if (ops.size() < MAX_OPS_BEFORE_EXCEPTION_ATTENDEE_REDACTION) {
ops.newAttendee(attValues, exceptionStart);
} else {
attendeesRedacted = true;
}
}
}
// And add the parent's reminder value
if (reminderMins > 0) {
ops.newReminder(reminderMins, exceptionStart);
}
if (attendeesRedacted) {
mService.userLog("Attendees redacted in this exception");
}
}
private int encodeVisibility(int easVisibility) {
int visibility = 0;
switch(easVisibility) {
case 0:
visibility = Events.ACCESS_DEFAULT;
break;
case 1:
visibility = Events.ACCESS_PUBLIC;
break;
case 2:
visibility = Events.ACCESS_PRIVATE;
break;
case 3:
visibility = Events.ACCESS_CONFIDENTIAL;
break;
}
return visibility;
}
private void exceptionsParser(CalendarOperations ops, ContentValues cv,
ArrayList<ContentValues> attendeeValues, int reminderMins, int busyStatus,
long startTime, long endTime) throws IOException {
while (nextTag(Tags.CALENDAR_EXCEPTIONS) != END) {
switch (tag) {
case Tags.CALENDAR_EXCEPTION:
exceptionParser(ops, cv, attendeeValues, reminderMins, busyStatus,
startTime, endTime);
break;
default:
skipTag();
}
}
}
private String categoriesParser(CalendarOperations ops) throws IOException {
StringBuilder categories = new StringBuilder();
while (nextTag(Tags.CALENDAR_CATEGORIES) != END) {
switch (tag) {
case Tags.CALENDAR_CATEGORY:
// TODO Handle categories (there's no similar concept for gdata AFAIK)
// We need to save them and spit them back when we update the event
categories.append(getValue());
categories.append(CATEGORY_TOKENIZER_DELIMITER);
break;
default:
skipTag();
}
}
return categories.toString();
}
/**
* For now, we ignore (but still have to parse) event attachments; these are new in EAS 14
*/
private void attachmentsParser() throws IOException {
while (nextTag(Tags.CALENDAR_ATTACHMENTS) != END) {
switch (tag) {
case Tags.CALENDAR_ATTACHMENT:
skipParser(Tags.CALENDAR_ATTACHMENT);
break;
default:
skipTag();
}
}
}
private ArrayList<ContentValues> attendeesParser(CalendarOperations ops, long eventId)
throws IOException {
int attendeeCount = 0;
ArrayList<ContentValues> attendeeValues = new ArrayList<ContentValues>();
while (nextTag(Tags.CALENDAR_ATTENDEES) != END) {
switch (tag) {
case Tags.CALENDAR_ATTENDEE:
ContentValues cv = attendeeParser(ops, eventId);
// If we're going to redact these attendees anyway, let's avoid unnecessary
// memory pressure, and not keep them around
// We still need to parse them all, however
attendeeCount++;
// Allow one more than MAX_ATTENDEES, so that the check for "too many" will
// succeed in addEvent
if (attendeeCount <= (MAX_SYNCED_ATTENDEES+1)) {
attendeeValues.add(cv);
}
break;
default:
skipTag();
}
}
return attendeeValues;
}
private ContentValues attendeeParser(CalendarOperations ops, long eventId)
throws IOException {
ContentValues cv = new ContentValues();
while (nextTag(Tags.CALENDAR_ATTENDEE) != END) {
switch (tag) {
case Tags.CALENDAR_ATTENDEE_EMAIL:
cv.put(Attendees.ATTENDEE_EMAIL, getValue());
break;
case Tags.CALENDAR_ATTENDEE_NAME:
cv.put(Attendees.ATTENDEE_NAME, getValue());
break;
case Tags.CALENDAR_ATTENDEE_STATUS:
int status = getValueInt();
cv.put(Attendees.ATTENDEE_STATUS,
(status == 2) ? Attendees.ATTENDEE_STATUS_TENTATIVE :
(status == 3) ? Attendees.ATTENDEE_STATUS_ACCEPTED :
(status == 4) ? Attendees.ATTENDEE_STATUS_DECLINED :
(status == 5) ? Attendees.ATTENDEE_STATUS_INVITED :
Attendees.ATTENDEE_STATUS_NONE);
break;
case Tags.CALENDAR_ATTENDEE_TYPE:
int type = Attendees.TYPE_NONE;
// EAS types: 1 = req'd, 2 = opt, 3 = resource
switch (getValueInt()) {
case 1:
type = Attendees.TYPE_REQUIRED;
break;
case 2:
type = Attendees.TYPE_OPTIONAL;
break;
}
cv.put(Attendees.ATTENDEE_TYPE, type);
break;
default:
skipTag();
}
}
cv.put(Attendees.ATTENDEE_RELATIONSHIP, Attendees.RELATIONSHIP_ATTENDEE);
return cv;
}
private String bodyParser() throws IOException {
String body = null;
while (nextTag(Tags.BASE_BODY) != END) {
switch (tag) {
case Tags.BASE_DATA:
body = getValue();
break;
default:
skipTag();
}
}
// Handle null data without error
if (body == null) return "";
// Remove \r's from any body text
return body.replace("\r\n", "\n");
}
public void addParser(CalendarOperations ops) throws IOException {
String serverId = null;
while (nextTag(Tags.SYNC_ADD) != END) {
switch (tag) {
case Tags.SYNC_SERVER_ID: // same as
serverId = getValue();
break;
case Tags.SYNC_APPLICATION_DATA:
addEvent(ops, serverId, false);
break;
default:
skipTag();
}
}
}
private Cursor getServerIdCursor(String serverId) {
return mContentResolver.query(mAccountUri, ID_PROJECTION, SERVER_ID_AND_CALENDAR_ID,
new String[] {serverId, mCalendarIdString}, null);
}
private Cursor getClientIdCursor(String clientId) {
mBindArgument[0] = clientId;
return mContentResolver.query(mAccountUri, ID_PROJECTION, CLIENT_ID_SELECTION,
mBindArgument, null);
}
public void deleteParser(CalendarOperations ops) throws IOException {
while (nextTag(Tags.SYNC_DELETE) != END) {
switch (tag) {
case Tags.SYNC_SERVER_ID:
String serverId = getValue();
// Find the event with the given serverId
Cursor c = getServerIdCursor(serverId);
try {
if (c.moveToFirst()) {
userLog("Deleting ", serverId);
ops.delete(c.getLong(0), serverId);
}
} finally {
c.close();
}
break;
default:
skipTag();
}
}
}
/**
* A change is handled as a delete (including all exceptions) and an add
* This isn't as efficient as attempting to traverse the original and all of its exceptions,
* but changes happen infrequently and this code is both simpler and easier to maintain
* @param ops the array of pending ContactProviderOperations.
* @throws IOException
*/
public void changeParser(CalendarOperations ops) throws IOException {
String serverId = null;
while (nextTag(Tags.SYNC_CHANGE) != END) {
switch (tag) {
case Tags.SYNC_SERVER_ID:
serverId = getValue();
break;
case Tags.SYNC_APPLICATION_DATA:
userLog("Changing " + serverId);
addEvent(ops, serverId, true);
break;
default:
skipTag();
}
}
}
@Override
public void commandsParser() throws IOException {
while (nextTag(Tags.SYNC_COMMANDS) != END) {
if (tag == Tags.SYNC_ADD) {
addParser(mOps);
incrementChangeCount();
} else if (tag == Tags.SYNC_DELETE) {
deleteParser(mOps);
incrementChangeCount();
} else if (tag == Tags.SYNC_CHANGE) {
changeParser(mOps);
incrementChangeCount();
} else
skipTag();
}
}
@Override
public void commit() throws IOException {
userLog("Calendar SyncKey saved as: ", mMailbox.mSyncKey);
// Save the syncKey here, using the Helper provider by Calendar provider
mOps.add(SyncStateContract.Helpers.newSetOperation(
asSyncAdapter(SyncState.CONTENT_URI, mEmailAddress,
Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE),
mAccountManagerAccount,
mMailbox.mSyncKey.getBytes()));
// We need to send cancellations now, because the Event won't exist after the commit
for (long eventId: mSendCancelIdList) {
EmailContent.Message msg;
try {
msg = CalendarUtilities.createMessageForEventId(mContext, eventId,
EmailContent.Message.FLAG_OUTGOING_MEETING_CANCEL, null,
mAccount);
} catch (RemoteException e) {
// Nothing to do here; the Event may no longer exist
continue;
}
if (msg != null) {
EasOutboxService.sendMessage(mContext, mAccount.mId, msg);
}
}
// Execute these all at once...
mOps.execute();
if (mOps.mResults != null) {
// Clear dirty and mark flags for updates sent to server
if (!mUploadedIdList.isEmpty()) {
ContentValues cv = new ContentValues();
cv.put(Events.DIRTY, 0);
cv.put(EVENT_SYNC_MARK, "0");
for (long eventId : mUploadedIdList) {
mContentResolver.update(
asSyncAdapter(
ContentUris.withAppendedId(Events.CONTENT_URI, eventId),
mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), cv,
null, null);
}
}
// Delete events marked for deletion
if (!mDeletedIdList.isEmpty()) {
for (long eventId : mDeletedIdList) {
mContentResolver.delete(
asSyncAdapter(
ContentUris.withAppendedId(Events.CONTENT_URI, eventId),
mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), null,
null);
}
}
// Send any queued up email (invitations replies, etc.)
for (Message msg: mOutgoingMailList) {
EasOutboxService.sendMessage(mContext, mAccount.mId, msg);
}
}
}
public void addResponsesParser() throws IOException {
String serverId = null;
String clientId = null;
int status = -1;
ContentValues cv = new ContentValues();
while (nextTag(Tags.SYNC_ADD) != END) {
switch (tag) {
case Tags.SYNC_SERVER_ID:
serverId = getValue();
break;
case Tags.SYNC_CLIENT_ID:
clientId = getValue();
break;
case Tags.SYNC_STATUS:
status = getValueInt();
if (status != 1) {
userLog("Attempt to add event failed with status: " + status);
}
break;
default:
skipTag();
}
}
if (clientId == null) return;
if (serverId == null) {
// TODO Reconsider how to handle this
serverId = "FAIL:" + status;
}
Cursor c = getClientIdCursor(clientId);
try {
if (c.moveToFirst()) {
cv.put(Events._SYNC_ID, serverId);
cv.put(Events.SYNC_DATA2, clientId);
long id = c.getLong(0);
// Write the serverId into the Event
mOps.add(ContentProviderOperation
.newUpdate(
asSyncAdapter(
ContentUris.withAppendedId(Events.CONTENT_URI, id),
mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE))
.withValues(cv).build());
userLog("New event " + clientId + " was given serverId: " + serverId);
}
} finally {
c.close();
}
}
public void changeResponsesParser() throws IOException {
String serverId = null;
String status = null;
while (nextTag(Tags.SYNC_CHANGE) != END) {
switch (tag) {
case Tags.SYNC_SERVER_ID:
serverId = getValue();
break;
case Tags.SYNC_STATUS:
status = getValue();
break;
default:
skipTag();
}
}
if (serverId != null && status != null) {
userLog("Changed event " + serverId + " failed with status: " + status);
}
}
@Override
public void responsesParser() throws IOException {
// Handle server responses here (for Add and Change)
while (nextTag(Tags.SYNC_RESPONSES) != END) {
if (tag == Tags.SYNC_ADD) {
addResponsesParser();
} else if (tag == Tags.SYNC_CHANGE) {
changeResponsesParser();
} else
skipTag();
}
}
}
protected class CalendarOperations extends ArrayList<ContentProviderOperation> {
private static final long serialVersionUID = 1L;
public int mCount = 0;
private ContentProviderResult[] mResults = null;
private int mEventStart = 0;
@Override
public boolean add(ContentProviderOperation op) {
super.add(op);
mCount++;
return true;
}
public int newEvent(ContentProviderOperation op) {
mEventStart = mCount;
add(op);
return mEventStart;
}
public int newDelete(long id, String serverId) {
int offset = mCount;
delete(id, serverId);
return offset;
}
public void newAttendee(ContentValues cv) {
newAttendee(cv, mEventStart);
}
public void newAttendee(ContentValues cv, int eventStart) {
add(ContentProviderOperation
.newInsert(asSyncAdapter(Attendees.CONTENT_URI, mEmailAddress,
Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE)).withValues(cv)
.withValueBackReference(Attendees.EVENT_ID, eventStart).build());
}
public void updatedAttendee(ContentValues cv, long id) {
cv.put(Attendees.EVENT_ID, id);
add(ContentProviderOperation.newInsert(asSyncAdapter(Attendees.CONTENT_URI,
mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE)).withValues(cv).build());
}
public void newException(ContentValues cv) {
add(ContentProviderOperation.newInsert(
asSyncAdapter(Events.CONTENT_URI, mEmailAddress,
Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE)).withValues(cv).build());
}
public void newExtendedProperty(String name, String value) {
add(ContentProviderOperation
.newInsert(asSyncAdapter(ExtendedProperties.CONTENT_URI, mEmailAddress,
Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE))
.withValue(ExtendedProperties.NAME, name)
.withValue(ExtendedProperties.VALUE, value)
.withValueBackReference(ExtendedProperties.EVENT_ID, mEventStart).build());
}
public void updatedExtendedProperty(String name, String value, long id) {
// Find an existing ExtendedProperties row for this event and property name
Cursor c = mService.mContentResolver.query(ExtendedProperties.CONTENT_URI,
EXTENDED_PROPERTY_PROJECTION, EVENT_ID_AND_NAME,
new String[] {Long.toString(id), name}, null);
long extendedPropertyId = -1;
// If there is one, capture its _id
if (c != null) {
try {
if (c.moveToFirst()) {
extendedPropertyId = c.getLong(EXTENDED_PROPERTY_ID);
}
} finally {
c.close();
}
}
// Either do an update or an insert, depending on whether one
// already exists
if (extendedPropertyId >= 0) {
add(ContentProviderOperation
.newUpdate(
ContentUris.withAppendedId(
asSyncAdapter(ExtendedProperties.CONTENT_URI,
mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE),
extendedPropertyId))
.withValue(ExtendedProperties.VALUE, value).build());
} else {
newExtendedProperty(name, value);
}
}
public void newReminder(int mins, int eventStart) {
add(ContentProviderOperation
.newInsert(asSyncAdapter(Reminders.CONTENT_URI, mEmailAddress,
Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE))
.withValue(Reminders.MINUTES, mins)
.withValue(Reminders.METHOD, Reminders.METHOD_ALERT)
.withValueBackReference(ExtendedProperties.EVENT_ID, eventStart).build());
}
public void newReminder(int mins) {
newReminder(mins, mEventStart);
}
public void delete(long id, String syncId) {
add(ContentProviderOperation.newDelete(
asSyncAdapter(ContentUris.withAppendedId(Events.CONTENT_URI, id),
mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE)).build());
// Delete the exceptions for this Event (CalendarProvider doesn't do
// this)
add(ContentProviderOperation
.newDelete(asSyncAdapter(Events.CONTENT_URI, mEmailAddress,
Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE))
.withSelection(Events.ORIGINAL_SYNC_ID + "=?", new String[] {syncId}).build());
}
public void execute() {
synchronized (mService.getSynchronizer()) {
if (!mService.isStopped()) {
try {
if (!isEmpty()) {
mService.userLog("Executing ", size(), " CPO's");
mResults = mContext.getContentResolver().applyBatch(
CalendarContract.AUTHORITY, this);
}
} catch (RemoteException e) {
// There is nothing sensible to be done here
Log.e(TAG, "problem inserting event during server update", e);
} catch (OperationApplicationException e) {
// There is nothing sensible to be done here
Log.e(TAG, "problem inserting event during server update", e);
}
}
}
}
}
private String decodeVisibility(int visibility) {
int easVisibility = 0;
switch(visibility) {
case Events.ACCESS_DEFAULT:
easVisibility = 0;
break;
case Events.ACCESS_PUBLIC:
easVisibility = 1;
break;
case Events.ACCESS_PRIVATE:
easVisibility = 2;
break;
case Events.ACCESS_CONFIDENTIAL:
easVisibility = 3;
break;
}
return Integer.toString(easVisibility);
}
private int getInt(ContentValues cv, String column) {
Integer i = cv.getAsInteger(column);
if (i == null) return 0;
return i;
}
private void sendEvent(Entity entity, String clientId, Serializer s)
throws IOException {
// Serialize for EAS here
// Set uid with the client id we created
// 1) Serialize the top-level event
// 2) Serialize attendees and reminders from subvalues
// 3) Look for exceptions and serialize with the top-level event
ContentValues entityValues = entity.getEntityValues();
final boolean isException = (clientId == null);
boolean hasAttendees = false;
final boolean isChange = entityValues.containsKey(Events._SYNC_ID);
final Double version = mService.mProtocolVersionDouble;
final boolean allDay =
CalendarUtilities.getIntegerValueAsBoolean(entityValues, Events.ALL_DAY);
// NOTE: Exchange 2003 (EAS 2.5) seems to require the "exception deleted" and "exception
// start time" data before other data in exceptions. Failure to do so results in a
// status 6 error during sync
if (isException) {
// Send exception deleted flag if necessary
Integer deleted = entityValues.getAsInteger(Events.DELETED);
boolean isDeleted = deleted != null && deleted == 1;
Integer eventStatus = entityValues.getAsInteger(Events.STATUS);
boolean isCanceled = eventStatus != null && eventStatus.equals(Events.STATUS_CANCELED);
if (isDeleted || isCanceled) {
s.data(Tags.CALENDAR_EXCEPTION_IS_DELETED, "1");
// If we're deleted, the UI will continue to show this exception until we mark
// it canceled, so we'll do that here...
if (isDeleted && !isCanceled) {
final long eventId = entityValues.getAsLong(Events._ID);
ContentValues cv = new ContentValues();
cv.put(Events.STATUS, Events.STATUS_CANCELED);
mService.mContentResolver.update(
asSyncAdapter(ContentUris.withAppendedId(Events.CONTENT_URI, eventId),
mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), cv, null,
null);
}
} else {
s.data(Tags.CALENDAR_EXCEPTION_IS_DELETED, "0");
}
// TODO Add reminders to exceptions (allow them to be specified!)
Long originalTime = entityValues.getAsLong(Events.ORIGINAL_INSTANCE_TIME);
if (originalTime != null) {
final boolean originalAllDay =
CalendarUtilities.getIntegerValueAsBoolean(entityValues,
Events.ORIGINAL_ALL_DAY);
if (originalAllDay) {
// For all day events, we need our local all-day time
originalTime =
CalendarUtilities.getLocalAllDayCalendarTime(originalTime, mLocalTimeZone);
}
s.data(Tags.CALENDAR_EXCEPTION_START_TIME,
CalendarUtilities.millisToEasDateTime(originalTime));
} else {
// Illegal; what should we do?
}
}
// Get the event's time zone
String timeZoneName =
entityValues.getAsString(allDay ? EVENT_SAVED_TIMEZONE_COLUMN : Events.EVENT_TIMEZONE);
if (timeZoneName == null) {
timeZoneName = mLocalTimeZone.getID();
}
TimeZone eventTimeZone = TimeZone.getTimeZone(timeZoneName);
if (!isException) {
// A time zone is required in all EAS events; we'll use the default if none is set
// Exchange 2003 seems to require this first... :-)
String timeZone = CalendarUtilities.timeZoneToTziString(eventTimeZone);
s.data(Tags.CALENDAR_TIME_ZONE, timeZone);
}
s.data(Tags.CALENDAR_ALL_DAY_EVENT, allDay ? "1" : "0");
// DTSTART is always supplied
long startTime = entityValues.getAsLong(Events.DTSTART);
// Determine endTime; it's either provided as DTEND or we calculate using DURATION
// If no DURATION is provided, we default to one hour
long endTime;
if (entityValues.containsKey(Events.DTEND)) {
endTime = entityValues.getAsLong(Events.DTEND);
} else {
long durationMillis = HOURS;
if (entityValues.containsKey(Events.DURATION)) {
Duration duration = new Duration();
try {
duration.parse(entityValues.getAsString(Events.DURATION));
durationMillis = duration.getMillis();
} catch (ParseException e) {
// Can't do much about this; use the default (1 hour)
}
}
endTime = startTime + durationMillis;
}
if (allDay) {
TimeZone tz = mLocalTimeZone;
startTime = CalendarUtilities.getLocalAllDayCalendarTime(startTime, tz);
endTime = CalendarUtilities.getLocalAllDayCalendarTime(endTime, tz);
}
s.data(Tags.CALENDAR_START_TIME, CalendarUtilities.millisToEasDateTime(startTime));
s.data(Tags.CALENDAR_END_TIME, CalendarUtilities.millisToEasDateTime(endTime));
s.data(Tags.CALENDAR_DTSTAMP,
CalendarUtilities.millisToEasDateTime(System.currentTimeMillis()));
String loc = entityValues.getAsString(Events.EVENT_LOCATION);
if (!TextUtils.isEmpty(loc)) {
if (version < Eas.SUPPORTED_PROTOCOL_EX2007_DOUBLE) {
// EAS 2.5 doesn't like bare line feeds
loc = Utility.replaceBareLfWithCrlf(loc);
}
s.data(Tags.CALENDAR_LOCATION, loc);
}
s.writeStringValue(entityValues, Events.TITLE, Tags.CALENDAR_SUBJECT);
if (version >= Eas.SUPPORTED_PROTOCOL_EX2007_DOUBLE) {
s.start(Tags.BASE_BODY);
s.data(Tags.BASE_TYPE, "1");
s.writeStringValue(entityValues, Events.DESCRIPTION, Tags.BASE_DATA);
s.end();
} else {
// EAS 2.5 doesn't like bare line feeds
s.writeStringValue(entityValues, Events.DESCRIPTION, Tags.CALENDAR_BODY);
}
if (!isException) {
// For Exchange 2003, only upsync if the event is new
if ((version >= Eas.SUPPORTED_PROTOCOL_EX2007_DOUBLE) || !isChange) {
s.writeStringValue(entityValues, Events.ORGANIZER, Tags.CALENDAR_ORGANIZER_EMAIL);
}
String rrule = entityValues.getAsString(Events.RRULE);
if (rrule != null) {
CalendarUtilities.recurrenceFromRrule(rrule, startTime, s);
}
// Handle associated data EXCEPT for attendees, which have to be grouped
ArrayList<NamedContentValues> subValues = entity.getSubValues();
// The earliest of the reminders for this Event; we can only send one reminder...
int earliestReminder = -1;
for (NamedContentValues ncv: subValues) {
Uri ncvUri = ncv.uri;
ContentValues ncvValues = ncv.values;
if (ncvUri.equals(ExtendedProperties.CONTENT_URI)) {
String propertyName =
ncvValues.getAsString(ExtendedProperties.NAME);
String propertyValue =
ncvValues.getAsString(ExtendedProperties.VALUE);
if (TextUtils.isEmpty(propertyValue)) {
continue;
}
if (propertyName.equals(EXTENDED_PROPERTY_CATEGORIES)) {
// Send all the categories back to the server
// We've saved them as a String of delimited tokens
StringTokenizer st =
new StringTokenizer(propertyValue, CATEGORY_TOKENIZER_DELIMITER);
if (st.countTokens() > 0) {
s.start(Tags.CALENDAR_CATEGORIES);
while (st.hasMoreTokens()) {
String category = st.nextToken();
s.data(Tags.CALENDAR_CATEGORY, category);
}
s.end();
}
}
} else if (ncvUri.equals(Reminders.CONTENT_URI)) {
Integer mins = ncvValues.getAsInteger(Reminders.MINUTES);
if (mins != null) {
// -1 means "default", which for Exchange, is 30
if (mins < 0) {
mins = 30;
}
// Save this away if it's the earliest reminder (greatest minutes)
if (mins > earliestReminder) {
earliestReminder = mins;
}
}
}
}
// If we have a reminder, send it to the server
if (earliestReminder >= 0) {
s.data(Tags.CALENDAR_REMINDER_MINS_BEFORE, Integer.toString(earliestReminder));
}
// We've got to send a UID, unless this is an exception. If the event is new, we've
// generated one; if not, we should have gotten one from extended properties.
if (clientId != null) {
s.data(Tags.CALENDAR_UID, clientId);
}
// Handle attendee data here; keep track of organizer and stream it afterward
String organizerName = null;
String organizerEmail = null;
for (NamedContentValues ncv: subValues) {
Uri ncvUri = ncv.uri;
ContentValues ncvValues = ncv.values;
if (ncvUri.equals(Attendees.CONTENT_URI)) {
Integer relationship = ncvValues.getAsInteger(Attendees.ATTENDEE_RELATIONSHIP);
// If there's no relationship, we can't create this for EAS
// Similarly, we need an attendee email for each invitee
if (relationship != null && ncvValues.containsKey(Attendees.ATTENDEE_EMAIL)) {
// Organizer isn't among attendees in EAS
if (relationship == Attendees.RELATIONSHIP_ORGANIZER) {
organizerName = ncvValues.getAsString(Attendees.ATTENDEE_NAME);
organizerEmail = ncvValues.getAsString(Attendees.ATTENDEE_EMAIL);
continue;
}
if (!hasAttendees) {
s.start(Tags.CALENDAR_ATTENDEES);
hasAttendees = true;
}
s.start(Tags.CALENDAR_ATTENDEE);
String attendeeEmail = ncvValues.getAsString(Attendees.ATTENDEE_EMAIL);
String attendeeName = ncvValues.getAsString(Attendees.ATTENDEE_NAME);
if (attendeeName == null) {
attendeeName = attendeeEmail;
}
s.data(Tags.CALENDAR_ATTENDEE_NAME, attendeeName);
s.data(Tags.CALENDAR_ATTENDEE_EMAIL, attendeeEmail);
if (version >= Eas.SUPPORTED_PROTOCOL_EX2007_DOUBLE) {
s.data(Tags.CALENDAR_ATTENDEE_TYPE, "1"); // Required
}
s.end(); // Attendee
}
}
}
if (hasAttendees) {
s.end(); // Attendees
}
// Get busy status from Attendees table
long eventId = entityValues.getAsLong(Events._ID);
int busyStatus = CalendarUtilities.BUSY_STATUS_TENTATIVE;
Cursor c = mService.mContentResolver.query(
asSyncAdapter(Attendees.CONTENT_URI, mEmailAddress,
Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE),
ATTENDEE_STATUS_PROJECTION, EVENT_AND_EMAIL,
new String[] {Long.toString(eventId), mEmailAddress}, null);
if (c != null) {
try {
if (c.moveToFirst()) {
busyStatus = CalendarUtilities.busyStatusFromAttendeeStatus(
c.getInt(ATTENDEE_STATUS_COLUMN_STATUS));
}
} finally {
c.close();
}
}
s.data(Tags.CALENDAR_BUSY_STATUS, Integer.toString(busyStatus));
// Meeting status, 0 = appointment, 1 = meeting, 3 = attendee
if (mEmailAddress.equalsIgnoreCase(organizerEmail)) {
s.data(Tags.CALENDAR_MEETING_STATUS, hasAttendees ? "1" : "0");
} else {
s.data(Tags.CALENDAR_MEETING_STATUS, "3");
}
// For Exchange 2003, only upsync if the event is new
if (((version >= Eas.SUPPORTED_PROTOCOL_EX2007_DOUBLE) || !isChange) &&
organizerName != null) {
s.data(Tags.CALENDAR_ORGANIZER_NAME, organizerName);
}
// NOTE: Sensitivity must NOT be sent to the server for exceptions in Exchange 2003
// The result will be a status 6 failure during sync
Integer visibility = entityValues.getAsInteger(Events.ACCESS_LEVEL);
if (visibility != null) {
s.data(Tags.CALENDAR_SENSITIVITY, decodeVisibility(visibility));
} else {
// Default to private if not set
s.data(Tags.CALENDAR_SENSITIVITY, "1");
}
}
}
/**
* Convenience method for sending an email to the organizer declining the meeting
* @param entity
* @param clientId
*/
private void sendDeclinedEmail(Entity entity, String clientId) {
Message msg =
CalendarUtilities.createMessageForEntity(mContext, entity,
Message.FLAG_OUTGOING_MEETING_DECLINE, clientId, mAccount);
if (msg != null) {
userLog("Queueing declined response to " + msg.mTo);
mOutgoingMailList.add(msg);
}
}
@Override
public boolean sendLocalChanges(Serializer s) throws IOException {
ContentResolver cr = mService.mContentResolver;
if (getSyncKey().equals("0")) {
return false;
}
try {
// We've got to handle exceptions as part of the parent when changes occur, so we need
// to find new/changed exceptions and mark the parent dirty
ArrayList<Long> orphanedExceptions = new ArrayList<Long>();
Cursor c = cr.query(Events.CONTENT_URI, ORIGINAL_EVENT_PROJECTION,
DIRTY_EXCEPTION_IN_CALENDAR, mCalendarIdArgument, null);
try {
ContentValues cv = new ContentValues();
// We use _sync_mark here to distinguish dirty parents from parents with dirty
// exceptions
cv.put(EVENT_SYNC_MARK, "1");
while (c.moveToNext()) {
// Mark the parents of dirty exceptions
long parentId = c.getLong(0);
int cnt = cr.update(
asSyncAdapter(Events.CONTENT_URI, mEmailAddress,
Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), cv,
EVENT_ID_AND_CALENDAR_ID, new String[] {
Long.toString(parentId), mCalendarIdString
});
// Keep track of any orphaned exceptions
if (cnt == 0) {
orphanedExceptions.add(c.getLong(1));
}
}
} finally {
c.close();
}
// Delete any orphaned exceptions
for (long orphan : orphanedExceptions) {
userLog(TAG, "Deleted orphaned exception: " + orphan);
cr.delete(
asSyncAdapter(ContentUris.withAppendedId(Events.CONTENT_URI, orphan),
mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), null, null);
}
orphanedExceptions.clear();
// Now we can go through dirty/marked top-level events and send them
// back to the server
EntityIterator eventIterator = EventsEntity.newEntityIterator(cr.query(
asSyncAdapter(Events.CONTENT_URI, mEmailAddress,
Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), null,
DIRTY_OR_MARKED_TOP_LEVEL_IN_CALENDAR, mCalendarIdArgument, null), cr);
ContentValues cidValues = new ContentValues();
try {
boolean first = true;
while (eventIterator.hasNext()) {
Entity entity = eventIterator.next();
// For each of these entities, create the change commands
ContentValues entityValues = entity.getEntityValues();
String serverId = entityValues.getAsString(Events._SYNC_ID);
// We first need to check whether we can upsync this event; our test for this
// is currently the value of EXTENDED_PROPERTY_ATTENDEES_REDACTED
// If this is set to "1", we can't upsync the event
for (NamedContentValues ncv: entity.getSubValues()) {
if (ncv.uri.equals(ExtendedProperties.CONTENT_URI)) {
ContentValues ncvValues = ncv.values;
if (ncvValues.getAsString(ExtendedProperties.NAME).equals(
EXTENDED_PROPERTY_UPSYNC_PROHIBITED)) {
if ("1".equals(ncvValues.getAsString(ExtendedProperties.VALUE))) {
// Make sure we mark this to clear the dirty flag
mUploadedIdList.add(entityValues.getAsLong(Events._ID));
continue;
}
}
}
}
// Find our uid in the entity; otherwise create one
String clientId = entityValues.getAsString(Events.SYNC_DATA2);
if (clientId == null) {
clientId = UUID.randomUUID().toString();
}
// EAS 2.5 needs: BusyStatus DtStamp EndTime Sensitivity StartTime TimeZone UID
// We can generate all but what we're testing for below
String organizerEmail = entityValues.getAsString(Events.ORGANIZER);
boolean selfOrganizer = organizerEmail.equalsIgnoreCase(mEmailAddress);
if (!entityValues.containsKey(Events.DTSTART)
|| (!entityValues.containsKey(Events.DURATION) &&
!entityValues.containsKey(Events.DTEND))
|| organizerEmail == null) {
continue;
}
if (first) {
s.start(Tags.SYNC_COMMANDS);
userLog("Sending Calendar changes to the server");
first = false;
}
long eventId = entityValues.getAsLong(Events._ID);
if (serverId == null) {
// This is a new event; create a clientId
userLog("Creating new event with clientId: ", clientId);
s.start(Tags.SYNC_ADD).data(Tags.SYNC_CLIENT_ID, clientId);
// And save it in the Event as the local id
cidValues.put(Events.SYNC_DATA2, clientId);
cidValues.put(EVENT_SYNC_VERSION, "0");
cr.update(
asSyncAdapter(
ContentUris.withAppendedId(Events.CONTENT_URI, eventId),
mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE),
cidValues, null, null);
} else {
if (entityValues.getAsInteger(Events.DELETED) == 1) {
userLog("Deleting event with serverId: ", serverId);
s.start(Tags.SYNC_DELETE).data(Tags.SYNC_SERVER_ID, serverId).end();
mDeletedIdList.add(eventId);
if (selfOrganizer) {
mSendCancelIdList.add(eventId);
} else {
sendDeclinedEmail(entity, clientId);
}
continue;
}
userLog("Upsync change to event with serverId: " + serverId);
// Get the current version
String version = entityValues.getAsString(EVENT_SYNC_VERSION);
// This should never be null, but catch this error anyway
// Version should be "0" when we create the event, so use that
if (version == null) {
version = "0";
} else {
// Increment and save
try {
version = Integer.toString((Integer.parseInt(version) + 1));
} catch (Exception e) {
// Handle the case in which someone writes a non-integer here;
// shouldn't happen, but we don't want to kill the sync for his
version = "0";
}
}
cidValues.put(EVENT_SYNC_VERSION, version);
// Also save in entityValues so that we send it this time around
entityValues.put(EVENT_SYNC_VERSION, version);
cr.update(
asSyncAdapter(
ContentUris.withAppendedId(Events.CONTENT_URI, eventId),
mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE),
cidValues, null, null);
s.start(Tags.SYNC_CHANGE).data(Tags.SYNC_SERVER_ID, serverId);
}
s.start(Tags.SYNC_APPLICATION_DATA);
sendEvent(entity, clientId, s);
// Now, the hard part; find exceptions for this event
if (serverId != null) {
EntityIterator exIterator = EventsEntity.newEntityIterator(cr.query(
asSyncAdapter(Events.CONTENT_URI, mEmailAddress,
Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), null,
ORIGINAL_EVENT_AND_CALENDAR, new String[] {
serverId, mCalendarIdString
}, null), cr);
boolean exFirst = true;
while (exIterator.hasNext()) {
Entity exEntity = exIterator.next();
if (exFirst) {
s.start(Tags.CALENDAR_EXCEPTIONS);
exFirst = false;
}
s.start(Tags.CALENDAR_EXCEPTION);
sendEvent(exEntity, null, s);
ContentValues exValues = exEntity.getEntityValues();
if (getInt(exValues, Events.DIRTY) == 1) {
// This is a new/updated exception, so we've got to notify our
// attendees about it
long exEventId = exValues.getAsLong(Events._ID);
int flag;
// Copy subvalues into the exception; otherwise, we won't see the
// attendees when preparing the message
for (NamedContentValues ncv: entity.getSubValues()) {
exEntity.addSubValue(ncv.uri, ncv.values);
}
if ((getInt(exValues, Events.DELETED) == 1) ||
(getInt(exValues, Events.STATUS) ==
Events.STATUS_CANCELED)) {
flag = Message.FLAG_OUTGOING_MEETING_CANCEL;
if (!selfOrganizer) {
// Send a cancellation notice to the organizer
// Since CalendarProvider2 sets the organizer of exceptions
// to the user, we have to reset it first to the original
// organizer
exValues.put(Events.ORGANIZER,
entityValues.getAsString(Events.ORGANIZER));
sendDeclinedEmail(exEntity, clientId);
}
} else {
flag = Message.FLAG_OUTGOING_MEETING_INVITE;
}
// Add the eventId of the exception to the uploaded id list, so that
// the dirty/mark bits are cleared
mUploadedIdList.add(exEventId);
// Copy version so the ics attachment shows the proper sequence #
exValues.put(EVENT_SYNC_VERSION,
entityValues.getAsString(EVENT_SYNC_VERSION));
// Copy location so that it's included in the outgoing email
if (entityValues.containsKey(Events.EVENT_LOCATION)) {
exValues.put(Events.EVENT_LOCATION,
entityValues.getAsString(Events.EVENT_LOCATION));
}
if (selfOrganizer) {
Message msg =
CalendarUtilities.createMessageForEntity(mContext,
exEntity, flag, clientId, mAccount);
if (msg != null) {
userLog("Queueing exception update to " + msg.mTo);
mOutgoingMailList.add(msg);
}
}
}
s.end(); // EXCEPTION
}
if (!exFirst) {
s.end(); // EXCEPTIONS
}
}
s.end().end(); // ApplicationData & Change
mUploadedIdList.add(eventId);
// Go through the extended properties of this Event and pull out our tokenized
// attendees list and the user attendee status; we will need them later
String attendeeString = null;
long attendeeStringId = -1;
String userAttendeeStatus = null;
long userAttendeeStatusId = -1;
for (NamedContentValues ncv: entity.getSubValues()) {
if (ncv.uri.equals(ExtendedProperties.CONTENT_URI)) {
ContentValues ncvValues = ncv.values;
String propertyName =
ncvValues.getAsString(ExtendedProperties.NAME);
if (propertyName.equals(EXTENDED_PROPERTY_ATTENDEES)) {
attendeeString =
ncvValues.getAsString(ExtendedProperties.VALUE);
attendeeStringId =
ncvValues.getAsLong(ExtendedProperties._ID);
} else if (propertyName.equals(
EXTENDED_PROPERTY_USER_ATTENDEE_STATUS)) {
userAttendeeStatus =
ncvValues.getAsString(ExtendedProperties.VALUE);
userAttendeeStatusId =
ncvValues.getAsLong(ExtendedProperties._ID);
}
}
}
// Send the meeting invite if there are attendees and we're the organizer AND
// if the Event itself is dirty (we might be syncing only because an exception
// is dirty, in which case we DON'T send email about the Event)
if (selfOrganizer &&
(getInt(entityValues, Events.DIRTY) == 1)) {
EmailContent.Message msg =
CalendarUtilities.createMessageForEventId(mContext, eventId,
EmailContent.Message.FLAG_OUTGOING_MEETING_INVITE, clientId,
mAccount);
if (msg != null) {
userLog("Queueing invitation to ", msg.mTo);
mOutgoingMailList.add(msg);
}
// Make a list out of our tokenized attendees, if we have any
ArrayList<String> originalAttendeeList = new ArrayList<String>();
if (attendeeString != null) {
StringTokenizer st =
new StringTokenizer(attendeeString, ATTENDEE_TOKENIZER_DELIMITER);
while (st.hasMoreTokens()) {
originalAttendeeList.add(st.nextToken());
}
}
StringBuilder newTokenizedAttendees = new StringBuilder();
// See if any attendees have been dropped and while we're at it, build
// an updated String with tokenized attendee addresses
for (NamedContentValues ncv: entity.getSubValues()) {
if (ncv.uri.equals(Attendees.CONTENT_URI)) {
String attendeeEmail =
ncv.values.getAsString(Attendees.ATTENDEE_EMAIL);
// Remove all found attendees
originalAttendeeList.remove(attendeeEmail);
newTokenizedAttendees.append(attendeeEmail);
newTokenizedAttendees.append(ATTENDEE_TOKENIZER_DELIMITER);
}
}
// Update extended properties with the new attendee list, if we have one
// Otherwise, create one (this would be the case for Events created on
// device or "legacy" events (before this code was added)
ContentValues cv = new ContentValues();
cv.put(ExtendedProperties.VALUE, newTokenizedAttendees.toString());
if (attendeeString != null) {
- cr.update(ContentUris.withAppendedId(ExtendedProperties.CONTENT_URI,
- attendeeStringId), cv, null, null);
+ cr.update(asSyncAdapter(ContentUris.withAppendedId(
+ ExtendedProperties.CONTENT_URI, attendeeStringId),
+ mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE),
+ cv, null, null);
} else {
// If there wasn't an "attendees" property, insert one
cv.put(ExtendedProperties.NAME, EXTENDED_PROPERTY_ATTENDEES);
cv.put(ExtendedProperties.EVENT_ID, eventId);
- cr.insert(ExtendedProperties.CONTENT_URI, cv);
+ cr.insert(asSyncAdapter(ExtendedProperties.CONTENT_URI,
+ mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), cv);
}
// Whoever is left has been removed from the attendee list; send them
// a cancellation
for (String removedAttendee: originalAttendeeList) {
// Send a cancellation message to each of them
msg = CalendarUtilities.createMessageForEventId(mContext, eventId,
Message.FLAG_OUTGOING_MEETING_CANCEL, clientId, mAccount,
removedAttendee);
if (msg != null) {
// Just send it to the removed attendee
userLog("Queueing cancellation to removed attendee " + msg.mTo);
mOutgoingMailList.add(msg);
}
}
} else if (!selfOrganizer) {
// If we're not the organizer, see if we've changed our attendee status
// Our last synced attendee status is in ExtendedProperties, and we've
// retrieved it above as userAttendeeStatus
int currentStatus = entityValues.getAsInteger(Events.SELF_ATTENDEE_STATUS);
int syncStatus = Attendees.ATTENDEE_STATUS_NONE;
if (userAttendeeStatus != null) {
try {
syncStatus = Integer.parseInt(userAttendeeStatus);
} catch (NumberFormatException e) {
// Just in case somebody else mucked with this and it's not Integer
}
}
if ((currentStatus != syncStatus) &&
(currentStatus != Attendees.ATTENDEE_STATUS_NONE)) {
// If so, send a meeting reply
int messageFlag = 0;
switch (currentStatus) {
case Attendees.ATTENDEE_STATUS_ACCEPTED:
messageFlag = Message.FLAG_OUTGOING_MEETING_ACCEPT;
break;
case Attendees.ATTENDEE_STATUS_DECLINED:
messageFlag = Message.FLAG_OUTGOING_MEETING_DECLINE;
break;
case Attendees.ATTENDEE_STATUS_TENTATIVE:
messageFlag = Message.FLAG_OUTGOING_MEETING_TENTATIVE;
break;
}
// Make sure we have a valid status (messageFlag should never be zero)
if (messageFlag != 0 && userAttendeeStatusId >= 0) {
// Save away the new status
cidValues.clear();
cidValues.put(ExtendedProperties.VALUE,
Integer.toString(currentStatus));
cr.update(ContentUris.withAppendedId(ExtendedProperties.CONTENT_URI,
userAttendeeStatusId), cidValues, null, null);
// Send mail to the organizer advising of the new status
EmailContent.Message msg =
CalendarUtilities.createMessageForEventId(mContext, eventId,
messageFlag, clientId, mAccount);
if (msg != null) {
userLog("Queueing invitation reply to " + msg.mTo);
mOutgoingMailList.add(msg);
}
}
}
}
}
if (!first) {
s.end(); // Commands
}
} finally {
eventIterator.close();
}
} catch (RemoteException e) {
Log.e(TAG, "Could not read dirty events.");
}
return false;
}
}
| false | true | public boolean sendLocalChanges(Serializer s) throws IOException {
ContentResolver cr = mService.mContentResolver;
if (getSyncKey().equals("0")) {
return false;
}
try {
// We've got to handle exceptions as part of the parent when changes occur, so we need
// to find new/changed exceptions and mark the parent dirty
ArrayList<Long> orphanedExceptions = new ArrayList<Long>();
Cursor c = cr.query(Events.CONTENT_URI, ORIGINAL_EVENT_PROJECTION,
DIRTY_EXCEPTION_IN_CALENDAR, mCalendarIdArgument, null);
try {
ContentValues cv = new ContentValues();
// We use _sync_mark here to distinguish dirty parents from parents with dirty
// exceptions
cv.put(EVENT_SYNC_MARK, "1");
while (c.moveToNext()) {
// Mark the parents of dirty exceptions
long parentId = c.getLong(0);
int cnt = cr.update(
asSyncAdapter(Events.CONTENT_URI, mEmailAddress,
Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), cv,
EVENT_ID_AND_CALENDAR_ID, new String[] {
Long.toString(parentId), mCalendarIdString
});
// Keep track of any orphaned exceptions
if (cnt == 0) {
orphanedExceptions.add(c.getLong(1));
}
}
} finally {
c.close();
}
// Delete any orphaned exceptions
for (long orphan : orphanedExceptions) {
userLog(TAG, "Deleted orphaned exception: " + orphan);
cr.delete(
asSyncAdapter(ContentUris.withAppendedId(Events.CONTENT_URI, orphan),
mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), null, null);
}
orphanedExceptions.clear();
// Now we can go through dirty/marked top-level events and send them
// back to the server
EntityIterator eventIterator = EventsEntity.newEntityIterator(cr.query(
asSyncAdapter(Events.CONTENT_URI, mEmailAddress,
Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), null,
DIRTY_OR_MARKED_TOP_LEVEL_IN_CALENDAR, mCalendarIdArgument, null), cr);
ContentValues cidValues = new ContentValues();
try {
boolean first = true;
while (eventIterator.hasNext()) {
Entity entity = eventIterator.next();
// For each of these entities, create the change commands
ContentValues entityValues = entity.getEntityValues();
String serverId = entityValues.getAsString(Events._SYNC_ID);
// We first need to check whether we can upsync this event; our test for this
// is currently the value of EXTENDED_PROPERTY_ATTENDEES_REDACTED
// If this is set to "1", we can't upsync the event
for (NamedContentValues ncv: entity.getSubValues()) {
if (ncv.uri.equals(ExtendedProperties.CONTENT_URI)) {
ContentValues ncvValues = ncv.values;
if (ncvValues.getAsString(ExtendedProperties.NAME).equals(
EXTENDED_PROPERTY_UPSYNC_PROHIBITED)) {
if ("1".equals(ncvValues.getAsString(ExtendedProperties.VALUE))) {
// Make sure we mark this to clear the dirty flag
mUploadedIdList.add(entityValues.getAsLong(Events._ID));
continue;
}
}
}
}
// Find our uid in the entity; otherwise create one
String clientId = entityValues.getAsString(Events.SYNC_DATA2);
if (clientId == null) {
clientId = UUID.randomUUID().toString();
}
// EAS 2.5 needs: BusyStatus DtStamp EndTime Sensitivity StartTime TimeZone UID
// We can generate all but what we're testing for below
String organizerEmail = entityValues.getAsString(Events.ORGANIZER);
boolean selfOrganizer = organizerEmail.equalsIgnoreCase(mEmailAddress);
if (!entityValues.containsKey(Events.DTSTART)
|| (!entityValues.containsKey(Events.DURATION) &&
!entityValues.containsKey(Events.DTEND))
|| organizerEmail == null) {
continue;
}
if (first) {
s.start(Tags.SYNC_COMMANDS);
userLog("Sending Calendar changes to the server");
first = false;
}
long eventId = entityValues.getAsLong(Events._ID);
if (serverId == null) {
// This is a new event; create a clientId
userLog("Creating new event with clientId: ", clientId);
s.start(Tags.SYNC_ADD).data(Tags.SYNC_CLIENT_ID, clientId);
// And save it in the Event as the local id
cidValues.put(Events.SYNC_DATA2, clientId);
cidValues.put(EVENT_SYNC_VERSION, "0");
cr.update(
asSyncAdapter(
ContentUris.withAppendedId(Events.CONTENT_URI, eventId),
mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE),
cidValues, null, null);
} else {
if (entityValues.getAsInteger(Events.DELETED) == 1) {
userLog("Deleting event with serverId: ", serverId);
s.start(Tags.SYNC_DELETE).data(Tags.SYNC_SERVER_ID, serverId).end();
mDeletedIdList.add(eventId);
if (selfOrganizer) {
mSendCancelIdList.add(eventId);
} else {
sendDeclinedEmail(entity, clientId);
}
continue;
}
userLog("Upsync change to event with serverId: " + serverId);
// Get the current version
String version = entityValues.getAsString(EVENT_SYNC_VERSION);
// This should never be null, but catch this error anyway
// Version should be "0" when we create the event, so use that
if (version == null) {
version = "0";
} else {
// Increment and save
try {
version = Integer.toString((Integer.parseInt(version) + 1));
} catch (Exception e) {
// Handle the case in which someone writes a non-integer here;
// shouldn't happen, but we don't want to kill the sync for his
version = "0";
}
}
cidValues.put(EVENT_SYNC_VERSION, version);
// Also save in entityValues so that we send it this time around
entityValues.put(EVENT_SYNC_VERSION, version);
cr.update(
asSyncAdapter(
ContentUris.withAppendedId(Events.CONTENT_URI, eventId),
mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE),
cidValues, null, null);
s.start(Tags.SYNC_CHANGE).data(Tags.SYNC_SERVER_ID, serverId);
}
s.start(Tags.SYNC_APPLICATION_DATA);
sendEvent(entity, clientId, s);
// Now, the hard part; find exceptions for this event
if (serverId != null) {
EntityIterator exIterator = EventsEntity.newEntityIterator(cr.query(
asSyncAdapter(Events.CONTENT_URI, mEmailAddress,
Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), null,
ORIGINAL_EVENT_AND_CALENDAR, new String[] {
serverId, mCalendarIdString
}, null), cr);
boolean exFirst = true;
while (exIterator.hasNext()) {
Entity exEntity = exIterator.next();
if (exFirst) {
s.start(Tags.CALENDAR_EXCEPTIONS);
exFirst = false;
}
s.start(Tags.CALENDAR_EXCEPTION);
sendEvent(exEntity, null, s);
ContentValues exValues = exEntity.getEntityValues();
if (getInt(exValues, Events.DIRTY) == 1) {
// This is a new/updated exception, so we've got to notify our
// attendees about it
long exEventId = exValues.getAsLong(Events._ID);
int flag;
// Copy subvalues into the exception; otherwise, we won't see the
// attendees when preparing the message
for (NamedContentValues ncv: entity.getSubValues()) {
exEntity.addSubValue(ncv.uri, ncv.values);
}
if ((getInt(exValues, Events.DELETED) == 1) ||
(getInt(exValues, Events.STATUS) ==
Events.STATUS_CANCELED)) {
flag = Message.FLAG_OUTGOING_MEETING_CANCEL;
if (!selfOrganizer) {
// Send a cancellation notice to the organizer
// Since CalendarProvider2 sets the organizer of exceptions
// to the user, we have to reset it first to the original
// organizer
exValues.put(Events.ORGANIZER,
entityValues.getAsString(Events.ORGANIZER));
sendDeclinedEmail(exEntity, clientId);
}
} else {
flag = Message.FLAG_OUTGOING_MEETING_INVITE;
}
// Add the eventId of the exception to the uploaded id list, so that
// the dirty/mark bits are cleared
mUploadedIdList.add(exEventId);
// Copy version so the ics attachment shows the proper sequence #
exValues.put(EVENT_SYNC_VERSION,
entityValues.getAsString(EVENT_SYNC_VERSION));
// Copy location so that it's included in the outgoing email
if (entityValues.containsKey(Events.EVENT_LOCATION)) {
exValues.put(Events.EVENT_LOCATION,
entityValues.getAsString(Events.EVENT_LOCATION));
}
if (selfOrganizer) {
Message msg =
CalendarUtilities.createMessageForEntity(mContext,
exEntity, flag, clientId, mAccount);
if (msg != null) {
userLog("Queueing exception update to " + msg.mTo);
mOutgoingMailList.add(msg);
}
}
}
s.end(); // EXCEPTION
}
if (!exFirst) {
s.end(); // EXCEPTIONS
}
}
s.end().end(); // ApplicationData & Change
mUploadedIdList.add(eventId);
// Go through the extended properties of this Event and pull out our tokenized
// attendees list and the user attendee status; we will need them later
String attendeeString = null;
long attendeeStringId = -1;
String userAttendeeStatus = null;
long userAttendeeStatusId = -1;
for (NamedContentValues ncv: entity.getSubValues()) {
if (ncv.uri.equals(ExtendedProperties.CONTENT_URI)) {
ContentValues ncvValues = ncv.values;
String propertyName =
ncvValues.getAsString(ExtendedProperties.NAME);
if (propertyName.equals(EXTENDED_PROPERTY_ATTENDEES)) {
attendeeString =
ncvValues.getAsString(ExtendedProperties.VALUE);
attendeeStringId =
ncvValues.getAsLong(ExtendedProperties._ID);
} else if (propertyName.equals(
EXTENDED_PROPERTY_USER_ATTENDEE_STATUS)) {
userAttendeeStatus =
ncvValues.getAsString(ExtendedProperties.VALUE);
userAttendeeStatusId =
ncvValues.getAsLong(ExtendedProperties._ID);
}
}
}
// Send the meeting invite if there are attendees and we're the organizer AND
// if the Event itself is dirty (we might be syncing only because an exception
// is dirty, in which case we DON'T send email about the Event)
if (selfOrganizer &&
(getInt(entityValues, Events.DIRTY) == 1)) {
EmailContent.Message msg =
CalendarUtilities.createMessageForEventId(mContext, eventId,
EmailContent.Message.FLAG_OUTGOING_MEETING_INVITE, clientId,
mAccount);
if (msg != null) {
userLog("Queueing invitation to ", msg.mTo);
mOutgoingMailList.add(msg);
}
// Make a list out of our tokenized attendees, if we have any
ArrayList<String> originalAttendeeList = new ArrayList<String>();
if (attendeeString != null) {
StringTokenizer st =
new StringTokenizer(attendeeString, ATTENDEE_TOKENIZER_DELIMITER);
while (st.hasMoreTokens()) {
originalAttendeeList.add(st.nextToken());
}
}
StringBuilder newTokenizedAttendees = new StringBuilder();
// See if any attendees have been dropped and while we're at it, build
// an updated String with tokenized attendee addresses
for (NamedContentValues ncv: entity.getSubValues()) {
if (ncv.uri.equals(Attendees.CONTENT_URI)) {
String attendeeEmail =
ncv.values.getAsString(Attendees.ATTENDEE_EMAIL);
// Remove all found attendees
originalAttendeeList.remove(attendeeEmail);
newTokenizedAttendees.append(attendeeEmail);
newTokenizedAttendees.append(ATTENDEE_TOKENIZER_DELIMITER);
}
}
// Update extended properties with the new attendee list, if we have one
// Otherwise, create one (this would be the case for Events created on
// device or "legacy" events (before this code was added)
ContentValues cv = new ContentValues();
cv.put(ExtendedProperties.VALUE, newTokenizedAttendees.toString());
if (attendeeString != null) {
cr.update(ContentUris.withAppendedId(ExtendedProperties.CONTENT_URI,
attendeeStringId), cv, null, null);
} else {
// If there wasn't an "attendees" property, insert one
cv.put(ExtendedProperties.NAME, EXTENDED_PROPERTY_ATTENDEES);
cv.put(ExtendedProperties.EVENT_ID, eventId);
cr.insert(ExtendedProperties.CONTENT_URI, cv);
}
// Whoever is left has been removed from the attendee list; send them
// a cancellation
for (String removedAttendee: originalAttendeeList) {
// Send a cancellation message to each of them
msg = CalendarUtilities.createMessageForEventId(mContext, eventId,
Message.FLAG_OUTGOING_MEETING_CANCEL, clientId, mAccount,
removedAttendee);
if (msg != null) {
// Just send it to the removed attendee
userLog("Queueing cancellation to removed attendee " + msg.mTo);
mOutgoingMailList.add(msg);
}
}
} else if (!selfOrganizer) {
// If we're not the organizer, see if we've changed our attendee status
// Our last synced attendee status is in ExtendedProperties, and we've
// retrieved it above as userAttendeeStatus
int currentStatus = entityValues.getAsInteger(Events.SELF_ATTENDEE_STATUS);
int syncStatus = Attendees.ATTENDEE_STATUS_NONE;
if (userAttendeeStatus != null) {
try {
syncStatus = Integer.parseInt(userAttendeeStatus);
} catch (NumberFormatException e) {
// Just in case somebody else mucked with this and it's not Integer
}
}
if ((currentStatus != syncStatus) &&
(currentStatus != Attendees.ATTENDEE_STATUS_NONE)) {
// If so, send a meeting reply
int messageFlag = 0;
switch (currentStatus) {
case Attendees.ATTENDEE_STATUS_ACCEPTED:
messageFlag = Message.FLAG_OUTGOING_MEETING_ACCEPT;
break;
case Attendees.ATTENDEE_STATUS_DECLINED:
messageFlag = Message.FLAG_OUTGOING_MEETING_DECLINE;
break;
case Attendees.ATTENDEE_STATUS_TENTATIVE:
messageFlag = Message.FLAG_OUTGOING_MEETING_TENTATIVE;
break;
}
// Make sure we have a valid status (messageFlag should never be zero)
if (messageFlag != 0 && userAttendeeStatusId >= 0) {
// Save away the new status
cidValues.clear();
cidValues.put(ExtendedProperties.VALUE,
Integer.toString(currentStatus));
cr.update(ContentUris.withAppendedId(ExtendedProperties.CONTENT_URI,
userAttendeeStatusId), cidValues, null, null);
// Send mail to the organizer advising of the new status
EmailContent.Message msg =
CalendarUtilities.createMessageForEventId(mContext, eventId,
messageFlag, clientId, mAccount);
if (msg != null) {
userLog("Queueing invitation reply to " + msg.mTo);
mOutgoingMailList.add(msg);
}
}
}
}
}
if (!first) {
s.end(); // Commands
}
} finally {
eventIterator.close();
}
} catch (RemoteException e) {
Log.e(TAG, "Could not read dirty events.");
}
return false;
}
| public boolean sendLocalChanges(Serializer s) throws IOException {
ContentResolver cr = mService.mContentResolver;
if (getSyncKey().equals("0")) {
return false;
}
try {
// We've got to handle exceptions as part of the parent when changes occur, so we need
// to find new/changed exceptions and mark the parent dirty
ArrayList<Long> orphanedExceptions = new ArrayList<Long>();
Cursor c = cr.query(Events.CONTENT_URI, ORIGINAL_EVENT_PROJECTION,
DIRTY_EXCEPTION_IN_CALENDAR, mCalendarIdArgument, null);
try {
ContentValues cv = new ContentValues();
// We use _sync_mark here to distinguish dirty parents from parents with dirty
// exceptions
cv.put(EVENT_SYNC_MARK, "1");
while (c.moveToNext()) {
// Mark the parents of dirty exceptions
long parentId = c.getLong(0);
int cnt = cr.update(
asSyncAdapter(Events.CONTENT_URI, mEmailAddress,
Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), cv,
EVENT_ID_AND_CALENDAR_ID, new String[] {
Long.toString(parentId), mCalendarIdString
});
// Keep track of any orphaned exceptions
if (cnt == 0) {
orphanedExceptions.add(c.getLong(1));
}
}
} finally {
c.close();
}
// Delete any orphaned exceptions
for (long orphan : orphanedExceptions) {
userLog(TAG, "Deleted orphaned exception: " + orphan);
cr.delete(
asSyncAdapter(ContentUris.withAppendedId(Events.CONTENT_URI, orphan),
mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), null, null);
}
orphanedExceptions.clear();
// Now we can go through dirty/marked top-level events and send them
// back to the server
EntityIterator eventIterator = EventsEntity.newEntityIterator(cr.query(
asSyncAdapter(Events.CONTENT_URI, mEmailAddress,
Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), null,
DIRTY_OR_MARKED_TOP_LEVEL_IN_CALENDAR, mCalendarIdArgument, null), cr);
ContentValues cidValues = new ContentValues();
try {
boolean first = true;
while (eventIterator.hasNext()) {
Entity entity = eventIterator.next();
// For each of these entities, create the change commands
ContentValues entityValues = entity.getEntityValues();
String serverId = entityValues.getAsString(Events._SYNC_ID);
// We first need to check whether we can upsync this event; our test for this
// is currently the value of EXTENDED_PROPERTY_ATTENDEES_REDACTED
// If this is set to "1", we can't upsync the event
for (NamedContentValues ncv: entity.getSubValues()) {
if (ncv.uri.equals(ExtendedProperties.CONTENT_URI)) {
ContentValues ncvValues = ncv.values;
if (ncvValues.getAsString(ExtendedProperties.NAME).equals(
EXTENDED_PROPERTY_UPSYNC_PROHIBITED)) {
if ("1".equals(ncvValues.getAsString(ExtendedProperties.VALUE))) {
// Make sure we mark this to clear the dirty flag
mUploadedIdList.add(entityValues.getAsLong(Events._ID));
continue;
}
}
}
}
// Find our uid in the entity; otherwise create one
String clientId = entityValues.getAsString(Events.SYNC_DATA2);
if (clientId == null) {
clientId = UUID.randomUUID().toString();
}
// EAS 2.5 needs: BusyStatus DtStamp EndTime Sensitivity StartTime TimeZone UID
// We can generate all but what we're testing for below
String organizerEmail = entityValues.getAsString(Events.ORGANIZER);
boolean selfOrganizer = organizerEmail.equalsIgnoreCase(mEmailAddress);
if (!entityValues.containsKey(Events.DTSTART)
|| (!entityValues.containsKey(Events.DURATION) &&
!entityValues.containsKey(Events.DTEND))
|| organizerEmail == null) {
continue;
}
if (first) {
s.start(Tags.SYNC_COMMANDS);
userLog("Sending Calendar changes to the server");
first = false;
}
long eventId = entityValues.getAsLong(Events._ID);
if (serverId == null) {
// This is a new event; create a clientId
userLog("Creating new event with clientId: ", clientId);
s.start(Tags.SYNC_ADD).data(Tags.SYNC_CLIENT_ID, clientId);
// And save it in the Event as the local id
cidValues.put(Events.SYNC_DATA2, clientId);
cidValues.put(EVENT_SYNC_VERSION, "0");
cr.update(
asSyncAdapter(
ContentUris.withAppendedId(Events.CONTENT_URI, eventId),
mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE),
cidValues, null, null);
} else {
if (entityValues.getAsInteger(Events.DELETED) == 1) {
userLog("Deleting event with serverId: ", serverId);
s.start(Tags.SYNC_DELETE).data(Tags.SYNC_SERVER_ID, serverId).end();
mDeletedIdList.add(eventId);
if (selfOrganizer) {
mSendCancelIdList.add(eventId);
} else {
sendDeclinedEmail(entity, clientId);
}
continue;
}
userLog("Upsync change to event with serverId: " + serverId);
// Get the current version
String version = entityValues.getAsString(EVENT_SYNC_VERSION);
// This should never be null, but catch this error anyway
// Version should be "0" when we create the event, so use that
if (version == null) {
version = "0";
} else {
// Increment and save
try {
version = Integer.toString((Integer.parseInt(version) + 1));
} catch (Exception e) {
// Handle the case in which someone writes a non-integer here;
// shouldn't happen, but we don't want to kill the sync for his
version = "0";
}
}
cidValues.put(EVENT_SYNC_VERSION, version);
// Also save in entityValues so that we send it this time around
entityValues.put(EVENT_SYNC_VERSION, version);
cr.update(
asSyncAdapter(
ContentUris.withAppendedId(Events.CONTENT_URI, eventId),
mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE),
cidValues, null, null);
s.start(Tags.SYNC_CHANGE).data(Tags.SYNC_SERVER_ID, serverId);
}
s.start(Tags.SYNC_APPLICATION_DATA);
sendEvent(entity, clientId, s);
// Now, the hard part; find exceptions for this event
if (serverId != null) {
EntityIterator exIterator = EventsEntity.newEntityIterator(cr.query(
asSyncAdapter(Events.CONTENT_URI, mEmailAddress,
Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), null,
ORIGINAL_EVENT_AND_CALENDAR, new String[] {
serverId, mCalendarIdString
}, null), cr);
boolean exFirst = true;
while (exIterator.hasNext()) {
Entity exEntity = exIterator.next();
if (exFirst) {
s.start(Tags.CALENDAR_EXCEPTIONS);
exFirst = false;
}
s.start(Tags.CALENDAR_EXCEPTION);
sendEvent(exEntity, null, s);
ContentValues exValues = exEntity.getEntityValues();
if (getInt(exValues, Events.DIRTY) == 1) {
// This is a new/updated exception, so we've got to notify our
// attendees about it
long exEventId = exValues.getAsLong(Events._ID);
int flag;
// Copy subvalues into the exception; otherwise, we won't see the
// attendees when preparing the message
for (NamedContentValues ncv: entity.getSubValues()) {
exEntity.addSubValue(ncv.uri, ncv.values);
}
if ((getInt(exValues, Events.DELETED) == 1) ||
(getInt(exValues, Events.STATUS) ==
Events.STATUS_CANCELED)) {
flag = Message.FLAG_OUTGOING_MEETING_CANCEL;
if (!selfOrganizer) {
// Send a cancellation notice to the organizer
// Since CalendarProvider2 sets the organizer of exceptions
// to the user, we have to reset it first to the original
// organizer
exValues.put(Events.ORGANIZER,
entityValues.getAsString(Events.ORGANIZER));
sendDeclinedEmail(exEntity, clientId);
}
} else {
flag = Message.FLAG_OUTGOING_MEETING_INVITE;
}
// Add the eventId of the exception to the uploaded id list, so that
// the dirty/mark bits are cleared
mUploadedIdList.add(exEventId);
// Copy version so the ics attachment shows the proper sequence #
exValues.put(EVENT_SYNC_VERSION,
entityValues.getAsString(EVENT_SYNC_VERSION));
// Copy location so that it's included in the outgoing email
if (entityValues.containsKey(Events.EVENT_LOCATION)) {
exValues.put(Events.EVENT_LOCATION,
entityValues.getAsString(Events.EVENT_LOCATION));
}
if (selfOrganizer) {
Message msg =
CalendarUtilities.createMessageForEntity(mContext,
exEntity, flag, clientId, mAccount);
if (msg != null) {
userLog("Queueing exception update to " + msg.mTo);
mOutgoingMailList.add(msg);
}
}
}
s.end(); // EXCEPTION
}
if (!exFirst) {
s.end(); // EXCEPTIONS
}
}
s.end().end(); // ApplicationData & Change
mUploadedIdList.add(eventId);
// Go through the extended properties of this Event and pull out our tokenized
// attendees list and the user attendee status; we will need them later
String attendeeString = null;
long attendeeStringId = -1;
String userAttendeeStatus = null;
long userAttendeeStatusId = -1;
for (NamedContentValues ncv: entity.getSubValues()) {
if (ncv.uri.equals(ExtendedProperties.CONTENT_URI)) {
ContentValues ncvValues = ncv.values;
String propertyName =
ncvValues.getAsString(ExtendedProperties.NAME);
if (propertyName.equals(EXTENDED_PROPERTY_ATTENDEES)) {
attendeeString =
ncvValues.getAsString(ExtendedProperties.VALUE);
attendeeStringId =
ncvValues.getAsLong(ExtendedProperties._ID);
} else if (propertyName.equals(
EXTENDED_PROPERTY_USER_ATTENDEE_STATUS)) {
userAttendeeStatus =
ncvValues.getAsString(ExtendedProperties.VALUE);
userAttendeeStatusId =
ncvValues.getAsLong(ExtendedProperties._ID);
}
}
}
// Send the meeting invite if there are attendees and we're the organizer AND
// if the Event itself is dirty (we might be syncing only because an exception
// is dirty, in which case we DON'T send email about the Event)
if (selfOrganizer &&
(getInt(entityValues, Events.DIRTY) == 1)) {
EmailContent.Message msg =
CalendarUtilities.createMessageForEventId(mContext, eventId,
EmailContent.Message.FLAG_OUTGOING_MEETING_INVITE, clientId,
mAccount);
if (msg != null) {
userLog("Queueing invitation to ", msg.mTo);
mOutgoingMailList.add(msg);
}
// Make a list out of our tokenized attendees, if we have any
ArrayList<String> originalAttendeeList = new ArrayList<String>();
if (attendeeString != null) {
StringTokenizer st =
new StringTokenizer(attendeeString, ATTENDEE_TOKENIZER_DELIMITER);
while (st.hasMoreTokens()) {
originalAttendeeList.add(st.nextToken());
}
}
StringBuilder newTokenizedAttendees = new StringBuilder();
// See if any attendees have been dropped and while we're at it, build
// an updated String with tokenized attendee addresses
for (NamedContentValues ncv: entity.getSubValues()) {
if (ncv.uri.equals(Attendees.CONTENT_URI)) {
String attendeeEmail =
ncv.values.getAsString(Attendees.ATTENDEE_EMAIL);
// Remove all found attendees
originalAttendeeList.remove(attendeeEmail);
newTokenizedAttendees.append(attendeeEmail);
newTokenizedAttendees.append(ATTENDEE_TOKENIZER_DELIMITER);
}
}
// Update extended properties with the new attendee list, if we have one
// Otherwise, create one (this would be the case for Events created on
// device or "legacy" events (before this code was added)
ContentValues cv = new ContentValues();
cv.put(ExtendedProperties.VALUE, newTokenizedAttendees.toString());
if (attendeeString != null) {
cr.update(asSyncAdapter(ContentUris.withAppendedId(
ExtendedProperties.CONTENT_URI, attendeeStringId),
mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE),
cv, null, null);
} else {
// If there wasn't an "attendees" property, insert one
cv.put(ExtendedProperties.NAME, EXTENDED_PROPERTY_ATTENDEES);
cv.put(ExtendedProperties.EVENT_ID, eventId);
cr.insert(asSyncAdapter(ExtendedProperties.CONTENT_URI,
mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), cv);
}
// Whoever is left has been removed from the attendee list; send them
// a cancellation
for (String removedAttendee: originalAttendeeList) {
// Send a cancellation message to each of them
msg = CalendarUtilities.createMessageForEventId(mContext, eventId,
Message.FLAG_OUTGOING_MEETING_CANCEL, clientId, mAccount,
removedAttendee);
if (msg != null) {
// Just send it to the removed attendee
userLog("Queueing cancellation to removed attendee " + msg.mTo);
mOutgoingMailList.add(msg);
}
}
} else if (!selfOrganizer) {
// If we're not the organizer, see if we've changed our attendee status
// Our last synced attendee status is in ExtendedProperties, and we've
// retrieved it above as userAttendeeStatus
int currentStatus = entityValues.getAsInteger(Events.SELF_ATTENDEE_STATUS);
int syncStatus = Attendees.ATTENDEE_STATUS_NONE;
if (userAttendeeStatus != null) {
try {
syncStatus = Integer.parseInt(userAttendeeStatus);
} catch (NumberFormatException e) {
// Just in case somebody else mucked with this and it's not Integer
}
}
if ((currentStatus != syncStatus) &&
(currentStatus != Attendees.ATTENDEE_STATUS_NONE)) {
// If so, send a meeting reply
int messageFlag = 0;
switch (currentStatus) {
case Attendees.ATTENDEE_STATUS_ACCEPTED:
messageFlag = Message.FLAG_OUTGOING_MEETING_ACCEPT;
break;
case Attendees.ATTENDEE_STATUS_DECLINED:
messageFlag = Message.FLAG_OUTGOING_MEETING_DECLINE;
break;
case Attendees.ATTENDEE_STATUS_TENTATIVE:
messageFlag = Message.FLAG_OUTGOING_MEETING_TENTATIVE;
break;
}
// Make sure we have a valid status (messageFlag should never be zero)
if (messageFlag != 0 && userAttendeeStatusId >= 0) {
// Save away the new status
cidValues.clear();
cidValues.put(ExtendedProperties.VALUE,
Integer.toString(currentStatus));
cr.update(ContentUris.withAppendedId(ExtendedProperties.CONTENT_URI,
userAttendeeStatusId), cidValues, null, null);
// Send mail to the organizer advising of the new status
EmailContent.Message msg =
CalendarUtilities.createMessageForEventId(mContext, eventId,
messageFlag, clientId, mAccount);
if (msg != null) {
userLog("Queueing invitation reply to " + msg.mTo);
mOutgoingMailList.add(msg);
}
}
}
}
}
if (!first) {
s.end(); // Commands
}
} finally {
eventIterator.close();
}
} catch (RemoteException e) {
Log.e(TAG, "Could not read dirty events.");
}
return false;
}
|
diff --git a/src/com/entertailion/java/fling/FileDrop.java b/src/com/entertailion/java/fling/FileDrop.java
index 580f468..55d0197 100644
--- a/src/com/entertailion/java/fling/FileDrop.java
+++ b/src/com/entertailion/java/fling/FileDrop.java
@@ -1,949 +1,953 @@
package com.entertailion.java.fling;
import java.awt.datatransfer.DataFlavor;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.io.Reader;
/**
* This class makes it easy to drag and drop files from the operating
* system to a Java program. Any <tt>java.awt.Component</tt> can be
* dropped onto, but only <tt>javax.swing.JComponent</tt>s will indicate
* the drop event with a changed border.
* <p/>
* To use this class, construct a new <tt>FileDrop</tt> by passing
* it the target component and a <tt>Listener</tt> to receive notification
* when file(s) have been dropped. Here is an example:
* <p/>
* <code><pre>
* JPanel myPanel = new JPanel();
* new FileDrop( myPanel, new FileDrop.Listener()
* { public void filesDropped( java.io.File[] files )
* {
* // handle file drop
* ...
* } // end filesDropped
* }); // end FileDrop.Listener
* </pre></code>
* <p/>
* You can specify the border that will appear when files are being dragged by
* calling the constructor with a <tt>javax.swing.border.Border</tt>. Only
* <tt>JComponent</tt>s will show any indication with a border.
* <p/>
* You can turn on some debugging features by passing a <tt>PrintStream</tt>
* object (such as <tt>System.out</tt>) into the full constructor. A <tt>null</tt>
* value will result in no extra debugging information being output.
* <p/>
*
* <p>I'm releasing this code into the Public Domain. Enjoy.
* </p>
* <p><em>Original author: Robert Harder, [email protected]</em></p>
* <p>2007-09-12 Nathan Blomquist -- Linux (KDE/Gnome) support added.</p>
*
* @author Robert Harder
* @author [email protected]
* @version 1.0.1
*/
/*
* Drag-and-drop file support
*
* http://iharder.sourceforge.net/current/java/filedrop/
*/
public class FileDrop
{
private static final String LOG_TAG = "FileDrop";
private transient javax.swing.border.Border normalBorder;
private transient java.awt.dnd.DropTargetListener dropListener;
/** Discover if the running JVM is modern enough to have drag and drop. */
private static Boolean supportsDnD;
// Default border color
private static java.awt.Color defaultBorderColor = new java.awt.Color( 0f, 0f, 1f, 0.25f );
/**
* Constructs a {@link FileDrop} with a default light-blue border
* and, if <var>c</var> is a {@link java.awt.Container}, recursively
* sets all elements contained within as drop targets, though only
* the top level container will change borders.
*
* @param c Component on which files will be dropped.
* @param listener Listens for <tt>filesDropped</tt>.
* @since 1.0
*/
public FileDrop(
final java.awt.Component c,
final Listener listener )
{ this( null, // Logging stream
c, // Drop target
javax.swing.BorderFactory.createMatteBorder( 2, 2, 2, 2, defaultBorderColor ), // Drag border
true, // Recursive
listener );
} // end constructor
/**
* Constructor with a default border and the option to recursively set drop targets.
* If your component is a <tt>java.awt.Container</tt>, then each of its children
* components will also listen for drops, though only the parent will change borders.
*
* @param c Component on which files will be dropped.
* @param recursive Recursively set children as drop targets.
* @param listener Listens for <tt>filesDropped</tt>.
* @since 1.0
*/
public FileDrop(
final java.awt.Component c,
final boolean recursive,
final Listener listener )
{ this( null, // Logging stream
c, // Drop target
javax.swing.BorderFactory.createMatteBorder( 2, 2, 2, 2, defaultBorderColor ), // Drag border
recursive, // Recursive
listener );
} // end constructor
/**
* Constructor with a default border and debugging optionally turned on.
* With Debugging turned on, more status messages will be displayed to
* <tt>out</tt>. A common way to use this constructor is with
* <tt>System.out</tt> or <tt>System.err</tt>. A <tt>null</tt> value for
* the parameter <tt>out</tt> will result in no debugging output.
*
* @param out PrintStream to record debugging info or null for no debugging.
* @param out
* @param c Component on which files will be dropped.
* @param listener Listens for <tt>filesDropped</tt>.
* @since 1.0
*/
public FileDrop(
final java.io.PrintStream out,
final java.awt.Component c,
final Listener listener )
{ this( out, // Logging stream
c, // Drop target
javax.swing.BorderFactory.createMatteBorder( 2, 2, 2, 2, defaultBorderColor ),
false, // Recursive
listener );
} // end constructor
/**
* Constructor with a default border, debugging optionally turned on
* and the option to recursively set drop targets.
* If your component is a <tt>java.awt.Container</tt>, then each of its children
* components will also listen for drops, though only the parent will change borders.
* With Debugging turned on, more status messages will be displayed to
* <tt>out</tt>. A common way to use this constructor is with
* <tt>System.out</tt> or <tt>System.err</tt>. A <tt>null</tt> value for
* the parameter <tt>out</tt> will result in no debugging output.
*
* @param out PrintStream to record debugging info or null for no debugging.
* @param out
* @param c Component on which files will be dropped.
* @param recursive Recursively set children as drop targets.
* @param listener Listens for <tt>filesDropped</tt>.
* @since 1.0
*/
public FileDrop(
final java.io.PrintStream out,
final java.awt.Component c,
final boolean recursive,
final Listener listener)
{ this( out, // Logging stream
c, // Drop target
javax.swing.BorderFactory.createMatteBorder( 2, 2, 2, 2, defaultBorderColor ), // Drag border
recursive, // Recursive
listener );
} // end constructor
/**
* Constructor with a specified border
*
* @param c Component on which files will be dropped.
* @param dragBorder Border to use on <tt>JComponent</tt> when dragging occurs.
* @param listener Listens for <tt>filesDropped</tt>.
* @since 1.0
*/
public FileDrop(
final java.awt.Component c,
final javax.swing.border.Border dragBorder,
final Listener listener)
{ this(
null, // Logging stream
c, // Drop target
dragBorder, // Drag border
false, // Recursive
listener );
} // end constructor
/**
* Constructor with a specified border and the option to recursively set drop targets.
* If your component is a <tt>java.awt.Container</tt>, then each of its children
* components will also listen for drops, though only the parent will change borders.
*
* @param c Component on which files will be dropped.
* @param dragBorder Border to use on <tt>JComponent</tt> when dragging occurs.
* @param recursive Recursively set children as drop targets.
* @param listener Listens for <tt>filesDropped</tt>.
* @since 1.0
*/
public FileDrop(
final java.awt.Component c,
final javax.swing.border.Border dragBorder,
final boolean recursive,
final Listener listener)
{ this(
null,
c,
dragBorder,
recursive,
listener );
} // end constructor
/**
* Constructor with a specified border and debugging optionally turned on.
* With Debugging turned on, more status messages will be displayed to
* <tt>out</tt>. A common way to use this constructor is with
* <tt>System.out</tt> or <tt>System.err</tt>. A <tt>null</tt> value for
* the parameter <tt>out</tt> will result in no debugging output.
*
* @param out PrintStream to record debugging info or null for no debugging.
* @param c Component on which files will be dropped.
* @param dragBorder Border to use on <tt>JComponent</tt> when dragging occurs.
* @param listener Listens for <tt>filesDropped</tt>.
* @since 1.0
*/
public FileDrop(
final java.io.PrintStream out,
final java.awt.Component c,
final javax.swing.border.Border dragBorder,
final Listener listener)
{ this(
out, // Logging stream
c, // Drop target
dragBorder, // Drag border
false, // Recursive
listener );
} // end constructor
/**
* Full constructor with a specified border and debugging optionally turned on.
* With Debugging turned on, more status messages will be displayed to
* <tt>out</tt>. A common way to use this constructor is with
* <tt>System.out</tt> or <tt>System.err</tt>. A <tt>null</tt> value for
* the parameter <tt>out</tt> will result in no debugging output.
*
* @param out PrintStream to record debugging info or null for no debugging.
* @param c Component on which files will be dropped.
* @param dragBorder Border to use on <tt>JComponent</tt> when dragging occurs.
* @param recursive Recursively set children as drop targets.
* @param listener Listens for <tt>filesDropped</tt>.
* @since 1.0
*/
public FileDrop(
final java.io.PrintStream out,
final java.awt.Component c,
final javax.swing.border.Border dragBorder,
final boolean recursive,
final Listener listener)
{
if( supportsDnD() )
{ // Make a drop listener
dropListener = new java.awt.dnd.DropTargetListener()
{ public void dragEnter( java.awt.dnd.DropTargetDragEvent evt )
{ log( out, "FileDrop: dragEnter event." );
// Is this an acceptable drag event?
if( isDragOk( out, evt ) )
{
// If it's a Swing component, set its border
if( c instanceof javax.swing.JComponent )
{ javax.swing.JComponent jc = (javax.swing.JComponent) c;
normalBorder = jc.getBorder();
log( out, "FileDrop: normal border saved." );
jc.setBorder( dragBorder );
log( out, "FileDrop: drag border set." );
} // end if: JComponent
// Acknowledge that it's okay to enter
//evt.acceptDrag( java.awt.dnd.DnDConstants.ACTION_COPY_OR_MOVE );
evt.acceptDrag( java.awt.dnd.DnDConstants.ACTION_COPY );
log( out, "FileDrop: event accepted." );
} // end if: drag ok
else
{ // Reject the drag event
evt.rejectDrag();
log( out, "FileDrop: event rejected." );
} // end else: drag not ok
} // end dragEnter
public void dragOver( java.awt.dnd.DropTargetDragEvent evt )
{ // This is called continually as long as the mouse is
// over the drag target.
} // end dragOver
public void drop( java.awt.dnd.DropTargetDropEvent evt )
{ log( out, "FileDrop: drop event." );
try
{ // Get whatever was dropped
java.awt.datatransfer.Transferable tr = evt.getTransferable();
// Is it a file list?
boolean isJavaFileListFlavor = false;
try {
isJavaFileListFlavor = tr.isDataFlavorSupported (java.awt.datatransfer.DataFlavor.javaFileListFlavor);
} catch (Exception e) {
e.printStackTrace();
}
if (isJavaFileListFlavor)
{
// Say we'll take it.
//evt.acceptDrop ( java.awt.dnd.DnDConstants.ACTION_COPY_OR_MOVE );
evt.acceptDrop ( java.awt.dnd.DnDConstants.ACTION_COPY );
log( out, "FileDrop: file list accepted." );
// Get a useful list
java.util.List fileList = (java.util.List)
tr.getTransferData(java.awt.datatransfer.DataFlavor.javaFileListFlavor);
java.util.Iterator iterator = fileList.iterator();
// Convert list to array
java.io.File[] filesTemp = new java.io.File[ fileList.size() ];
fileList.toArray( filesTemp );
final java.io.File[] files = filesTemp;
// Alert listener to drop.
if( listener != null )
listener.filesDropped( files );
// Mark that drop is completed.
evt.getDropTargetContext().dropComplete(true);
log( out, "FileDrop: drop complete." );
} // end if: file list
else // this section will check for a reader flavor.
{
// Thanks, Nathan!
// BEGIN 2007-09-12 Nathan Blomquist -- Linux (KDE/Gnome) support added.
DataFlavor[] flavors = tr.getTransferDataFlavors();
boolean handled = false;
for (int zz = 0; zz < flavors.length; zz++) {
if (flavors[zz].isRepresentationClassReader()) {
// Say we'll take it.
//evt.acceptDrop ( java.awt.dnd.DnDConstants.ACTION_COPY_OR_MOVE );
evt.acceptDrop(java.awt.dnd.DnDConstants.ACTION_COPY);
log(out, "FileDrop: reader accepted.");
Reader reader = flavors[zz].getReaderForText(tr);
BufferedReader br = new BufferedReader(reader);
if(listener != null)
listener.filesDropped(createFileArray(br, out));
// Mark that drop is completed.
evt.getDropTargetContext().dropComplete(true);
log(out, "FileDrop: drop complete.");
handled = true;
break;
}
}
if(!handled){
log( out, "FileDrop: not a file list or reader - abort." );
evt.rejectDrop();
}
// END 2007-09-12 Nathan Blomquist -- Linux (KDE/Gnome) support added.
} // end else: not a file list
} // end try
catch (Exception e)
{ log( out, "FileDrop: Exception - abort:" );
e.printStackTrace();
- evt.rejectDrop();
+ try {
+ evt.rejectDrop();
+ } catch (Exception e1) {
+ e1.printStackTrace();
+ }
} // end catch: Exception
finally
{
// If it's a Swing component, reset its border
if( c instanceof javax.swing.JComponent )
{ javax.swing.JComponent jc = (javax.swing.JComponent) c;
jc.setBorder( normalBorder );
log( out, "FileDrop: normal border restored." );
} // end if: JComponent
} // end finally
} // end drop
public void dragExit( java.awt.dnd.DropTargetEvent evt )
{ log( out, "FileDrop: dragExit event." );
// If it's a Swing component, reset its border
if( c instanceof javax.swing.JComponent )
{ javax.swing.JComponent jc = (javax.swing.JComponent) c;
jc.setBorder( normalBorder );
log( out, "FileDrop: normal border restored." );
} // end if: JComponent
} // end dragExit
public void dropActionChanged( java.awt.dnd.DropTargetDragEvent evt )
{ log( out, "FileDrop: dropActionChanged event." );
// Is this an acceptable drag event?
if( isDragOk( out, evt ) )
{ //evt.acceptDrag( java.awt.dnd.DnDConstants.ACTION_COPY_OR_MOVE );
evt.acceptDrag( java.awt.dnd.DnDConstants.ACTION_COPY );
log( out, "FileDrop: event accepted." );
} // end if: drag ok
else
{ evt.rejectDrag();
log( out, "FileDrop: event rejected." );
} // end else: drag not ok
} // end dropActionChanged
}; // end DropTargetListener
// Make the component (and possibly children) drop targets
makeDropTarget( out, c, recursive );
} // end if: supports dnd
else
{ log( out, "FileDrop: Drag and drop is not supported with this JVM" );
} // end else: does not support DnD
} // end constructor
private static boolean supportsDnD()
{ // Static Boolean
if( supportsDnD == null )
{
boolean support = false;
try
{ Class arbitraryDndClass = Class.forName( "java.awt.dnd.DnDConstants" );
support = true;
} // end try
catch( Exception e )
{ support = false;
} // end catch
supportsDnD = new Boolean( support );
} // end if: first time through
return supportsDnD.booleanValue();
} // end supportsDnD
// BEGIN 2007-09-12 Nathan Blomquist -- Linux (KDE/Gnome) support added.
private static String ZERO_CHAR_STRING = "" + (char)0;
private static File[] createFileArray(BufferedReader bReader, PrintStream out)
{
try {
java.util.List list = new java.util.ArrayList();
java.lang.String line = null;
while ((line = bReader.readLine()) != null) {
try {
// kde seems to append a 0 char to the end of the reader
if(ZERO_CHAR_STRING.equals(line)) continue;
java.io.File file = new java.io.File(new java.net.URI(line));
list.add(file);
} catch (Exception ex) {
log(out, "Error with " + line + ": " + ex.getMessage());
}
}
return (java.io.File[]) list.toArray(new File[list.size()]);
} catch (IOException ex) {
log(out, "FileDrop: IOException");
}
return new File[0];
}
// END 2007-09-12 Nathan Blomquist -- Linux (KDE/Gnome) support added.
private void makeDropTarget( final java.io.PrintStream out, final java.awt.Component c, boolean recursive )
{
// Make drop target
final java.awt.dnd.DropTarget dt = new java.awt.dnd.DropTarget();
try
{ dt.addDropTargetListener( dropListener );
} // end try
catch( java.util.TooManyListenersException e )
{ e.printStackTrace();
log(out, "FileDrop: Drop will not work due to previous error. Do you have another listener attached?" );
} // end catch
// Listen for hierarchy changes and remove the drop target when the parent gets cleared out.
c.addHierarchyListener( new java.awt.event.HierarchyListener()
{ public void hierarchyChanged( java.awt.event.HierarchyEvent evt )
{ log( out, "FileDrop: Hierarchy changed." );
java.awt.Component parent = c.getParent();
if( parent == null )
{ c.setDropTarget( null );
log( out, "FileDrop: Drop target cleared from component." );
} // end if: null parent
else
{ new java.awt.dnd.DropTarget(c, dropListener);
log( out, "FileDrop: Drop target added to component." );
} // end else: parent not null
} // end hierarchyChanged
}); // end hierarchy listener
if( c.getParent() != null )
new java.awt.dnd.DropTarget(c, dropListener);
if( recursive && (c instanceof java.awt.Container ) )
{
// Get the container
java.awt.Container cont = (java.awt.Container) c;
// Get it's components
java.awt.Component[] comps = cont.getComponents();
// Set it's components as listeners also
for( int i = 0; i < comps.length; i++ )
makeDropTarget( out, comps[i], recursive );
} // end if: recursively set components as listener
} // end dropListener
/** Determine if the dragged data is a file list. */
private boolean isDragOk( final java.io.PrintStream out, final java.awt.dnd.DropTargetDragEvent evt )
{ boolean ok = false;
// Get data flavors being dragged
java.awt.datatransfer.DataFlavor[] flavors = evt.getCurrentDataFlavors();
// See if any of the flavors are a file list
int i = 0;
while( !ok && i < flavors.length )
{
// BEGIN 2007-09-12 Nathan Blomquist -- Linux (KDE/Gnome) support added.
// Is the flavor a file list?
final DataFlavor curFlavor = flavors[i];
if( curFlavor.equals( java.awt.datatransfer.DataFlavor.javaFileListFlavor ) ||
curFlavor.isRepresentationClassReader()){
ok = true;
}
// END 2007-09-12 Nathan Blomquist -- Linux (KDE/Gnome) support added.
i++;
} // end while: through flavors
// If logging is enabled, show data flavors
if( out != null )
{ if( flavors.length == 0 )
log( out, "FileDrop: no data flavors." );
for( i = 0; i < flavors.length; i++ )
log( out, flavors[i].toString() );
} // end if: logging enabled
return ok;
} // end isDragOk
/** Outputs <tt>message</tt> to <tt>out</tt> if it's not null. */
private static void log( java.io.PrintStream out, String message )
{ // Log message if requested
// if( out != null )
// out.println( message );
Log.d(LOG_TAG, message);
} // end log
/**
* Removes the drag-and-drop hooks from the component and optionally
* from the all children. You should call this if you add and remove
* components after you've set up the drag-and-drop.
* This will recursively unregister all components contained within
* <var>c</var> if <var>c</var> is a {@link java.awt.Container}.
*
* @param c The component to unregister as a drop target
* @since 1.0
*/
public static boolean remove( java.awt.Component c)
{ return remove( null, c, true );
} // end remove
/**
* Removes the drag-and-drop hooks from the component and optionally
* from the all children. You should call this if you add and remove
* components after you've set up the drag-and-drop.
*
* @param out Optional {@link java.io.PrintStream} for logging drag and drop messages
* @param c The component to unregister
* @param recursive Recursively unregister components within a container
* @since 1.0
*/
public static boolean remove( java.io.PrintStream out, java.awt.Component c, boolean recursive )
{ // Make sure we support dnd.
if( supportsDnD() )
{ log( out, "FileDrop: Removing drag-and-drop hooks." );
c.setDropTarget( null );
if( recursive && ( c instanceof java.awt.Container ) )
{ java.awt.Component[] comps = ((java.awt.Container)c).getComponents();
for( int i = 0; i < comps.length; i++ )
remove( out, comps[i], recursive );
return true;
} // end if: recursive
else return false;
} // end if: supports DnD
else return false;
} // end remove
/* ******** I N N E R I N T E R F A C E L I S T E N E R ******** */
/**
* Implement this inner interface to listen for when files are dropped. For example
* your class declaration may begin like this:
* <code><pre>
* public class MyClass implements FileDrop.Listener
* ...
* public void filesDropped( java.io.File[] files )
* {
* ...
* } // end filesDropped
* ...
* </pre></code>
*
* @since 1.1
*/
public static interface Listener {
/**
* This method is called when files have been successfully dropped.
*
* @param files An array of <tt>File</tt>s that were dropped.
* @since 1.0
*/
public abstract void filesDropped( java.io.File[] files );
} // end inner-interface Listener
/* ******** I N N E R C L A S S ******** */
/**
* This is the event that is passed to the
* {@link FileDropListener#filesDropped filesDropped(...)} method in
* your {@link FileDropListener} when files are dropped onto
* a registered drop target.
*
* <p>I'm releasing this code into the Public Domain. Enjoy.</p>
*
* @author Robert Harder
* @author [email protected]
* @version 1.2
*/
public static class Event extends java.util.EventObject {
private java.io.File[] files;
/**
* Constructs an {@link Event} with the array
* of files that were dropped and the
* {@link FileDrop} that initiated the event.
*
* @param files The array of files that were dropped
* @source The event source
* @since 1.1
*/
public Event( java.io.File[] files, Object source ) {
super( source );
this.files = files;
} // end constructor
/**
* Returns an array of files that were dropped on a
* registered drop target.
*
* @return array of files that were dropped
* @since 1.1
*/
public java.io.File[] getFiles() {
return files;
} // end getFiles
} // end inner class Event
/* ******** I N N E R C L A S S ******** */
/**
* At last an easy way to encapsulate your custom objects for dragging and dropping
* in your Java programs!
* When you need to create a {@link java.awt.datatransfer.Transferable} object,
* use this class to wrap your object.
* For example:
* <pre><code>
* ...
* MyCoolClass myObj = new MyCoolClass();
* Transferable xfer = new TransferableObject( myObj );
* ...
* </code></pre>
* Or if you need to know when the data was actually dropped, like when you're
* moving data out of a list, say, you can use the {@link TransferableObject.Fetcher}
* inner class to return your object Just in Time.
* For example:
* <pre><code>
* ...
* final MyCoolClass myObj = new MyCoolClass();
*
* TransferableObject.Fetcher fetcher = new TransferableObject.Fetcher()
* { public Object getObject(){ return myObj; }
* }; // end fetcher
*
* Transferable xfer = new TransferableObject( fetcher );
* ...
* </code></pre>
*
* The {@link java.awt.datatransfer.DataFlavor} associated with
* {@link TransferableObject} has the representation class
* <tt>net.iharder.dnd.TransferableObject.class</tt> and MIME type
* <tt>application/x-net.iharder.dnd.TransferableObject</tt>.
* This data flavor is accessible via the static
* {@link #DATA_FLAVOR} property.
*
*
* <p>I'm releasing this code into the Public Domain. Enjoy.</p>
*
* @author Robert Harder
* @author [email protected]
* @version 1.2
*/
public static class TransferableObject implements java.awt.datatransfer.Transferable
{
/**
* The MIME type for {@link #DATA_FLAVOR} is
* <tt>application/x-net.iharder.dnd.TransferableObject</tt>.
*
* @since 1.1
*/
public final static String MIME_TYPE = "application/x-net.iharder.dnd.TransferableObject";
/**
* The default {@link java.awt.datatransfer.DataFlavor} for
* {@link TransferableObject} has the representation class
* <tt>net.iharder.dnd.TransferableObject.class</tt>
* and the MIME type
* <tt>application/x-net.iharder.dnd.TransferableObject</tt>.
*
* @since 1.1
*/
public final static java.awt.datatransfer.DataFlavor DATA_FLAVOR =
new java.awt.datatransfer.DataFlavor( FileDrop.TransferableObject.class, MIME_TYPE );
private Fetcher fetcher;
private Object data;
private java.awt.datatransfer.DataFlavor customFlavor;
/**
* Creates a new {@link TransferableObject} that wraps <var>data</var>.
* Along with the {@link #DATA_FLAVOR} associated with this class,
* this creates a custom data flavor with a representation class
* determined from <code>data.getClass()</code> and the MIME type
* <tt>application/x-net.iharder.dnd.TransferableObject</tt>.
*
* @param data The data to transfer
* @since 1.1
*/
public TransferableObject( Object data )
{ this.data = data;
this.customFlavor = new java.awt.datatransfer.DataFlavor( data.getClass(), MIME_TYPE );
} // end constructor
/**
* Creates a new {@link TransferableObject} that will return the
* object that is returned by <var>fetcher</var>.
* No custom data flavor is set other than the default
* {@link #DATA_FLAVOR}.
*
* @see Fetcher
* @param fetcher The {@link Fetcher} that will return the data object
* @since 1.1
*/
public TransferableObject( Fetcher fetcher )
{ this.fetcher = fetcher;
} // end constructor
/**
* Creates a new {@link TransferableObject} that will return the
* object that is returned by <var>fetcher</var>.
* Along with the {@link #DATA_FLAVOR} associated with this class,
* this creates a custom data flavor with a representation class <var>dataClass</var>
* and the MIME type
* <tt>application/x-net.iharder.dnd.TransferableObject</tt>.
*
* @see Fetcher
* @param dataClass The {@link java.lang.Class} to use in the custom data flavor
* @param fetcher The {@link Fetcher} that will return the data object
* @since 1.1
*/
public TransferableObject( Class dataClass, Fetcher fetcher )
{ this.fetcher = fetcher;
this.customFlavor = new java.awt.datatransfer.DataFlavor( dataClass, MIME_TYPE );
} // end constructor
/**
* Returns the custom {@link java.awt.datatransfer.DataFlavor} associated
* with the encapsulated object or <tt>null</tt> if the {@link Fetcher}
* constructor was used without passing a {@link java.lang.Class}.
*
* @return The custom data flavor for the encapsulated object
* @since 1.1
*/
public java.awt.datatransfer.DataFlavor getCustomDataFlavor()
{ return customFlavor;
} // end getCustomDataFlavor
/* ******** T R A N S F E R A B L E M E T H O D S ******** */
/**
* Returns a two- or three-element array containing first
* the custom data flavor, if one was created in the constructors,
* second the default {@link #DATA_FLAVOR} associated with
* {@link TransferableObject}, and third the
* {@link java.awt.datatransfer.DataFlavor.stringFlavor}.
*
* @return An array of supported data flavors
* @since 1.1
*/
public java.awt.datatransfer.DataFlavor[] getTransferDataFlavors()
{
if( customFlavor != null )
return new java.awt.datatransfer.DataFlavor[]
{ customFlavor,
DATA_FLAVOR,
java.awt.datatransfer.DataFlavor.stringFlavor
}; // end flavors array
else
return new java.awt.datatransfer.DataFlavor[]
{ DATA_FLAVOR,
java.awt.datatransfer.DataFlavor.stringFlavor
}; // end flavors array
} // end getTransferDataFlavors
/**
* Returns the data encapsulated in this {@link TransferableObject}.
* If the {@link Fetcher} constructor was used, then this is when
* the {@link Fetcher#getObject getObject()} method will be called.
* If the requested data flavor is not supported, then the
* {@link Fetcher#getObject getObject()} method will not be called.
*
* @param flavor The data flavor for the data to return
* @return The dropped data
* @since 1.1
*/
public Object getTransferData( java.awt.datatransfer.DataFlavor flavor )
throws java.awt.datatransfer.UnsupportedFlavorException, java.io.IOException
{
// Native object
if( flavor.equals( DATA_FLAVOR ) )
return fetcher == null ? data : fetcher.getObject();
// String
if( flavor.equals( java.awt.datatransfer.DataFlavor.stringFlavor ) )
return fetcher == null ? data.toString() : fetcher.getObject().toString();
// We can't do anything else
throw new java.awt.datatransfer.UnsupportedFlavorException(flavor);
} // end getTransferData
/**
* Returns <tt>true</tt> if <var>flavor</var> is one of the supported
* flavors. Flavors are supported using the <code>equals(...)</code> method.
*
* @param flavor The data flavor to check
* @return Whether or not the flavor is supported
* @since 1.1
*/
public boolean isDataFlavorSupported( java.awt.datatransfer.DataFlavor flavor )
{
// Native object
if( flavor.equals( DATA_FLAVOR ) )
return true;
// String
if( flavor.equals( java.awt.datatransfer.DataFlavor.stringFlavor ) )
return true;
// We can't do anything else
return false;
} // end isDataFlavorSupported
/* ******** I N N E R I N T E R F A C E F E T C H E R ******** */
/**
* Instead of passing your data directly to the {@link TransferableObject}
* constructor, you may want to know exactly when your data was received
* in case you need to remove it from its source (or do anyting else to it).
* When the {@link #getTransferData getTransferData(...)} method is called
* on the {@link TransferableObject}, the {@link Fetcher}'s
* {@link #getObject getObject()} method will be called.
*
* @author Robert Harder
* @copyright 2001
* @version 1.1
* @since 1.1
*/
public static interface Fetcher
{
/**
* Return the object being encapsulated in the
* {@link TransferableObject}.
*
* @return The dropped object
* @since 1.1
*/
public abstract Object getObject();
} // end inner interface Fetcher
} // end class TransferableObject
} // end class FileDrop
| true | true | public FileDrop(
final java.io.PrintStream out,
final java.awt.Component c,
final javax.swing.border.Border dragBorder,
final boolean recursive,
final Listener listener)
{
if( supportsDnD() )
{ // Make a drop listener
dropListener = new java.awt.dnd.DropTargetListener()
{ public void dragEnter( java.awt.dnd.DropTargetDragEvent evt )
{ log( out, "FileDrop: dragEnter event." );
// Is this an acceptable drag event?
if( isDragOk( out, evt ) )
{
// If it's a Swing component, set its border
if( c instanceof javax.swing.JComponent )
{ javax.swing.JComponent jc = (javax.swing.JComponent) c;
normalBorder = jc.getBorder();
log( out, "FileDrop: normal border saved." );
jc.setBorder( dragBorder );
log( out, "FileDrop: drag border set." );
} // end if: JComponent
// Acknowledge that it's okay to enter
//evt.acceptDrag( java.awt.dnd.DnDConstants.ACTION_COPY_OR_MOVE );
evt.acceptDrag( java.awt.dnd.DnDConstants.ACTION_COPY );
log( out, "FileDrop: event accepted." );
} // end if: drag ok
else
{ // Reject the drag event
evt.rejectDrag();
log( out, "FileDrop: event rejected." );
} // end else: drag not ok
} // end dragEnter
public void dragOver( java.awt.dnd.DropTargetDragEvent evt )
{ // This is called continually as long as the mouse is
// over the drag target.
} // end dragOver
public void drop( java.awt.dnd.DropTargetDropEvent evt )
{ log( out, "FileDrop: drop event." );
try
{ // Get whatever was dropped
java.awt.datatransfer.Transferable tr = evt.getTransferable();
// Is it a file list?
boolean isJavaFileListFlavor = false;
try {
isJavaFileListFlavor = tr.isDataFlavorSupported (java.awt.datatransfer.DataFlavor.javaFileListFlavor);
} catch (Exception e) {
e.printStackTrace();
}
if (isJavaFileListFlavor)
{
// Say we'll take it.
//evt.acceptDrop ( java.awt.dnd.DnDConstants.ACTION_COPY_OR_MOVE );
evt.acceptDrop ( java.awt.dnd.DnDConstants.ACTION_COPY );
log( out, "FileDrop: file list accepted." );
// Get a useful list
java.util.List fileList = (java.util.List)
tr.getTransferData(java.awt.datatransfer.DataFlavor.javaFileListFlavor);
java.util.Iterator iterator = fileList.iterator();
// Convert list to array
java.io.File[] filesTemp = new java.io.File[ fileList.size() ];
fileList.toArray( filesTemp );
final java.io.File[] files = filesTemp;
// Alert listener to drop.
if( listener != null )
listener.filesDropped( files );
// Mark that drop is completed.
evt.getDropTargetContext().dropComplete(true);
log( out, "FileDrop: drop complete." );
} // end if: file list
else // this section will check for a reader flavor.
{
// Thanks, Nathan!
// BEGIN 2007-09-12 Nathan Blomquist -- Linux (KDE/Gnome) support added.
DataFlavor[] flavors = tr.getTransferDataFlavors();
boolean handled = false;
for (int zz = 0; zz < flavors.length; zz++) {
if (flavors[zz].isRepresentationClassReader()) {
// Say we'll take it.
//evt.acceptDrop ( java.awt.dnd.DnDConstants.ACTION_COPY_OR_MOVE );
evt.acceptDrop(java.awt.dnd.DnDConstants.ACTION_COPY);
log(out, "FileDrop: reader accepted.");
Reader reader = flavors[zz].getReaderForText(tr);
BufferedReader br = new BufferedReader(reader);
if(listener != null)
listener.filesDropped(createFileArray(br, out));
// Mark that drop is completed.
evt.getDropTargetContext().dropComplete(true);
log(out, "FileDrop: drop complete.");
handled = true;
break;
}
}
if(!handled){
log( out, "FileDrop: not a file list or reader - abort." );
evt.rejectDrop();
}
// END 2007-09-12 Nathan Blomquist -- Linux (KDE/Gnome) support added.
} // end else: not a file list
} // end try
catch (Exception e)
{ log( out, "FileDrop: Exception - abort:" );
e.printStackTrace();
evt.rejectDrop();
} // end catch: Exception
finally
{
// If it's a Swing component, reset its border
if( c instanceof javax.swing.JComponent )
{ javax.swing.JComponent jc = (javax.swing.JComponent) c;
jc.setBorder( normalBorder );
log( out, "FileDrop: normal border restored." );
} // end if: JComponent
} // end finally
} // end drop
public void dragExit( java.awt.dnd.DropTargetEvent evt )
{ log( out, "FileDrop: dragExit event." );
// If it's a Swing component, reset its border
if( c instanceof javax.swing.JComponent )
{ javax.swing.JComponent jc = (javax.swing.JComponent) c;
jc.setBorder( normalBorder );
log( out, "FileDrop: normal border restored." );
} // end if: JComponent
} // end dragExit
public void dropActionChanged( java.awt.dnd.DropTargetDragEvent evt )
{ log( out, "FileDrop: dropActionChanged event." );
// Is this an acceptable drag event?
if( isDragOk( out, evt ) )
{ //evt.acceptDrag( java.awt.dnd.DnDConstants.ACTION_COPY_OR_MOVE );
evt.acceptDrag( java.awt.dnd.DnDConstants.ACTION_COPY );
log( out, "FileDrop: event accepted." );
} // end if: drag ok
else
{ evt.rejectDrag();
log( out, "FileDrop: event rejected." );
} // end else: drag not ok
} // end dropActionChanged
}; // end DropTargetListener
// Make the component (and possibly children) drop targets
makeDropTarget( out, c, recursive );
} // end if: supports dnd
else
{ log( out, "FileDrop: Drag and drop is not supported with this JVM" );
} // end else: does not support DnD
} // end constructor
| public FileDrop(
final java.io.PrintStream out,
final java.awt.Component c,
final javax.swing.border.Border dragBorder,
final boolean recursive,
final Listener listener)
{
if( supportsDnD() )
{ // Make a drop listener
dropListener = new java.awt.dnd.DropTargetListener()
{ public void dragEnter( java.awt.dnd.DropTargetDragEvent evt )
{ log( out, "FileDrop: dragEnter event." );
// Is this an acceptable drag event?
if( isDragOk( out, evt ) )
{
// If it's a Swing component, set its border
if( c instanceof javax.swing.JComponent )
{ javax.swing.JComponent jc = (javax.swing.JComponent) c;
normalBorder = jc.getBorder();
log( out, "FileDrop: normal border saved." );
jc.setBorder( dragBorder );
log( out, "FileDrop: drag border set." );
} // end if: JComponent
// Acknowledge that it's okay to enter
//evt.acceptDrag( java.awt.dnd.DnDConstants.ACTION_COPY_OR_MOVE );
evt.acceptDrag( java.awt.dnd.DnDConstants.ACTION_COPY );
log( out, "FileDrop: event accepted." );
} // end if: drag ok
else
{ // Reject the drag event
evt.rejectDrag();
log( out, "FileDrop: event rejected." );
} // end else: drag not ok
} // end dragEnter
public void dragOver( java.awt.dnd.DropTargetDragEvent evt )
{ // This is called continually as long as the mouse is
// over the drag target.
} // end dragOver
public void drop( java.awt.dnd.DropTargetDropEvent evt )
{ log( out, "FileDrop: drop event." );
try
{ // Get whatever was dropped
java.awt.datatransfer.Transferable tr = evt.getTransferable();
// Is it a file list?
boolean isJavaFileListFlavor = false;
try {
isJavaFileListFlavor = tr.isDataFlavorSupported (java.awt.datatransfer.DataFlavor.javaFileListFlavor);
} catch (Exception e) {
e.printStackTrace();
}
if (isJavaFileListFlavor)
{
// Say we'll take it.
//evt.acceptDrop ( java.awt.dnd.DnDConstants.ACTION_COPY_OR_MOVE );
evt.acceptDrop ( java.awt.dnd.DnDConstants.ACTION_COPY );
log( out, "FileDrop: file list accepted." );
// Get a useful list
java.util.List fileList = (java.util.List)
tr.getTransferData(java.awt.datatransfer.DataFlavor.javaFileListFlavor);
java.util.Iterator iterator = fileList.iterator();
// Convert list to array
java.io.File[] filesTemp = new java.io.File[ fileList.size() ];
fileList.toArray( filesTemp );
final java.io.File[] files = filesTemp;
// Alert listener to drop.
if( listener != null )
listener.filesDropped( files );
// Mark that drop is completed.
evt.getDropTargetContext().dropComplete(true);
log( out, "FileDrop: drop complete." );
} // end if: file list
else // this section will check for a reader flavor.
{
// Thanks, Nathan!
// BEGIN 2007-09-12 Nathan Blomquist -- Linux (KDE/Gnome) support added.
DataFlavor[] flavors = tr.getTransferDataFlavors();
boolean handled = false;
for (int zz = 0; zz < flavors.length; zz++) {
if (flavors[zz].isRepresentationClassReader()) {
// Say we'll take it.
//evt.acceptDrop ( java.awt.dnd.DnDConstants.ACTION_COPY_OR_MOVE );
evt.acceptDrop(java.awt.dnd.DnDConstants.ACTION_COPY);
log(out, "FileDrop: reader accepted.");
Reader reader = flavors[zz].getReaderForText(tr);
BufferedReader br = new BufferedReader(reader);
if(listener != null)
listener.filesDropped(createFileArray(br, out));
// Mark that drop is completed.
evt.getDropTargetContext().dropComplete(true);
log(out, "FileDrop: drop complete.");
handled = true;
break;
}
}
if(!handled){
log( out, "FileDrop: not a file list or reader - abort." );
evt.rejectDrop();
}
// END 2007-09-12 Nathan Blomquist -- Linux (KDE/Gnome) support added.
} // end else: not a file list
} // end try
catch (Exception e)
{ log( out, "FileDrop: Exception - abort:" );
e.printStackTrace();
try {
evt.rejectDrop();
} catch (Exception e1) {
e1.printStackTrace();
}
} // end catch: Exception
finally
{
// If it's a Swing component, reset its border
if( c instanceof javax.swing.JComponent )
{ javax.swing.JComponent jc = (javax.swing.JComponent) c;
jc.setBorder( normalBorder );
log( out, "FileDrop: normal border restored." );
} // end if: JComponent
} // end finally
} // end drop
public void dragExit( java.awt.dnd.DropTargetEvent evt )
{ log( out, "FileDrop: dragExit event." );
// If it's a Swing component, reset its border
if( c instanceof javax.swing.JComponent )
{ javax.swing.JComponent jc = (javax.swing.JComponent) c;
jc.setBorder( normalBorder );
log( out, "FileDrop: normal border restored." );
} // end if: JComponent
} // end dragExit
public void dropActionChanged( java.awt.dnd.DropTargetDragEvent evt )
{ log( out, "FileDrop: dropActionChanged event." );
// Is this an acceptable drag event?
if( isDragOk( out, evt ) )
{ //evt.acceptDrag( java.awt.dnd.DnDConstants.ACTION_COPY_OR_MOVE );
evt.acceptDrag( java.awt.dnd.DnDConstants.ACTION_COPY );
log( out, "FileDrop: event accepted." );
} // end if: drag ok
else
{ evt.rejectDrag();
log( out, "FileDrop: event rejected." );
} // end else: drag not ok
} // end dropActionChanged
}; // end DropTargetListener
// Make the component (and possibly children) drop targets
makeDropTarget( out, c, recursive );
} // end if: supports dnd
else
{ log( out, "FileDrop: Drag and drop is not supported with this JVM" );
} // end else: does not support DnD
} // end constructor
|
diff --git a/freeplane/src/org/freeplane/features/common/note/NoteBuilder.java b/freeplane/src/org/freeplane/features/common/note/NoteBuilder.java
index 14a519430..f67ecd82b 100644
--- a/freeplane/src/org/freeplane/features/common/note/NoteBuilder.java
+++ b/freeplane/src/org/freeplane/features/common/note/NoteBuilder.java
@@ -1,59 +1,59 @@
/*
* Freeplane - mind map editor
* Copyright (C) 2008 Joerg Mueller, Daniel Polansky, Christian Foltin, Dimitry Polivaev
*
* This file is created by Dimitry Polivaev in 2008.
*
* 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, see <http://www.gnu.org/licenses/>.
*/
package org.freeplane.features.common.note;
import org.freeplane.core.io.IElementContentHandler;
import org.freeplane.core.model.NodeModel;
import org.freeplane.features.common.text.NodeTextBuilder;
import org.freeplane.n3.nanoxml.XMLElement;
/**
* @author Dimitry Polivaev
*/
class NoteBuilder implements IElementContentHandler {
final private NoteController noteController;
public NoteBuilder(final NoteController noteController) {
super();
this.noteController = noteController;
}
public Object createElement(final Object parent, final String tag, final XMLElement attributes) {
if (attributes == null) {
return null;
}
final Object typeAttribute = attributes.getAttribute(NodeTextBuilder.XML_NODE_XHTML_TYPE_TAG, null);
- if (typeAttribute == null || NodeTextBuilder.XML_NODE_XHTML_TYPE_NODE.equals(typeAttribute)) {
+ if (! NodeTextBuilder.XML_NODE_XHTML_TYPE_NOTE.equals(typeAttribute)) {
return null;
}
return parent;
}
public void endElement(final Object parent, final String tag, final Object node, final XMLElement attributes,
final String content) {
if (tag.equals("richcontent")) {
final String xmlText = content;
final NoteModel note = new NoteModel();
note.setXmlNoteText(xmlText);
((NodeModel) node).addExtension(note);
noteController.setStateIcon(((NodeModel) node), true);
}
}
}
| true | true | public Object createElement(final Object parent, final String tag, final XMLElement attributes) {
if (attributes == null) {
return null;
}
final Object typeAttribute = attributes.getAttribute(NodeTextBuilder.XML_NODE_XHTML_TYPE_TAG, null);
if (typeAttribute == null || NodeTextBuilder.XML_NODE_XHTML_TYPE_NODE.equals(typeAttribute)) {
return null;
}
return parent;
}
| public Object createElement(final Object parent, final String tag, final XMLElement attributes) {
if (attributes == null) {
return null;
}
final Object typeAttribute = attributes.getAttribute(NodeTextBuilder.XML_NODE_XHTML_TYPE_TAG, null);
if (! NodeTextBuilder.XML_NODE_XHTML_TYPE_NOTE.equals(typeAttribute)) {
return null;
}
return parent;
}
|
diff --git a/RealFarm/src/com/commonsensenet/realfarm/sync/UpstreamTask.java b/RealFarm/src/com/commonsensenet/realfarm/sync/UpstreamTask.java
index d783a10..8809cb1 100755
--- a/RealFarm/src/com/commonsensenet/realfarm/sync/UpstreamTask.java
+++ b/RealFarm/src/com/commonsensenet/realfarm/sync/UpstreamTask.java
@@ -1,257 +1,257 @@
package com.commonsensenet.realfarm.sync;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.widget.Toast;
import com.buzzbox.mob.android.scheduler.Task;
import com.buzzbox.mob.android.scheduler.TaskResult;
import com.commonsensenet.realfarm.dataaccess.RealFarmProvider;
import com.commonsensenet.realfarm.model.Action;
import com.commonsensenet.realfarm.model.Model;
import com.commonsensenet.realfarm.model.Plot;
import com.commonsensenet.realfarm.model.User;
import com.commonsensenet.realfarm.utils.ApplicationTracker;
import com.commonsensenet.realfarm.utils.ApplicationTracker.EventType;
/**
* Recurring Task that implements your business logic. The BuzzBox SDK Scheduler
* will take care of running the doWork method according to the scheduling.
*
*/
public class UpstreamTask implements Task {
/** Identifies when an SMS has been delivered. */
private static final String DELIVERED = "SMS_DELIVERED";
/** Identifies when an SMS has been sent. */
private static final String SENT = "SMS_SENT";
/** Phone number of the server. */
public static final String SERVER_PHONE_NUMBER = "9742016861";
/** List of Actions obtained from the Database. */
private List<Action> mActionList;
/** Access to the underlying database. */
private RealFarmProvider mDataProvider;
/** Receiver used to detect if an SMS was delivered correctly. */
private BroadcastReceiver mDeliveredBroadcastReceiver;
/** List of messages to send to the server. */
private List<Model> mMessageList;
/** List of Plots obtained from the Database. */
private List<Plot> mPlotList;
/** Receiver used to detect if an SMS was sent correctly. */
private BroadcastReceiver mSendBroadcastReceiver;
/** List of Users obtained from the Database. */
private List<User> mUserList;
public void registerReceivers(Context context) {
mSendBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent arg1) {
// gets the extras from the Bundle.
Bundle extras = arg1.getExtras();
long id = -1;
int type = -1;
// obtains the values from the bundle.
if (extras != null) {
- id = extras.getInt("id");
+ id = extras.getLong("id");
type = extras.getInt("type");
}
String resultMessage;
switch (getResultCode()) {
case Activity.RESULT_OK:
resultMessage = "SMS sent";
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
resultMessage = "Generic Failure";
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
resultMessage = "No Service";
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
resultMessage = "Null PDU";
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
resultMessage = "Radio Off";
break;
default:
resultMessage = "Error";
break;
}
// tracks the send notification.
ApplicationTracker.getInstance().logSyncEvent(EventType.SYNC,
"SEND-" + resultMessage, "type:" + type + ", id:" + id);
Toast.makeText(arg0, resultMessage, Toast.LENGTH_LONG).show();
}
};
mDeliveredBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent arg1) {
// gets the extras from the Bundle.
Bundle extras = arg1.getExtras();
long id = -1;
int type = -1;
// obtains the values from the bundle.
if (extras != null) {
id = extras.getLong("id");
type = extras.getInt("type");
}
// checks the obtained code.
switch (getResultCode()) {
case Activity.RESULT_OK:
// marks the message as delivered.
updateStatus(type, id, Model.STATUS_CONFIRMED);
Toast.makeText(arg0, "SMS delivered", Toast.LENGTH_SHORT)
.show();
break;
case Activity.RESULT_CANCELED:
Toast.makeText(arg0, "SMS not delivered",
Toast.LENGTH_SHORT).show();
break;
}
// tracks the sync activity.
ApplicationTracker.getInstance().logSyncEvent(EventType.SYNC,
"DELIVERY", "type:" + type + ", id:" + id);
}
};
// registers the Broadcast Receivers with their corresponding filter.
context.registerReceiver(mSendBroadcastReceiver, new IntentFilter(SENT));
context.registerReceiver(mDeliveredBroadcastReceiver, new IntentFilter(
DELIVERED));
}
/**
* Updates the status of the entry in the database that matches the given
* type and id with the new status.
*
* @param type
* type of the Model to update.
* @param id
* id of the Model to update.
* @param status
* new status. It can be 0 (unsent), 1(sent) or 2(confirmed).
*/
private void updateStatus(int type, long id, int status) {
switch (type) {
case 1000: // Action
// changes the status of the action
mDataProvider.setActionStatus(id, status);
break;
case 1001: // Plot
// changes the status of the plot
mDataProvider.setPlotStatus(id, status);
break;
case 1002: // User
// changes the status of the user.
mDataProvider.setUserStatus(id, status);
break;
}
}
public TaskResult doWork(ContextWrapper ctx) {
TaskResult res = new TaskResult();
// adds the Broadcast receivers if needed.
registerReceivers(ctx.getApplicationContext());
// gets the database provider.
mDataProvider = RealFarmProvider.getInstance(ctx);
// gets all the data from the server that has not being sent.
mActionList = mDataProvider.getActionsBySendStatus(Model.STATUS_UNSENT);
mPlotList = mDataProvider.getPlotsBySendStatus(Model.STATUS_UNSENT);
mUserList = mDataProvider.getUsersBySendStatus(Model.STATUS_UNSENT);
// initializes the list used to send the messages.
mMessageList = new ArrayList<Model>();
// adds all the elements into the message list.
mMessageList.addAll(mUserList);
mMessageList.addAll(mPlotList);
mMessageList.addAll(mActionList);
// sends all the messages to the server via SMS.
for (int i = 0; i < mMessageList.size(); i++) {
// sends the message.
sendMessage(ctx, mMessageList.get(i));
}
// sets the flag for the sent actions.
for (int x = 0; x < mActionList.size(); x++) {
mDataProvider.setActionStatus(mActionList.get(x).getId(), 1);
}
// sets the flag for the sent plots.
for (int x = 0; x < mPlotList.size(); x++) {
mDataProvider.setPlotStatus(mPlotList.get(x).getId(), 1);
}
// sets the flag for the sent users.
for (int x = 0; x < mUserList.size(); x++) {
mDataProvider.setUserStatus(mUserList.get(x).getId(), 1);
}
return res;
}
public String getId() {
return "reminder";
}
public String getTitle() {
return "Reminder";
}
protected void sendMessage(ContextWrapper context, Model message) {
Intent sentIntent = new Intent(SENT);
sentIntent.putExtra("type", message.getModelTypeId());
sentIntent.putExtra("id", message.getId());
PendingIntent sentPI = PendingIntent.getBroadcast(
context.getApplicationContext(), 0, sentIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
Intent deliveredIntent = new Intent(DELIVERED);
deliveredIntent.putExtra("type", message.getModelTypeId());
deliveredIntent.putExtra("id", message.getId());
PendingIntent deliveredPI = PendingIntent.getBroadcast(
context.getApplicationContext(), 0, deliveredIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
// gets the data to send.
String sms = message.toSmsString();
// tracks that the data that has been sent to the Server.
ApplicationTracker.getInstance().logSyncEvent(EventType.SYNC,
"Upstream", sms);
// gets the manager in charge of sending SMS.
SmsManager sm = SmsManager.getDefault();
// sends the messages from the phone number
sm.sendTextMessage(SERVER_PHONE_NUMBER, null, sms, sentPI, deliveredPI);
}
}
| true | true | public void registerReceivers(Context context) {
mSendBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent arg1) {
// gets the extras from the Bundle.
Bundle extras = arg1.getExtras();
long id = -1;
int type = -1;
// obtains the values from the bundle.
if (extras != null) {
id = extras.getInt("id");
type = extras.getInt("type");
}
String resultMessage;
switch (getResultCode()) {
case Activity.RESULT_OK:
resultMessage = "SMS sent";
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
resultMessage = "Generic Failure";
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
resultMessage = "No Service";
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
resultMessage = "Null PDU";
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
resultMessage = "Radio Off";
break;
default:
resultMessage = "Error";
break;
}
// tracks the send notification.
ApplicationTracker.getInstance().logSyncEvent(EventType.SYNC,
"SEND-" + resultMessage, "type:" + type + ", id:" + id);
Toast.makeText(arg0, resultMessage, Toast.LENGTH_LONG).show();
}
};
mDeliveredBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent arg1) {
// gets the extras from the Bundle.
Bundle extras = arg1.getExtras();
long id = -1;
int type = -1;
// obtains the values from the bundle.
if (extras != null) {
id = extras.getLong("id");
type = extras.getInt("type");
}
// checks the obtained code.
switch (getResultCode()) {
case Activity.RESULT_OK:
// marks the message as delivered.
updateStatus(type, id, Model.STATUS_CONFIRMED);
Toast.makeText(arg0, "SMS delivered", Toast.LENGTH_SHORT)
.show();
break;
case Activity.RESULT_CANCELED:
Toast.makeText(arg0, "SMS not delivered",
Toast.LENGTH_SHORT).show();
break;
}
// tracks the sync activity.
ApplicationTracker.getInstance().logSyncEvent(EventType.SYNC,
"DELIVERY", "type:" + type + ", id:" + id);
}
};
// registers the Broadcast Receivers with their corresponding filter.
context.registerReceiver(mSendBroadcastReceiver, new IntentFilter(SENT));
context.registerReceiver(mDeliveredBroadcastReceiver, new IntentFilter(
DELIVERED));
}
| public void registerReceivers(Context context) {
mSendBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent arg1) {
// gets the extras from the Bundle.
Bundle extras = arg1.getExtras();
long id = -1;
int type = -1;
// obtains the values from the bundle.
if (extras != null) {
id = extras.getLong("id");
type = extras.getInt("type");
}
String resultMessage;
switch (getResultCode()) {
case Activity.RESULT_OK:
resultMessage = "SMS sent";
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
resultMessage = "Generic Failure";
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
resultMessage = "No Service";
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
resultMessage = "Null PDU";
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
resultMessage = "Radio Off";
break;
default:
resultMessage = "Error";
break;
}
// tracks the send notification.
ApplicationTracker.getInstance().logSyncEvent(EventType.SYNC,
"SEND-" + resultMessage, "type:" + type + ", id:" + id);
Toast.makeText(arg0, resultMessage, Toast.LENGTH_LONG).show();
}
};
mDeliveredBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent arg1) {
// gets the extras from the Bundle.
Bundle extras = arg1.getExtras();
long id = -1;
int type = -1;
// obtains the values from the bundle.
if (extras != null) {
id = extras.getLong("id");
type = extras.getInt("type");
}
// checks the obtained code.
switch (getResultCode()) {
case Activity.RESULT_OK:
// marks the message as delivered.
updateStatus(type, id, Model.STATUS_CONFIRMED);
Toast.makeText(arg0, "SMS delivered", Toast.LENGTH_SHORT)
.show();
break;
case Activity.RESULT_CANCELED:
Toast.makeText(arg0, "SMS not delivered",
Toast.LENGTH_SHORT).show();
break;
}
// tracks the sync activity.
ApplicationTracker.getInstance().logSyncEvent(EventType.SYNC,
"DELIVERY", "type:" + type + ", id:" + id);
}
};
// registers the Broadcast Receivers with their corresponding filter.
context.registerReceiver(mSendBroadcastReceiver, new IntentFilter(SENT));
context.registerReceiver(mDeliveredBroadcastReceiver, new IntentFilter(
DELIVERED));
}
|
diff --git a/FastBoard/java/fastboard/lineconverter/LineConverter.java b/FastBoard/java/fastboard/lineconverter/LineConverter.java
index 7acf007..4af443d 100644
--- a/FastBoard/java/fastboard/lineconverter/LineConverter.java
+++ b/FastBoard/java/fastboard/lineconverter/LineConverter.java
@@ -1,29 +1,29 @@
package fastboard.lineconverter;
/**
* Created by IntelliJ IDEA.
* User: knhjp
* Date: 10-Nov-2009
* Time: 4:51:39 PM
* This converts a line into character string, and the other way around
*/
public class LineConverter {
public static String convertLineToString(int line) {
char[] charArr = new char[8];
- for (int i=0 ; i<charArr.length ; i++) {
+ for (int i=charArr.length-1 ; i>=0 ; i--) {
int value = line % 3;
switch (value) {
case 0:
charArr[i] = '_';
break;
case 1:
charArr[i] = 'x';
break;
case 2:
charArr[i] = 'o';
}
-// line /=3;
+ line /=3;
}
return new String(charArr);
}
}
| false | true | public static String convertLineToString(int line) {
char[] charArr = new char[8];
for (int i=0 ; i<charArr.length ; i++) {
int value = line % 3;
switch (value) {
case 0:
charArr[i] = '_';
break;
case 1:
charArr[i] = 'x';
break;
case 2:
charArr[i] = 'o';
}
// line /=3;
}
return new String(charArr);
}
| public static String convertLineToString(int line) {
char[] charArr = new char[8];
for (int i=charArr.length-1 ; i>=0 ; i--) {
int value = line % 3;
switch (value) {
case 0:
charArr[i] = '_';
break;
case 1:
charArr[i] = 'x';
break;
case 2:
charArr[i] = 'o';
}
line /=3;
}
return new String(charArr);
}
|
diff --git a/src/net/minecore/mineplot/PlotCommandInterpreter.java b/src/net/minecore/mineplot/PlotCommandInterpreter.java
index e19df52..9b68089 100644
--- a/src/net/minecore/mineplot/PlotCommandInterpreter.java
+++ b/src/net/minecore/mineplot/PlotCommandInterpreter.java
@@ -1,256 +1,256 @@
package net.minecore.mineplot;
import java.util.ArrayList;
import net.minecore.mineplot.miner.PlotPlayer;
import net.minecore.mineplot.plot.Plot;
import net.minecore.mineplot.world.PlotWorld;
import org.bukkit.ChatColor;
import org.bukkit.World;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.entity.Player;
public class PlotCommandInterpreter implements CommandExecutor {
private MinePlot mp;
public PlotCommandInterpreter(MinePlot minePermit) {
this.mp = minePermit;
}
@Override
public boolean onCommand(CommandSender sender, Command command,
String label, String[] args) {
if(sender instanceof ConsoleCommandSender){
mp.log.info("Console cannot use the Plot command");
return true;
}
if(args.length == 0)
return false;
if(args[0].equalsIgnoreCase("list")){
if(args.length > 1){
World w = mp.getServer().getWorld(args[1]);
if(w == null){
sender.sendMessage(ChatColor.RED + "Invalid World!");
return true;
}
PlotWorld pw = mp.getPWM().getPlotWorld(w);
if(pw == null){
sender.sendMessage(ChatColor.DARK_GRAY + "That world is not able to have plots.");
return true;
}
if(pw.getPlots().size() == 0)
sender.sendMessage("You have no plots in that world!");
else
sender.sendMessage("Your Plots in world " + w.getName() + ":");
for (Plot p : pw.getPlots()){
if(p.getOwner().equals(sender.getName()))
sender.sendMessage(ChatColor.GREEN + p.toString());
else if(p.canUse(sender.getName()))
sender.sendMessage(ChatColor.YELLOW + p.toString());
}
return true;
} else {
ArrayList<Plot> plots = mp.getPlotPlayerManager().getPlotPlayer(sender.getName()).getPlots();
if(plots.size() == 0)
sender.sendMessage("You have no plots!");
else
sender.sendMessage("Your Plots:");
for (Plot p : plots){
sender.sendMessage(ChatColor.GREEN + p.toString());
}
return true;
}
}
if(args[0].equalsIgnoreCase("buy")){
if(args.length < 3)
return false;
PlotWorld pw = mp.getPWM().getPlotWorld(mp.getServer().getPlayer(sender.getName()).getLocation().getWorld());
if(pw == null){
sender.sendMessage("This world does not allow you to buy plots!");
return true;
}
String[] loc1 = args[1].split(":"), loc2 = args[2].split(":");
if(loc1.length < 2 || loc2.length < 2)
return false;
Plot new1;
try {
new1 = pw.getNewPlot(Integer.parseInt(loc1[0]), Integer.parseInt(loc1[1]), Integer.parseInt(loc2[0]), Integer.parseInt(loc2[1]));
} catch (NumberFormatException e){
return false;
}
if(new1 == null){
sender.sendMessage(ChatColor.DARK_RED + "Plot invalid!");
return true;
}
PlotPlayer m = mp.getPlotPlayerManager().getPlotPlayer(sender.getName());
int numPlots = 0;
for(Plot p : m.getPlots())
if(p.getLocation1().getWorld().equals(pw.getWorld()))
numPlots++;
if(numPlots >= pw.getMaxPlots()){
sender.sendMessage(ChatColor.DARK_RED + "You already have the maximum number of plots for this world!");
return true;
}
- int cost = new1.calculateCost();
+ double cost = new1.calculateCost();
if(!mp.getMineCore().getEconomyManager().charge((Player)sender, cost)){
sender.sendMessage(ChatColor.DARK_RED + "You dont have enough money! Costs " + cost);
return true;
}
if(!pw.registerPlot(new1)){
sender.sendMessage(ChatColor.DARK_RED + "Couldn't buy plot!");
return true;
}
if(args.length >= 4)
new1.setName(args[3]);
else {
String base = "Plot";
int num = 1;
while(m.getPlot(base + num) != null)
num++;
new1.setName(base + num);
}
sender.sendMessage(ChatColor.GOLD + "You have bought a new plot! It has been named " + new1.getName());
m.addPlot(new1);
new1.createCorners();
return true;
}
if(args[0].equalsIgnoreCase("price")){
if(args.length < 3)
return false;
PlotWorld pw = mp.getPWM().getPlotWorld(mp.getServer().getPlayer(sender.getName()).getLocation().getWorld());
if(pw == null){
sender.sendMessage("This world does not allow you to buy plots!");
return true;
}
String[] loc1 = args[1].split(":"), loc2 = args[2].split(":");
if(loc1.length < 2 || loc2.length < 2)
return false;
Plot new1;
try {
new1 = pw.getNewPlot(Integer.parseInt(loc1[0]), Integer.parseInt(loc1[1]), Integer.parseInt(loc2[0]), Integer.parseInt(loc2[1]));
} catch (NumberFormatException e){
return false;
}
if(new1 == null){
sender.sendMessage(ChatColor.DARK_RED + "Plot invalid!");
return true;
}
sender.sendMessage(ChatColor.GOLD + "The price to buy this plot is " + new1.calculateCost());
return true;
}
if(args[0].equalsIgnoreCase("init")){
if(args.length < 2)
return false;
World w = mp.getServer().getWorld(args[1]);
if(w == null){
if(sender instanceof ConsoleCommandSender)
mp.log.info("Invalid world!");
else
sender.sendMessage(ChatColor.RED + "Invalid World!");
return true;
}
if(mp.getPWM().getPlotWorld(w) != null){
if(sender instanceof ConsoleCommandSender)
mp.log.info("World already initialized!");
else
sender.sendMessage(ChatColor.RED + "World already initialized!");
return true;
}
if(mp.initWorld(w)){
if(sender instanceof ConsoleCommandSender)
mp.log.info("World initialized!");
else
sender.sendMessage(ChatColor.GREEN + "World initialized!");
} else {
if(sender instanceof ConsoleCommandSender)
mp.log.info("Couldn't initialize world!");
else
sender.sendMessage(ChatColor.RED + "Couldn't initialize world!");
}
return true;
}
return false;
}
}
| true | true | public boolean onCommand(CommandSender sender, Command command,
String label, String[] args) {
if(sender instanceof ConsoleCommandSender){
mp.log.info("Console cannot use the Plot command");
return true;
}
if(args.length == 0)
return false;
if(args[0].equalsIgnoreCase("list")){
if(args.length > 1){
World w = mp.getServer().getWorld(args[1]);
if(w == null){
sender.sendMessage(ChatColor.RED + "Invalid World!");
return true;
}
PlotWorld pw = mp.getPWM().getPlotWorld(w);
if(pw == null){
sender.sendMessage(ChatColor.DARK_GRAY + "That world is not able to have plots.");
return true;
}
if(pw.getPlots().size() == 0)
sender.sendMessage("You have no plots in that world!");
else
sender.sendMessage("Your Plots in world " + w.getName() + ":");
for (Plot p : pw.getPlots()){
if(p.getOwner().equals(sender.getName()))
sender.sendMessage(ChatColor.GREEN + p.toString());
else if(p.canUse(sender.getName()))
sender.sendMessage(ChatColor.YELLOW + p.toString());
}
return true;
} else {
ArrayList<Plot> plots = mp.getPlotPlayerManager().getPlotPlayer(sender.getName()).getPlots();
if(plots.size() == 0)
sender.sendMessage("You have no plots!");
else
sender.sendMessage("Your Plots:");
for (Plot p : plots){
sender.sendMessage(ChatColor.GREEN + p.toString());
}
return true;
}
}
if(args[0].equalsIgnoreCase("buy")){
if(args.length < 3)
return false;
PlotWorld pw = mp.getPWM().getPlotWorld(mp.getServer().getPlayer(sender.getName()).getLocation().getWorld());
if(pw == null){
sender.sendMessage("This world does not allow you to buy plots!");
return true;
}
String[] loc1 = args[1].split(":"), loc2 = args[2].split(":");
if(loc1.length < 2 || loc2.length < 2)
return false;
Plot new1;
try {
new1 = pw.getNewPlot(Integer.parseInt(loc1[0]), Integer.parseInt(loc1[1]), Integer.parseInt(loc2[0]), Integer.parseInt(loc2[1]));
} catch (NumberFormatException e){
return false;
}
if(new1 == null){
sender.sendMessage(ChatColor.DARK_RED + "Plot invalid!");
return true;
}
PlotPlayer m = mp.getPlotPlayerManager().getPlotPlayer(sender.getName());
int numPlots = 0;
for(Plot p : m.getPlots())
if(p.getLocation1().getWorld().equals(pw.getWorld()))
numPlots++;
if(numPlots >= pw.getMaxPlots()){
sender.sendMessage(ChatColor.DARK_RED + "You already have the maximum number of plots for this world!");
return true;
}
int cost = new1.calculateCost();
if(!mp.getMineCore().getEconomyManager().charge((Player)sender, cost)){
sender.sendMessage(ChatColor.DARK_RED + "You dont have enough money! Costs " + cost);
return true;
}
if(!pw.registerPlot(new1)){
sender.sendMessage(ChatColor.DARK_RED + "Couldn't buy plot!");
return true;
}
if(args.length >= 4)
new1.setName(args[3]);
else {
String base = "Plot";
int num = 1;
while(m.getPlot(base + num) != null)
num++;
new1.setName(base + num);
}
sender.sendMessage(ChatColor.GOLD + "You have bought a new plot! It has been named " + new1.getName());
m.addPlot(new1);
new1.createCorners();
return true;
}
if(args[0].equalsIgnoreCase("price")){
if(args.length < 3)
return false;
PlotWorld pw = mp.getPWM().getPlotWorld(mp.getServer().getPlayer(sender.getName()).getLocation().getWorld());
if(pw == null){
sender.sendMessage("This world does not allow you to buy plots!");
return true;
}
String[] loc1 = args[1].split(":"), loc2 = args[2].split(":");
if(loc1.length < 2 || loc2.length < 2)
return false;
Plot new1;
try {
new1 = pw.getNewPlot(Integer.parseInt(loc1[0]), Integer.parseInt(loc1[1]), Integer.parseInt(loc2[0]), Integer.parseInt(loc2[1]));
} catch (NumberFormatException e){
return false;
}
if(new1 == null){
sender.sendMessage(ChatColor.DARK_RED + "Plot invalid!");
return true;
}
sender.sendMessage(ChatColor.GOLD + "The price to buy this plot is " + new1.calculateCost());
return true;
}
if(args[0].equalsIgnoreCase("init")){
if(args.length < 2)
return false;
World w = mp.getServer().getWorld(args[1]);
if(w == null){
if(sender instanceof ConsoleCommandSender)
mp.log.info("Invalid world!");
else
sender.sendMessage(ChatColor.RED + "Invalid World!");
return true;
}
if(mp.getPWM().getPlotWorld(w) != null){
if(sender instanceof ConsoleCommandSender)
mp.log.info("World already initialized!");
else
sender.sendMessage(ChatColor.RED + "World already initialized!");
return true;
}
if(mp.initWorld(w)){
if(sender instanceof ConsoleCommandSender)
mp.log.info("World initialized!");
else
sender.sendMessage(ChatColor.GREEN + "World initialized!");
} else {
if(sender instanceof ConsoleCommandSender)
mp.log.info("Couldn't initialize world!");
else
sender.sendMessage(ChatColor.RED + "Couldn't initialize world!");
}
return true;
}
return false;
}
| public boolean onCommand(CommandSender sender, Command command,
String label, String[] args) {
if(sender instanceof ConsoleCommandSender){
mp.log.info("Console cannot use the Plot command");
return true;
}
if(args.length == 0)
return false;
if(args[0].equalsIgnoreCase("list")){
if(args.length > 1){
World w = mp.getServer().getWorld(args[1]);
if(w == null){
sender.sendMessage(ChatColor.RED + "Invalid World!");
return true;
}
PlotWorld pw = mp.getPWM().getPlotWorld(w);
if(pw == null){
sender.sendMessage(ChatColor.DARK_GRAY + "That world is not able to have plots.");
return true;
}
if(pw.getPlots().size() == 0)
sender.sendMessage("You have no plots in that world!");
else
sender.sendMessage("Your Plots in world " + w.getName() + ":");
for (Plot p : pw.getPlots()){
if(p.getOwner().equals(sender.getName()))
sender.sendMessage(ChatColor.GREEN + p.toString());
else if(p.canUse(sender.getName()))
sender.sendMessage(ChatColor.YELLOW + p.toString());
}
return true;
} else {
ArrayList<Plot> plots = mp.getPlotPlayerManager().getPlotPlayer(sender.getName()).getPlots();
if(plots.size() == 0)
sender.sendMessage("You have no plots!");
else
sender.sendMessage("Your Plots:");
for (Plot p : plots){
sender.sendMessage(ChatColor.GREEN + p.toString());
}
return true;
}
}
if(args[0].equalsIgnoreCase("buy")){
if(args.length < 3)
return false;
PlotWorld pw = mp.getPWM().getPlotWorld(mp.getServer().getPlayer(sender.getName()).getLocation().getWorld());
if(pw == null){
sender.sendMessage("This world does not allow you to buy plots!");
return true;
}
String[] loc1 = args[1].split(":"), loc2 = args[2].split(":");
if(loc1.length < 2 || loc2.length < 2)
return false;
Plot new1;
try {
new1 = pw.getNewPlot(Integer.parseInt(loc1[0]), Integer.parseInt(loc1[1]), Integer.parseInt(loc2[0]), Integer.parseInt(loc2[1]));
} catch (NumberFormatException e){
return false;
}
if(new1 == null){
sender.sendMessage(ChatColor.DARK_RED + "Plot invalid!");
return true;
}
PlotPlayer m = mp.getPlotPlayerManager().getPlotPlayer(sender.getName());
int numPlots = 0;
for(Plot p : m.getPlots())
if(p.getLocation1().getWorld().equals(pw.getWorld()))
numPlots++;
if(numPlots >= pw.getMaxPlots()){
sender.sendMessage(ChatColor.DARK_RED + "You already have the maximum number of plots for this world!");
return true;
}
double cost = new1.calculateCost();
if(!mp.getMineCore().getEconomyManager().charge((Player)sender, cost)){
sender.sendMessage(ChatColor.DARK_RED + "You dont have enough money! Costs " + cost);
return true;
}
if(!pw.registerPlot(new1)){
sender.sendMessage(ChatColor.DARK_RED + "Couldn't buy plot!");
return true;
}
if(args.length >= 4)
new1.setName(args[3]);
else {
String base = "Plot";
int num = 1;
while(m.getPlot(base + num) != null)
num++;
new1.setName(base + num);
}
sender.sendMessage(ChatColor.GOLD + "You have bought a new plot! It has been named " + new1.getName());
m.addPlot(new1);
new1.createCorners();
return true;
}
if(args[0].equalsIgnoreCase("price")){
if(args.length < 3)
return false;
PlotWorld pw = mp.getPWM().getPlotWorld(mp.getServer().getPlayer(sender.getName()).getLocation().getWorld());
if(pw == null){
sender.sendMessage("This world does not allow you to buy plots!");
return true;
}
String[] loc1 = args[1].split(":"), loc2 = args[2].split(":");
if(loc1.length < 2 || loc2.length < 2)
return false;
Plot new1;
try {
new1 = pw.getNewPlot(Integer.parseInt(loc1[0]), Integer.parseInt(loc1[1]), Integer.parseInt(loc2[0]), Integer.parseInt(loc2[1]));
} catch (NumberFormatException e){
return false;
}
if(new1 == null){
sender.sendMessage(ChatColor.DARK_RED + "Plot invalid!");
return true;
}
sender.sendMessage(ChatColor.GOLD + "The price to buy this plot is " + new1.calculateCost());
return true;
}
if(args[0].equalsIgnoreCase("init")){
if(args.length < 2)
return false;
World w = mp.getServer().getWorld(args[1]);
if(w == null){
if(sender instanceof ConsoleCommandSender)
mp.log.info("Invalid world!");
else
sender.sendMessage(ChatColor.RED + "Invalid World!");
return true;
}
if(mp.getPWM().getPlotWorld(w) != null){
if(sender instanceof ConsoleCommandSender)
mp.log.info("World already initialized!");
else
sender.sendMessage(ChatColor.RED + "World already initialized!");
return true;
}
if(mp.initWorld(w)){
if(sender instanceof ConsoleCommandSender)
mp.log.info("World initialized!");
else
sender.sendMessage(ChatColor.GREEN + "World initialized!");
} else {
if(sender instanceof ConsoleCommandSender)
mp.log.info("Couldn't initialize world!");
else
sender.sendMessage(ChatColor.RED + "Couldn't initialize world!");
}
return true;
}
return false;
}
|
diff --git a/Dart/src/com/jetbrains/lang/dart/sdk/listPackageDirs/PubListPackageDirsAction2.java b/Dart/src/com/jetbrains/lang/dart/sdk/listPackageDirs/PubListPackageDirsAction2.java
index ce18a2ae02..d8d80713fc 100644
--- a/Dart/src/com/jetbrains/lang/dart/sdk/listPackageDirs/PubListPackageDirsAction2.java
+++ b/Dart/src/com/jetbrains/lang/dart/sdk/listPackageDirs/PubListPackageDirsAction2.java
@@ -1,296 +1,296 @@
package com.jetbrains.lang.dart.sdk.listPackageDirs;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.*;
import com.intellij.openapi.roots.impl.libraries.LibraryEx;
import com.intellij.openapi.roots.impl.libraries.LibraryTableBase;
import com.intellij.openapi.roots.impl.libraries.ProjectLibraryTable;
import com.intellij.openapi.roots.libraries.Library;
import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.PathUtil;
import com.jetbrains.lang.dart.analyzer.DartAnalysisServerAnnotator;
import com.jetbrains.lang.dart.analyzer.DartAnalysisServerService;
import com.jetbrains.lang.dart.sdk.DartSdk;
import com.jetbrains.lang.dart.sdk.DartSdkGlobalLibUtil;
import com.jetbrains.lang.dart.util.PubspecYamlUtil;
import gnu.trove.THashMap;
import gnu.trove.THashSet;
import icons.DartIcons;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.util.*;
// todo instead of unioning all of the package name maps and configuring all Dart modules to the unioned value, the module roots could be
// todo used as a key to only set the specific package map information for the specific module.
public class PubListPackageDirsAction2 extends AnAction {
public static final String PUB_LIST_PACKAGE_DIRS_LIB_NAME = "Dart pub list-package-dirs";
private static final Logger LOG = Logger.getInstance(PubListPackageDirsAction2.class.getName());
public PubListPackageDirsAction2() {
super("Configure Dart package roots using 'pub list-package-dirs'", null, DartIcons.Dart_16);
}
private static void computeLibraryRoots(@NotNull final Project project,
@NotNull final DartSdk dartSdk,
@NotNull final String[] libraries,
@NotNull final Collection<String> rootsToAddToLib) {
@NotNull final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex();
for (final String path : libraries) {
if (path == null) continue;
final String libRoot = PathUtil.getParentPath(FileUtil.toSystemIndependentName(path));
final VirtualFile vFile = LocalFileSystem.getInstance().findFileByPath(libRoot);
if (!libRoot.startsWith(dartSdk.getHomePath() + "/") && (vFile == null || !fileIndex.isInContent(vFile))) {
// todo skip nested roots?
rootsToAddToLib.add(libRoot);
}
}
}
private static void computePackageMap(@NotNull final Map<String, Map<String, List<String>>> packageMapMap,
@NotNull final Map<String, List<File>> packageNameToDirMap) {
for (final Map.Entry<String, Map<String, List<String>>> entry : packageMapMap.entrySet()) {
Map<String, List<String>> packageMapN = entry.getValue();
for (final Map.Entry<String, List<String>> entry2 : packageMapN.entrySet()) {
String packageName = entry2.getKey();
List<String> listStr = entry2.getValue();
List<File> packageDirList = new ArrayList<File>(listStr.size());
for (final String path : listStr) {
packageDirList.add(new File(FileUtil.toSystemDependentName(path)));
}
packageNameToDirMap.put(packageName, packageDirList);
}
}
}
public void update(@NotNull final AnActionEvent e) {
final Project project = e.getProject();
final DartSdk sdk = project == null ? null : DartSdk.getDartSdk(project);
e.getPresentation().setEnabled(sdk != null && DartAnalysisServerAnnotator.isDartSDKVersionSufficient(sdk));
}
public void actionPerformed(@NotNull final AnActionEvent e) {
final Project project = e.getProject();
final DartSdk sdk = project == null ? null : DartSdk.getDartSdk(project);
if (sdk == null || !DartAnalysisServerAnnotator.isDartSDKVersionSufficient(sdk)) return;
FileDocumentManager.getInstance().saveAllDocuments();
@NotNull final Set<Module> affectedModules = new THashSet<Module>();
@NotNull final Collection<String> rootsToAddToLib = new THashSet<String>();
- @NotNull final Map<String, List<File>> packageNameToDirMap = new THashMap<String, List<File>>();
+ final Map<String, List<File>> packageNameToDirMap = new TreeMap<String, List<File>>();
final Runnable runnable = new Runnable() {
public void run() {
final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
if (indicator != null) {
indicator.setIndeterminate(true);
indicator.setText("pub list-package-dirs");
}
if (!DartAnalysisServerService.getInstance().serverReadyForRequest(project, sdk)) return;
DartAnalysisServerService.getInstance().updateFilesContent();
DartAnalysisServerService.LibraryDependenciesResult libraryDependenciesResult =
DartAnalysisServerService.getInstance().analysis_getLibraryDependencies();
if (libraryDependenciesResult == null) {
libraryDependenciesResult = new DartAnalysisServerService.LibraryDependenciesResult(new String[]{}, Collections
.<String, Map<String, List<String>>>emptyMap());
}
String[] libraries = libraryDependenciesResult.getLibraries();
if (libraries == null) {
libraries = new String[]{};
}
Map<String, Map<String, List<String>>> packageMapMap = libraryDependenciesResult.getPackageMap();
if (packageMapMap == null) {
packageMapMap = Collections.emptyMap();
}
@NotNull final Module[] modules = ModuleManager.getInstance(project).getModules();
for (@NotNull final Module module : modules) {
if (DartSdkGlobalLibUtil.isDartSdkGlobalLibAttached(module, sdk.getGlobalLibName())) {
for (@NotNull final VirtualFile contentRoot : ModuleRootManager.getInstance(module).getContentRoots()) {
// if there is a pubspec, skip this contentRoot
if (contentRoot.findChild(PubspecYamlUtil.PUBSPEC_YAML) != null) continue;
affectedModules.add(module);
}
}
}
computeLibraryRoots(project, sdk, libraries, rootsToAddToLib);
computePackageMap(packageMapMap, packageNameToDirMap);
}
};
if (ProgressManager.getInstance().runProcessWithProgressSynchronously(runnable, "pub list-package-dirs", true, project)) {
@NotNull final DartListPackageDirsDialog dialog = new DartListPackageDirsDialog(project, rootsToAddToLib, packageNameToDirMap);
dialog.show();
if (dialog.getExitCode() == DialogWrapper.OK_EXIT_CODE) {
configurePubListPackageDirsLibrary(project, affectedModules, rootsToAddToLib, packageNameToDirMap);
}
if (dialog.getExitCode() == DartListPackageDirsDialog.CONFIGURE_NONE_EXIT_CODE) {
removePubListPackageDirsLibrary(project);
}
}
}
private static void configurePubListPackageDirsLibrary(@NotNull final Project project,
@NotNull final Set<Module> modules,
@NotNull final Collection<String> rootsToAddToLib,
@NotNull final Map<String, List<File>> packageMap) {
if (modules.isEmpty() || packageMap.isEmpty()) {
removePubListPackageDirsLibrary(project);
return;
}
ApplicationManager.getApplication().runWriteAction(
new Runnable() {
public void run() {
doConfigurePubListPackageDirsLibrary(project, modules, rootsToAddToLib, packageMap);
}
}
);
}
private static void doConfigurePubListPackageDirsLibrary(@NotNull final Project project,
@NotNull final Set<Module> modules,
@NotNull final Collection<String> rootsToAddToLib,
@NotNull final Map<String, List<File>> packageMap) {
final Library library = createPubListPackageDirsLibrary(project, rootsToAddToLib, packageMap);
for (final Module module : ModuleManager.getInstance(project).getModules()) {
final ModifiableRootModel modifiableModel = ModuleRootManager.getInstance(module).getModifiableModel();
try {
OrderEntry existingEntry = null;
for (final OrderEntry entry : modifiableModel.getOrderEntries()) {
if (entry instanceof LibraryOrderEntry &&
LibraryTablesRegistrar.PROJECT_LEVEL.equals(((LibraryOrderEntry)entry).getLibraryLevel()) &&
PUB_LIST_PACKAGE_DIRS_LIB_NAME.equals(((LibraryOrderEntry)entry).getLibraryName())) {
existingEntry = entry;
break;
}
}
final boolean contains = existingEntry != null;
final boolean mustContain = modules.contains(module);
if (contains != mustContain) {
if (mustContain) {
modifiableModel.addLibraryEntry(library);
}
else {
modifiableModel.removeOrderEntry(existingEntry);
}
}
if (modifiableModel.isChanged()) {
modifiableModel.commit();
}
}
finally {
if (!modifiableModel.isDisposed()) {
modifiableModel.dispose();
}
}
}
}
private static Library createPubListPackageDirsLibrary(@NotNull final Project project,
@NotNull final Collection<String> rootsToAddToLib,
@NotNull final Map<String, List<File>> packageMap) {
Library library = ProjectLibraryTable.getInstance(project).getLibraryByName(PUB_LIST_PACKAGE_DIRS_LIB_NAME);
if (library == null) {
final LibraryTableBase.ModifiableModel libTableModel = ProjectLibraryTable.getInstance(project).getModifiableModel();
library = libTableModel.createLibrary(PUB_LIST_PACKAGE_DIRS_LIB_NAME, DartListPackageDirsLibraryType.LIBRARY_KIND);
libTableModel.commit();
}
final LibraryEx.ModifiableModelEx libModel = (LibraryEx.ModifiableModelEx)library.getModifiableModel();
try {
for (String url : libModel.getUrls(OrderRootType.CLASSES)) {
libModel.removeRoot(url, OrderRootType.CLASSES);
}
for (String packageDir : rootsToAddToLib) {
libModel.addRoot(VfsUtilCore.pathToUrl(packageDir), OrderRootType.CLASSES);
}
final DartListPackageDirsLibraryProperties libraryProperties = new DartListPackageDirsLibraryProperties();
libraryProperties.setPackageNameToFileDirsMap(packageMap);
libModel.setProperties(libraryProperties);
libModel.commit();
}
finally {
if (!Disposer.isDisposed(libModel)) {
Disposer.dispose(libModel);
}
}
return library;
}
static void removePubListPackageDirsLibrary(final @NotNull Project project) {
ApplicationManager.getApplication().runWriteAction(
new Runnable() {
public void run() {
doRemovePubListPackageDirsLibrary(project);
}
}
);
}
private static void doRemovePubListPackageDirsLibrary(final @NotNull Project project) {
for (final Module module : ModuleManager.getInstance(project).getModules()) {
final ModifiableRootModel modifiableModel = ModuleRootManager.getInstance(module).getModifiableModel();
try {
for (final OrderEntry entry : modifiableModel.getOrderEntries()) {
if (entry instanceof LibraryOrderEntry &&
LibraryTablesRegistrar.PROJECT_LEVEL.equals(((LibraryOrderEntry)entry).getLibraryLevel()) &&
PUB_LIST_PACKAGE_DIRS_LIB_NAME.equals(((LibraryOrderEntry)entry).getLibraryName())) {
modifiableModel.removeOrderEntry(entry);
}
}
if (modifiableModel.isChanged()) {
modifiableModel.commit();
}
}
finally {
if (!modifiableModel.isDisposed()) {
modifiableModel.dispose();
}
}
}
final Library library = ProjectLibraryTable.getInstance(project).getLibraryByName(PUB_LIST_PACKAGE_DIRS_LIB_NAME);
if (library != null) {
ProjectLibraryTable.getInstance(project).removeLibrary(library);
}
}
}
| true | true | public void actionPerformed(@NotNull final AnActionEvent e) {
final Project project = e.getProject();
final DartSdk sdk = project == null ? null : DartSdk.getDartSdk(project);
if (sdk == null || !DartAnalysisServerAnnotator.isDartSDKVersionSufficient(sdk)) return;
FileDocumentManager.getInstance().saveAllDocuments();
@NotNull final Set<Module> affectedModules = new THashSet<Module>();
@NotNull final Collection<String> rootsToAddToLib = new THashSet<String>();
@NotNull final Map<String, List<File>> packageNameToDirMap = new THashMap<String, List<File>>();
final Runnable runnable = new Runnable() {
public void run() {
final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
if (indicator != null) {
indicator.setIndeterminate(true);
indicator.setText("pub list-package-dirs");
}
if (!DartAnalysisServerService.getInstance().serverReadyForRequest(project, sdk)) return;
DartAnalysisServerService.getInstance().updateFilesContent();
DartAnalysisServerService.LibraryDependenciesResult libraryDependenciesResult =
DartAnalysisServerService.getInstance().analysis_getLibraryDependencies();
if (libraryDependenciesResult == null) {
libraryDependenciesResult = new DartAnalysisServerService.LibraryDependenciesResult(new String[]{}, Collections
.<String, Map<String, List<String>>>emptyMap());
}
String[] libraries = libraryDependenciesResult.getLibraries();
if (libraries == null) {
libraries = new String[]{};
}
Map<String, Map<String, List<String>>> packageMapMap = libraryDependenciesResult.getPackageMap();
if (packageMapMap == null) {
packageMapMap = Collections.emptyMap();
}
@NotNull final Module[] modules = ModuleManager.getInstance(project).getModules();
for (@NotNull final Module module : modules) {
if (DartSdkGlobalLibUtil.isDartSdkGlobalLibAttached(module, sdk.getGlobalLibName())) {
for (@NotNull final VirtualFile contentRoot : ModuleRootManager.getInstance(module).getContentRoots()) {
// if there is a pubspec, skip this contentRoot
if (contentRoot.findChild(PubspecYamlUtil.PUBSPEC_YAML) != null) continue;
affectedModules.add(module);
}
}
}
computeLibraryRoots(project, sdk, libraries, rootsToAddToLib);
computePackageMap(packageMapMap, packageNameToDirMap);
}
};
if (ProgressManager.getInstance().runProcessWithProgressSynchronously(runnable, "pub list-package-dirs", true, project)) {
@NotNull final DartListPackageDirsDialog dialog = new DartListPackageDirsDialog(project, rootsToAddToLib, packageNameToDirMap);
dialog.show();
if (dialog.getExitCode() == DialogWrapper.OK_EXIT_CODE) {
configurePubListPackageDirsLibrary(project, affectedModules, rootsToAddToLib, packageNameToDirMap);
}
if (dialog.getExitCode() == DartListPackageDirsDialog.CONFIGURE_NONE_EXIT_CODE) {
removePubListPackageDirsLibrary(project);
}
}
}
| public void actionPerformed(@NotNull final AnActionEvent e) {
final Project project = e.getProject();
final DartSdk sdk = project == null ? null : DartSdk.getDartSdk(project);
if (sdk == null || !DartAnalysisServerAnnotator.isDartSDKVersionSufficient(sdk)) return;
FileDocumentManager.getInstance().saveAllDocuments();
@NotNull final Set<Module> affectedModules = new THashSet<Module>();
@NotNull final Collection<String> rootsToAddToLib = new THashSet<String>();
final Map<String, List<File>> packageNameToDirMap = new TreeMap<String, List<File>>();
final Runnable runnable = new Runnable() {
public void run() {
final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
if (indicator != null) {
indicator.setIndeterminate(true);
indicator.setText("pub list-package-dirs");
}
if (!DartAnalysisServerService.getInstance().serverReadyForRequest(project, sdk)) return;
DartAnalysisServerService.getInstance().updateFilesContent();
DartAnalysisServerService.LibraryDependenciesResult libraryDependenciesResult =
DartAnalysisServerService.getInstance().analysis_getLibraryDependencies();
if (libraryDependenciesResult == null) {
libraryDependenciesResult = new DartAnalysisServerService.LibraryDependenciesResult(new String[]{}, Collections
.<String, Map<String, List<String>>>emptyMap());
}
String[] libraries = libraryDependenciesResult.getLibraries();
if (libraries == null) {
libraries = new String[]{};
}
Map<String, Map<String, List<String>>> packageMapMap = libraryDependenciesResult.getPackageMap();
if (packageMapMap == null) {
packageMapMap = Collections.emptyMap();
}
@NotNull final Module[] modules = ModuleManager.getInstance(project).getModules();
for (@NotNull final Module module : modules) {
if (DartSdkGlobalLibUtil.isDartSdkGlobalLibAttached(module, sdk.getGlobalLibName())) {
for (@NotNull final VirtualFile contentRoot : ModuleRootManager.getInstance(module).getContentRoots()) {
// if there is a pubspec, skip this contentRoot
if (contentRoot.findChild(PubspecYamlUtil.PUBSPEC_YAML) != null) continue;
affectedModules.add(module);
}
}
}
computeLibraryRoots(project, sdk, libraries, rootsToAddToLib);
computePackageMap(packageMapMap, packageNameToDirMap);
}
};
if (ProgressManager.getInstance().runProcessWithProgressSynchronously(runnable, "pub list-package-dirs", true, project)) {
@NotNull final DartListPackageDirsDialog dialog = new DartListPackageDirsDialog(project, rootsToAddToLib, packageNameToDirMap);
dialog.show();
if (dialog.getExitCode() == DialogWrapper.OK_EXIT_CODE) {
configurePubListPackageDirsLibrary(project, affectedModules, rootsToAddToLib, packageNameToDirMap);
}
if (dialog.getExitCode() == DartListPackageDirsDialog.CONFIGURE_NONE_EXIT_CODE) {
removePubListPackageDirsLibrary(project);
}
}
}
|
diff --git a/disambiguation-work/disambiguation-work-impl/src/main/java/pl/edu/icm/coansys/disambiguation/work/voter/AuthorsVoter.java b/disambiguation-work/disambiguation-work-impl/src/main/java/pl/edu/icm/coansys/disambiguation/work/voter/AuthorsVoter.java
index 08f52c65..ca70e9af 100644
--- a/disambiguation-work/disambiguation-work-impl/src/main/java/pl/edu/icm/coansys/disambiguation/work/voter/AuthorsVoter.java
+++ b/disambiguation-work/disambiguation-work-impl/src/main/java/pl/edu/icm/coansys/disambiguation/work/voter/AuthorsVoter.java
@@ -1,144 +1,144 @@
/*
* This file is part of CoAnSys project.
* Copyright (c) 2012-2013 ICM-UW
*
* CoAnSys 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.
* CoAnSys 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 CoAnSys. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.icm.coansys.disambiguation.work.voter;
import java.util.List;
import pl.edu.icm.coansys.commons.java.Pair;
import pl.edu.icm.coansys.commons.java.StringTools;
import pl.edu.icm.coansys.commons.reparser.Node;
import pl.edu.icm.coansys.commons.reparser.RegexpParser;
import pl.edu.icm.coansys.commons.stringsimilarity.JaroWinklerSimilarity;
import pl.edu.icm.coansys.commons.stringsimilarity.SimilarityCalculator;
import pl.edu.icm.coansys.models.DocumentProtos;
/**
*
* @author Artur Czeczko <[email protected]>
*/
public class AuthorsVoter extends AbstractSimilarityVoter {
@Override
public Vote vote(DocumentProtos.DocumentWrapper doc1, DocumentProtos.DocumentWrapper doc2) {
Pair<String[], Boolean> doc1surnames = extractSurnames(doc1);
Pair<String[], Boolean> doc2surnames = extractSurnames(doc2);
if (doc1surnames.getX().length == 0 || doc2surnames.getX().length == 0) {
return new Vote(Vote.VoteStatus.ABSTAIN);
}
float firstAuthorComponent = 0.0f;
float allAuthorsMatchFactor = 0.75f;
if (doc1surnames.getY() && doc2surnames.getY()) {
String doc1firstAuthor = doc1surnames.getX()[0];
String doc2firstAuthor = doc2surnames.getX()[0];
SimilarityCalculator similarity = getSimilarityCalculator();
if (similarity.calculateSimilarity(doc1firstAuthor, doc2firstAuthor) > 0.5f) {
firstAuthorComponent = 0.667f;
allAuthorsMatchFactor = 0.33f;
} else {
allAuthorsMatchFactor = 0.667f;
}
}
float probability = firstAuthorComponent +
allAuthorsMatchFactor * allAuthorsMatching(doc1surnames.getX(), doc2surnames.getX());
if (probability > 1.0f) {
probability = 1.0f;
}
if (probability < 0.0f) {
probability = 0.0f;
}
return new Vote(Vote.VoteStatus.PROBABILITY, probability);
}
private Pair<String[], Boolean> extractSurnames(DocumentProtos.DocumentWrapper doc) {
RegexpParser authorParser = new RegexpParser("authorParser.properties", "author");
List<DocumentProtos.Author> authorList = doc.getDocumentMetadata().getBasicMetadata().getAuthorList();
String[] resultByPositionNb = new String[authorList.size()];
String[] resultByOrder = new String[authorList.size()];
boolean positionsCorrect = true;
int orderNb = 0;
for (DocumentProtos.Author author : doc.getDocumentMetadata().getBasicMetadata().getAuthorList()) {
String surname;
if (author.hasSurname()) {
surname = author.getSurname();
} else {
String fullname = author.getName();
try {
Node authorNode = authorParser.parse(fullname);
Node surnameNode = authorNode.getFirstField("surname");
surname = surnameNode.getValue();
} catch (NullPointerException ex) {
surname = fullname;
}
}
surname = StringTools.normalize(surname);
if (positionsCorrect) {
if (!author.hasPositionNumber()) {
positionsCorrect = false;
} else {
int authorPosition = author.getPositionNumber() - 1;
- if (authorPosition >= resultByPositionNb.length || resultByPositionNb[authorPosition] != null) {
+ if (authorPosition < 0 || authorPosition >= resultByPositionNb.length || resultByPositionNb[authorPosition] != null) {
positionsCorrect = false;
} else {
resultByPositionNb[authorPosition] = surname;
}
}
}
resultByOrder[orderNb] = surname;
orderNb++;
}
return new Pair<String[], Boolean>(positionsCorrect ? resultByPositionNb : resultByOrder, positionsCorrect);
}
private SimilarityCalculator getSimilarityCalculator() {
return new JaroWinklerSimilarity();
}
/**
*
*
* @param doc1authors
* @param doc2authors
* @return
*/
private float allAuthorsMatching(String[] doc1authors, String[] doc2authors) {
int intersectionSize = 0;
SimilarityCalculator similarity = getSimilarityCalculator();
for (String d1author : doc1authors) {
for (String d2author : doc2authors) {
if (similarity.calculateSimilarity(d1author, d2author) > 0.5) {
intersectionSize++;
break;
}
}
}
return 2.0f * intersectionSize / (doc1authors.length + doc2authors.length);
}
}
| true | true | private Pair<String[], Boolean> extractSurnames(DocumentProtos.DocumentWrapper doc) {
RegexpParser authorParser = new RegexpParser("authorParser.properties", "author");
List<DocumentProtos.Author> authorList = doc.getDocumentMetadata().getBasicMetadata().getAuthorList();
String[] resultByPositionNb = new String[authorList.size()];
String[] resultByOrder = new String[authorList.size()];
boolean positionsCorrect = true;
int orderNb = 0;
for (DocumentProtos.Author author : doc.getDocumentMetadata().getBasicMetadata().getAuthorList()) {
String surname;
if (author.hasSurname()) {
surname = author.getSurname();
} else {
String fullname = author.getName();
try {
Node authorNode = authorParser.parse(fullname);
Node surnameNode = authorNode.getFirstField("surname");
surname = surnameNode.getValue();
} catch (NullPointerException ex) {
surname = fullname;
}
}
surname = StringTools.normalize(surname);
if (positionsCorrect) {
if (!author.hasPositionNumber()) {
positionsCorrect = false;
} else {
int authorPosition = author.getPositionNumber() - 1;
if (authorPosition >= resultByPositionNb.length || resultByPositionNb[authorPosition] != null) {
positionsCorrect = false;
} else {
resultByPositionNb[authorPosition] = surname;
}
}
}
resultByOrder[orderNb] = surname;
orderNb++;
}
return new Pair<String[], Boolean>(positionsCorrect ? resultByPositionNb : resultByOrder, positionsCorrect);
}
| private Pair<String[], Boolean> extractSurnames(DocumentProtos.DocumentWrapper doc) {
RegexpParser authorParser = new RegexpParser("authorParser.properties", "author");
List<DocumentProtos.Author> authorList = doc.getDocumentMetadata().getBasicMetadata().getAuthorList();
String[] resultByPositionNb = new String[authorList.size()];
String[] resultByOrder = new String[authorList.size()];
boolean positionsCorrect = true;
int orderNb = 0;
for (DocumentProtos.Author author : doc.getDocumentMetadata().getBasicMetadata().getAuthorList()) {
String surname;
if (author.hasSurname()) {
surname = author.getSurname();
} else {
String fullname = author.getName();
try {
Node authorNode = authorParser.parse(fullname);
Node surnameNode = authorNode.getFirstField("surname");
surname = surnameNode.getValue();
} catch (NullPointerException ex) {
surname = fullname;
}
}
surname = StringTools.normalize(surname);
if (positionsCorrect) {
if (!author.hasPositionNumber()) {
positionsCorrect = false;
} else {
int authorPosition = author.getPositionNumber() - 1;
if (authorPosition < 0 || authorPosition >= resultByPositionNb.length || resultByPositionNb[authorPosition] != null) {
positionsCorrect = false;
} else {
resultByPositionNb[authorPosition] = surname;
}
}
}
resultByOrder[orderNb] = surname;
orderNb++;
}
return new Pair<String[], Boolean>(positionsCorrect ? resultByPositionNb : resultByOrder, positionsCorrect);
}
|
diff --git a/war/src/main/java/com/tommytony/war/event/WarEntityListener.java b/war/src/main/java/com/tommytony/war/event/WarEntityListener.java
index a7c9608..09f82f3 100644
--- a/war/src/main/java/com/tommytony/war/event/WarEntityListener.java
+++ b/war/src/main/java/com/tommytony/war/event/WarEntityListener.java
@@ -1,628 +1,628 @@
package com.tommytony.war.event;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.logging.Level;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.entity.Arrow;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.entity.TNTPrimed;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.entity.EntityCombustEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.entity.EntityRegainHealthEvent;
import org.bukkit.event.entity.EntityRegainHealthEvent.RegainReason;
import org.bukkit.event.entity.ExplosionPrimeEvent;
import org.bukkit.event.entity.FoodLevelChangeEvent;
import org.getspout.spoutapi.SpoutManager;
import org.getspout.spoutapi.player.SpoutPlayer;
import com.tommytony.war.Team;
import com.tommytony.war.War;
import com.tommytony.war.Warzone;
import com.tommytony.war.config.TeamConfig;
import com.tommytony.war.config.WarConfig;
import com.tommytony.war.config.WarzoneConfig;
import com.tommytony.war.job.DeferredBlockResetsJob;
import com.tommytony.war.spout.SpoutDisplayer;
import com.tommytony.war.structure.Bomb;
import com.tommytony.war.utility.LoadoutSelection;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.LivingEntity;
import org.bukkit.event.entity.ProjectileHitEvent;
import org.bukkit.event.entity.ProjectileLaunchEvent;
import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.util.Vector;
/**
* Handles Entity-Events
*
* @author tommytony, Tim Düsterhus
* @package com.tommytony.war.event
*/
public class WarEntityListener implements Listener {
private final Random killSeed = new Random();
/**
* Handles PVP-Damage
*
* @param event
* fired event
*/
private void handlerAttackDefend(EntityDamageByEntityEvent event) {
Entity attacker = event.getDamager();
Entity defender = event.getEntity();
// Maybe an arrow was thrown
if (attacker != null && event.getDamager() instanceof Projectile && ((Projectile)event.getDamager()).getShooter() instanceof Player){
attacker = ((Player)((Projectile)event.getDamager()).getShooter());
}
if (attacker != null && defender != null && attacker instanceof Player && defender instanceof Player) {
// only let adversaries (same warzone, different team) attack each other
Player a = (Player) attacker;
Player d = (Player) defender;
Warzone attackerWarzone = Warzone.getZoneByPlayerName(a.getName());
Team attackerTeam = Team.getTeamByPlayerName(a.getName());
Warzone defenderWarzone = Warzone.getZoneByPlayerName(d.getName());
Team defenderTeam = Team.getTeamByPlayerName(d.getName());
if ((attackerTeam != null && defenderTeam != null && attackerTeam != defenderTeam && attackerWarzone == defenderWarzone)
|| (attackerTeam != null && defenderTeam != null && attacker.getEntityId() == defender.getEntityId())) {
LoadoutSelection defenderLoadoutState = defenderWarzone.getLoadoutSelections().get(d.getName());
if (defenderLoadoutState != null && defenderLoadoutState.isStillInSpawn()) {
War.war.badMsg(a, "pvp.target.spawn");
event.setCancelled(true);
return;
}
LoadoutSelection attackerLoadoutState = attackerWarzone.getLoadoutSelections().get(a.getName());
if (attackerLoadoutState != null && attackerLoadoutState.isStillInSpawn()) {
War.war.badMsg(a, "pvp.self.spawn");
event.setCancelled(true);
return;
}
// Make sure none of them are locked in by respawn timer
if (defenderWarzone.isRespawning(d)) {
War.war.badMsg(a, "pvp.target.respawn");
event.setCancelled(true);
return;
} else if (attackerWarzone.isRespawning(a)) {
War.war.badMsg(a, "pvp.self.respawn");
event.setCancelled(true);
return;
}
if (!attackerWarzone.getWarzoneConfig().getBoolean(WarzoneConfig.PVPINZONE)) {
// spleef-like, non-pvp, zone
event.setCancelled(true);
return;
}
// Detect death, prevent it and respawn the player
if (event.getDamage() >= d.getHealth()) {
if (defenderWarzone.getReallyDeadFighters().contains(d.getName())) {
// don't re-kill a dead person
if (d.getHealth() != 0) {
d.setHealth(0);
}
return;
}
if (attackerWarzone.getWarzoneConfig().getBoolean(WarzoneConfig.DEATHMESSAGES)) {
String attackerString = attackerTeam.getKind().getColor() + a.getName();
String defenderString = defenderTeam.getKind().getColor() + d.getName();
if (attacker.getEntityId() != defender.getEntityId()) {
Material killerWeapon = a.getItemInHand().getType();
String weaponString = killerWeapon.toString();
if (a.getItemInHand().hasItemMeta() && a.getItemInHand().getItemMeta().hasDisplayName()) {
weaponString = a.getItemInHand().getItemMeta().getDisplayName() + ChatColor.WHITE;
}
if (killerWeapon == Material.AIR) {
weaponString = War.war.getString("pvp.kill.weapon.hand");
} else if (killerWeapon == Material.BOW || event.getDamager() instanceof Arrow) {
int rand = killSeed.nextInt(3);
if (rand == 0) {
weaponString = War.war.getString("pvp.kill.weapon.bow");
} else {
weaponString = War.war.getString("pvp.kill.weapon.aim");
}
} else if (event.getDamager() instanceof Projectile) {
weaponString = War.war.getString("pvp.kill.weapon.aim");
}
- String adjectiveString = War.war.getDeadlyAdjectives().get(this.killSeed.nextInt(War.war.getDeadlyAdjectives().size()));
- String verbString = War.war.getKillerVerbs().get(this.killSeed.nextInt(War.war.getKillerVerbs().size()));
+ String adjectiveString = War.war.getDeadlyAdjectives().isEmpty() ? "" : War.war.getDeadlyAdjectives().get(this.killSeed.nextInt(War.war.getDeadlyAdjectives().size()));
+ String verbString = War.war.getKillerVerbs().isEmpty() ? "" : War.war.getKillerVerbs().get(this.killSeed.nextInt(War.war.getKillerVerbs().size()));
defenderWarzone.broadcast("pvp.kill.format", attackerString + ChatColor.WHITE, adjectiveString,
weaponString.toLowerCase().replace('_', ' '), verbString, defenderString);
} else {
defenderWarzone.broadcast("pvp.kill.self", defenderString + ChatColor.WHITE);
}
}
if (attacker.getEntityId() != defender.getEntityId()) {
defenderWarzone.addKillCount(a.getName(), 1);
defenderWarzone.addKillDeathRecord(a, 1, 0);
defenderWarzone.addKillDeathRecord(d, 0, 1);
if (attackerTeam.getTeamConfig().resolveBoolean(TeamConfig.XPKILLMETER)) {
a.setLevel(defenderWarzone.getKillCount(a.getName()));
}
if (attackerTeam.getTeamConfig().resolveBoolean(TeamConfig.KILLSTREAK)) {
War.war.getKillstreakReward().rewardPlayer(a, defenderWarzone.getKillCount(a.getName()));
}
}
WarPlayerDeathEvent event1 = new WarPlayerDeathEvent(defenderWarzone, d, a, event.getCause());
War.war.getServer().getPluginManager().callEvent(event1);
defenderWarzone.handleDeath(d);
if (!defenderWarzone.getWarzoneConfig().getBoolean(WarzoneConfig.REALDEATHS)) {
// fast respawn, don't really die
event.setCancelled(true);
return;
}
} else if (defenderWarzone.isBombThief(d.getName()) && d.getLocation().distance(a.getLocation()) < 2) {
// Close combat, close enough to detonate
Bomb bomb = defenderWarzone.getBombForThief(d.getName());
// Kill the bomber
WarPlayerDeathEvent event1 = new WarPlayerDeathEvent(defenderWarzone, d, null, event.getCause());
War.war.getServer().getPluginManager().callEvent(event1);
defenderWarzone.handleDeath(d);
if (defenderWarzone.getWarzoneConfig().getBoolean(WarzoneConfig.REALDEATHS)) {
// and respawn him and remove from deadmen (cause realdeath + handleDeath means no respawn and getting queued up for onPlayerRespawn)
defenderWarzone.getReallyDeadFighters().remove(d.getName());
defenderWarzone.respawnPlayer(defenderTeam, d);
}
// Blow up bomb
if (!defenderWarzone.getWarzoneConfig().getBoolean(WarzoneConfig.UNBREAKABLE)) {
defenderWarzone.getWorld().createExplosion(a.getLocation(), 2F);
}
// bring back tnt
bomb.getVolume().resetBlocks();
bomb.addBombBlocks();
// Notify everyone
for (Team t : defenderWarzone.getTeams()) {
if (War.war.isSpoutServer()) {
for (Player p : t.getPlayers()) {
SpoutPlayer sp = SpoutManager.getPlayer(p);
if (sp.isSpoutCraftEnabled()) {
sp.sendNotification(
SpoutDisplayer.cleanForNotification(attackerTeam.getKind().getColor() + a.getName() + ChatColor.YELLOW + " made "),
SpoutDisplayer.cleanForNotification(defenderTeam.getKind().getColor() + d.getName() + ChatColor.YELLOW + " blow up!"),
Material.TNT,
(short)0,
10000);
}
}
}
t.teamcast("pvp.kill.bomb", attackerTeam.getKind().getColor() + a.getName() + ChatColor.WHITE,
defenderTeam.getKind().getColor() + d.getName() + ChatColor.WHITE);
}
}
} else if (attackerTeam != null && defenderTeam != null && attackerTeam == defenderTeam && attackerWarzone == defenderWarzone && attacker.getEntityId() != defender.getEntityId()) {
// same team, but not same person
if (attackerWarzone.getWarzoneConfig().getBoolean(WarzoneConfig.FRIENDLYFIRE)) {
War.war.badMsg(a, "pvp.ff.enabled"); // if ff is on, let the attack go through
} else {
War.war.badMsg(a, "pvp.ff.disabled");
event.setCancelled(true); // ff is off
}
} else if (attackerTeam == null && defenderTeam == null && War.war.canPvpOutsideZones(a)) {
// let normal PVP through is its not turned off or if you have perms
} else if (attackerTeam == null && defenderTeam == null && !War.war.canPvpOutsideZones(a)) {
if (!War.war.getWarConfig().getBoolean(WarConfig.DISABLEPVPMESSAGE)) {
War.war.badMsg(a, "pvp.outside.permission");
}
event.setCancelled(true); // global pvp is off
} else {
if (attackerTeam == null) {
War.war.badMsg(a, "pvp.self.notplaying");
} else if (defenderTeam == null) {
War.war.badMsg(a, "pvp.target.notplaying");
} else if (attacker != null && defender != null && attacker.getEntityId() == defender.getEntityId()) {
// You just hit yourself, probably with a bouncing arrow
} else if (attackerTeam == defenderTeam) {
War.war.badMsg(a, "pvp.ff.disabled");
} else if (attackerWarzone != defenderWarzone) {
War.war.badMsg(a, "pvp.target.otherzone");
}
event.setCancelled(true); // can't attack someone inside a warzone if you're not in a team
}
} else if (defender instanceof Player) {
// attacked by dispenser arrow most probably
// Detect death, prevent it and respawn the player
Player d = (Player) defender;
Warzone defenderWarzone = Warzone.getZoneByPlayerName(d.getName());
if (d != null && defenderWarzone != null && event.getDamage() >= d.getHealth()) {
LoadoutSelection defenderLoadoutState = defenderWarzone.getLoadoutSelections().get(d.getName());
if (defenderLoadoutState != null && defenderLoadoutState.isStillInSpawn()) {
event.setCancelled(true);
return;
}
if (defenderWarzone.getReallyDeadFighters().contains(d.getName())) {
// don't re-kill a dead person
if (d.getHealth() != 0) {
d.setHealth(0);
}
return;
}
if (defenderWarzone.getWarzoneConfig().getBoolean(WarzoneConfig.DEATHMESSAGES)) {
String defenderString = Team.getTeamByPlayerName(d.getName()).getKind().getColor() + d.getName();
if (event.getDamager() instanceof TNTPrimed) {
defenderWarzone.broadcast("pvp.death.explosion", defenderString + ChatColor.WHITE);
} else {
defenderWarzone.broadcast("pvp.death.other", defenderString + ChatColor.WHITE);
}
}
WarPlayerDeathEvent event1 = new WarPlayerDeathEvent(defenderWarzone, d, null, event.getCause());
War.war.getServer().getPluginManager().callEvent(event1);
defenderWarzone.handleDeath(d);
if (!defenderWarzone.getWarzoneConfig().getBoolean(WarzoneConfig.REALDEATHS)) {
// fast respawn, don't really die
event.setCancelled(true);
return;
}
}
}
}
/**
* Protects important structures from explosions
*
* @see EntityListener.onEntityExplode()
*/
@EventHandler
public void onEntityExplode(final EntityExplodeEvent event) {
if (!War.war.isLoaded()) {
return;
}
// protect zones elements, lobbies and warhub from creepers and tnt
List<Block> explodedBlocks = event.blockList();
List<Block> dontExplode = new ArrayList<Block>();
boolean explosionInAWarzone = event.getEntity() != null && Warzone.getZoneByLocation(event.getEntity().getLocation()) != null;
if (!explosionInAWarzone && War.war.getWarConfig().getBoolean(WarConfig.TNTINZONESONLY) && event.getEntity() instanceof TNTPrimed) {
// if tntinzonesonly:true, no tnt blows up outside zones
event.setCancelled(true);
return;
}
for (Block block : explodedBlocks) {
if (block.getType() == Material.TNT) {
continue; // don't restore TNT (failed to track down regression cause)
}
if (War.war.getWarHub() != null && War.war.getWarHub().getVolume().contains(block)) {
dontExplode.add(block);
} else {
boolean inOneZone = false;
for (Warzone zone : War.war.getWarzones()) {
if (zone.isImportantBlock(block)) {
dontExplode.add(block);
if (zone.isBombBlock(block)) {
// tnt doesn't get reset like normal blocks, gotta schedule a later reset just for the Bomb
// structure's tnt block
DeferredBlockResetsJob job = new DeferredBlockResetsJob();
BlockState tnt = block.getState();
tnt.setType(Material.TNT);
job.add(tnt);
War.war.getServer().getScheduler().scheduleSyncDelayedTask(War.war, job, 10);
}
inOneZone = true;
break;
} else if (zone.getLobby() != null && zone.getLobby().getVolume().contains(block)) {
dontExplode.add(block);
inOneZone = true;
break;
} else if (zone.getVolume().contains(block)) {
inOneZone = true;
}
}
if (!inOneZone && explosionInAWarzone) {
// if the explosion originated in warzone, always rollback
dontExplode.add(block);
}
}
}
int dontExplodeSize = dontExplode.size();
if (dontExplode.size() > 0) {
// Reset the exploded blocks that shouldn't have exploded (some of these are zone artifacts, if rollbackexplosion some may be outside-of-zone blocks
DeferredBlockResetsJob job = new DeferredBlockResetsJob();
for (Block dont : dontExplode) {
job.add(dont.getState());
}
War.war.getServer().getScheduler().scheduleSyncDelayedTask(War.war, job);
// Changed explosion yield following proportion of explosion prevention (makes drops less buggy too)
int explodedSize = explodedBlocks.size();
float middleYeild = (float)(explodedSize - dontExplodeSize) / (float)explodedSize;
float newYeild = middleYeild * event.getYield();
event.setYield(newYeild);
}
}
/**
* Handles damage on Players
*
* @see EntityListener.onEntityDamage()
*/
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onEntityDamage(final EntityDamageEvent event) {
if (!War.war.isLoaded()) {
return;
}
Entity entity = event.getEntity();
if (!(entity instanceof Player)) {
return;
}
Player player = (Player) entity;
// prevent godmode
Warzone zone = Warzone.getZoneByPlayerName(player.getName());
if (zone != null) {
event.setCancelled(false);
}
// pass pvp-damage
if (event instanceof EntityDamageByEntityEvent) {
this.handlerAttackDefend((EntityDamageByEntityEvent) event);
} else {
Team team = Team.getTeamByPlayerName(player.getName());
if (zone != null && team != null) {
LoadoutSelection playerLoadoutState = zone.getLoadoutSelections().get(player.getName());
if (team.isSpawnLocation(player.getLocation())
&& playerLoadoutState != null && playerLoadoutState.isStillInSpawn()) {
// don't let a player still in spawn get damaged
event.setCancelled(true);
} else if (event.getDamage() >= player.getHealth()) {
if (zone.getReallyDeadFighters().contains(player.getName())) {
// don't re-count the death points of an already dead person, make sure they are dead though
// (reason for this is that onEntityDamage sometimes fires more than once for one death)
if (player.getHealth() != 0) {
player.setHealth(0);
}
return;
}
// Detect death, prevent it and respawn the player
if (zone.getWarzoneConfig().getBoolean(WarzoneConfig.DEATHMESSAGES)) {
String playerName = Team.getTeamByPlayerName(player.getName()).getKind().getColor() + player.getName() + ChatColor.WHITE;
if (event.getCause() == DamageCause.FIRE || event.getCause() == DamageCause.FIRE_TICK
|| event.getCause() == DamageCause.LAVA || event.getCause() == DamageCause.LIGHTNING) {
zone.broadcast("pvp.death.fire", playerName);
} else if (event.getCause() == DamageCause.DROWNING) {
zone.broadcast("pvp.death.drown", playerName);
} else if (event.getCause() == DamageCause.FALL) {
zone.broadcast("pvp.death.fall", playerName);
} else {
zone.broadcast("pvp.death.other", playerName);
}
}
WarPlayerDeathEvent event1 = new WarPlayerDeathEvent(zone, player, null, event.getCause());
War.war.getServer().getPluginManager().callEvent(event1);
zone.handleDeath(player);
if (!zone.getWarzoneConfig().getBoolean(WarzoneConfig.REALDEATHS)) {
// fast respawn, don't really die
event.setCancelled(true);
}
}
}
}
}
@EventHandler
public void onEntityCombust(final EntityCombustEvent event) {
if (!War.war.isLoaded()) {
return;
}
Entity entity = event.getEntity();
if (entity instanceof Player) {
Player player = (Player) entity;
Team team = Team.getTeamByPlayerName(player.getName());
Warzone zone = Warzone.getZoneByPlayerName(player.getName());
LoadoutSelection playerLoadoutState = null;
if (zone != null) {
playerLoadoutState = zone.getLoadoutSelections().get(player.getName());
}
if (team != null
&& zone != null
&& team.isSpawnLocation(player.getLocation())
&& playerLoadoutState != null
&& playerLoadoutState.isStillInSpawn()) {
// smother out the fire that didn't burn out when you respawned
// Stop fire (but not if you came back to spawn after leaving it a first time)
player.setFireTicks(0);
event.setCancelled(true);
}
}
}
/**
* Prevents creatures from spawning in warzones if no creatures is active
*
* @see EntityListener.onCreatureSpawn()
*/
@EventHandler
public void onCreatureSpawn(final CreatureSpawnEvent event) {
if (!War.war.isLoaded()) {
return;
}
Location location = event.getLocation();
Warzone zone = Warzone.getZoneByLocation(location);
if (zone != null && zone.getWarzoneConfig().getBoolean(WarzoneConfig.NOCREATURES)) {
event.setCancelled(true);
}
}
/**
* Prevents health regaining caused by peaceful mode
*
* @see EntityListener.onEntityRegainHealth()
*/
@EventHandler
public void onEntityRegainHealth(final EntityRegainHealthEvent event) {
if (!War.war.isLoaded() ||
(event.getRegainReason() != RegainReason.REGEN
&& event.getRegainReason() != RegainReason.EATING
&& event.getRegainReason() != RegainReason.SATIATED)) {
return;
}
Entity entity = event.getEntity();
if (!(entity instanceof Player)) {
return;
}
Player player = (Player) entity;
Warzone zone = Warzone.getZoneByPlayerName(player.getName());
if (zone != null) {
Team team = Team.getTeamByPlayerName(player.getName());
if ((event.getRegainReason() == RegainReason.EATING
|| event.getRegainReason() != RegainReason.SATIATED )
&& team.getTeamConfig().resolveBoolean(TeamConfig.NOHUNGER)) {
// noHunger setting means you can't auto-heal with full hunger bar (use saturation instead to control how fast you get hungry)
event.setCancelled(true);
} else if (event.getRegainReason() == RegainReason.REGEN) {
// disable peaceful mode regen
event.setCancelled(true);
}
}
}
@EventHandler
public void onFoodLevelChange(final FoodLevelChangeEvent event) {
if (!War.war.isLoaded() || !(event.getEntity() instanceof Player)) {
return;
}
Player player = (Player) event.getEntity();
Warzone zone = Warzone.getZoneByPlayerName(player.getName());
Team team = Team.getTeamByPlayerName(player.getName());
if (zone != null && team.getTeamConfig().resolveBoolean(TeamConfig.NOHUNGER)){
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onEntityDeath(final EntityDeathEvent event) {
if (!War.war.isLoaded() || !(event.getEntity() instanceof Player)) {
return;
}
Player player = (Player) event.getEntity();
Warzone zone = Warzone.getZoneByPlayerName(player.getName());
if (zone != null) {
event.getDrops().clear();
if (!zone.getWarzoneConfig().getBoolean(WarzoneConfig.REALDEATHS)) {
// catch the odd death that gets away from us when usually intercepting and preventing deaths
zone.handleDeath(player);
Team team = Team.getTeamByPlayerName(player.getName());
if (zone.getWarzoneConfig().getBoolean(WarzoneConfig.DEATHMESSAGES)) {
zone.broadcast("pvp.death.other", team.getKind().getColor() + player.getName());
}
}
}
}
@EventHandler
public void onExplosionPrime(final ExplosionPrimeEvent event) {
if (!War.war.isLoaded()) {
return;
}
Location eventLocation = event.getEntity().getLocation();
for (Warzone zone : War.war.getWarzones()) {
if (zone.isBombBlock(eventLocation.getBlock())) {
// prevent the Bomb from exploding on its pedestral
event.setCancelled(true);
return;
}
}
}
@EventHandler
public void onProjectileHit(final ProjectileHitEvent event) {
if (!War.war.isLoaded()) {
return;
}
if (event.getEntityType() == EntityType.EGG) {
if (event.getEntity().hasMetadata("warAirstrike")) {
Location loc = event.getEntity().getLocation();
Warzone zone = Warzone.getZoneByLocation(loc);
if (zone == null) {
return;
}
Location tntPlace = new Location(loc.getWorld(), loc.getX(), Warzone.getZoneByLocation(loc).getVolume().getMaxY(), loc.getZ());
loc.getWorld().spawnEntity(tntPlace, EntityType.PRIMED_TNT);
loc.getWorld().spawnEntity(tntPlace.clone().add(new Vector(2, 0, 0)), EntityType.PRIMED_TNT);
loc.getWorld().spawnEntity(tntPlace.clone().add(new Vector(-2, 0, 0)), EntityType.PRIMED_TNT);
loc.getWorld().spawnEntity(tntPlace.clone().add(new Vector(0, 0, 2)), EntityType.PRIMED_TNT);
loc.getWorld().spawnEntity(tntPlace.clone().add(new Vector(0, 0, -2)), EntityType.PRIMED_TNT);
}
}
}
@EventHandler
public void onProjectileLaunch(final ProjectileLaunchEvent event) {
if (!War.war.isLoaded()) {
return;
}
if (event.getEntityType() == EntityType.EGG) {
LivingEntity shooter = event.getEntity().getShooter();
if (shooter instanceof Player) {
Player player = (Player) shooter;
Warzone zone = Warzone.getZoneByPlayerName(player.getName());
Team team = Team.getTeamByPlayerName(player.getName());
if (zone != null) {
if (War.war.getKillstreakReward().getAirstrikePlayers().remove(player.getName())) {
event.getEntity().setMetadata("warAirstrike", new FixedMetadataValue(War.war, true));
zone.broadcast("zone.airstrike", team.getKind().getColor() + player.getName() + ChatColor.WHITE);
}
}
}
}
}
}
| true | true | private void handlerAttackDefend(EntityDamageByEntityEvent event) {
Entity attacker = event.getDamager();
Entity defender = event.getEntity();
// Maybe an arrow was thrown
if (attacker != null && event.getDamager() instanceof Projectile && ((Projectile)event.getDamager()).getShooter() instanceof Player){
attacker = ((Player)((Projectile)event.getDamager()).getShooter());
}
if (attacker != null && defender != null && attacker instanceof Player && defender instanceof Player) {
// only let adversaries (same warzone, different team) attack each other
Player a = (Player) attacker;
Player d = (Player) defender;
Warzone attackerWarzone = Warzone.getZoneByPlayerName(a.getName());
Team attackerTeam = Team.getTeamByPlayerName(a.getName());
Warzone defenderWarzone = Warzone.getZoneByPlayerName(d.getName());
Team defenderTeam = Team.getTeamByPlayerName(d.getName());
if ((attackerTeam != null && defenderTeam != null && attackerTeam != defenderTeam && attackerWarzone == defenderWarzone)
|| (attackerTeam != null && defenderTeam != null && attacker.getEntityId() == defender.getEntityId())) {
LoadoutSelection defenderLoadoutState = defenderWarzone.getLoadoutSelections().get(d.getName());
if (defenderLoadoutState != null && defenderLoadoutState.isStillInSpawn()) {
War.war.badMsg(a, "pvp.target.spawn");
event.setCancelled(true);
return;
}
LoadoutSelection attackerLoadoutState = attackerWarzone.getLoadoutSelections().get(a.getName());
if (attackerLoadoutState != null && attackerLoadoutState.isStillInSpawn()) {
War.war.badMsg(a, "pvp.self.spawn");
event.setCancelled(true);
return;
}
// Make sure none of them are locked in by respawn timer
if (defenderWarzone.isRespawning(d)) {
War.war.badMsg(a, "pvp.target.respawn");
event.setCancelled(true);
return;
} else if (attackerWarzone.isRespawning(a)) {
War.war.badMsg(a, "pvp.self.respawn");
event.setCancelled(true);
return;
}
if (!attackerWarzone.getWarzoneConfig().getBoolean(WarzoneConfig.PVPINZONE)) {
// spleef-like, non-pvp, zone
event.setCancelled(true);
return;
}
// Detect death, prevent it and respawn the player
if (event.getDamage() >= d.getHealth()) {
if (defenderWarzone.getReallyDeadFighters().contains(d.getName())) {
// don't re-kill a dead person
if (d.getHealth() != 0) {
d.setHealth(0);
}
return;
}
if (attackerWarzone.getWarzoneConfig().getBoolean(WarzoneConfig.DEATHMESSAGES)) {
String attackerString = attackerTeam.getKind().getColor() + a.getName();
String defenderString = defenderTeam.getKind().getColor() + d.getName();
if (attacker.getEntityId() != defender.getEntityId()) {
Material killerWeapon = a.getItemInHand().getType();
String weaponString = killerWeapon.toString();
if (a.getItemInHand().hasItemMeta() && a.getItemInHand().getItemMeta().hasDisplayName()) {
weaponString = a.getItemInHand().getItemMeta().getDisplayName() + ChatColor.WHITE;
}
if (killerWeapon == Material.AIR) {
weaponString = War.war.getString("pvp.kill.weapon.hand");
} else if (killerWeapon == Material.BOW || event.getDamager() instanceof Arrow) {
int rand = killSeed.nextInt(3);
if (rand == 0) {
weaponString = War.war.getString("pvp.kill.weapon.bow");
} else {
weaponString = War.war.getString("pvp.kill.weapon.aim");
}
} else if (event.getDamager() instanceof Projectile) {
weaponString = War.war.getString("pvp.kill.weapon.aim");
}
String adjectiveString = War.war.getDeadlyAdjectives().get(this.killSeed.nextInt(War.war.getDeadlyAdjectives().size()));
String verbString = War.war.getKillerVerbs().get(this.killSeed.nextInt(War.war.getKillerVerbs().size()));
defenderWarzone.broadcast("pvp.kill.format", attackerString + ChatColor.WHITE, adjectiveString,
weaponString.toLowerCase().replace('_', ' '), verbString, defenderString);
} else {
defenderWarzone.broadcast("pvp.kill.self", defenderString + ChatColor.WHITE);
}
}
if (attacker.getEntityId() != defender.getEntityId()) {
defenderWarzone.addKillCount(a.getName(), 1);
defenderWarzone.addKillDeathRecord(a, 1, 0);
defenderWarzone.addKillDeathRecord(d, 0, 1);
if (attackerTeam.getTeamConfig().resolveBoolean(TeamConfig.XPKILLMETER)) {
a.setLevel(defenderWarzone.getKillCount(a.getName()));
}
if (attackerTeam.getTeamConfig().resolveBoolean(TeamConfig.KILLSTREAK)) {
War.war.getKillstreakReward().rewardPlayer(a, defenderWarzone.getKillCount(a.getName()));
}
}
WarPlayerDeathEvent event1 = new WarPlayerDeathEvent(defenderWarzone, d, a, event.getCause());
War.war.getServer().getPluginManager().callEvent(event1);
defenderWarzone.handleDeath(d);
if (!defenderWarzone.getWarzoneConfig().getBoolean(WarzoneConfig.REALDEATHS)) {
// fast respawn, don't really die
event.setCancelled(true);
return;
}
} else if (defenderWarzone.isBombThief(d.getName()) && d.getLocation().distance(a.getLocation()) < 2) {
// Close combat, close enough to detonate
Bomb bomb = defenderWarzone.getBombForThief(d.getName());
// Kill the bomber
WarPlayerDeathEvent event1 = new WarPlayerDeathEvent(defenderWarzone, d, null, event.getCause());
War.war.getServer().getPluginManager().callEvent(event1);
defenderWarzone.handleDeath(d);
if (defenderWarzone.getWarzoneConfig().getBoolean(WarzoneConfig.REALDEATHS)) {
// and respawn him and remove from deadmen (cause realdeath + handleDeath means no respawn and getting queued up for onPlayerRespawn)
defenderWarzone.getReallyDeadFighters().remove(d.getName());
defenderWarzone.respawnPlayer(defenderTeam, d);
}
// Blow up bomb
if (!defenderWarzone.getWarzoneConfig().getBoolean(WarzoneConfig.UNBREAKABLE)) {
defenderWarzone.getWorld().createExplosion(a.getLocation(), 2F);
}
// bring back tnt
bomb.getVolume().resetBlocks();
bomb.addBombBlocks();
// Notify everyone
for (Team t : defenderWarzone.getTeams()) {
if (War.war.isSpoutServer()) {
for (Player p : t.getPlayers()) {
SpoutPlayer sp = SpoutManager.getPlayer(p);
if (sp.isSpoutCraftEnabled()) {
sp.sendNotification(
SpoutDisplayer.cleanForNotification(attackerTeam.getKind().getColor() + a.getName() + ChatColor.YELLOW + " made "),
SpoutDisplayer.cleanForNotification(defenderTeam.getKind().getColor() + d.getName() + ChatColor.YELLOW + " blow up!"),
Material.TNT,
(short)0,
10000);
}
}
}
t.teamcast("pvp.kill.bomb", attackerTeam.getKind().getColor() + a.getName() + ChatColor.WHITE,
defenderTeam.getKind().getColor() + d.getName() + ChatColor.WHITE);
}
}
} else if (attackerTeam != null && defenderTeam != null && attackerTeam == defenderTeam && attackerWarzone == defenderWarzone && attacker.getEntityId() != defender.getEntityId()) {
// same team, but not same person
if (attackerWarzone.getWarzoneConfig().getBoolean(WarzoneConfig.FRIENDLYFIRE)) {
War.war.badMsg(a, "pvp.ff.enabled"); // if ff is on, let the attack go through
} else {
War.war.badMsg(a, "pvp.ff.disabled");
event.setCancelled(true); // ff is off
}
} else if (attackerTeam == null && defenderTeam == null && War.war.canPvpOutsideZones(a)) {
// let normal PVP through is its not turned off or if you have perms
} else if (attackerTeam == null && defenderTeam == null && !War.war.canPvpOutsideZones(a)) {
if (!War.war.getWarConfig().getBoolean(WarConfig.DISABLEPVPMESSAGE)) {
War.war.badMsg(a, "pvp.outside.permission");
}
event.setCancelled(true); // global pvp is off
} else {
if (attackerTeam == null) {
War.war.badMsg(a, "pvp.self.notplaying");
} else if (defenderTeam == null) {
War.war.badMsg(a, "pvp.target.notplaying");
} else if (attacker != null && defender != null && attacker.getEntityId() == defender.getEntityId()) {
// You just hit yourself, probably with a bouncing arrow
} else if (attackerTeam == defenderTeam) {
War.war.badMsg(a, "pvp.ff.disabled");
} else if (attackerWarzone != defenderWarzone) {
War.war.badMsg(a, "pvp.target.otherzone");
}
event.setCancelled(true); // can't attack someone inside a warzone if you're not in a team
}
} else if (defender instanceof Player) {
// attacked by dispenser arrow most probably
// Detect death, prevent it and respawn the player
Player d = (Player) defender;
Warzone defenderWarzone = Warzone.getZoneByPlayerName(d.getName());
if (d != null && defenderWarzone != null && event.getDamage() >= d.getHealth()) {
LoadoutSelection defenderLoadoutState = defenderWarzone.getLoadoutSelections().get(d.getName());
if (defenderLoadoutState != null && defenderLoadoutState.isStillInSpawn()) {
event.setCancelled(true);
return;
}
if (defenderWarzone.getReallyDeadFighters().contains(d.getName())) {
// don't re-kill a dead person
if (d.getHealth() != 0) {
d.setHealth(0);
}
return;
}
if (defenderWarzone.getWarzoneConfig().getBoolean(WarzoneConfig.DEATHMESSAGES)) {
String defenderString = Team.getTeamByPlayerName(d.getName()).getKind().getColor() + d.getName();
if (event.getDamager() instanceof TNTPrimed) {
defenderWarzone.broadcast("pvp.death.explosion", defenderString + ChatColor.WHITE);
} else {
defenderWarzone.broadcast("pvp.death.other", defenderString + ChatColor.WHITE);
}
}
WarPlayerDeathEvent event1 = new WarPlayerDeathEvent(defenderWarzone, d, null, event.getCause());
War.war.getServer().getPluginManager().callEvent(event1);
defenderWarzone.handleDeath(d);
if (!defenderWarzone.getWarzoneConfig().getBoolean(WarzoneConfig.REALDEATHS)) {
// fast respawn, don't really die
event.setCancelled(true);
return;
}
}
}
}
| private void handlerAttackDefend(EntityDamageByEntityEvent event) {
Entity attacker = event.getDamager();
Entity defender = event.getEntity();
// Maybe an arrow was thrown
if (attacker != null && event.getDamager() instanceof Projectile && ((Projectile)event.getDamager()).getShooter() instanceof Player){
attacker = ((Player)((Projectile)event.getDamager()).getShooter());
}
if (attacker != null && defender != null && attacker instanceof Player && defender instanceof Player) {
// only let adversaries (same warzone, different team) attack each other
Player a = (Player) attacker;
Player d = (Player) defender;
Warzone attackerWarzone = Warzone.getZoneByPlayerName(a.getName());
Team attackerTeam = Team.getTeamByPlayerName(a.getName());
Warzone defenderWarzone = Warzone.getZoneByPlayerName(d.getName());
Team defenderTeam = Team.getTeamByPlayerName(d.getName());
if ((attackerTeam != null && defenderTeam != null && attackerTeam != defenderTeam && attackerWarzone == defenderWarzone)
|| (attackerTeam != null && defenderTeam != null && attacker.getEntityId() == defender.getEntityId())) {
LoadoutSelection defenderLoadoutState = defenderWarzone.getLoadoutSelections().get(d.getName());
if (defenderLoadoutState != null && defenderLoadoutState.isStillInSpawn()) {
War.war.badMsg(a, "pvp.target.spawn");
event.setCancelled(true);
return;
}
LoadoutSelection attackerLoadoutState = attackerWarzone.getLoadoutSelections().get(a.getName());
if (attackerLoadoutState != null && attackerLoadoutState.isStillInSpawn()) {
War.war.badMsg(a, "pvp.self.spawn");
event.setCancelled(true);
return;
}
// Make sure none of them are locked in by respawn timer
if (defenderWarzone.isRespawning(d)) {
War.war.badMsg(a, "pvp.target.respawn");
event.setCancelled(true);
return;
} else if (attackerWarzone.isRespawning(a)) {
War.war.badMsg(a, "pvp.self.respawn");
event.setCancelled(true);
return;
}
if (!attackerWarzone.getWarzoneConfig().getBoolean(WarzoneConfig.PVPINZONE)) {
// spleef-like, non-pvp, zone
event.setCancelled(true);
return;
}
// Detect death, prevent it and respawn the player
if (event.getDamage() >= d.getHealth()) {
if (defenderWarzone.getReallyDeadFighters().contains(d.getName())) {
// don't re-kill a dead person
if (d.getHealth() != 0) {
d.setHealth(0);
}
return;
}
if (attackerWarzone.getWarzoneConfig().getBoolean(WarzoneConfig.DEATHMESSAGES)) {
String attackerString = attackerTeam.getKind().getColor() + a.getName();
String defenderString = defenderTeam.getKind().getColor() + d.getName();
if (attacker.getEntityId() != defender.getEntityId()) {
Material killerWeapon = a.getItemInHand().getType();
String weaponString = killerWeapon.toString();
if (a.getItemInHand().hasItemMeta() && a.getItemInHand().getItemMeta().hasDisplayName()) {
weaponString = a.getItemInHand().getItemMeta().getDisplayName() + ChatColor.WHITE;
}
if (killerWeapon == Material.AIR) {
weaponString = War.war.getString("pvp.kill.weapon.hand");
} else if (killerWeapon == Material.BOW || event.getDamager() instanceof Arrow) {
int rand = killSeed.nextInt(3);
if (rand == 0) {
weaponString = War.war.getString("pvp.kill.weapon.bow");
} else {
weaponString = War.war.getString("pvp.kill.weapon.aim");
}
} else if (event.getDamager() instanceof Projectile) {
weaponString = War.war.getString("pvp.kill.weapon.aim");
}
String adjectiveString = War.war.getDeadlyAdjectives().isEmpty() ? "" : War.war.getDeadlyAdjectives().get(this.killSeed.nextInt(War.war.getDeadlyAdjectives().size()));
String verbString = War.war.getKillerVerbs().isEmpty() ? "" : War.war.getKillerVerbs().get(this.killSeed.nextInt(War.war.getKillerVerbs().size()));
defenderWarzone.broadcast("pvp.kill.format", attackerString + ChatColor.WHITE, adjectiveString,
weaponString.toLowerCase().replace('_', ' '), verbString, defenderString);
} else {
defenderWarzone.broadcast("pvp.kill.self", defenderString + ChatColor.WHITE);
}
}
if (attacker.getEntityId() != defender.getEntityId()) {
defenderWarzone.addKillCount(a.getName(), 1);
defenderWarzone.addKillDeathRecord(a, 1, 0);
defenderWarzone.addKillDeathRecord(d, 0, 1);
if (attackerTeam.getTeamConfig().resolveBoolean(TeamConfig.XPKILLMETER)) {
a.setLevel(defenderWarzone.getKillCount(a.getName()));
}
if (attackerTeam.getTeamConfig().resolveBoolean(TeamConfig.KILLSTREAK)) {
War.war.getKillstreakReward().rewardPlayer(a, defenderWarzone.getKillCount(a.getName()));
}
}
WarPlayerDeathEvent event1 = new WarPlayerDeathEvent(defenderWarzone, d, a, event.getCause());
War.war.getServer().getPluginManager().callEvent(event1);
defenderWarzone.handleDeath(d);
if (!defenderWarzone.getWarzoneConfig().getBoolean(WarzoneConfig.REALDEATHS)) {
// fast respawn, don't really die
event.setCancelled(true);
return;
}
} else if (defenderWarzone.isBombThief(d.getName()) && d.getLocation().distance(a.getLocation()) < 2) {
// Close combat, close enough to detonate
Bomb bomb = defenderWarzone.getBombForThief(d.getName());
// Kill the bomber
WarPlayerDeathEvent event1 = new WarPlayerDeathEvent(defenderWarzone, d, null, event.getCause());
War.war.getServer().getPluginManager().callEvent(event1);
defenderWarzone.handleDeath(d);
if (defenderWarzone.getWarzoneConfig().getBoolean(WarzoneConfig.REALDEATHS)) {
// and respawn him and remove from deadmen (cause realdeath + handleDeath means no respawn and getting queued up for onPlayerRespawn)
defenderWarzone.getReallyDeadFighters().remove(d.getName());
defenderWarzone.respawnPlayer(defenderTeam, d);
}
// Blow up bomb
if (!defenderWarzone.getWarzoneConfig().getBoolean(WarzoneConfig.UNBREAKABLE)) {
defenderWarzone.getWorld().createExplosion(a.getLocation(), 2F);
}
// bring back tnt
bomb.getVolume().resetBlocks();
bomb.addBombBlocks();
// Notify everyone
for (Team t : defenderWarzone.getTeams()) {
if (War.war.isSpoutServer()) {
for (Player p : t.getPlayers()) {
SpoutPlayer sp = SpoutManager.getPlayer(p);
if (sp.isSpoutCraftEnabled()) {
sp.sendNotification(
SpoutDisplayer.cleanForNotification(attackerTeam.getKind().getColor() + a.getName() + ChatColor.YELLOW + " made "),
SpoutDisplayer.cleanForNotification(defenderTeam.getKind().getColor() + d.getName() + ChatColor.YELLOW + " blow up!"),
Material.TNT,
(short)0,
10000);
}
}
}
t.teamcast("pvp.kill.bomb", attackerTeam.getKind().getColor() + a.getName() + ChatColor.WHITE,
defenderTeam.getKind().getColor() + d.getName() + ChatColor.WHITE);
}
}
} else if (attackerTeam != null && defenderTeam != null && attackerTeam == defenderTeam && attackerWarzone == defenderWarzone && attacker.getEntityId() != defender.getEntityId()) {
// same team, but not same person
if (attackerWarzone.getWarzoneConfig().getBoolean(WarzoneConfig.FRIENDLYFIRE)) {
War.war.badMsg(a, "pvp.ff.enabled"); // if ff is on, let the attack go through
} else {
War.war.badMsg(a, "pvp.ff.disabled");
event.setCancelled(true); // ff is off
}
} else if (attackerTeam == null && defenderTeam == null && War.war.canPvpOutsideZones(a)) {
// let normal PVP through is its not turned off or if you have perms
} else if (attackerTeam == null && defenderTeam == null && !War.war.canPvpOutsideZones(a)) {
if (!War.war.getWarConfig().getBoolean(WarConfig.DISABLEPVPMESSAGE)) {
War.war.badMsg(a, "pvp.outside.permission");
}
event.setCancelled(true); // global pvp is off
} else {
if (attackerTeam == null) {
War.war.badMsg(a, "pvp.self.notplaying");
} else if (defenderTeam == null) {
War.war.badMsg(a, "pvp.target.notplaying");
} else if (attacker != null && defender != null && attacker.getEntityId() == defender.getEntityId()) {
// You just hit yourself, probably with a bouncing arrow
} else if (attackerTeam == defenderTeam) {
War.war.badMsg(a, "pvp.ff.disabled");
} else if (attackerWarzone != defenderWarzone) {
War.war.badMsg(a, "pvp.target.otherzone");
}
event.setCancelled(true); // can't attack someone inside a warzone if you're not in a team
}
} else if (defender instanceof Player) {
// attacked by dispenser arrow most probably
// Detect death, prevent it and respawn the player
Player d = (Player) defender;
Warzone defenderWarzone = Warzone.getZoneByPlayerName(d.getName());
if (d != null && defenderWarzone != null && event.getDamage() >= d.getHealth()) {
LoadoutSelection defenderLoadoutState = defenderWarzone.getLoadoutSelections().get(d.getName());
if (defenderLoadoutState != null && defenderLoadoutState.isStillInSpawn()) {
event.setCancelled(true);
return;
}
if (defenderWarzone.getReallyDeadFighters().contains(d.getName())) {
// don't re-kill a dead person
if (d.getHealth() != 0) {
d.setHealth(0);
}
return;
}
if (defenderWarzone.getWarzoneConfig().getBoolean(WarzoneConfig.DEATHMESSAGES)) {
String defenderString = Team.getTeamByPlayerName(d.getName()).getKind().getColor() + d.getName();
if (event.getDamager() instanceof TNTPrimed) {
defenderWarzone.broadcast("pvp.death.explosion", defenderString + ChatColor.WHITE);
} else {
defenderWarzone.broadcast("pvp.death.other", defenderString + ChatColor.WHITE);
}
}
WarPlayerDeathEvent event1 = new WarPlayerDeathEvent(defenderWarzone, d, null, event.getCause());
War.war.getServer().getPluginManager().callEvent(event1);
defenderWarzone.handleDeath(d);
if (!defenderWarzone.getWarzoneConfig().getBoolean(WarzoneConfig.REALDEATHS)) {
// fast respawn, don't really die
event.setCancelled(true);
return;
}
}
}
}
|
diff --git a/core/src/main/java/com/digitalpebble/storm/crawler/persistence/Status.java b/core/src/main/java/com/digitalpebble/storm/crawler/persistence/Status.java
index 3142cbc7..a318044b 100644
--- a/core/src/main/java/com/digitalpebble/storm/crawler/persistence/Status.java
+++ b/core/src/main/java/com/digitalpebble/storm/crawler/persistence/Status.java
@@ -1,34 +1,34 @@
/**
* Licensed to DigitalPebble Ltd under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* DigitalPebble 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 com.digitalpebble.storm.crawler.persistence;
public enum Status {
DISCOVERED, FETCHED, FETCH_ERROR, REDIRECTION, ERROR;
/** Maps the HTTP Code to FETCHED, FETCH_ERROR or REDIRECTION */
public static Status fromHTTPCode(int code) {
if (code == 200)
return Status.FETCHED;
// REDIRS?
- if (code >= 300 && code <= 400)
+ if (code >= 300 && code < 400)
return Status.REDIRECTION;
// error otherwise
return Status.FETCH_ERROR;
}
}
| true | true | public static Status fromHTTPCode(int code) {
if (code == 200)
return Status.FETCHED;
// REDIRS?
if (code >= 300 && code <= 400)
return Status.REDIRECTION;
// error otherwise
return Status.FETCH_ERROR;
}
| public static Status fromHTTPCode(int code) {
if (code == 200)
return Status.FETCHED;
// REDIRS?
if (code >= 300 && code < 400)
return Status.REDIRECTION;
// error otherwise
return Status.FETCH_ERROR;
}
|
diff --git a/src/Spielfeld/Spielfeld.java b/src/Spielfeld/Spielfeld.java
index dc39972..4780eeb 100644
--- a/src/Spielfeld/Spielfeld.java
+++ b/src/Spielfeld/Spielfeld.java
@@ -1,851 +1,863 @@
package Spielfeld;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Random;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import Gui.Main;
import Gui.OeffnenDialogClass;
import Objects.Bomb;
import Objects.Spieler;
/**
* Klasse zur Erstellung des Basis-Spielfelds mit den zugewiesenen Grafiken
*
* @author Gruppe37
* @version 0.9
* @param Main
* parent
*/
public class Spielfeld extends JPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* Variablen der verschiedenen Stati eines Spielfeldblocks und der Grafiken
* bei Spielende
*/
private ImageIcon solidBlock;
private ImageIcon brkbleBlock;
private ImageIcon grndBlock;
private ImageIcon player;
private ImageIcon player2;
private ImageIcon bombe;
private ImageIcon exp_h;
private ImageIcon exp_v;
private ImageIcon exp_m;
private ImageIcon playeronbomb;
private ImageIcon player2onbomb;
private ImageIcon portal;
private ImageIcon player1wins;
private ImageIcon player2wins;
private ImageIcon bothplayerdead;
/** horizontale Feldgr��e */
private int Feldgroesse_x = 100;
/** vertikale Feldgr��e */
private int Feldgroesse_y = 100;
/** Dichte der zerst�rbaren Bl�cke */
private double Blockdichte = 0.7;
/** Array in dem das Feld erstellt wird */
private final JLabel fblock[][] = new JLabel[Feldgroesse_x][Feldgroesse_y];
/** Definition der einzelnen Spielfeldelemente */
private final int blockStatus[][] = new int[Feldgroesse_x][Feldgroesse_y];
/** horizontale Koordinate des Spielfelds */
private int m = 0;
/** vertikale Koordinate des Spielfelds */
private int n = 0;
/** horizontale Koordinate von Spieler 1 */
private final int x[] = { 1, 1 };
/** vertikale Koordinate von Spieler 1 */
private final int y[] = { 1, 1 };
private int bombsLeftP1 = 2;
private int bombsLeftP2 = 2;
/** horizontale Koordinate der Bombe von Spieler 1 */
private final int a[][] = new int[2][3];
/** vertikale Koo rdinate der Bombe von Spieler 1 */
private final int b[][] = new int[2][3];
// Radien der beiden bomben
/** Radius der Bombe von Spieler 1 */
private final int radius1 = 2;
/** Radius der Bombe von Spieler 2 */
private final int radius2 = 2;
/** Radius von Spieler 1 und 2 f�r die Explosion */
private final int radius[] = new int[2];
/** freies Bodenfeld */
private final int ground = 13;
/** unzerst�rbarer Block */
private final int solid = 1;
/** zerst�rbarer Block */
private final int breakblock = 2;
/** Bombe auf einem freien Feld */
private final int bombesetzen = 3;
/** Spieler 1 auf seiner Bombe */
private final int spieler_bombe[] = { 4, 12 };
/** Mittelpunkt der Explosion */
private final int explosion_mitte = 5;
/** horizontale Komponente der Explosion */
private final int explosion_horizontal = 6;
/** vertikale Komponente der Explosion */
private final int explosion_vertikal = 7;
/** Spielfigur von Spieler 1 */
private final int spieler[] = { 8, 11 };
/** Ausgang unter einem zerst�rbaren Block */
private final int versteckterausgang = 9;
/** offengelegter Ausgang */
private final int ausgang = 10;
/*
* F�higkeit Bomben zu legen wird erm�glicht
*/
/** F�higkeit des 1. Spielers eine Bombe zu legen */
public static boolean nextbomb[] = { true, true };
/**
* Festlegung, dass die Spielfiguren am Leben sind
*/
boolean playeralive[] = { true, true };
/** Gibt an, ob ein Portal vorhanden ist */
private static boolean Portal_vorhanden = false;
private final Main window;
/** Spielfeld wird im Fenster Main angezeigt */
public Spielfeld(Main parent) {
loadContentImages();
// Fenstereinstellungen
window = parent;
}
/****************************************
* Laden der einzelnen Icons der Bl�cke *
****************************************/
private void loadContentImages() {
solidBlock = new ImageIcon("Images/HardBlock.png");
brkbleBlock = new ImageIcon("Images/breakstone.jpg");
grndBlock = new ImageIcon("Images/ground.jpg");
player = new ImageIcon("Images/Player.png");
player2 = new ImageIcon("Images/Player2.png");
bombe = new ImageIcon("Images/bomb.jpg");
exp_h = new ImageIcon("Images/exp_h.jpg");
exp_v = new ImageIcon("Images/exp_v.jpg");
exp_m = new ImageIcon("Images/exp_m.jpg");
playeronbomb = new ImageIcon("Images/Playeronbomb.png");
player2onbomb = new ImageIcon("Images/Player2onbomb.png");
portal = new ImageIcon("Images/portal.gif");
player1wins = new ImageIcon("Images/Player1Wins.jpg");
player2wins = new ImageIcon("Images/Player2Wins.jpg");
bothplayerdead = new ImageIcon("Images/BothPlayerDead.jpg");
}
/*******************************
* Initialisieren der XML-Datei*
******************************/
public static void XMLInit() throws SAXException, IOException,
ParserConfigurationException, NullPointerException,
FileNotFoundException {
OeffnenDialogClass oeffne = new OeffnenDialogClass(null);
File field = new File(oeffne.getLevelName());
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory
.newDocumentBuilder();
Document dok = documentBuilder.parse(field);
XMLReader.handleChannelTag(dok);
}
public void XMLFeld() {
try {
XMLInit();
Feldgroesse_x = XMLReader.breite_max;
Feldgroesse_y = XMLReader.hoehe_max;
window.setSize(((Feldgroesse_x * 30) + 10),
((Feldgroesse_y * 30) + 50));
window.gamepanel.setBounds(0, 0, Feldgroesse_x * 30,
Feldgroesse_y * 30);
for (int breite = 0; breite < Feldgroesse_x; breite++) {
for (int hoehe = 0; hoehe < Feldgroesse_y; hoehe++) {
if (XMLReader.xmlStatus[breite][hoehe] == 0) {
JOptionPane
.showMessageDialog(
null,
"Spielfeld entspricht nicht dem vorgegeben Format. Bitte Datei �berarbeiten oder anderes Spielfeld ausw�hlen");
XMLInit();
}
if (XMLReader.xmlStatus[breite][hoehe] == XMLReader.solid) {
blockStatus[breite][hoehe] = solid;
} else if (XMLReader.xmlStatus[breite][hoehe] == XMLReader.breakblock) {
blockStatus[breite][hoehe] = breakblock;
} else if (XMLReader.xmlStatus[breite][hoehe] == XMLReader.ground) {
blockStatus[breite][hoehe] = ground;
} else if (XMLReader.xmlStatus[breite][hoehe] == XMLReader.spieler) {
blockStatus[breite][hoehe] = spieler[0];
x[0] = breite;
y[0] = hoehe;
} else if (XMLReader.xmlStatus[breite][hoehe] == XMLReader.spieler2) {
blockStatus[breite][hoehe] = spieler[1];
x[1] = breite;
y[1] = hoehe;
}
}
}
/*******************************************************
* Sicherstellung, dass die Startpositionen frei sind. *
*******************************************************/
window.setSize(((Feldgroesse_x * 30) + 10),
((Feldgroesse_y * 30) + 50));
window.gamepanel.setBounds(0, 0, Feldgroesse_x * 30,
Feldgroesse_y * 30);
// Spieler setzen und Positions-Reset bei Neustart
zeichnen();
XMLReader.Reset();
playeralive[0] = true;
playeralive[1] = true;
radius[0] = radius1;
radius[1] = radius2;
} catch (SAXException e) {
} catch (IOException e) {
} catch (ParserConfigurationException e) {
} catch (NullPointerException e) {
}
}
/*
* Standardspielfeld mit variabler Groesse und zuf�lligem aufbau aus
* zerst�rbare und freien Bl�cken in Array schreiben
*/
public void standardfeld() {
/** horizontale Feldgr��e */
Feldgroesse_x = Gui.Einstellungen.breite;
/** vertikale Feldgr��e */
Feldgroesse_y = Gui.Einstellungen.hoehe;
/** Dichte der zerst�rbaren Bl�cke */
Blockdichte = (Gui.Einstellungen.dichte * 0.01);
window.setSize(((Feldgroesse_x * 30) + 10), ((Feldgroesse_y * 30) + 50));
window.gamepanel
.setBounds(0, 0, Feldgroesse_x * 30, Feldgroesse_y * 30);
for (n = 0; n < Feldgroesse_y; n++) {
for (m = 0; m < Feldgroesse_x; m++) {
if (m % 2 != 1 && n % 2 != 1 || m == 0 || n == 0
|| n == Feldgroesse_y - 1 || m == Feldgroesse_x - 1) {
blockStatus[m][n] = solid;
}
else {
if ((1 - Math.random()) >= Blockdichte) {
blockStatus[m][n] = ground;
} else {
blockStatus[m][n] = breakblock;
}
}
}
}
/*******************************************************
* Sicherstellung, dass die Startpositionen frei sind. *
*******************************************************/
// Oben links
blockStatus[1][1] = ground;
blockStatus[1][2] = ground;
blockStatus[2][1] = ground;
// Oben rechts
blockStatus[Feldgroesse_x - 2][1] = ground;
blockStatus[Feldgroesse_x - 2][2] = ground;
blockStatus[Feldgroesse_x - 3][1] = ground;
// Unten links
blockStatus[1][Feldgroesse_y - 2] = ground;
blockStatus[1][Feldgroesse_y - 3] = ground;
blockStatus[2][Feldgroesse_y - 2] = ground;
// Unten rechts
blockStatus[Feldgroesse_x - 2][Feldgroesse_y - 2] = ground;
blockStatus[Feldgroesse_x - 2][Feldgroesse_y - 3] = ground;
blockStatus[Feldgroesse_x - 3][Feldgroesse_y - 2] = ground;
// Spieler setzen und Positions-Reset bei Neustart
/** horizontale Position von Spieler 1 */
x[0] = 1;
/** vertikale Position von Spieler 1 */
y[0] = 1;
/** horizontale Position von Spieler 2 */
x[1] = (Feldgroesse_x - 2);
/** vertikale Position von Spieler 2 */
y[1] = (Feldgroesse_y - 2);
blockStatus[x[0]][y[0]] = spieler[0];
blockStatus[x[1]][y[1]] = spieler[1];
playeralive[0] = true;
playeralive[1] = true;
radius[0] = radius1;
radius[1] = radius2;
Portal_vorhanden = false;
}
/***********************************************************************
* Auslesen der Blockstati und zuordnung der passenden Icons zu diesen *
***********************************************************************/
public void zeichnen() {
window.gamepanel.removeAll();
for (m = 0; m < Feldgroesse_x; m++) {
for (n = 0; n < Feldgroesse_y; n++) {
if (blockStatus[m][n] == ground) {
fblock[m][n] = new JLabel(grndBlock);
window.gamepanel.add(fblock[m][n]);
fblock[m][n].setBounds(m * 30, n * 30, 30, 30);
}
else if (blockStatus[m][n] == solid) {
fblock[m][n] = new JLabel(solidBlock);
window.gamepanel.add(fblock[m][n]);
fblock[m][n].setBounds(m * 30, n * 30, 30, 30);
}
else if (blockStatus[m][n] == breakblock) {
fblock[m][n] = new JLabel(brkbleBlock);
window.gamepanel.add(fblock[m][n]);
fblock[m][n].setBounds(m * 30, n * 30, 30, 30);
}
/*
* Bombe und Explosion
*/
else if (blockStatus[m][n] == bombesetzen) {
fblock[m][n] = new JLabel(bombe);
window.gamepanel.add(fblock[m][n]);
fblock[m][n].setBounds(m * 30, n * 30, 30, 30);
} else if (blockStatus[m][n] == spieler_bombe[0]) {
fblock[m][n] = new JLabel(playeronbomb);
window.gamepanel.add(fblock[m][n]);
fblock[m][n].setBounds(m * 30, n * 30, 30, 30);
} else if (blockStatus[m][n] == spieler_bombe[1]) {
fblock[m][n] = new JLabel(player2onbomb);
window.gamepanel.add(fblock[m][n]);
fblock[m][n].setBounds(m * 30, n * 30, 30, 30);
} else if (blockStatus[m][n] == explosion_mitte) {
fblock[m][n] = new JLabel(exp_m);
window.gamepanel.add(fblock[m][n]);
fblock[m][n].setBounds(m * 30, n * 30, 30, 30);
} else if (blockStatus[m][n] == explosion_horizontal) {
fblock[m][n] = new JLabel(exp_h);
window.gamepanel.add(fblock[m][n]);
fblock[m][n].setBounds(m * 30, n * 30, 30, 30);
} else if (blockStatus[m][n] == explosion_vertikal) {
fblock[m][n] = new JLabel(exp_v);
window.gamepanel.add(fblock[m][n]);
fblock[m][n].setBounds(m * 30, n * 30, 30, 30);
}
/*
* Spieler
*/
else if (blockStatus[m][n] == spieler[0]) {
fblock[m][n] = new JLabel(player);
window.gamepanel.add(fblock[m][n]);
fblock[m][n].setBounds(m * 30, n * 30, 30, 30);
}
/*
* Spieler2
*/
else if (blockStatus[m][n] == spieler[1]) {
fblock[m][n] = new JLabel(player2);
window.gamepanel.add(fblock[m][n]);
fblock[m][n].setBounds(m * 30, n * 30, 30, 30);
}
/*
* Ausgang
*/
else if (blockStatus[m][n] == ausgang) {
fblock[m][n] = new JLabel(portal);
window.gamepanel.add(fblock[m][n]);
fblock[m][n].setBounds(m * 30, n * 30, 30, 30);
} else if (blockStatus[m][n] == versteckterausgang) {
fblock[m][n] = new JLabel(brkbleBlock);
window.gamepanel.add(fblock[m][n]);
fblock[m][n].setBounds(m * 30, n * 30, 30, 30);
}
}
}
}
/*****************
* Bombe *
*****************/
public void explozeichnen(int playerNR, int bombsLeft) {
int k = a[playerNR][bombsLeft];
int l = b[playerNR][bombsLeft];
System.out.println(k + "+" + l);
for (int z1 = 1; z1 <= radius[playerNR]; z1++) {
if (blockStatus[k][l] == spieler_bombe[playerNR]) {
playeralive[playerNR] = false;
}
if (k + z1 < Feldgroesse_x) {
if (blockStatus[k + z1][l] == solid) {
break;
} else {
- if (blockStatus[k + z1][l] == spieler[playerNR]) {
- playeralive[playerNR] = false;
+ if (blockStatus[k + z1][l] == spieler[0]) {
+ playeralive[0] = false;
+ }
+ if (blockStatus[k + z1][l] == spieler[1]) {
+ playeralive[1] = false;
}
}
}
}
for (int z1 = 1; z1 <= radius[playerNR]; z1++) {
if (k - z1 > 0) {
if (blockStatus[k - z1][l] == solid) {
break;
} else {
- if (blockStatus[k - z1][l] == spieler[playerNR]) {
- playeralive[playerNR] = false;
+ if (blockStatus[k - z1][l] == spieler[0]) {
+ playeralive[0] = false;
+ }
+ if (blockStatus[k - z1][l] == spieler[1]) {
+ playeralive[1] = false;
}
}
}
}
for (int z1 = 1; z1 <= radius[playerNR]; z1++) {
if (l + z1 < Feldgroesse_y) {
if (blockStatus[k][l + z1] == solid) {
break;
} else {
- if (blockStatus[k][l + z1] == spieler[playerNR]) {
- playeralive[playerNR] = false;
+ if (blockStatus[k][l + z1] == spieler[0]) {
+ playeralive[0] = false;
+ }
+ if (blockStatus[k][l + z1] == spieler[1]) {
+ playeralive[1] = false;
}
}
}
}
for (int z1 = 1; z1 <= radius[playerNR]; z1++) {
if (l - z1 > 0) {
if (blockStatus[k][l - z1] == solid) {
break;
} else {
- if (blockStatus[k][l - z1] == spieler[playerNR]) {
- playeralive[playerNR] = false;
+ if (blockStatus[k][l - z1] == spieler[0]) {
+ playeralive[0] = false;
+ }
+ if (blockStatus[k][l - z1] == spieler[1]) {
+ playeralive[1] = false;
}
}
}
}
if (playeralive[0] == false || playeralive[1] == false) {
if (playeralive[0] == false && playeralive[1] == false) {
game_over.start();
} else {
zufallsPortal();
}
}
/**********************************************************
* ersetzen der break- und spieler blocks durch explosion *
**********************************************************/
for (int z1 = 1; z1 <= radius[playerNR]; z1++) {
if (k + z1 < Feldgroesse_x) {
if (blockStatus[k + z1][l] == solid) {
break;
} else {
if (blockStatus[k + z1][l] == spieler[1]
|| blockStatus[k + z1][l] == spieler[0]
|| blockStatus[k + z1][l] == breakblock
|| blockStatus[k + z1][l] == ground) {
blockStatus[k + z1][l] = explosion_horizontal;
}
if (blockStatus[k + z1][l] == bombesetzen
|| blockStatus[k + z1][l] == spieler_bombe[1]
|| blockStatus[k + z1][l] == spieler_bombe[0]) {
// explosion2.stop();
// explosion2_zeichnen.start();
}
if (blockStatus[k + z1][l] == versteckterausgang) {
blockStatus[k + z1][l] = ausgang;
}
}
}
}
for (int z1 = 1; z1 <= radius[playerNR]; z1++) {
if (k - z1 > 0) {
if (blockStatus[k - z1][l] == solid) {
break;
} else {
if (blockStatus[k - z1][l] == spieler[1]
|| blockStatus[k - z1][l] == spieler[0]
|| blockStatus[k - z1][l] == breakblock
|| blockStatus[k - z1][l] == ground) {
blockStatus[k - z1][l] = explosion_horizontal;
}
if (blockStatus[k - z1][l] == bombesetzen
|| blockStatus[k - z1][l] == spieler_bombe[1]
|| blockStatus[k - z1][l] == spieler_bombe[0]) {
// explosion2.stop();
// explosion2_zeichnen.start();
}
if (blockStatus[k - z1][l] == versteckterausgang) {
blockStatus[k - z1][l] = ausgang;
}
}
}
}
for (int z1 = 1; z1 <= radius[playerNR]; z1++) {
if (l - z1 > 0) {
if (blockStatus[k][l - z1] == solid) {
break;
} else {
if (blockStatus[k][l - z1] == spieler[1]
|| blockStatus[k][l - z1] == spieler[0]
|| blockStatus[k][l - z1] == breakblock
|| blockStatus[k][l - z1] == ground) {
blockStatus[k][l - z1] = explosion_vertikal;
}
if (blockStatus[k][l - z1] == bombesetzen
|| blockStatus[k][l - z1] == spieler_bombe[1]
|| blockStatus[k][l - z1] == spieler_bombe[0]) {
// explosion2.stop();
// explosion2_zeichnen.start();
}
if (blockStatus[k][l - z1] == versteckterausgang) {
blockStatus[k][l - z1] = ausgang;
}
}
}
}
for (int z1 = 1; z1 <= radius[playerNR]; z1++) {
if (l + z1 < Feldgroesse_y) {
if (blockStatus[k][l + z1] == solid) {
break;
} else {
if (blockStatus[k][l + z1] == spieler[1]
|| blockStatus[k][l + z1] == spieler[0]
|| blockStatus[k][l + z1] == breakblock
|| blockStatus[k][l + z1] == ground) {
blockStatus[k][l + z1] = explosion_vertikal;
}
if (blockStatus[k][l + z1] == bombesetzen
|| blockStatus[k][l + z1] == spieler_bombe[1]
|| blockStatus[k][l + z1] == spieler_bombe[0]) {
// explosion.stop();
// explozeichnen(playerNR, bombsLeft);
}
if (blockStatus[k][l + z1] == versteckterausgang) {
blockStatus[k][l + z1] = ausgang;
}
}
}
}
blockStatus[k][l] = explosion_mitte;
zeichnen();
Sound.soundeffekt("Audio/boom.au");
}
public void exploende(int playerNR, int bombs) {
int k = a[playerNR][bombs];
int l = b[playerNR][bombs];
for (int z1 = 1; z1 <= radius[playerNR]; z1++) {
if (k + z1 < Feldgroesse_x) {
if (blockStatus[k + (z1 - 1)][l] != solid) {
if (blockStatus[k + z1][l] == explosion_horizontal) {
blockStatus[k + z1][l] = ground;
}
}
}
if (k - z1 > 0) {
if (blockStatus[k - (z1 - 1)][l] != solid) {
if (blockStatus[k - z1][l] == explosion_horizontal) {
blockStatus[k - z1][l] = ground;
}
}
}
if (l - z1 > 0) {
if (blockStatus[k][l - (z1 - 1)] != solid) {
if (blockStatus[k][l - z1] == explosion_vertikal) {
blockStatus[k][l - z1] = ground;
}
}
}
if (l + z1 < Feldgroesse_y) {
if (blockStatus[k][l + (z1 - 1)] != solid) {
if (blockStatus[k][l + z1] == explosion_vertikal) {
blockStatus[k][l + z1] = ground;
}
}
}
}
blockStatus[k][l] = ground;
zeichnen();
nextbomb[0] = true;
if (playerNR == 0)
bombsLeftP1++;
if (playerNR == 1)
bombsLeftP2++;
}
/*********************************************************************
* Timer f�r eine kurze verz�gerung vor neustart bei sieg/niederlage *
*********************************************************************/
// Einblenden der Sieg/ Niederlage Bilder
javax.swing.Timer game_over = new javax.swing.Timer(600,
new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (playeralive[0] == true && playeralive[1] == false) {
window.setSize(320, 230);
JLabel endscreen;
window.gamepanel.removeAll();
endscreen = new JLabel(player1wins);
endscreen.setBounds(0, 0, 320, 180);
window.gamepanel.add(endscreen);
Sound.stoppen();
Sound.soundeffekt("Audio/player1wins.au");
}
if (playeralive[0] == false && playeralive[1] == true) {
window.setSize(330, 230);
JLabel endscreen;
window.gamepanel.removeAll();
endscreen = new JLabel(player2wins);
endscreen.setBounds(0, 0, 320, 180);
window.gamepanel.add(endscreen);
Sound.stoppen();
Sound.soundeffekt("Audio/player2wins.au");
}
if (playeralive[0] == false && playeralive[1] == false) {
window.setSize(330, 230);
JLabel endscreen;
window.gamepanel.removeAll();
endscreen = new JLabel(bothplayerdead);
endscreen.setBounds(0, 0, 320, 180);
window.gamepanel.add(endscreen);
Sound.stoppen();
Sound.soundeffekt("Audio/bothplayersdead2.au");
}
x[0] = 1;
y[0] = 1;
x[1] = (Feldgroesse_x - 2);
y[1] = (Feldgroesse_y - 2);
blockStatus[x[0]][y[0]] = spieler[0];
blockStatus[x[1]][y[1]] = spieler[1];
playeralive[0] = true;
playeralive[1] = true;
game_over_intern.start();
game_over.stop();
}
});
// Neustart
javax.swing.Timer game_over_intern = new javax.swing.Timer(3800,
new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Sound.loopen();
standardfeld();
zeichnen();
game_over_intern.stop();
}
});
/*****************************************************************
* erstellt ein Portal unter einem zuf�lligen zerst�rbaren Block *
*****************************************************************/
private void zufallsPortal() {
if (Portal_vorhanden == false) {
Random r = new Random();
int random_x = r.nextInt(Feldgroesse_x);
int random_y = r.nextInt(Feldgroesse_y);
if (blockStatus[random_x][random_y] == breakblock) {
blockStatus[random_x][random_y] = versteckterausgang;
Portal_vorhanden = true;
} else if (blockStatus[random_x][random_y] == ground) {
blockStatus[random_x][random_y] = ausgang;
Portal_vorhanden = true;
} else {
zufallsPortal();
}
}
}
/***********************************
* Methode fuer die erste Steurung *
**********************************/
public void control(int playerNR) {
boolean moveRight = Spieler.moveRight;
/** Bewegung nach links */
boolean moveLeft = Spieler.moveLeft;
/** Bewegung nach unten */
boolean moveDown = Spieler.moveDown;
/** Bewegung nach oben */
boolean moveUp = Spieler.moveUp;
/** Bombe legen */
boolean bomb = Spieler.bomb;
if (moveRight == true
&& playeralive[playerNR] == true
&& (blockStatus[x[playerNR] + 1][y[playerNR]] == ground || blockStatus[x[playerNR] + 1][y[playerNR]] == ausgang)) {
if (blockStatus[x[playerNR] + 1][y[playerNR]] == ausgang) {
blockStatus[x[playerNR]][y[playerNR]] = ground;
game_over.start();
} else if (blockStatus[x[playerNR]][y[playerNR]] == spieler_bombe[playerNR]) {
blockStatus[x[playerNR]][y[playerNR]] = bombesetzen;
} else {
blockStatus[x[playerNR]][y[playerNR]] = ground;
}
x[playerNR]++;
blockStatus[x[playerNR]][y[playerNR]] = spieler[playerNR];
zeichnen();
}
if (moveLeft == true
&& playeralive[playerNR] == true
&& (blockStatus[x[playerNR] - 1][y[playerNR]] == ground || blockStatus[x[playerNR] - 1][y[playerNR]] == ausgang)) {
if (blockStatus[x[playerNR] - 1][y[playerNR]] == ausgang) {
blockStatus[x[playerNR]][y[playerNR]] = ground;
game_over.start();
} else if (blockStatus[x[playerNR]][y[playerNR]] == spieler_bombe[playerNR]) {
blockStatus[x[playerNR]][y[playerNR]] = bombesetzen;
} else {
blockStatus[x[playerNR]][y[playerNR]] = ground;
}
x[playerNR]--;
blockStatus[x[playerNR]][y[playerNR]] = spieler[playerNR];
zeichnen();
}
if (moveUp == true
&& playeralive[playerNR] == true
&& (blockStatus[x[playerNR]][y[playerNR] - 1] == ground || blockStatus[x[playerNR]][y[playerNR] - 1] == ausgang)) {
if (blockStatus[x[playerNR]][y[playerNR] - 1] == ausgang) {
blockStatus[x[playerNR]][y[playerNR]] = ground;
game_over.start();
} else if (blockStatus[x[playerNR]][y[playerNR]] == spieler_bombe[playerNR]) {
blockStatus[x[playerNR]][y[playerNR]] = bombesetzen;
} else {
blockStatus[x[playerNR]][y[playerNR]] = ground;
}
y[playerNR]--;
blockStatus[x[playerNR]][y[playerNR]] = spieler[playerNR];
zeichnen();
}
if (moveDown == true
&& playeralive[playerNR] == true
&& (blockStatus[x[playerNR]][y[playerNR] + 1] == ground || blockStatus[x[playerNR]][y[playerNR] + 1] == ausgang)) {
if (blockStatus[x[playerNR]][y[playerNR] + 1] == ausgang) {
blockStatus[x[playerNR]][y[playerNR]] = ground;
game_over.start();
}
if (blockStatus[x[playerNR]][y[playerNR]] == spieler_bombe[playerNR]) {
blockStatus[x[playerNR]][y[playerNR]] = bombesetzen;
} else {
blockStatus[x[playerNR]][y[playerNR]] = ground;
}
y[playerNR]++;
blockStatus[x[playerNR]][y[playerNR]] = spieler[playerNR];
zeichnen();
}
if (bomb == true && playeralive[playerNR] == true) {
if (playerNR == 0 && bombsLeftP1 >= 0) {
blockStatus[x[0]][y[0]] = spieler_bombe[0];
a[0][bombsLeftP1] = x[0];
b[0][bombsLeftP1] = y[0];
Bomb bombe = new Bomb(this, 0, bombsLeftP1);
zeichnen();
bombe.explosion.start();
bombsLeftP1--;
}
else if (playerNR == 1 && bombsLeftP2 >= 0) {
blockStatus[x[1]][y[1]] = spieler_bombe[1];
a[1][bombsLeftP2] = x[1];
b[1][bombsLeftP2] = y[1];
Bomb bombe = new Bomb(this, 1, bombsLeftP2);
zeichnen();
bombe.explosion.start();
bombsLeftP2--;
}
}
}
// Getter - Setter
public int getFeldgroesse_x() {
return Feldgroesse_x;
}
public int getFeldgroesse_y() {
return Feldgroesse_y;
}
public int[][] getBlockStatus() {
return blockStatus;
}
}
| false | true | public void explozeichnen(int playerNR, int bombsLeft) {
int k = a[playerNR][bombsLeft];
int l = b[playerNR][bombsLeft];
System.out.println(k + "+" + l);
for (int z1 = 1; z1 <= radius[playerNR]; z1++) {
if (blockStatus[k][l] == spieler_bombe[playerNR]) {
playeralive[playerNR] = false;
}
if (k + z1 < Feldgroesse_x) {
if (blockStatus[k + z1][l] == solid) {
break;
} else {
if (blockStatus[k + z1][l] == spieler[playerNR]) {
playeralive[playerNR] = false;
}
}
}
}
for (int z1 = 1; z1 <= radius[playerNR]; z1++) {
if (k - z1 > 0) {
if (blockStatus[k - z1][l] == solid) {
break;
} else {
if (blockStatus[k - z1][l] == spieler[playerNR]) {
playeralive[playerNR] = false;
}
}
}
}
for (int z1 = 1; z1 <= radius[playerNR]; z1++) {
if (l + z1 < Feldgroesse_y) {
if (blockStatus[k][l + z1] == solid) {
break;
} else {
if (blockStatus[k][l + z1] == spieler[playerNR]) {
playeralive[playerNR] = false;
}
}
}
}
for (int z1 = 1; z1 <= radius[playerNR]; z1++) {
if (l - z1 > 0) {
if (blockStatus[k][l - z1] == solid) {
break;
} else {
if (blockStatus[k][l - z1] == spieler[playerNR]) {
playeralive[playerNR] = false;
}
}
}
}
if (playeralive[0] == false || playeralive[1] == false) {
if (playeralive[0] == false && playeralive[1] == false) {
game_over.start();
} else {
zufallsPortal();
}
}
/**********************************************************
* ersetzen der break- und spieler blocks durch explosion *
**********************************************************/
for (int z1 = 1; z1 <= radius[playerNR]; z1++) {
if (k + z1 < Feldgroesse_x) {
if (blockStatus[k + z1][l] == solid) {
break;
} else {
if (blockStatus[k + z1][l] == spieler[1]
|| blockStatus[k + z1][l] == spieler[0]
|| blockStatus[k + z1][l] == breakblock
|| blockStatus[k + z1][l] == ground) {
blockStatus[k + z1][l] = explosion_horizontal;
}
if (blockStatus[k + z1][l] == bombesetzen
|| blockStatus[k + z1][l] == spieler_bombe[1]
|| blockStatus[k + z1][l] == spieler_bombe[0]) {
// explosion2.stop();
// explosion2_zeichnen.start();
}
if (blockStatus[k + z1][l] == versteckterausgang) {
blockStatus[k + z1][l] = ausgang;
}
}
}
}
for (int z1 = 1; z1 <= radius[playerNR]; z1++) {
if (k - z1 > 0) {
if (blockStatus[k - z1][l] == solid) {
break;
} else {
if (blockStatus[k - z1][l] == spieler[1]
|| blockStatus[k - z1][l] == spieler[0]
|| blockStatus[k - z1][l] == breakblock
|| blockStatus[k - z1][l] == ground) {
blockStatus[k - z1][l] = explosion_horizontal;
}
if (blockStatus[k - z1][l] == bombesetzen
|| blockStatus[k - z1][l] == spieler_bombe[1]
|| blockStatus[k - z1][l] == spieler_bombe[0]) {
// explosion2.stop();
// explosion2_zeichnen.start();
}
if (blockStatus[k - z1][l] == versteckterausgang) {
blockStatus[k - z1][l] = ausgang;
}
}
}
}
for (int z1 = 1; z1 <= radius[playerNR]; z1++) {
if (l - z1 > 0) {
if (blockStatus[k][l - z1] == solid) {
break;
} else {
if (blockStatus[k][l - z1] == spieler[1]
|| blockStatus[k][l - z1] == spieler[0]
|| blockStatus[k][l - z1] == breakblock
|| blockStatus[k][l - z1] == ground) {
blockStatus[k][l - z1] = explosion_vertikal;
}
if (blockStatus[k][l - z1] == bombesetzen
|| blockStatus[k][l - z1] == spieler_bombe[1]
|| blockStatus[k][l - z1] == spieler_bombe[0]) {
// explosion2.stop();
// explosion2_zeichnen.start();
}
if (blockStatus[k][l - z1] == versteckterausgang) {
blockStatus[k][l - z1] = ausgang;
}
}
}
}
for (int z1 = 1; z1 <= radius[playerNR]; z1++) {
if (l + z1 < Feldgroesse_y) {
if (blockStatus[k][l + z1] == solid) {
break;
} else {
if (blockStatus[k][l + z1] == spieler[1]
|| blockStatus[k][l + z1] == spieler[0]
|| blockStatus[k][l + z1] == breakblock
|| blockStatus[k][l + z1] == ground) {
blockStatus[k][l + z1] = explosion_vertikal;
}
if (blockStatus[k][l + z1] == bombesetzen
|| blockStatus[k][l + z1] == spieler_bombe[1]
|| blockStatus[k][l + z1] == spieler_bombe[0]) {
// explosion.stop();
// explozeichnen(playerNR, bombsLeft);
}
if (blockStatus[k][l + z1] == versteckterausgang) {
blockStatus[k][l + z1] = ausgang;
}
}
}
}
blockStatus[k][l] = explosion_mitte;
zeichnen();
Sound.soundeffekt("Audio/boom.au");
}
| public void explozeichnen(int playerNR, int bombsLeft) {
int k = a[playerNR][bombsLeft];
int l = b[playerNR][bombsLeft];
System.out.println(k + "+" + l);
for (int z1 = 1; z1 <= radius[playerNR]; z1++) {
if (blockStatus[k][l] == spieler_bombe[playerNR]) {
playeralive[playerNR] = false;
}
if (k + z1 < Feldgroesse_x) {
if (blockStatus[k + z1][l] == solid) {
break;
} else {
if (blockStatus[k + z1][l] == spieler[0]) {
playeralive[0] = false;
}
if (blockStatus[k + z1][l] == spieler[1]) {
playeralive[1] = false;
}
}
}
}
for (int z1 = 1; z1 <= radius[playerNR]; z1++) {
if (k - z1 > 0) {
if (blockStatus[k - z1][l] == solid) {
break;
} else {
if (blockStatus[k - z1][l] == spieler[0]) {
playeralive[0] = false;
}
if (blockStatus[k - z1][l] == spieler[1]) {
playeralive[1] = false;
}
}
}
}
for (int z1 = 1; z1 <= radius[playerNR]; z1++) {
if (l + z1 < Feldgroesse_y) {
if (blockStatus[k][l + z1] == solid) {
break;
} else {
if (blockStatus[k][l + z1] == spieler[0]) {
playeralive[0] = false;
}
if (blockStatus[k][l + z1] == spieler[1]) {
playeralive[1] = false;
}
}
}
}
for (int z1 = 1; z1 <= radius[playerNR]; z1++) {
if (l - z1 > 0) {
if (blockStatus[k][l - z1] == solid) {
break;
} else {
if (blockStatus[k][l - z1] == spieler[0]) {
playeralive[0] = false;
}
if (blockStatus[k][l - z1] == spieler[1]) {
playeralive[1] = false;
}
}
}
}
if (playeralive[0] == false || playeralive[1] == false) {
if (playeralive[0] == false && playeralive[1] == false) {
game_over.start();
} else {
zufallsPortal();
}
}
/**********************************************************
* ersetzen der break- und spieler blocks durch explosion *
**********************************************************/
for (int z1 = 1; z1 <= radius[playerNR]; z1++) {
if (k + z1 < Feldgroesse_x) {
if (blockStatus[k + z1][l] == solid) {
break;
} else {
if (blockStatus[k + z1][l] == spieler[1]
|| blockStatus[k + z1][l] == spieler[0]
|| blockStatus[k + z1][l] == breakblock
|| blockStatus[k + z1][l] == ground) {
blockStatus[k + z1][l] = explosion_horizontal;
}
if (blockStatus[k + z1][l] == bombesetzen
|| blockStatus[k + z1][l] == spieler_bombe[1]
|| blockStatus[k + z1][l] == spieler_bombe[0]) {
// explosion2.stop();
// explosion2_zeichnen.start();
}
if (blockStatus[k + z1][l] == versteckterausgang) {
blockStatus[k + z1][l] = ausgang;
}
}
}
}
for (int z1 = 1; z1 <= radius[playerNR]; z1++) {
if (k - z1 > 0) {
if (blockStatus[k - z1][l] == solid) {
break;
} else {
if (blockStatus[k - z1][l] == spieler[1]
|| blockStatus[k - z1][l] == spieler[0]
|| blockStatus[k - z1][l] == breakblock
|| blockStatus[k - z1][l] == ground) {
blockStatus[k - z1][l] = explosion_horizontal;
}
if (blockStatus[k - z1][l] == bombesetzen
|| blockStatus[k - z1][l] == spieler_bombe[1]
|| blockStatus[k - z1][l] == spieler_bombe[0]) {
// explosion2.stop();
// explosion2_zeichnen.start();
}
if (blockStatus[k - z1][l] == versteckterausgang) {
blockStatus[k - z1][l] = ausgang;
}
}
}
}
for (int z1 = 1; z1 <= radius[playerNR]; z1++) {
if (l - z1 > 0) {
if (blockStatus[k][l - z1] == solid) {
break;
} else {
if (blockStatus[k][l - z1] == spieler[1]
|| blockStatus[k][l - z1] == spieler[0]
|| blockStatus[k][l - z1] == breakblock
|| blockStatus[k][l - z1] == ground) {
blockStatus[k][l - z1] = explosion_vertikal;
}
if (blockStatus[k][l - z1] == bombesetzen
|| blockStatus[k][l - z1] == spieler_bombe[1]
|| blockStatus[k][l - z1] == spieler_bombe[0]) {
// explosion2.stop();
// explosion2_zeichnen.start();
}
if (blockStatus[k][l - z1] == versteckterausgang) {
blockStatus[k][l - z1] = ausgang;
}
}
}
}
for (int z1 = 1; z1 <= radius[playerNR]; z1++) {
if (l + z1 < Feldgroesse_y) {
if (blockStatus[k][l + z1] == solid) {
break;
} else {
if (blockStatus[k][l + z1] == spieler[1]
|| blockStatus[k][l + z1] == spieler[0]
|| blockStatus[k][l + z1] == breakblock
|| blockStatus[k][l + z1] == ground) {
blockStatus[k][l + z1] = explosion_vertikal;
}
if (blockStatus[k][l + z1] == bombesetzen
|| blockStatus[k][l + z1] == spieler_bombe[1]
|| blockStatus[k][l + z1] == spieler_bombe[0]) {
// explosion.stop();
// explozeichnen(playerNR, bombsLeft);
}
if (blockStatus[k][l + z1] == versteckterausgang) {
blockStatus[k][l + z1] = ausgang;
}
}
}
}
blockStatus[k][l] = explosion_mitte;
zeichnen();
Sound.soundeffekt("Audio/boom.au");
}
|
diff --git a/src/com/jgaap/ui/JGAAP_UI_MainForm.java b/src/com/jgaap/ui/JGAAP_UI_MainForm.java
index baac2b4..23c91ce 100644
--- a/src/com/jgaap/ui/JGAAP_UI_MainForm.java
+++ b/src/com/jgaap/ui/JGAAP_UI_MainForm.java
@@ -1,3007 +1,3007 @@
// Copyright (c) 2009, 2011 by Patrick Juola. All rights reserved. All unauthorized use prohibited.
package com.jgaap.ui;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* JGAAP_UI_MainForm.java
*
* Created on Nov 2, 2010, 1:14:56 PM
*/
/**
*
* @author Patrick Brennan
*/
//Package Imports
import java.util.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import javax.swing.*;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeSelectionModel;
import javax.swing.tree.TreePath;
import javax.swing.table.DefaultTableModel;
//import java.awt.event.*;
import com.jgaap.generics.*;
import com.jgaap.jgaapConstants;
import com.jgaap.backend.API;
import com.jgaap.backend.CSVIO;
import java.awt.Color;
import java.io.IOException;
public class JGAAP_UI_MainForm extends javax.swing.JFrame {
private static final long serialVersionUID = 1L;
JGAAP_UI_NotesDialog NotesPage = new JGAAP_UI_NotesDialog(JGAAP_UI_MainForm.this, true);
JGAAP_UI_ResultsDialog ResultsPage = new JGAAP_UI_ResultsDialog(JGAAP_UI_MainForm.this, false);
String[] Notes = new String [5];
DefaultListModel AnalysisMethodListBox_Model = new DefaultListModel();
DefaultListModel SelectedAnalysisMethodListBox_Model = new DefaultListModel();
DefaultListModel CanonicizerListBox_Model = new DefaultListModel();
DefaultListModel SelectedCanonicizerListBox_Model = new DefaultListModel();
DefaultListModel EventCullingListBox_Model = new DefaultListModel();
DefaultListModel SelectedEventCullingListBox_Model = new DefaultListModel();
DefaultListModel EventSetsListBox_Model = new DefaultListModel();
DefaultListModel SelectedEventSetsListBox_Model = new DefaultListModel();
DefaultListModel DistanceFunctionsListBox_Model = new DefaultListModel();
DefaultComboBoxModel LanguageComboBox_Model = new DefaultComboBoxModel();
DefaultTreeModel KnownAuthorsTree_Model = new DefaultTreeModel(new DefaultMutableTreeNode("Authors"));
DefaultTableModel UnknownAuthorDocumentsTable_Model = new DefaultTableModel() {
private static final long serialVersionUID = 1L;
@Override
public boolean isCellEditable(int row, int column) {
if (column == 0)
{
return true;
}
else
{
return false;
}
}
};
DefaultTableModel DocumentsTable_Model = new DefaultTableModel() {
private static final long serialVersionUID = 1L;
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
API JGAAP_API = new API();
JFileChooser FileChoser;
String filepath = "..";
List<Canonicizer> CanonicizerMasterList = JGAAP_API.getAllCanonicizers();
List<EventDriver> EventDriverMasterList = JGAAP_API.getAllEventDrivers();
List<AnalysisDriver> AnalysisDriverMasterList = JGAAP_API.getAllAnalysisDrivers();
List<DistanceFunction> DistanceFunctionsMasterList = JGAAP_API.getAllDistanceFunctions();
List<EventCuller> EventCullersMasterList = JGAAP_API.getAllEventCullers();
List<Language> LanguagesMasterList = JGAAP_API.getAllLanguages();
List<EventDriver> SelectedEventDriverList = new ArrayList<EventDriver>();
List<EventCuller> SelectedEventCullersList = new ArrayList<EventCuller>();
List<AnalysisDriver> SelectedAnalysisDriverList = new ArrayList<AnalysisDriver>();
List<Canonicizer> SelectedCanonicizerList = new ArrayList<Canonicizer>();
List<Document> UnknownDocumentList = new ArrayList<Document>();
List<Document> KnownDocumentList = new ArrayList<Document>();
List<Document> DocumentList = new ArrayList<Document>();
List<String> AuthorList = new ArrayList<String>();
/** Creates new form JGAAP_UI_MainForm */
public JGAAP_UI_MainForm() {
initComponents();
SanatizeMasterLists();
SetAnalysisMethodList();
SetDistanceFunctionList();
SetCanonicizerList();
SetEventSetList();
SetEventCullingList();
SetUnknownDocumentColumns();
SetKnownDocumentTree();
SetDocumentColumns();
SetLanguagesList();
SelectedEventDriverList.clear();
SelectedAnalysisDriverList.clear();
CheckMinimumRequirements();
// DefaultMutableTreeNode top = new DefaultMutableTreeNode("The Java Series");
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings({ "deprecation" })
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
helpDialog = new javax.swing.JDialog();
helpCloseButton = new javax.swing.JButton();
jLabel11 = new javax.swing.JLabel();
jLabel12 = new javax.swing.JLabel();
jLabel13 = new javax.swing.JLabel();
jLabel23 = new javax.swing.JLabel();
jLabel24 = new javax.swing.JLabel();
jLabel25 = new javax.swing.JLabel();
jLabel26 = new javax.swing.JLabel();
JGAAP_TabbedPane = new javax.swing.JTabbedPane();
JGAAP_DocumentsPanel = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
DocumentsPanel_UnknownAuthorsTable = new javax.swing.JTable();
jScrollPane2 = new javax.swing.JScrollPane();
DocumentsPanel_KnownAuthorsTree = new javax.swing.JTree();
DocumentsPanel_AddDocumentsButton = new javax.swing.JButton();
DocumentsPanel_RemoveDocumentsButton = new javax.swing.JButton();
DocumentsPanel_AddAuthorButton = new javax.swing.JButton();
DocumentsPanel_EditAuthorButton = new javax.swing.JButton();
DocumentsPanel_RemoveAuthorButton = new javax.swing.JButton();
DocumentsPanel_NotesButton = new javax.swing.JButton();
jLabel10 = new javax.swing.JLabel();
DocumentsPanel_LanguageComboBox = new javax.swing.JComboBox();
JGAAP_CanonicizerPanel = new javax.swing.JPanel();
CanonicizersPanel_RemoveCanonicizerButton = new javax.swing.JButton();
jLabel27 = new javax.swing.JLabel();
CanonicizersPanel_NotesButton = new javax.swing.JButton();
jScrollPane11 = new javax.swing.JScrollPane();
CanonicizersPanel_DocumentsCanonicizerDescriptionTextBox = new javax.swing.JTextArea();
CanonicizersPanel_AddCanonicizerButton = new javax.swing.JButton();
CanonicizersPanel_AddAllCanonicizersButton = new javax.swing.JButton();
jScrollPane12 = new javax.swing.JScrollPane();
CanonicizersPanel_CanonicizerListBox = new javax.swing.JList();
jScrollPane13 = new javax.swing.JScrollPane();
CanonicizersPanel_SelectedCanonicizerListBox = new javax.swing.JList();
CanonicizersPanel_RemoveAllCanonicizersButton = new javax.swing.JButton();
jLabel31 = new javax.swing.JLabel();
jScrollPane20 = new javax.swing.JScrollPane();
CanonicizersPanel_DocumentsTable = new javax.swing.JTable();
jScrollPane21 = new javax.swing.JScrollPane();
CanonicizersPanel_DocumentsCurrentCanonicizersTextBox = new javax.swing.JTextArea();
CanonicizersPanel_SetToDocumentButton = new javax.swing.JButton();
CanonicizersPanel_SetToDocumentTypeButton = new javax.swing.JButton();
CanonicizersPanel_SetToAllDocuments = new javax.swing.JButton();
jLabel29 = new javax.swing.JLabel();
jLabel30 = new javax.swing.JLabel();
jLabel32 = new javax.swing.JLabel();
jLabel33 = new javax.swing.JLabel();
jLabel34 = new javax.swing.JLabel();
JGAAP_EventSetsPanel = new javax.swing.JPanel();
EventSetsPanel_NotesButton = new javax.swing.JButton();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
jScrollPane9 = new javax.swing.JScrollPane();
EventSetsPanel_EventSetListBox = new javax.swing.JList();
jScrollPane10 = new javax.swing.JScrollPane();
EventSetsPanel_SelectedEventSetListBox = new javax.swing.JList();
EventSetsPanel_ParametersPanel = new javax.swing.JPanel();
jScrollPane6 = new javax.swing.JScrollPane();
EventSetsPanel_EventSetDescriptionTextBox = new javax.swing.JTextArea();
EventSetsPanel_AddEventSetButton = new javax.swing.JButton();
EventSetsPanel_RemoveEventSetButton = new javax.swing.JButton();
EventSetsPanel_AddAllEventSetsButton = new javax.swing.JButton();
EventSetsPanel_RemoveAllEventSetsButton = new javax.swing.JButton();
JGAAP_EventCullingPanel = new javax.swing.JPanel();
jLabel15 = new javax.swing.JLabel();
jLabel16 = new javax.swing.JLabel();
jLabel17 = new javax.swing.JLabel();
EventCullingPanel_NotesButton = new javax.swing.JButton();
jScrollPane14 = new javax.swing.JScrollPane();
EventCullingPanel_SelectedEventCullingListBox = new javax.swing.JList();
EventCullingPanel_AddEventCullingButton = new javax.swing.JButton();
EventCullingPanel_RemoveEventCullingButton = new javax.swing.JButton();
EventCullingPanel_AddAllEventCullingButton = new javax.swing.JButton();
EventCullingPanel_RemoveAllEventCullingButton = new javax.swing.JButton();
EventCullingPanel_ParametersPanel = new javax.swing.JPanel();
jScrollPane15 = new javax.swing.JScrollPane();
EventCullingPanel_EventCullingListBox = new javax.swing.JList();
jScrollPane16 = new javax.swing.JScrollPane();
EventCullingPanel_EventCullingDescriptionTextbox = new javax.swing.JTextArea();
jLabel18 = new javax.swing.JLabel();
JGAAP_AnalysisMethodPanel = new javax.swing.JPanel();
jLabel20 = new javax.swing.JLabel();
jLabel21 = new javax.swing.JLabel();
jLabel22 = new javax.swing.JLabel();
AnalysisMethodPanel_NotesButton = new javax.swing.JButton();
jScrollPane17 = new javax.swing.JScrollPane();
AnalysisMethodPanel_SelectedAnalysisMethodsListBox = new javax.swing.JList();
AnalysisMethodPanel_AddAnalysisMethodButton = new javax.swing.JButton();
AnalysisMethodPanel_RemoveAnalysisMethodsButton = new javax.swing.JButton();
AnalysisMethodPanel_AddAllAnalysisMethodsButton = new javax.swing.JButton();
AnalysisMethodPanel_RemoveAllAnalysisMethodsButton = new javax.swing.JButton();
AnalysisMethodPanel_AMParametersPanel = new javax.swing.JPanel();
jScrollPane18 = new javax.swing.JScrollPane();
AnalysisMethodPanel_AnalysisMethodsListBox = new javax.swing.JList();
jLabel28 = new javax.swing.JLabel();
jScrollPane19 = new javax.swing.JScrollPane();
AnalysisMethodPanel_AnalysisMethodDescriptionTextBox = new javax.swing.JTextArea();
jScrollPane22 = new javax.swing.JScrollPane();
AnalysisMethodPanel_DistanceFunctionsListBox = new javax.swing.JList();
jLabel35 = new javax.swing.JLabel();
jScrollPane23 = new javax.swing.JScrollPane();
AnalysisMethodPanel_DistanceFunctionDescriptionTextBox = new javax.swing.JTextArea();
jLabel36 = new javax.swing.JLabel();
AnalysisMethodPanel_DFParametersPanel = new javax.swing.JPanel();
jLabel37 = new javax.swing.JLabel();
JGAAP_ReviewPanel = new javax.swing.JPanel();
ReviewPanel_ProcessButton = new javax.swing.JButton();
ReviewPanel_DocumentsLabel = new javax.swing.JLabel();
jScrollPane24 = new javax.swing.JScrollPane();
ReviewPanel_DocumentsTable = new javax.swing.JTable();
ReviewPanel_SelectedEventSetLabel = new javax.swing.JLabel();
ReviewPanel_SelectedEventCullingLabel = new javax.swing.JLabel();
ReviewPanel_SelectedAnalysisMethodsLabel = new javax.swing.JLabel();
jScrollPane25 = new javax.swing.JScrollPane();
ReviewPanel_SelectedEventSetListBox = new javax.swing.JList();
jScrollPane26 = new javax.swing.JScrollPane();
ReviewPanel_SelectedEventCullingListBox = new javax.swing.JList();
jScrollPane27 = new javax.swing.JScrollPane();
ReviewPanel_SelectedAnalysisMethodsListBox = new javax.swing.JList();
Next_Button = new javax.swing.JButton();
Review_Button = new javax.swing.JButton();
JGAAP_MenuBar = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenu4 = new javax.swing.JMenu();
BatchSaveMenuItem = new javax.swing.JMenuItem();
BatchLoadMenuItem = new javax.swing.JMenuItem();
jMenu2 = new javax.swing.JMenu();
ProblemAMenuItem = new javax.swing.JMenuItem();
ProblemBMenuItem = new javax.swing.JMenuItem();
ProblemCMenuItem = new javax.swing.JMenuItem();
ProblemDMenuItem = new javax.swing.JMenuItem();
ProblemEMenuItem = new javax.swing.JMenuItem();
ProblemFMenuItem = new javax.swing.JMenuItem();
ProblemGMenuItem = new javax.swing.JMenuItem();
ProblemHMenuItem = new javax.swing.JMenuItem();
ProblemIMenuItem = new javax.swing.JMenuItem();
ProblemJMenuItem = new javax.swing.JMenuItem();
ProblemKMenuItem = new javax.swing.JMenuItem();
ProblemLMenuItem = new javax.swing.JMenuItem();
ProblemMMenuItem = new javax.swing.JMenuItem();
exitMenuItem = new javax.swing.JMenuItem();
helpMenu = new javax.swing.JMenu();
aboutMenuItem = new javax.swing.JMenuItem();
helpDialog.setTitle("About");
helpDialog.setMinimumSize(new java.awt.Dimension(520, 300));
helpDialog.setResizable(false);
helpCloseButton.setText("close");
helpCloseButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
helpCloseButtonActionPerformed(evt);
}
});
jLabel11.setFont(new java.awt.Font("Lucida Grande", 0, 24));
jLabel11.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel11.setText("JGAAP 5.0");
jLabel12.setText("<html> JGAAP, the Java Graphical Authorship Attribution Program, <br/>is an opensource author attribution / text classification tool <br/>Developed by the EVL lab (Evaluating Variation in Language Labratory) <br/> Released by Patrick Juola under the GPL v3.0");
- jLabel13.setText("©2011 EVL lab");
+ jLabel13.setText("�2011 EVL lab");
jLabel23.setForeground(new java.awt.Color(0, 0, 255));
jLabel23.setText("http://evllabs.com");
jLabel23.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel23MouseClicked(evt);
}
});
jLabel24.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/jgaap/ui/resources/jgaap_icon.png"))); // NOI18N
jLabel25.setForeground(new java.awt.Color(0, 0, 255));
jLabel25.setText("http://jgaap.com");
jLabel25.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel25MouseClicked(evt);
}
});
jLabel26.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/jgaap/ui/resources/EVLlab_icon.png"))); // NOI18N
javax.swing.GroupLayout helpDialogLayout = new javax.swing.GroupLayout(helpDialog.getContentPane());
helpDialog.getContentPane().setLayout(helpDialogLayout);
helpDialogLayout.setHorizontalGroup(
helpDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(helpDialogLayout.createSequentialGroup()
.addGroup(helpDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(helpDialogLayout.createSequentialGroup()
.addContainerGap()
.addGroup(helpDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(helpDialogLayout.createSequentialGroup()
.addComponent(jLabel24)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, 153, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel26))
.addComponent(helpCloseButton, javax.swing.GroupLayout.Alignment.TRAILING)))
.addGroup(helpDialogLayout.createSequentialGroup()
.addGap(199, 199, 199)
.addGroup(helpDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel23)
.addGroup(helpDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel13)
.addComponent(jLabel25))))
.addGroup(helpDialogLayout.createSequentialGroup()
.addGap(58, 58, 58)
.addComponent(jLabel12, javax.swing.GroupLayout.PREFERRED_SIZE, 452, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
helpDialogLayout.setVerticalGroup(
helpDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(helpDialogLayout.createSequentialGroup()
.addGroup(helpDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(helpDialogLayout.createSequentialGroup()
.addGroup(helpDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel24)
.addGroup(helpDialogLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel26, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, helpDialogLayout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel11)
.addGap(44, 44, 44)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel12, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel23)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel25)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 8, Short.MAX_VALUE)
.addGroup(helpDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(helpCloseButton)
.addComponent(jLabel13))
.addContainerGap())
);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("JGAAP");
JGAAP_TabbedPane.setName("JGAAP_TabbedPane"); // NOI18N
jLabel1.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24));
jLabel1.setText("Unknown Authors");
jLabel2.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24));
jLabel2.setText("Known Authors");
DocumentsPanel_UnknownAuthorsTable.setModel(UnknownAuthorDocumentsTable_Model);
DocumentsPanel_UnknownAuthorsTable.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_LAST_COLUMN);
DocumentsPanel_UnknownAuthorsTable.setColumnSelectionAllowed(true);
DocumentsPanel_UnknownAuthorsTable.getTableHeader().setReorderingAllowed(false);
jScrollPane1.setViewportView(DocumentsPanel_UnknownAuthorsTable);
DocumentsPanel_UnknownAuthorsTable.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
DocumentsPanel_KnownAuthorsTree.setModel(KnownAuthorsTree_Model);
DocumentsPanel_KnownAuthorsTree.setShowsRootHandles(true);
jScrollPane2.setViewportView(DocumentsPanel_KnownAuthorsTree);
DocumentsPanel_AddDocumentsButton.setText("Add Document");
DocumentsPanel_AddDocumentsButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
DocumentsPanel_AddDocumentsButtonActionPerformed(evt);
}
});
DocumentsPanel_RemoveDocumentsButton.setText("Remove Document");
DocumentsPanel_RemoveDocumentsButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
DocumentsPanel_RemoveDocumentsButtonActionPerformed(evt);
}
});
DocumentsPanel_AddAuthorButton.setLabel("Add Author");
DocumentsPanel_AddAuthorButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
DocumentsPanel_AddAuthorButtonActionPerformed(evt);
}
});
DocumentsPanel_EditAuthorButton.setLabel("Edit Author");
DocumentsPanel_EditAuthorButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
DocumentsPanel_EditAuthorButtonActionPerformed(evt);
}
});
DocumentsPanel_RemoveAuthorButton.setLabel("Remove Author");
DocumentsPanel_RemoveAuthorButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
DocumentsPanel_RemoveAuthorButtonActionPerformed(evt);
}
});
DocumentsPanel_NotesButton.setLabel("Notes");
DocumentsPanel_NotesButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
DocumentsPanel_NotesButtonActionPerformed(evt);
}
});
jLabel10.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24));
jLabel10.setText("Language");
DocumentsPanel_LanguageComboBox.setModel(LanguageComboBox_Model);
DocumentsPanel_LanguageComboBox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
DocumentsPanel_LanguageComboBoxActionPerformed(evt);
}
});
javax.swing.GroupLayout JGAAP_DocumentsPanelLayout = new javax.swing.GroupLayout(JGAAP_DocumentsPanel);
JGAAP_DocumentsPanel.setLayout(JGAAP_DocumentsPanelLayout);
JGAAP_DocumentsPanelLayout.setHorizontalGroup(
JGAAP_DocumentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, JGAAP_DocumentsPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(JGAAP_DocumentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 824, Short.MAX_VALUE)
.addGroup(JGAAP_DocumentsPanelLayout.createSequentialGroup()
.addGroup(JGAAP_DocumentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel10)
.addComponent(DocumentsPanel_LanguageComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 656, Short.MAX_VALUE)
.addComponent(DocumentsPanel_NotesButton))
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 824, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, JGAAP_DocumentsPanelLayout.createSequentialGroup()
.addGroup(JGAAP_DocumentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addGroup(JGAAP_DocumentsPanelLayout.createSequentialGroup()
.addComponent(DocumentsPanel_AddDocumentsButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(DocumentsPanel_RemoveDocumentsButton))
.addComponent(jLabel2))
.addGap(512, 512, 512))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, JGAAP_DocumentsPanelLayout.createSequentialGroup()
.addComponent(DocumentsPanel_AddAuthorButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(DocumentsPanel_EditAuthorButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(DocumentsPanel_RemoveAuthorButton)))
.addContainerGap())
);
JGAAP_DocumentsPanelLayout.setVerticalGroup(
JGAAP_DocumentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(JGAAP_DocumentsPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(JGAAP_DocumentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(DocumentsPanel_NotesButton)
.addGroup(JGAAP_DocumentsPanelLayout.createSequentialGroup()
.addComponent(jLabel10)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(DocumentsPanel_LanguageComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_DocumentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(DocumentsPanel_RemoveDocumentsButton)
.addComponent(DocumentsPanel_AddDocumentsButton))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 191, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_DocumentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(DocumentsPanel_RemoveAuthorButton)
.addComponent(DocumentsPanel_EditAuthorButton)
.addComponent(DocumentsPanel_AddAuthorButton))
.addContainerGap())
);
JGAAP_TabbedPane.addTab("Documents", JGAAP_DocumentsPanel);
CanonicizersPanel_RemoveCanonicizerButton.setText("<");
CanonicizersPanel_RemoveCanonicizerButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CanonicizersPanel_RemoveCanonicizerButtonActionPerformed(evt);
}
});
jLabel27.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N
jLabel27.setText("Documents");
CanonicizersPanel_NotesButton.setLabel("Notes");
CanonicizersPanel_NotesButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CanonicizersPanel_NotesButtonActionPerformed(evt);
}
});
CanonicizersPanel_DocumentsCanonicizerDescriptionTextBox.setColumns(20);
CanonicizersPanel_DocumentsCanonicizerDescriptionTextBox.setLineWrap(true);
CanonicizersPanel_DocumentsCanonicizerDescriptionTextBox.setRows(5);
CanonicizersPanel_DocumentsCanonicizerDescriptionTextBox.setWrapStyleWord(true);
jScrollPane11.setViewportView(CanonicizersPanel_DocumentsCanonicizerDescriptionTextBox);
CanonicizersPanel_AddCanonicizerButton.setText(">");
CanonicizersPanel_AddCanonicizerButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CanonicizersPanel_AddCanonicizerButtonActionPerformed(evt);
}
});
CanonicizersPanel_AddAllCanonicizersButton.setText("All");
CanonicizersPanel_AddAllCanonicizersButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CanonicizersPanel_AddAllCanonicizersButtonActionPerformed(evt);
}
});
CanonicizersPanel_CanonicizerListBox.setModel(CanonicizerListBox_Model);
CanonicizersPanel_CanonicizerListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
CanonicizersPanel_CanonicizerListBox.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
CanonicizersPanel_CanonicizerListBoxMouseClicked(evt);
}
});
CanonicizersPanel_CanonicizerListBox.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseMoved(java.awt.event.MouseEvent evt) {
CanonicizersPanel_CanonicizerListBoxMouseMoved(evt);
}
});
jScrollPane12.setViewportView(CanonicizersPanel_CanonicizerListBox);
CanonicizersPanel_SelectedCanonicizerListBox.setModel(SelectedCanonicizerListBox_Model);
CanonicizersPanel_SelectedCanonicizerListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
CanonicizersPanel_SelectedCanonicizerListBox.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
CanonicizersPanel_SelectedCanonicizerListBoxMouseClicked(evt);
}
});
CanonicizersPanel_SelectedCanonicizerListBox.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseMoved(java.awt.event.MouseEvent evt) {
CanonicizersPanel_SelectedCanonicizerListBoxMouseMoved(evt);
}
});
jScrollPane13.setViewportView(CanonicizersPanel_SelectedCanonicizerListBox);
CanonicizersPanel_RemoveAllCanonicizersButton.setText("Clear");
CanonicizersPanel_RemoveAllCanonicizersButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CanonicizersPanel_RemoveAllCanonicizersButtonActionPerformed(evt);
}
});
jLabel31.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24));
jLabel31.setText("Document's Current Canonicizers");
CanonicizersPanel_DocumentsTable.setModel(DocumentsTable_Model);
jScrollPane20.setViewportView(CanonicizersPanel_DocumentsTable);
CanonicizersPanel_DocumentsCurrentCanonicizersTextBox.setColumns(20);
CanonicizersPanel_DocumentsCurrentCanonicizersTextBox.setLineWrap(true);
CanonicizersPanel_DocumentsCurrentCanonicizersTextBox.setRows(5);
CanonicizersPanel_DocumentsCurrentCanonicizersTextBox.setWrapStyleWord(true);
jScrollPane21.setViewportView(CanonicizersPanel_DocumentsCurrentCanonicizersTextBox);
CanonicizersPanel_SetToDocumentButton.setText("Set to Doc");
CanonicizersPanel_SetToDocumentButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CanonicizersPanel_SetToDocumentButtonActionPerformed(evt);
}
});
CanonicizersPanel_SetToDocumentTypeButton.setText("Set to Doc Type");
CanonicizersPanel_SetToDocumentTypeButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CanonicizersPanel_SetToDocumentTypeButtonActionPerformed(evt);
}
});
CanonicizersPanel_SetToAllDocuments.setText("Set to All Docs");
CanonicizersPanel_SetToAllDocuments.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CanonicizersPanel_SetToAllDocumentsActionPerformed(evt);
}
});
jLabel29.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24));
jLabel29.setText("Selected");
jLabel30.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24));
jLabel30.setText("Canonicizers");
jLabel32.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24));
jLabel32.setText("Canonicizer Description");
jLabel33.setText("Note: These buttons are used to add");
jLabel34.setText("selected canonicizers to documents.");
javax.swing.GroupLayout JGAAP_CanonicizerPanelLayout = new javax.swing.GroupLayout(JGAAP_CanonicizerPanel);
JGAAP_CanonicizerPanel.setLayout(JGAAP_CanonicizerPanelLayout);
JGAAP_CanonicizerPanelLayout.setHorizontalGroup(
JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(JGAAP_CanonicizerPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(JGAAP_CanonicizerPanelLayout.createSequentialGroup()
.addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(JGAAP_CanonicizerPanelLayout.createSequentialGroup()
.addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel30)
.addComponent(jScrollPane12, javax.swing.GroupLayout.DEFAULT_SIZE, 155, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(CanonicizersPanel_AddCanonicizerButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(CanonicizersPanel_RemoveCanonicizerButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(CanonicizersPanel_AddAllCanonicizersButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(CanonicizersPanel_RemoveAllCanonicizersButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
.addComponent(jLabel33)
.addComponent(jLabel34))
.addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(CanonicizersPanel_SetToDocumentTypeButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 153, Short.MAX_VALUE)
.addComponent(jLabel29)
.addComponent(CanonicizersPanel_SetToDocumentButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 153, Short.MAX_VALUE)
.addComponent(jScrollPane13, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 153, Short.MAX_VALUE)
.addComponent(CanonicizersPanel_SetToAllDocuments, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 153, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane20, javax.swing.GroupLayout.DEFAULT_SIZE, 437, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, JGAAP_CanonicizerPanelLayout.createSequentialGroup()
.addComponent(jLabel27)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 255, Short.MAX_VALUE)
.addComponent(CanonicizersPanel_NotesButton))))
.addGroup(JGAAP_CanonicizerPanelLayout.createSequentialGroup()
.addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jScrollPane21, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel31, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel32)
.addComponent(jScrollPane11, javax.swing.GroupLayout.DEFAULT_SIZE, 463, Short.MAX_VALUE))))
.addContainerGap())
);
JGAAP_CanonicizerPanelLayout.setVerticalGroup(
JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, JGAAP_CanonicizerPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel27)
.addComponent(jLabel30)
.addComponent(jLabel29))
.addGroup(JGAAP_CanonicizerPanelLayout.createSequentialGroup()
.addGap(5, 5, 5)
.addComponent(CanonicizersPanel_NotesButton)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane20, javax.swing.GroupLayout.DEFAULT_SIZE, 304, Short.MAX_VALUE)
.addGroup(JGAAP_CanonicizerPanelLayout.createSequentialGroup()
.addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(JGAAP_CanonicizerPanelLayout.createSequentialGroup()
.addComponent(CanonicizersPanel_AddCanonicizerButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(CanonicizersPanel_RemoveCanonicizerButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(CanonicizersPanel_AddAllCanonicizersButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(CanonicizersPanel_RemoveAllCanonicizersButton))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, JGAAP_CanonicizerPanelLayout.createSequentialGroup()
.addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane13, javax.swing.GroupLayout.DEFAULT_SIZE, 217, Short.MAX_VALUE)
.addComponent(jScrollPane12, javax.swing.GroupLayout.DEFAULT_SIZE, 217, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(CanonicizersPanel_SetToDocumentButton)))
.addGap(6, 6, 6)
.addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(JGAAP_CanonicizerPanelLayout.createSequentialGroup()
.addComponent(jLabel33)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel34)
.addGap(18, 18, 18))
.addGroup(JGAAP_CanonicizerPanelLayout.createSequentialGroup()
.addComponent(CanonicizersPanel_SetToDocumentTypeButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(CanonicizersPanel_SetToAllDocuments)))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel31)
.addComponent(jLabel32))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane21, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jScrollPane11, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
JGAAP_TabbedPane.addTab("Canonicizers", JGAAP_CanonicizerPanel);
EventSetsPanel_NotesButton.setLabel("Notes");
EventSetsPanel_NotesButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EventSetsPanel_NotesButtonActionPerformed(evt);
}
});
jLabel6.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N
jLabel6.setText("Event Drivers");
jLabel7.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24));
jLabel7.setText("Parameters");
jLabel8.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24));
jLabel8.setText("Event Driver Description");
jLabel9.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24));
jLabel9.setText("Selected");
EventSetsPanel_EventSetListBox.setModel(EventSetsListBox_Model);
EventSetsPanel_EventSetListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
EventSetsPanel_EventSetListBox.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
EventSetsPanel_EventSetListBoxMouseClicked(evt);
}
});
EventSetsPanel_EventSetListBox.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseMoved(java.awt.event.MouseEvent evt) {
EventSetsPanel_EventSetListBoxMouseMoved(evt);
}
});
jScrollPane9.setViewportView(EventSetsPanel_EventSetListBox);
EventSetsPanel_SelectedEventSetListBox.setModel(SelectedEventSetsListBox_Model);
EventSetsPanel_SelectedEventSetListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
EventSetsPanel_SelectedEventSetListBox.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
EventSetsPanel_SelectedEventSetListBoxMouseClicked(evt);
}
});
EventSetsPanel_SelectedEventSetListBox.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseMoved(java.awt.event.MouseEvent evt) {
EventSetsPanel_SelectedEventSetListBoxMouseMoved(evt);
}
});
jScrollPane10.setViewportView(EventSetsPanel_SelectedEventSetListBox);
EventSetsPanel_ParametersPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder());
javax.swing.GroupLayout EventSetsPanel_ParametersPanelLayout = new javax.swing.GroupLayout(EventSetsPanel_ParametersPanel);
EventSetsPanel_ParametersPanel.setLayout(EventSetsPanel_ParametersPanelLayout);
EventSetsPanel_ParametersPanelLayout.setHorizontalGroup(
EventSetsPanel_ParametersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 344, Short.MAX_VALUE)
);
EventSetsPanel_ParametersPanelLayout.setVerticalGroup(
EventSetsPanel_ParametersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
EventSetsPanel_EventSetDescriptionTextBox.setColumns(20);
EventSetsPanel_EventSetDescriptionTextBox.setLineWrap(true);
EventSetsPanel_EventSetDescriptionTextBox.setRows(5);
EventSetsPanel_EventSetDescriptionTextBox.setWrapStyleWord(true);
jScrollPane6.setViewportView(EventSetsPanel_EventSetDescriptionTextBox);
EventSetsPanel_AddEventSetButton.setText(">");
EventSetsPanel_AddEventSetButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EventSetsPanel_AddEventSetButtonActionPerformed(evt);
}
});
EventSetsPanel_RemoveEventSetButton.setText("<");
EventSetsPanel_RemoveEventSetButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EventSetsPanel_RemoveEventSetButtonActionPerformed(evt);
}
});
EventSetsPanel_AddAllEventSetsButton.setText("All");
EventSetsPanel_AddAllEventSetsButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EventSetsPanel_AddAllEventSetsButtonActionPerformed(evt);
}
});
EventSetsPanel_RemoveAllEventSetsButton.setText("Clear");
EventSetsPanel_RemoveAllEventSetsButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EventSetsPanel_RemoveAllEventSetsButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout JGAAP_EventSetsPanelLayout = new javax.swing.GroupLayout(JGAAP_EventSetsPanel);
JGAAP_EventSetsPanel.setLayout(JGAAP_EventSetsPanelLayout);
JGAAP_EventSetsPanelLayout.setHorizontalGroup(
JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, JGAAP_EventSetsPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane6, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 824, Short.MAX_VALUE)
.addComponent(jLabel8, javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(JGAAP_EventSetsPanelLayout.createSequentialGroup()
.addGroup(JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane9, javax.swing.GroupLayout.PREFERRED_SIZE, 178, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel6))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(EventSetsPanel_RemoveEventSetButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(EventSetsPanel_AddAllEventSetsButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(EventSetsPanel_AddEventSetButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(EventSetsPanel_RemoveAllEventSetsButton, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel9)
.addComponent(jScrollPane10, javax.swing.GroupLayout.PREFERRED_SIZE, 216, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(JGAAP_EventSetsPanelLayout.createSequentialGroup()
.addComponent(jLabel7)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 163, Short.MAX_VALUE)
.addComponent(EventSetsPanel_NotesButton))
.addComponent(EventSetsPanel_ParametersPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
.addContainerGap())
);
JGAAP_EventSetsPanelLayout.setVerticalGroup(
JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(JGAAP_EventSetsPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6)
.addComponent(jLabel9))
.addGroup(JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(EventSetsPanel_NotesButton)
.addComponent(jLabel7)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(EventSetsPanel_ParametersPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane10, javax.swing.GroupLayout.DEFAULT_SIZE, 304, Short.MAX_VALUE)
.addComponent(jScrollPane9, javax.swing.GroupLayout.DEFAULT_SIZE, 304, Short.MAX_VALUE)
.addGroup(JGAAP_EventSetsPanelLayout.createSequentialGroup()
.addComponent(EventSetsPanel_AddEventSetButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(EventSetsPanel_RemoveEventSetButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(EventSetsPanel_AddAllEventSetsButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(EventSetsPanel_RemoveAllEventSetsButton)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel8)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane6, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
JGAAP_TabbedPane.addTab("Event Drivers", JGAAP_EventSetsPanel);
jLabel15.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N
jLabel15.setText("Event Culling");
jLabel16.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24));
jLabel16.setText("Parameters");
jLabel17.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24));
jLabel17.setText("Selected");
EventCullingPanel_NotesButton.setLabel("Notes");
EventCullingPanel_NotesButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EventCullingPanel_NotesButtonActionPerformed(evt);
}
});
EventCullingPanel_SelectedEventCullingListBox.setModel(SelectedEventCullingListBox_Model);
EventCullingPanel_SelectedEventCullingListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
EventCullingPanel_SelectedEventCullingListBox.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
EventCullingPanel_SelectedEventCullingListBoxMouseClicked(evt);
}
});
EventCullingPanel_SelectedEventCullingListBox.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseMoved(java.awt.event.MouseEvent evt) {
EventCullingPanel_SelectedEventCullingListBoxMouseMoved(evt);
}
});
jScrollPane14.setViewportView(EventCullingPanel_SelectedEventCullingListBox);
EventCullingPanel_AddEventCullingButton.setText(">");
EventCullingPanel_AddEventCullingButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EventCullingPanel_AddEventCullingButtonActionPerformed(evt);
}
});
EventCullingPanel_RemoveEventCullingButton.setText("<");
EventCullingPanel_RemoveEventCullingButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EventCullingPanel_RemoveEventCullingButtonActionPerformed(evt);
}
});
EventCullingPanel_AddAllEventCullingButton.setText("All");
EventCullingPanel_AddAllEventCullingButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EventCullingPanel_AddAllEventCullingButtonActionPerformed(evt);
}
});
EventCullingPanel_RemoveAllEventCullingButton.setText("Clear");
EventCullingPanel_RemoveAllEventCullingButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EventCullingPanel_RemoveAllEventCullingButtonActionPerformed(evt);
}
});
EventCullingPanel_ParametersPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder());
javax.swing.GroupLayout EventCullingPanel_ParametersPanelLayout = new javax.swing.GroupLayout(EventCullingPanel_ParametersPanel);
EventCullingPanel_ParametersPanel.setLayout(EventCullingPanel_ParametersPanelLayout);
EventCullingPanel_ParametersPanelLayout.setHorizontalGroup(
EventCullingPanel_ParametersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 343, Short.MAX_VALUE)
);
EventCullingPanel_ParametersPanelLayout.setVerticalGroup(
EventCullingPanel_ParametersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
EventCullingPanel_EventCullingListBox.setModel(EventCullingListBox_Model);
EventCullingPanel_EventCullingListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
EventCullingPanel_EventCullingListBox.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
EventCullingPanel_EventCullingListBoxMouseClicked(evt);
}
});
EventCullingPanel_EventCullingListBox.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseMoved(java.awt.event.MouseEvent evt) {
EventCullingPanel_EventCullingListBoxMouseMoved(evt);
}
});
jScrollPane15.setViewportView(EventCullingPanel_EventCullingListBox);
EventCullingPanel_EventCullingDescriptionTextbox.setColumns(20);
EventCullingPanel_EventCullingDescriptionTextbox.setLineWrap(true);
EventCullingPanel_EventCullingDescriptionTextbox.setRows(5);
EventCullingPanel_EventCullingDescriptionTextbox.setWrapStyleWord(true);
jScrollPane16.setViewportView(EventCullingPanel_EventCullingDescriptionTextbox);
jLabel18.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24));
jLabel18.setText("Event Culling Description");
javax.swing.GroupLayout JGAAP_EventCullingPanelLayout = new javax.swing.GroupLayout(JGAAP_EventCullingPanel);
JGAAP_EventCullingPanel.setLayout(JGAAP_EventCullingPanelLayout);
JGAAP_EventCullingPanelLayout.setHorizontalGroup(
JGAAP_EventCullingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, JGAAP_EventCullingPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(JGAAP_EventCullingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane16, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 824, Short.MAX_VALUE)
.addComponent(jLabel18, javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(JGAAP_EventCullingPanelLayout.createSequentialGroup()
.addGroup(JGAAP_EventCullingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane15, javax.swing.GroupLayout.PREFERRED_SIZE, 178, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel15))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_EventCullingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(EventCullingPanel_RemoveEventCullingButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(EventCullingPanel_AddAllEventCullingButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(EventCullingPanel_AddEventCullingButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(EventCullingPanel_RemoveAllEventCullingButton, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_EventCullingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel17)
.addComponent(jScrollPane14, javax.swing.GroupLayout.PREFERRED_SIZE, 217, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_EventCullingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(JGAAP_EventCullingPanelLayout.createSequentialGroup()
.addComponent(jLabel16)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 162, Short.MAX_VALUE)
.addComponent(EventCullingPanel_NotesButton))
.addComponent(EventCullingPanel_ParametersPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
.addContainerGap())
);
JGAAP_EventCullingPanelLayout.setVerticalGroup(
JGAAP_EventCullingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(JGAAP_EventCullingPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(JGAAP_EventCullingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(JGAAP_EventCullingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel15)
.addComponent(jLabel17)
.addComponent(jLabel16))
.addComponent(EventCullingPanel_NotesButton))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_EventCullingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane14, javax.swing.GroupLayout.DEFAULT_SIZE, 304, Short.MAX_VALUE)
.addComponent(EventCullingPanel_ParametersPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane15, javax.swing.GroupLayout.DEFAULT_SIZE, 304, Short.MAX_VALUE)
.addGroup(JGAAP_EventCullingPanelLayout.createSequentialGroup()
.addComponent(EventCullingPanel_AddEventCullingButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(EventCullingPanel_RemoveEventCullingButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(EventCullingPanel_AddAllEventCullingButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(EventCullingPanel_RemoveAllEventCullingButton)
.addGap(107, 107, 107)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel18)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane16, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
JGAAP_TabbedPane.addTab("Event Culling", JGAAP_EventCullingPanel);
jLabel20.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N
jLabel20.setText("Analysis Methods");
jLabel21.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24));
jLabel21.setText("AM Parameters");
jLabel22.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24));
jLabel22.setText("Selected");
AnalysisMethodPanel_NotesButton.setLabel("Notes");
AnalysisMethodPanel_NotesButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
AnalysisMethodPanel_NotesButtonActionPerformed(evt);
}
});
AnalysisMethodPanel_SelectedAnalysisMethodsListBox.setModel(SelectedAnalysisMethodListBox_Model);
AnalysisMethodPanel_SelectedAnalysisMethodsListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
AnalysisMethodPanel_SelectedAnalysisMethodsListBox.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
AnalysisMethodPanel_SelectedAnalysisMethodsListBoxMouseClicked(evt);
}
});
AnalysisMethodPanel_SelectedAnalysisMethodsListBox.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseMoved(java.awt.event.MouseEvent evt) {
AnalysisMethodPanel_SelectedAnalysisMethodsListBoxMouseMoved(evt);
}
});
jScrollPane17.setViewportView(AnalysisMethodPanel_SelectedAnalysisMethodsListBox);
AnalysisMethodPanel_AddAnalysisMethodButton.setText(">");
AnalysisMethodPanel_AddAnalysisMethodButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
AnalysisMethodPanel_AddAnalysisMethodButtonActionPerformed(evt);
}
});
AnalysisMethodPanel_RemoveAnalysisMethodsButton.setText("<");
AnalysisMethodPanel_RemoveAnalysisMethodsButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
AnalysisMethodPanel_RemoveAnalysisMethodsButtonActionPerformed(evt);
}
});
AnalysisMethodPanel_AddAllAnalysisMethodsButton.setText("All");
AnalysisMethodPanel_AddAllAnalysisMethodsButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
AnalysisMethodPanel_AddAllAnalysisMethodsButtonActionPerformed(evt);
}
});
AnalysisMethodPanel_RemoveAllAnalysisMethodsButton.setText("Clear");
AnalysisMethodPanel_RemoveAllAnalysisMethodsButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
AnalysisMethodPanel_RemoveAllAnalysisMethodsButtonActionPerformed(evt);
}
});
AnalysisMethodPanel_AMParametersPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder());
javax.swing.GroupLayout AnalysisMethodPanel_AMParametersPanelLayout = new javax.swing.GroupLayout(AnalysisMethodPanel_AMParametersPanel);
AnalysisMethodPanel_AMParametersPanel.setLayout(AnalysisMethodPanel_AMParametersPanelLayout);
AnalysisMethodPanel_AMParametersPanelLayout.setHorizontalGroup(
AnalysisMethodPanel_AMParametersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 355, Short.MAX_VALUE)
);
AnalysisMethodPanel_AMParametersPanelLayout.setVerticalGroup(
AnalysisMethodPanel_AMParametersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 125, Short.MAX_VALUE)
);
AnalysisMethodPanel_AnalysisMethodsListBox.setModel(AnalysisMethodListBox_Model);
AnalysisMethodPanel_AnalysisMethodsListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
AnalysisMethodPanel_AnalysisMethodsListBox.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
AnalysisMethodPanel_AnalysisMethodsListBoxMouseClicked(evt);
}
});
AnalysisMethodPanel_AnalysisMethodsListBox.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseMoved(java.awt.event.MouseEvent evt) {
AnalysisMethodPanel_AnalysisMethodsListBoxMouseMoved(evt);
}
});
jScrollPane18.setViewportView(AnalysisMethodPanel_AnalysisMethodsListBox);
jLabel28.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N
jLabel28.setText("Distance Function Description");
AnalysisMethodPanel_AnalysisMethodDescriptionTextBox.setColumns(20);
AnalysisMethodPanel_AnalysisMethodDescriptionTextBox.setLineWrap(true);
AnalysisMethodPanel_AnalysisMethodDescriptionTextBox.setRows(5);
AnalysisMethodPanel_AnalysisMethodDescriptionTextBox.setWrapStyleWord(true);
jScrollPane19.setViewportView(AnalysisMethodPanel_AnalysisMethodDescriptionTextBox);
AnalysisMethodPanel_DistanceFunctionsListBox.setModel(DistanceFunctionsListBox_Model);
AnalysisMethodPanel_DistanceFunctionsListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
AnalysisMethodPanel_DistanceFunctionsListBox.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
AnalysisMethodPanel_DistanceFunctionsListBoxMouseClicked(evt);
}
});
AnalysisMethodPanel_DistanceFunctionsListBox.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseMoved(java.awt.event.MouseEvent evt) {
AnalysisMethodPanel_DistanceFunctionsListBoxMouseMoved(evt);
}
});
jScrollPane22.setViewportView(AnalysisMethodPanel_DistanceFunctionsListBox);
jLabel35.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N
jLabel35.setText("Distance Functions");
AnalysisMethodPanel_DistanceFunctionDescriptionTextBox.setColumns(20);
AnalysisMethodPanel_DistanceFunctionDescriptionTextBox.setLineWrap(true);
AnalysisMethodPanel_DistanceFunctionDescriptionTextBox.setRows(5);
AnalysisMethodPanel_DistanceFunctionDescriptionTextBox.setWrapStyleWord(true);
jScrollPane23.setViewportView(AnalysisMethodPanel_DistanceFunctionDescriptionTextBox);
jLabel36.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N
jLabel36.setText("Analysis Method Description");
AnalysisMethodPanel_DFParametersPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder());
javax.swing.GroupLayout AnalysisMethodPanel_DFParametersPanelLayout = new javax.swing.GroupLayout(AnalysisMethodPanel_DFParametersPanel);
AnalysisMethodPanel_DFParametersPanel.setLayout(AnalysisMethodPanel_DFParametersPanelLayout);
AnalysisMethodPanel_DFParametersPanelLayout.setHorizontalGroup(
AnalysisMethodPanel_DFParametersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 355, Short.MAX_VALUE)
);
AnalysisMethodPanel_DFParametersPanelLayout.setVerticalGroup(
AnalysisMethodPanel_DFParametersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 128, Short.MAX_VALUE)
);
jLabel37.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24));
jLabel37.setText("DF Parameters");
javax.swing.GroupLayout JGAAP_AnalysisMethodPanelLayout = new javax.swing.GroupLayout(JGAAP_AnalysisMethodPanel);
JGAAP_AnalysisMethodPanel.setLayout(JGAAP_AnalysisMethodPanelLayout);
JGAAP_AnalysisMethodPanelLayout.setHorizontalGroup(
JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, JGAAP_AnalysisMethodPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(JGAAP_AnalysisMethodPanelLayout.createSequentialGroup()
.addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel35, javax.swing.GroupLayout.DEFAULT_SIZE, 257, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, JGAAP_AnalysisMethodPanelLayout.createSequentialGroup()
.addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane22, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 187, Short.MAX_VALUE)
.addComponent(jScrollPane18, javax.swing.GroupLayout.Alignment.LEADING, 0, 0, Short.MAX_VALUE)
.addComponent(jLabel20, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(AnalysisMethodPanel_RemoveAnalysisMethodsButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(AnalysisMethodPanel_AddAllAnalysisMethodsButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(AnalysisMethodPanel_AddAnalysisMethodButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(AnalysisMethodPanel_RemoveAllAnalysisMethodsButton, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel22)
.addComponent(jScrollPane17, javax.swing.GroupLayout.PREFERRED_SIZE, 196, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(AnalysisMethodPanel_DFParametersPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(AnalysisMethodPanel_AMParametersPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(JGAAP_AnalysisMethodPanelLayout.createSequentialGroup()
.addComponent(jLabel21)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 133, Short.MAX_VALUE)
.addComponent(AnalysisMethodPanel_NotesButton))
.addComponent(jLabel37)))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, JGAAP_AnalysisMethodPanelLayout.createSequentialGroup()
.addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane19, javax.swing.GroupLayout.PREFERRED_SIZE, 405, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel36))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel28)
.addComponent(jScrollPane23, javax.swing.GroupLayout.DEFAULT_SIZE, 413, Short.MAX_VALUE))))
.addContainerGap())
);
JGAAP_AnalysisMethodPanelLayout.setVerticalGroup(
JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(JGAAP_AnalysisMethodPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel20)
.addComponent(jLabel21)
.addComponent(jLabel22)
.addComponent(AnalysisMethodPanel_NotesButton))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane17, javax.swing.GroupLayout.DEFAULT_SIZE, 301, Short.MAX_VALUE)
.addGroup(JGAAP_AnalysisMethodPanelLayout.createSequentialGroup()
.addComponent(AnalysisMethodPanel_AMParametersPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel37)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(AnalysisMethodPanel_DFParametersPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(JGAAP_AnalysisMethodPanelLayout.createSequentialGroup()
.addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(JGAAP_AnalysisMethodPanelLayout.createSequentialGroup()
.addComponent(AnalysisMethodPanel_AddAnalysisMethodButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(AnalysisMethodPanel_RemoveAnalysisMethodsButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(AnalysisMethodPanel_AddAllAnalysisMethodsButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(AnalysisMethodPanel_RemoveAllAnalysisMethodsButton))
.addComponent(jScrollPane18, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel35)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane22, javax.swing.GroupLayout.DEFAULT_SIZE, 132, Short.MAX_VALUE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel28)
.addComponent(jLabel36))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane19, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jScrollPane23, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
JGAAP_TabbedPane.addTab("Analysis Methods", JGAAP_AnalysisMethodPanel);
ReviewPanel_ProcessButton.setLabel("Process");
ReviewPanel_ProcessButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ReviewPanel_ProcessButtonActionPerformed(evt);
}
});
ReviewPanel_DocumentsLabel.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N
ReviewPanel_DocumentsLabel.setText("Documents");
ReviewPanel_DocumentsLabel.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
ReviewPanel_DocumentsLabelMouseClicked(evt);
}
});
ReviewPanel_DocumentsTable.setModel(DocumentsTable_Model);
ReviewPanel_DocumentsTable.setEnabled(false);
ReviewPanel_DocumentsTable.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
ReviewPanel_DocumentsTableMouseClicked(evt);
}
});
jScrollPane24.setViewportView(ReviewPanel_DocumentsTable);
ReviewPanel_SelectedEventSetLabel.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N
ReviewPanel_SelectedEventSetLabel.setText("Event Driver");
ReviewPanel_SelectedEventSetLabel.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
ReviewPanel_SelectedEventSetLabelMouseClicked(evt);
}
});
ReviewPanel_SelectedEventCullingLabel.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N
ReviewPanel_SelectedEventCullingLabel.setText("Event Culling");
ReviewPanel_SelectedEventCullingLabel.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
ReviewPanel_SelectedEventCullingLabelMouseClicked(evt);
}
});
ReviewPanel_SelectedAnalysisMethodsLabel.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N
ReviewPanel_SelectedAnalysisMethodsLabel.setText("Analysis Methods");
ReviewPanel_SelectedAnalysisMethodsLabel.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
ReviewPanel_SelectedAnalysisMethodsLabelMouseClicked(evt);
}
});
ReviewPanel_SelectedEventSetListBox.setModel(SelectedEventSetsListBox_Model);
ReviewPanel_SelectedEventSetListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
ReviewPanel_SelectedEventSetListBox.setEnabled(false);
ReviewPanel_SelectedEventSetListBox.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
ReviewPanel_SelectedEventSetListBoxMouseClicked(evt);
}
});
jScrollPane25.setViewportView(ReviewPanel_SelectedEventSetListBox);
ReviewPanel_SelectedEventCullingListBox.setModel(SelectedEventCullingListBox_Model);
ReviewPanel_SelectedEventCullingListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
ReviewPanel_SelectedEventCullingListBox.setEnabled(false);
ReviewPanel_SelectedEventCullingListBox.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
ReviewPanel_SelectedEventCullingListBoxMouseClicked(evt);
}
});
jScrollPane26.setViewportView(ReviewPanel_SelectedEventCullingListBox);
ReviewPanel_SelectedAnalysisMethodsListBox.setModel(SelectedAnalysisMethodListBox_Model);
ReviewPanel_SelectedAnalysisMethodsListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
ReviewPanel_SelectedAnalysisMethodsListBox.setEnabled(false);
ReviewPanel_SelectedAnalysisMethodsListBox.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
ReviewPanel_SelectedAnalysisMethodsListBoxMouseClicked(evt);
}
});
jScrollPane27.setViewportView(ReviewPanel_SelectedAnalysisMethodsListBox);
javax.swing.GroupLayout JGAAP_ReviewPanelLayout = new javax.swing.GroupLayout(JGAAP_ReviewPanel);
JGAAP_ReviewPanel.setLayout(JGAAP_ReviewPanelLayout);
JGAAP_ReviewPanelLayout.setHorizontalGroup(
JGAAP_ReviewPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, JGAAP_ReviewPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(JGAAP_ReviewPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane24, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 824, Short.MAX_VALUE)
.addComponent(ReviewPanel_DocumentsLabel, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(ReviewPanel_ProcessButton)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, JGAAP_ReviewPanelLayout.createSequentialGroup()
.addGroup(JGAAP_ReviewPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane25, javax.swing.GroupLayout.PREFERRED_SIZE, 273, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(ReviewPanel_SelectedEventSetLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_ReviewPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(ReviewPanel_SelectedEventCullingLabel)
.addComponent(jScrollPane26, javax.swing.GroupLayout.PREFERRED_SIZE, 268, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_ReviewPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(ReviewPanel_SelectedAnalysisMethodsLabel)
.addComponent(jScrollPane27, javax.swing.GroupLayout.DEFAULT_SIZE, 271, Short.MAX_VALUE))))
.addContainerGap())
);
JGAAP_ReviewPanelLayout.setVerticalGroup(
JGAAP_ReviewPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(JGAAP_ReviewPanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(ReviewPanel_DocumentsLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane24, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_ReviewPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(ReviewPanel_SelectedEventSetLabel)
.addComponent(ReviewPanel_SelectedEventCullingLabel)
.addComponent(ReviewPanel_SelectedAnalysisMethodsLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_ReviewPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane27, javax.swing.GroupLayout.DEFAULT_SIZE, 258, Short.MAX_VALUE)
.addComponent(jScrollPane26, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 258, Short.MAX_VALUE)
.addComponent(jScrollPane25, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 258, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(ReviewPanel_ProcessButton)
.addContainerGap())
);
JGAAP_TabbedPane.addTab("Review & Process", JGAAP_ReviewPanel);
Next_Button.setText("Next >");
Next_Button.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Next_ButtonActionPerformed(evt);
}
});
Review_Button.setText("Finish & Review");
Review_Button.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Review_ButtonActionPerformed(evt);
}
});
jMenu1.setText("File");
jMenu4.setText("Batch Documents");
BatchSaveMenuItem.setText("Save Documents");
BatchSaveMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BatchSaveMenuItemActionPerformed(evt);
}
});
jMenu4.add(BatchSaveMenuItem);
BatchLoadMenuItem.setText("Load Documents");
BatchLoadMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BatchLoadMenuItemActionPerformed(evt);
}
});
jMenu4.add(BatchLoadMenuItem);
jMenu1.add(jMenu4);
jMenu2.setText("AAAC Problems");
ProblemAMenuItem.setText("Problem A");
ProblemAMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ProblemAMenuItemActionPerformed(evt);
}
});
jMenu2.add(ProblemAMenuItem);
ProblemBMenuItem.setText("Problem B");
ProblemBMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ProblemBMenuItemActionPerformed(evt);
}
});
jMenu2.add(ProblemBMenuItem);
ProblemCMenuItem.setText("Problem C");
ProblemCMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ProblemCMenuItemActionPerformed(evt);
}
});
jMenu2.add(ProblemCMenuItem);
ProblemDMenuItem.setText("Problem D");
ProblemDMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ProblemDMenuItemActionPerformed(evt);
}
});
jMenu2.add(ProblemDMenuItem);
ProblemEMenuItem.setText("Problem E");
ProblemEMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ProblemEMenuItemActionPerformed(evt);
}
});
jMenu2.add(ProblemEMenuItem);
ProblemFMenuItem.setText("Problem F");
ProblemFMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ProblemFMenuItemActionPerformed(evt);
}
});
jMenu2.add(ProblemFMenuItem);
ProblemGMenuItem.setText("Problem G");
ProblemGMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ProblemGMenuItemActionPerformed(evt);
}
});
jMenu2.add(ProblemGMenuItem);
ProblemHMenuItem.setText("Problem H");
ProblemHMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ProblemHMenuItemActionPerformed(evt);
}
});
jMenu2.add(ProblemHMenuItem);
ProblemIMenuItem.setText("Problem I");
ProblemIMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ProblemIMenuItemActionPerformed(evt);
}
});
jMenu2.add(ProblemIMenuItem);
ProblemJMenuItem.setText("Problem J");
ProblemJMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ProblemJMenuItemActionPerformed(evt);
}
});
jMenu2.add(ProblemJMenuItem);
ProblemKMenuItem.setText("Problem K");
ProblemKMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ProblemKMenuItemActionPerformed(evt);
}
});
jMenu2.add(ProblemKMenuItem);
ProblemLMenuItem.setText("Problem L");
ProblemLMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ProblemLMenuItemActionPerformed(evt);
}
});
jMenu2.add(ProblemLMenuItem);
ProblemMMenuItem.setText("Problem M");
ProblemMMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ProblemMMenuItemActionPerformed(evt);
}
});
jMenu2.add(ProblemMMenuItem);
jMenu1.add(jMenu2);
exitMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Q, java.awt.event.InputEvent.CTRL_MASK));
exitMenuItem.setText("Exit");
exitMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
exitMenuItemActionPerformed(evt);
}
});
jMenu1.add(exitMenuItem);
JGAAP_MenuBar.add(jMenu1);
helpMenu.setText("Help");
aboutMenuItem.setText("About..");
aboutMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
aboutMenuItemActionPerformed(evt);
}
});
helpMenu.add(aboutMenuItem);
JGAAP_MenuBar.add(helpMenu);
setJMenuBar(JGAAP_MenuBar);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(JGAAP_TabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, 849, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(Review_Button)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(Next_Button)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(JGAAP_TabbedPane, javax.swing.GroupLayout.PREFERRED_SIZE, 529, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(Next_Button)
.addComponent(Review_Button))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void ReviewPanel_ProcessButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ReviewPanel_ProcessButtonActionPerformed
try {
JGAAP_API.clearResults();
JGAAP_API.execute();
List<Document> unknowns = JGAAP_API.getUnknownDocuments();
StringBuffer buffer = new StringBuffer();
for (Document unknown : unknowns) {
buffer.append(unknown.getResult());
}
//ResultsPage.DisplayResults(buffer.toString());
ResultsPage.AddResults(buffer.toString());
ResultsPage.setVisible(true);
} catch (Exception e){
}
}//GEN-LAST:event_ReviewPanel_ProcessButtonActionPerformed
private void LoadProblemMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_LoadProblemMenuItemActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_LoadProblemMenuItemActionPerformed
private void BatchLoadMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BatchLoadMenuItemActionPerformed
FileChoser = new JFileChooser(filepath);
int choice = FileChoser.showOpenDialog(JGAAP_UI_MainForm.this);
if (choice == JFileChooser.APPROVE_OPTION)
{
try
{
filepath = FileChoser.getSelectedFile().getCanonicalPath();
List<List<String>> DocumentCSVs = CSVIO.readCSV(filepath);
for (int i = 0; i < DocumentCSVs.size(); i++)
{
JGAAP_API.addDocument(DocumentCSVs.get(i).get(1),DocumentCSVs.get(i).get(0),(DocumentCSVs.get(i).size()>2?DocumentCSVs.get(i).get(2):null));
}
UpdateKnownDocumentsTree();
UpdateUnknownDocumentsTable();
}
catch (Exception e)
{
}
}
}//GEN-LAST:event_BatchLoadMenuItemActionPerformed
private void BatchSaveMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BatchSaveMenuItemActionPerformed
FileChoser = new JFileChooser(filepath);
int choice = FileChoser.showSaveDialog(JGAAP_UI_MainForm.this);
if (choice == JFileChooser.APPROVE_OPTION)
{
try
{
filepath = FileChoser.getSelectedFile().getCanonicalPath();
List<List<String>> DocumentCSVs = new ArrayList<List<String>>();
DocumentList = JGAAP_API.getDocuments();
for (int i = 0; i < DocumentList.size(); i++)
{
List<String> doc = new ArrayList<String>();
if (DocumentList.get(i).getAuthor() != null)
{
doc.add(DocumentList.get(i).getAuthor());
}
else
{
doc.add("");
}
doc.add(DocumentList.get(i).getFilePath());
doc.add(DocumentList.get(i).getTitle());
DocumentCSVs.add(doc);
}
CSVIO.writeCSV(DocumentCSVs, filepath);
}
catch (Exception e)
{
}
}
}//GEN-LAST:event_BatchSaveMenuItemActionPerformed
private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitMenuItemActionPerformed
dispose();
System.exit(0);
}//GEN-LAST:event_exitMenuItemActionPerformed
private void helpCloseButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_helpCloseButtonActionPerformed
toggleHelpDialog();
}//GEN-LAST:event_helpCloseButtonActionPerformed
private void jLabel23MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel23MouseClicked
browseToURL("http://evllabs.com");
}//GEN-LAST:event_jLabel23MouseClicked
private void jLabel25MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel25MouseClicked
if(!browseToURL("http://jgaap.com")){
browseToURL("http://server8.mathcomp.duq.edu/jgaap/w");
}
}//GEN-LAST:event_jLabel25MouseClicked
private void aboutMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_aboutMenuItemActionPerformed
toggleHelpDialog();
}//GEN-LAST:event_aboutMenuItemActionPerformed
private void AnalysisMethodPanel_AnalysisMethodsListBoxMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_AnalysisMethodPanel_AnalysisMethodsListBoxMouseMoved
JList theList = (JList) evt.getSource();
int index = theList.locationToIndex(evt.getPoint());
if (index > -1)
{
String text = AnalysisDriverMasterList.get(index).tooltipText();
theList.setToolTipText(text);
}
}//GEN-LAST:event_AnalysisMethodPanel_AnalysisMethodsListBoxMouseMoved
private void AnalysisMethodPanel_AnalysisMethodsListBoxMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_AnalysisMethodPanel_AnalysisMethodsListBoxMouseClicked
AnalysisMethodPanel_AnalysisMethodDescriptionTextBox.setText(AnalysisDriverMasterList.get(AnalysisMethodPanel_AnalysisMethodsListBox.getSelectedIndex()).longDescription());
if (evt.getClickCount() == 2)
{
AddAnalysisMethodSelection();
}
}//GEN-LAST:event_AnalysisMethodPanel_AnalysisMethodsListBoxMouseClicked
private void AnalysisMethodPanel_RemoveAllAnalysisMethodsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AnalysisMethodPanel_RemoveAllAnalysisMethodsButtonActionPerformed
JGAAP_API.removeAllAnalysisDrivers();
UpdateSelectedAnalysisMethodListBox();
}//GEN-LAST:event_AnalysisMethodPanel_RemoveAllAnalysisMethodsButtonActionPerformed
private void AnalysisMethodPanel_AddAllAnalysisMethodsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AnalysisMethodPanel_AddAllAnalysisMethodsButtonActionPerformed
try{
for (int i = 0; i < AnalysisDriverMasterList.size(); i++) {
JGAAP_API.addAnalysisDriver(AnalysisDriverMasterList.get(i).displayName());
}
UpdateSelectedAnalysisMethodListBox();
} catch (Exception e){
System.out.println(e.getMessage());
}
}//GEN-LAST:event_AnalysisMethodPanel_AddAllAnalysisMethodsButtonActionPerformed
private void AnalysisMethodPanel_RemoveAnalysisMethodsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AnalysisMethodPanel_RemoveAnalysisMethodsButtonActionPerformed
RemoveAnalysisMethodSelection();
}//GEN-LAST:event_AnalysisMethodPanel_RemoveAnalysisMethodsButtonActionPerformed
private void RemoveAnalysisMethodSelection() {
SelectedAnalysisDriverList = JGAAP_API.getAnalysisDrivers();
JGAAP_API.removeAnalysisDriver(SelectedAnalysisDriverList.get(AnalysisMethodPanel_SelectedAnalysisMethodsListBox.getSelectedIndex()));
UpdateSelectedAnalysisMethodListBox();
}
private void AnalysisMethodPanel_AddAnalysisMethodButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AnalysisMethodPanel_AddAnalysisMethodButtonActionPerformed
AddAnalysisMethodSelection();
}//GEN-LAST:event_AnalysisMethodPanel_AddAnalysisMethodButtonActionPerformed
private void CheckMinimumRequirements() {
boolean OK = true;
if (DocumentList.isEmpty())
{
OK = false;
ReviewPanel_DocumentsLabel.setForeground(Color.RED);
}
else
{
ReviewPanel_DocumentsLabel.setForeground(Color.GREEN);
}
if (SelectedEventDriverList.isEmpty())
{
OK = false;
ReviewPanel_SelectedEventSetLabel.setForeground(Color.RED);
}
else
{
ReviewPanel_SelectedEventSetLabel.setForeground(Color.GREEN);
}
ReviewPanel_SelectedEventCullingLabel.setForeground(Color.GREEN);
if (SelectedAnalysisDriverList.isEmpty())
{
OK = false;
ReviewPanel_SelectedAnalysisMethodsLabel.setForeground(Color.RED);
}
else
{
ReviewPanel_SelectedAnalysisMethodsLabel.setForeground(Color.GREEN);
}
ReviewPanel_ProcessButton.setEnabled(OK);
}
private void AddAnalysisMethodSelection() {
try{
AnalysisDriver temp = JGAAP_API.addAnalysisDriver(AnalysisMethodPanel_AnalysisMethodsListBox.getSelectedValue().toString());
if (temp instanceof NeighborAnalysisDriver)
{
JGAAP_API.addDistanceFunction(AnalysisMethodPanel_DistanceFunctionsListBox.getSelectedValue().toString(), temp);
}
UpdateSelectedAnalysisMethodListBox();
} catch (Exception e){
System.out.println(e.getMessage());
}
}
private void AnalysisMethodPanel_SelectedAnalysisMethodsListBoxMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_AnalysisMethodPanel_SelectedAnalysisMethodsListBoxMouseMoved
JList theList = (JList) evt.getSource();
int index = theList.locationToIndex(evt.getPoint());
if (index > -1) {
String text = SelectedAnalysisDriverList.get(index).tooltipText();
theList.setToolTipText(text);
}
}//GEN-LAST:event_AnalysisMethodPanel_SelectedAnalysisMethodsListBoxMouseMoved
private void AnalysisMethodPanel_SelectedAnalysisMethodsListBoxMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_AnalysisMethodPanel_SelectedAnalysisMethodsListBoxMouseClicked
AnalysisDriver temp = SelectedAnalysisDriverList.get(AnalysisMethodPanel_SelectedAnalysisMethodsListBox.getSelectedIndex());
AnalysisMethodPanel_AMParametersPanel.removeAll();
AnalysisMethodPanel_DFParametersPanel.removeAll();
AnalysisMethodPanel_AMParametersPanel.setLayout(temp.getGUILayout(AnalysisMethodPanel_AMParametersPanel));
if (temp instanceof NeighborAnalysisDriver)
{
AnalysisMethodPanel_DFParametersPanel.setLayout(((NeighborAnalysisDriver)temp).getDistanceFunction().getGUILayout(AnalysisMethodPanel_DFParametersPanel));
}
AnalysisMethodPanel_AnalysisMethodDescriptionTextBox.setText(temp.longDescription());
if (temp instanceof NeighborAnalysisDriver)
{
AnalysisMethodPanel_DistanceFunctionDescriptionTextBox.setText(((NeighborAnalysisDriver)temp).getDistanceFunction().longDescription());
}
if (evt.getClickCount() == 2)
{
RemoveAnalysisMethodSelection();
}
}//GEN-LAST:event_AnalysisMethodPanel_SelectedAnalysisMethodsListBoxMouseClicked
private void EventCullingPanel_EventCullingListBoxMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_EventCullingPanel_EventCullingListBoxMouseMoved
JList theList = (JList) evt.getSource();
int index = theList.locationToIndex(evt.getPoint());
if (index > -1) {
String text = EventCullersMasterList.get(index).tooltipText();
theList.setToolTipText(text);
}
}//GEN-LAST:event_EventCullingPanel_EventCullingListBoxMouseMoved
private void EventCullingPanel_EventCullingListBoxMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_EventCullingPanel_EventCullingListBoxMouseClicked
EventCullingPanel_EventCullingDescriptionTextbox.setText(EventCullersMasterList.get(EventCullingPanel_EventCullingListBox.getSelectedIndex()).longDescription());
if (evt.getClickCount() == 2)
{
AddEventCullerSelection();
}
}//GEN-LAST:event_EventCullingPanel_EventCullingListBoxMouseClicked
private void EventCullingPanel_RemoveAllEventCullingButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EventCullingPanel_RemoveAllEventCullingButtonActionPerformed
JGAAP_API.removeAllEventCullers();
UpdateSelectedEventCullingListBox();
}//GEN-LAST:event_EventCullingPanel_RemoveAllEventCullingButtonActionPerformed
private void EventCullingPanel_AddAllEventCullingButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EventCullingPanel_AddAllEventCullingButtonActionPerformed
try{
for (int i = 0; i < EventCullersMasterList.size(); i++) {
JGAAP_API.addEventCuller(EventCullersMasterList.get(i).displayName());
}
UpdateSelectedEventCullingListBox();
} catch (Exception e){
System.out.println(e.getMessage());
} // TODO add your handling code here:
}//GEN-LAST:event_EventCullingPanel_AddAllEventCullingButtonActionPerformed
private void EventCullingPanel_RemoveEventCullingButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EventCullingPanel_RemoveEventCullingButtonActionPerformed
RemoveEventCullerSelection();
}//GEN-LAST:event_EventCullingPanel_RemoveEventCullingButtonActionPerformed
private void RemoveEventCullerSelection() {
SelectedEventCullersList = JGAAP_API.getEventCullers();
JGAAP_API.removeEventCuller(SelectedEventCullersList.get(EventCullingPanel_SelectedEventCullingListBox.getSelectedIndex()));
UpdateSelectedEventCullingListBox();
}
private void EventCullingPanel_AddEventCullingButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EventCullingPanel_AddEventCullingButtonActionPerformed
AddEventCullerSelection();
}//GEN-LAST:event_EventCullingPanel_AddEventCullingButtonActionPerformed
private void AddEventCullerSelection() {
try{
JGAAP_API.addEventCuller(EventCullingPanel_EventCullingListBox.getSelectedValue().toString());
UpdateSelectedEventCullingListBox();
} catch (Exception e){
System.out.println(e.getMessage());
}
}
private void EventCullingPanel_SelectedEventCullingListBoxMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_EventCullingPanel_SelectedEventCullingListBoxMouseMoved
JList theList = (JList) evt.getSource();
int index = theList.locationToIndex(evt.getPoint());
if (index > -1) {
String text = SelectedEventCullersList.get(index).tooltipText();
theList.setToolTipText(text);
}
}//GEN-LAST:event_EventCullingPanel_SelectedEventCullingListBoxMouseMoved
private void EventCullingPanel_SelectedEventCullingListBoxMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_EventCullingPanel_SelectedEventCullingListBoxMouseClicked
EventCullingPanel_ParametersPanel.removeAll();
EventCullingPanel_ParametersPanel.setLayout(SelectedEventCullersList.get(EventCullingPanel_SelectedEventCullingListBox.getSelectedIndex()).getGUILayout(EventCullingPanel_ParametersPanel));
EventCullingPanel_EventCullingDescriptionTextbox.setText(SelectedEventCullersList.get(EventCullingPanel_SelectedEventCullingListBox.getSelectedIndex()).longDescription());
if (evt.getClickCount() == 2)
{
RemoveEventCullerSelection();
}
}//GEN-LAST:event_EventCullingPanel_SelectedEventCullingListBoxMouseClicked
private void EventSetsPanel_RemoveAllEventSetsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EventSetsPanel_RemoveAllEventSetsButtonActionPerformed
JGAAP_API.removeAllEventDrivers();
UpdateSelectedEventSetListBox();
}//GEN-LAST:event_EventSetsPanel_RemoveAllEventSetsButtonActionPerformed
private void EventSetsPanel_AddAllEventSetsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EventSetsPanel_AddAllEventSetsButtonActionPerformed
try{
for (int i = 0; i < EventDriverMasterList.size(); i++) {
JGAAP_API.addEventDriver(EventDriverMasterList.get(i).displayName());
}
UpdateSelectedEventSetListBox();
} catch (Exception e){
System.out.println(e.getMessage());
}
}//GEN-LAST:event_EventSetsPanel_AddAllEventSetsButtonActionPerformed
private void EventSetsPanel_RemoveEventSetButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EventSetsPanel_RemoveEventSetButtonActionPerformed
RemoveEventSetSelection();
}//GEN-LAST:event_EventSetsPanel_RemoveEventSetButtonActionPerformed
private void RemoveEventSetSelection()
{
SelectedEventDriverList = JGAAP_API.getEventDrivers();
JGAAP_API.removeEventDriver(SelectedEventDriverList.get(EventSetsPanel_SelectedEventSetListBox.getSelectedIndex()));
UpdateSelectedEventSetListBox();
}
private void EventSetsPanel_AddEventSetButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EventSetsPanel_AddEventSetButtonActionPerformed
AddEventSetSelection();
}//GEN-LAST:event_EventSetsPanel_AddEventSetButtonActionPerformed
private void AddEventSetSelection()
{
try{
JGAAP_API.addEventDriver(EventSetsPanel_EventSetListBox.getSelectedValue().toString());
UpdateSelectedEventSetListBox();
} catch (Exception e){
System.out.println(e.getMessage());
}
}
private void EventSetsPanel_SelectedEventSetListBoxMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_EventSetsPanel_SelectedEventSetListBoxMouseMoved
JList theList = (JList) evt.getSource();
int index = theList.locationToIndex(evt.getPoint());
if (index > -1) {
String text = SelectedEventDriverList.get(index).tooltipText();
theList.setToolTipText(text);
}
}//GEN-LAST:event_EventSetsPanel_SelectedEventSetListBoxMouseMoved
private void EventSetsPanel_SelectedEventSetListBoxMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_EventSetsPanel_SelectedEventSetListBoxMouseClicked
EventSetsPanel_ParametersPanel.removeAll();
EventSetsPanel_ParametersPanel.setLayout(SelectedEventDriverList.get(EventSetsPanel_SelectedEventSetListBox.getSelectedIndex()).getGUILayout(EventSetsPanel_ParametersPanel));
EventSetsPanel_EventSetDescriptionTextBox.setText(SelectedEventDriverList.get(EventSetsPanel_SelectedEventSetListBox.getSelectedIndex()).longDescription());
if (evt.getClickCount() == 2)
{
RemoveEventSetSelection();
}
}//GEN-LAST:event_EventSetsPanel_SelectedEventSetListBoxMouseClicked
private void EventSetsPanel_EventSetListBoxMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_EventSetsPanel_EventSetListBoxMouseMoved
JList theList = (JList) evt.getSource();
int index = theList.locationToIndex(evt.getPoint());
if (index > -1) {
String text = EventDriverMasterList.get(index).tooltipText();
theList.setToolTipText(text);
}
}//GEN-LAST:event_EventSetsPanel_EventSetListBoxMouseMoved
private void EventSetsPanel_EventSetListBoxMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_EventSetsPanel_EventSetListBoxMouseClicked
EventSetsPanel_EventSetDescriptionTextBox.setText(EventDriverMasterList.get(EventSetsPanel_EventSetListBox.getSelectedIndex()).longDescription());
if (evt.getClickCount() == 2)
{
AddEventSetSelection();
}
}//GEN-LAST:event_EventSetsPanel_EventSetListBoxMouseClicked
private void CanonicizersPanel_RemoveAllCanonicizersButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CanonicizersPanel_RemoveAllCanonicizersButtonActionPerformed
SelectedCanonicizerList.clear();
UpdateSelectedCanonicizerListBox();
}//GEN-LAST:event_CanonicizersPanel_RemoveAllCanonicizersButtonActionPerformed
private void CanonicizersPanel_AddAllCanonicizersButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CanonicizersPanel_AddAllCanonicizersButtonActionPerformed
try{
for (int i = 0; i < CanonicizerMasterList.size(); i++){
Canonicizer temp = CanonicizerMasterList.get(i).getClass().newInstance();
SelectedCanonicizerList.add(temp);
}
UpdateSelectedCanonicizerListBox();
} catch (Exception e){
System.out.println(e.getMessage());
}
}//GEN-LAST:event_CanonicizersPanel_AddAllCanonicizersButtonActionPerformed
private void CanonicizersPanel_RemoveCanonicizerButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CanonicizersPanel_RemoveCanonicizerButtonActionPerformed
RemoveCanonicizerSelection();
}//GEN-LAST:event_CanonicizersPanel_RemoveCanonicizerButtonActionPerformed
private void RemoveCanonicizerSelection() {
SelectedCanonicizerList.remove(CanonicizersPanel_SelectedCanonicizerListBox.getSelectedIndex());
UpdateSelectedCanonicizerListBox();
}
private void CanonicizersPanel_AddCanonicizerButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CanonicizersPanel_AddCanonicizerButtonActionPerformed
AddCanonicizerSelection();
}//GEN-LAST:event_CanonicizersPanel_AddCanonicizerButtonActionPerformed
private void AddCanonicizerSelection()
{
try{
for (int i = 0; i < CanonicizerMasterList.size(); i++){
if (CanonicizerMasterList.get(i).displayName().equals(CanonicizersPanel_CanonicizerListBox.getSelectedValue().toString())){
Canonicizer temp = CanonicizerMasterList.get(i).getClass().newInstance();
SelectedCanonicizerList.add(temp);
UpdateSelectedCanonicizerListBox();
}
}
} catch (Exception e){
System.out.println(e.getMessage());
}
}
private void CanonicizersPanel_SelectedCanonicizerListBoxMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_CanonicizersPanel_SelectedCanonicizerListBoxMouseMoved
JList theList = (JList) evt.getSource();
int index = theList.locationToIndex(evt.getPoint());
if (index > -1) {
String text = SelectedCanonicizerList.get(index).tooltipText();
theList.setToolTipText(text);
}
}//GEN-LAST:event_CanonicizersPanel_SelectedCanonicizerListBoxMouseMoved
private void CanonicizersPanel_SelectedCanonicizerListBoxMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_CanonicizersPanel_SelectedCanonicizerListBoxMouseClicked
CanonicizersPanel_DocumentsCanonicizerDescriptionTextBox.setText(SelectedCanonicizerList.get(CanonicizersPanel_SelectedCanonicizerListBox.getSelectedIndex()).longDescription());
if (evt.getClickCount() == 2)
{
RemoveCanonicizerSelection();
}
}//GEN-LAST:event_CanonicizersPanel_SelectedCanonicizerListBoxMouseClicked
private void CanonicizersPanel_CanonicizerListBoxMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_CanonicizersPanel_CanonicizerListBoxMouseMoved
JList theList = (JList) evt.getSource();
int index = theList.locationToIndex(evt.getPoint());
if (index > -1) {
String text = CanonicizerMasterList.get(index).tooltipText();
theList.setToolTipText(text);
}
}//GEN-LAST:event_CanonicizersPanel_CanonicizerListBoxMouseMoved
private void CanonicizersPanel_CanonicizerListBoxMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_CanonicizersPanel_CanonicizerListBoxMouseClicked
CanonicizersPanel_DocumentsCanonicizerDescriptionTextBox.setText(CanonicizerMasterList.get(CanonicizersPanel_CanonicizerListBox.getSelectedIndex()).longDescription());
if (evt.getClickCount() == 2)
{
AddCanonicizerSelection();
}
}//GEN-LAST:event_CanonicizersPanel_CanonicizerListBoxMouseClicked
private void DocumentsPanel_LanguageComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DocumentsPanel_LanguageComboBoxActionPerformed
try {
JGAAP_API.setLanguage(DocumentsPanel_LanguageComboBox.getSelectedItem().toString());
} catch (Exception e) {
}
}//GEN-LAST:event_DocumentsPanel_LanguageComboBoxActionPerformed
private void DocumentsPanel_RemoveAuthorButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DocumentsPanel_RemoveAuthorButtonActionPerformed
TreePath Path = DocumentsPanel_KnownAuthorsTree.getSelectionPath();
String AuthorName;
if(Path.getPathCount() != 1) {
AuthorName = Path.getPathComponent(1).toString();
KnownDocumentList = JGAAP_API.getDocumentsByAuthor(AuthorName);
for (int i = KnownDocumentList.size() - 1; i >= 0; i--) {
JGAAP_API.removeDocument(KnownDocumentList.get(i));
}
UpdateKnownDocumentsTree();
} else {
}
}//GEN-LAST:event_DocumentsPanel_RemoveAuthorButtonActionPerformed
private void DocumentsPanel_EditAuthorButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DocumentsPanel_EditAuthorButtonActionPerformed
TreePath Path = DocumentsPanel_KnownAuthorsTree.getSelectionPath();
String AuthorName;
if(Path.getPathCount() != 1) {
AuthorName = Path.getPathComponent(1).toString();
JGAAP_UI_AddAuthorDialog AddAuthorDialog= new JGAAP_UI_AddAuthorDialog(JGAAP_UI_MainForm.this, true, JGAAP_API, AuthorName, filepath);
AddAuthorDialog.setVisible(true);
UpdateKnownDocumentsTree();
} else {
}
}//GEN-LAST:event_DocumentsPanel_EditAuthorButtonActionPerformed
private void DocumentsPanel_AddAuthorButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DocumentsPanel_AddAuthorButtonActionPerformed
JGAAP_UI_AddAuthorDialog AddAuthorDialog= new JGAAP_UI_AddAuthorDialog(JGAAP_UI_MainForm.this, true, JGAAP_API,"",filepath);
AddAuthorDialog.setVisible(true);
filepath = AddAuthorDialog.getFilePath();
UpdateKnownDocumentsTree();
}//GEN-LAST:event_DocumentsPanel_AddAuthorButtonActionPerformed
private void DocumentsPanel_RemoveDocumentsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DocumentsPanel_RemoveDocumentsButtonActionPerformed
UnknownDocumentList = JGAAP_API.getUnknownDocuments();
JGAAP_API.removeDocument(UnknownDocumentList.get(DocumentsPanel_UnknownAuthorsTable.getSelectedRow()));
UpdateUnknownDocumentsTable();
}//GEN-LAST:event_DocumentsPanel_RemoveDocumentsButtonActionPerformed
private void DocumentsPanel_AddDocumentsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DocumentsPanel_AddDocumentsButtonActionPerformed
FileChoser = new JFileChooser(filepath);
FileChoser.setMultiSelectionEnabled(true);
int choice = FileChoser.showOpenDialog(JGAAP_UI_MainForm.this);
if (choice == JFileChooser.APPROVE_OPTION) {
for(File file : FileChoser.getSelectedFiles()){
try {
JGAAP_API.addDocument(file.getCanonicalPath(), "","");
filepath = file.getCanonicalPath();
} catch (Exception e) {
//TODO: add error dialog here
}
UpdateUnknownDocumentsTable();
}
}
}//GEN-LAST:event_DocumentsPanel_AddDocumentsButtonActionPerformed
private void CanonicizersPanel_SetToDocumentButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CanonicizersPanel_SetToDocumentButtonActionPerformed
int row = CanonicizersPanel_DocumentsTable.getSelectedRow();
if (row >= 0) {
DocumentList = JGAAP_API.getDocuments();
Document temp = DocumentList.get(row);
temp.clearCanonicizers();
for (int i = 0; i < SelectedCanonicizerList.size(); i++) {
try {
JGAAP_API.addCanonicizer(SelectedCanonicizerList.get(i).displayName(),temp);
} catch (Exception e) {
}
}
UpdateCurrentCanonicizerBox();
UpdateDocumentsTable();
}
}//GEN-LAST:event_CanonicizersPanel_SetToDocumentButtonActionPerformed
private void CanonicizersPanel_SetToDocumentTypeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CanonicizersPanel_SetToDocumentTypeButtonActionPerformed
int row = CanonicizersPanel_DocumentsTable.getSelectedRow();
if (row >= 0) {
DocumentList = JGAAP_API.getDocuments();
Document temp = DocumentList.get(row);
temp.clearCanonicizers();
for (int i = 0; i < SelectedCanonicizerList.size(); i++) {
try {
JGAAP_API.addCanonicizer(SelectedCanonicizerList.get(i).displayName(),temp);
} catch (Exception e) {
}
}
UpdateCurrentCanonicizerBox();
UpdateDocumentsTable();
}
}//GEN-LAST:event_CanonicizersPanel_SetToDocumentTypeButtonActionPerformed
private void CanonicizersPanel_SetToAllDocumentsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CanonicizersPanel_SetToAllDocumentsActionPerformed
JGAAP_API.removeAllCanonicizers();
for (int i = 0; i < SelectedCanonicizerList.size(); i++) {
try {
JGAAP_API.addCanonicizer(SelectedCanonicizerList.get(i).displayName());
} catch (Exception e) {
}
}
UpdateCurrentCanonicizerBox();
UpdateDocumentsTable();
}//GEN-LAST:event_CanonicizersPanel_SetToAllDocumentsActionPerformed
private void DocumentsPanel_NotesButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DocumentsPanel_NotesButtonActionPerformed
try {
NotesPage.DisplayNote(Notes[0]);
NotesPage.setVisible(true);
if (NotesPage.SavedNote != null)
{
Notes[0] = NotesPage.SavedNote;
}
} catch (Exception e){
}
}//GEN-LAST:event_DocumentsPanel_NotesButtonActionPerformed
private void CanonicizersPanel_NotesButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CanonicizersPanel_NotesButtonActionPerformed
try {
NotesPage.DisplayNote(Notes[1]);
NotesPage.setVisible(true);
if (NotesPage.SavedNote != null)
{
Notes[1] = NotesPage.SavedNote;
}
} catch (Exception e){
}
}//GEN-LAST:event_CanonicizersPanel_NotesButtonActionPerformed
private void EventSetsPanel_NotesButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EventSetsPanel_NotesButtonActionPerformed
try {
NotesPage.DisplayNote(Notes[2]);
NotesPage.setVisible(true);
if (NotesPage.SavedNote != null)
{
Notes[2] = NotesPage.SavedNote;
}
} catch (Exception e){
}
}//GEN-LAST:event_EventSetsPanel_NotesButtonActionPerformed
private void EventCullingPanel_NotesButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EventCullingPanel_NotesButtonActionPerformed
try {
NotesPage.DisplayNote(Notes[3]);
NotesPage.setVisible(true);
if (NotesPage.SavedNote != null)
{
Notes[3] = NotesPage.SavedNote;
}
} catch (Exception e){
}
}//GEN-LAST:event_EventCullingPanel_NotesButtonActionPerformed
private void AnalysisMethodPanel_NotesButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AnalysisMethodPanel_NotesButtonActionPerformed
try {
NotesPage.DisplayNote(Notes[4]);
NotesPage.setVisible(true);
if (NotesPage.SavedNote != null)
{
Notes[4] = NotesPage.SavedNote;
}
} catch (Exception e){
}
}//GEN-LAST:event_AnalysisMethodPanel_NotesButtonActionPerformed
private void AnalysisMethodPanel_DistanceFunctionsListBoxMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_AnalysisMethodPanel_DistanceFunctionsListBoxMouseClicked
AnalysisMethodPanel_DistanceFunctionDescriptionTextBox.setText(DistanceFunctionsMasterList.get(AnalysisMethodPanel_DistanceFunctionsListBox.getSelectedIndex()).longDescription());
if (evt.getClickCount() == 2)
{
AddAnalysisMethodSelection();
}
}//GEN-LAST:event_AnalysisMethodPanel_DistanceFunctionsListBoxMouseClicked
private void AnalysisMethodPanel_DistanceFunctionsListBoxMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_AnalysisMethodPanel_DistanceFunctionsListBoxMouseMoved
JList theList = (JList) evt.getSource();
int index = theList.locationToIndex(evt.getPoint());
if (index > -1)
{
String text = DistanceFunctionsMasterList.get(index).tooltipText();
theList.setToolTipText(text);
}
}//GEN-LAST:event_AnalysisMethodPanel_DistanceFunctionsListBoxMouseMoved
private void Next_ButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Next_ButtonActionPerformed
int count = JGAAP_TabbedPane.getSelectedIndex();
if (count < 5)
{
JGAAP_TabbedPane.setSelectedIndex(count + 1);
}
}//GEN-LAST:event_Next_ButtonActionPerformed
private void Review_ButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Review_ButtonActionPerformed
JGAAP_TabbedPane.setSelectedIndex(5);
}//GEN-LAST:event_Review_ButtonActionPerformed
private void ProblemAMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ProblemAMenuItemActionPerformed
try
{
filepath = jgaapConstants.docsDir()+"aaac/Demos/loadA.csv";
List<List<String>> DocumentCSVs = CSVIO.readCSV(filepath);
for (int i = 0; i < DocumentCSVs.size(); i++)
{
JGAAP_API.addDocument(DocumentCSVs.get(i).get(1),DocumentCSVs.get(i).get(0),(DocumentCSVs.get(i).size()>2?DocumentCSVs.get(i).get(2):null));
}
UpdateKnownDocumentsTree();
UpdateUnknownDocumentsTable();
}
catch (Exception e)
{
}
}//GEN-LAST:event_ProblemAMenuItemActionPerformed
private void ProblemBMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ProblemBMenuItemActionPerformed
try
{
filepath = jgaapConstants.docsDir()+"aaac/Demos/loadB.csv";
List<List<String>> DocumentCSVs = CSVIO.readCSV(filepath);
for (int i = 0; i < DocumentCSVs.size(); i++)
{
JGAAP_API.addDocument(DocumentCSVs.get(i).get(1),DocumentCSVs.get(i).get(0),(DocumentCSVs.get(i).size()>2?DocumentCSVs.get(i).get(2):null));
}
UpdateKnownDocumentsTree();
UpdateUnknownDocumentsTable();
}
catch (Exception e)
{
}
}//GEN-LAST:event_ProblemBMenuItemActionPerformed
private void ProblemCMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ProblemCMenuItemActionPerformed
try
{
filepath = jgaapConstants.docsDir()+"aaac/Demos/loadC.csv";
List<List<String>> DocumentCSVs = CSVIO.readCSV(filepath);
for (int i = 0; i < DocumentCSVs.size(); i++)
{
JGAAP_API.addDocument(DocumentCSVs.get(i).get(1),DocumentCSVs.get(i).get(0),(DocumentCSVs.get(i).size()>2?DocumentCSVs.get(i).get(2):null));
}
UpdateKnownDocumentsTree();
UpdateUnknownDocumentsTable();
}
catch (Exception e)
{
}
}//GEN-LAST:event_ProblemCMenuItemActionPerformed
private void ProblemDMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ProblemDMenuItemActionPerformed
try
{
filepath = jgaapConstants.docsDir()+"aaac/Demos/loadD.csv";
List<List<String>> DocumentCSVs = CSVIO.readCSV(filepath);
for (int i = 0; i < DocumentCSVs.size(); i++)
{
JGAAP_API.addDocument(DocumentCSVs.get(i).get(1),DocumentCSVs.get(i).get(0),(DocumentCSVs.get(i).size()>2?DocumentCSVs.get(i).get(2):null));
}
UpdateKnownDocumentsTree();
UpdateUnknownDocumentsTable();
}
catch (Exception e)
{
}
}//GEN-LAST:event_ProblemDMenuItemActionPerformed
private void ProblemEMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ProblemEMenuItemActionPerformed
try
{
filepath = jgaapConstants.docsDir()+"aaac/Demos/loadE.csv";
List<List<String>> DocumentCSVs = CSVIO.readCSV(filepath);
for (int i = 0; i < DocumentCSVs.size(); i++)
{
JGAAP_API.addDocument(DocumentCSVs.get(i).get(1),DocumentCSVs.get(i).get(0),(DocumentCSVs.get(i).size()>2?DocumentCSVs.get(i).get(2):null));
}
UpdateKnownDocumentsTree();
UpdateUnknownDocumentsTable();
}
catch (Exception e)
{
}
}//GEN-LAST:event_ProblemEMenuItemActionPerformed
private void ProblemFMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ProblemFMenuItemActionPerformed
try
{
filepath = jgaapConstants.docsDir()+"aaac/Demos/loadF.csv";
List<List<String>> DocumentCSVs = CSVIO.readCSV(filepath);
for (int i = 0; i < DocumentCSVs.size(); i++)
{
JGAAP_API.addDocument(DocumentCSVs.get(i).get(1),DocumentCSVs.get(i).get(0),(DocumentCSVs.get(i).size()>2?DocumentCSVs.get(i).get(2):null));
}
UpdateKnownDocumentsTree();
UpdateUnknownDocumentsTable();
}
catch (Exception e)
{
}
}//GEN-LAST:event_ProblemFMenuItemActionPerformed
private void ProblemGMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ProblemGMenuItemActionPerformed
try
{
filepath = jgaapConstants.docsDir()+"aaac/Demos/loadG.csv";
List<List<String>> DocumentCSVs = CSVIO.readCSV(filepath);
for (int i = 0; i < DocumentCSVs.size(); i++)
{
JGAAP_API.addDocument(DocumentCSVs.get(i).get(1),DocumentCSVs.get(i).get(0),(DocumentCSVs.get(i).size()>2?DocumentCSVs.get(i).get(2):null));
}
UpdateKnownDocumentsTree();
UpdateUnknownDocumentsTable();
}
catch (Exception e)
{
}
}//GEN-LAST:event_ProblemGMenuItemActionPerformed
private void ProblemHMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ProblemHMenuItemActionPerformed
try
{
filepath = jgaapConstants.docsDir()+"aaac/Demos/loadH.csv";
List<List<String>> DocumentCSVs = CSVIO.readCSV(filepath);
for (int i = 0; i < DocumentCSVs.size(); i++)
{
JGAAP_API.addDocument(DocumentCSVs.get(i).get(1),DocumentCSVs.get(i).get(0),(DocumentCSVs.get(i).size()>2?DocumentCSVs.get(i).get(2):null));
}
UpdateKnownDocumentsTree();
UpdateUnknownDocumentsTable();
}
catch (Exception e)
{
}
}//GEN-LAST:event_ProblemHMenuItemActionPerformed
private void ProblemIMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ProblemIMenuItemActionPerformed
try
{
filepath = jgaapConstants.docsDir()+"aaac/Demos/loadI.csv";
List<List<String>> DocumentCSVs = CSVIO.readCSV(filepath);
for (int i = 0; i < DocumentCSVs.size(); i++)
{
JGAAP_API.addDocument(DocumentCSVs.get(i).get(1),DocumentCSVs.get(i).get(0),(DocumentCSVs.get(i).size()>2?DocumentCSVs.get(i).get(2):null));
}
UpdateKnownDocumentsTree();
UpdateUnknownDocumentsTable();
}
catch (Exception e)
{
}
}//GEN-LAST:event_ProblemIMenuItemActionPerformed
private void ProblemJMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ProblemJMenuItemActionPerformed
try
{
filepath = jgaapConstants.docsDir()+"aaac/Demos/loadJ.csv";
List<List<String>> DocumentCSVs = CSVIO.readCSV(filepath);
for (int i = 0; i < DocumentCSVs.size(); i++)
{
JGAAP_API.addDocument(DocumentCSVs.get(i).get(1),DocumentCSVs.get(i).get(0),(DocumentCSVs.get(i).size()>2?DocumentCSVs.get(i).get(2):null));
}
UpdateKnownDocumentsTree();
UpdateUnknownDocumentsTable();
}
catch (Exception e)
{
}
}//GEN-LAST:event_ProblemJMenuItemActionPerformed
private void ProblemKMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ProblemKMenuItemActionPerformed
try
{
filepath = jgaapConstants.docsDir()+"aaac/Demos/loadK.csv";
List<List<String>> DocumentCSVs = CSVIO.readCSV(filepath);
for (int i = 0; i < DocumentCSVs.size(); i++)
{
JGAAP_API.addDocument(DocumentCSVs.get(i).get(1),DocumentCSVs.get(i).get(0),(DocumentCSVs.get(i).size()>2?DocumentCSVs.get(i).get(2):null));
}
UpdateKnownDocumentsTree();
UpdateUnknownDocumentsTable();
}
catch (Exception e)
{
}
}//GEN-LAST:event_ProblemKMenuItemActionPerformed
private void ProblemLMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ProblemLMenuItemActionPerformed
try
{
filepath = jgaapConstants.docsDir()+"aaac/Demos/loadL.csv";
List<List<String>> DocumentCSVs = CSVIO.readCSV(filepath);
for (int i = 0; i < DocumentCSVs.size(); i++)
{
JGAAP_API.addDocument(DocumentCSVs.get(i).get(1),DocumentCSVs.get(i).get(0),(DocumentCSVs.get(i).size()>2?DocumentCSVs.get(i).get(2):null));
}
UpdateKnownDocumentsTree();
UpdateUnknownDocumentsTable();
}
catch (Exception e)
{
}
}//GEN-LAST:event_ProblemLMenuItemActionPerformed
private void ProblemMMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ProblemMMenuItemActionPerformed
try
{
filepath = jgaapConstants.docsDir()+"aaac/Demos/loadM.csv";
List<List<String>> DocumentCSVs = CSVIO.readCSV(filepath);
for (int i = 0; i < DocumentCSVs.size(); i++)
{
JGAAP_API.addDocument(DocumentCSVs.get(i).get(1),DocumentCSVs.get(i).get(0),(DocumentCSVs.get(i).size()>2?DocumentCSVs.get(i).get(2):null));
}
UpdateKnownDocumentsTree();
UpdateUnknownDocumentsTable();
}
catch (Exception e)
{
}
}//GEN-LAST:event_ProblemMMenuItemActionPerformed
private void ReviewPanel_DocumentsLabelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ReviewPanel_DocumentsLabelMouseClicked
JGAAP_TabbedPane.setSelectedIndex(0);
}//GEN-LAST:event_ReviewPanel_DocumentsLabelMouseClicked
private void ReviewPanel_DocumentsTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ReviewPanel_DocumentsTableMouseClicked
JGAAP_TabbedPane.setSelectedIndex(0);
}//GEN-LAST:event_ReviewPanel_DocumentsTableMouseClicked
private void ReviewPanel_SelectedEventSetLabelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ReviewPanel_SelectedEventSetLabelMouseClicked
JGAAP_TabbedPane.setSelectedIndex(2);
}//GEN-LAST:event_ReviewPanel_SelectedEventSetLabelMouseClicked
private void ReviewPanel_SelectedEventSetListBoxMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ReviewPanel_SelectedEventSetListBoxMouseClicked
JGAAP_TabbedPane.setSelectedIndex(2);
}//GEN-LAST:event_ReviewPanel_SelectedEventSetListBoxMouseClicked
private void ReviewPanel_SelectedEventCullingLabelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ReviewPanel_SelectedEventCullingLabelMouseClicked
JGAAP_TabbedPane.setSelectedIndex(3);
}//GEN-LAST:event_ReviewPanel_SelectedEventCullingLabelMouseClicked
private void ReviewPanel_SelectedEventCullingListBoxMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ReviewPanel_SelectedEventCullingListBoxMouseClicked
JGAAP_TabbedPane.setSelectedIndex(3);
}//GEN-LAST:event_ReviewPanel_SelectedEventCullingListBoxMouseClicked
private void ReviewPanel_SelectedAnalysisMethodsLabelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ReviewPanel_SelectedAnalysisMethodsLabelMouseClicked
JGAAP_TabbedPane.setSelectedIndex(4);
}//GEN-LAST:event_ReviewPanel_SelectedAnalysisMethodsLabelMouseClicked
private void ReviewPanel_SelectedAnalysisMethodsListBoxMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ReviewPanel_SelectedAnalysisMethodsListBoxMouseClicked
JGAAP_TabbedPane.setSelectedIndex(4);
}//GEN-LAST:event_ReviewPanel_SelectedAnalysisMethodsListBoxMouseClicked
private void toggleHelpDialog(){
helpDialog.setVisible(!helpDialog.isVisible());
}
public boolean browseToURL(String url){
boolean succees = false;
try {
java.awt.Desktop.getDesktop().browse(java.net.URI.create(url));
succees = true;
} catch (IOException ex) {
ex.printStackTrace();
}
return succees;
}
private void UpdateSelectedAnalysisMethodListBox()
{
SelectedAnalysisMethodListBox_Model.clear();
SelectedAnalysisDriverList = JGAAP_API.getAnalysisDrivers();
for (int i = 0; i < SelectedAnalysisDriverList.size(); i++)
{
SelectedAnalysisMethodListBox_Model.addElement(SelectedAnalysisDriverList.get(i).displayName());
}
CheckMinimumRequirements();
}
private void UpdateSelectedEventSetListBox()
{
SelectedEventSetsListBox_Model.clear();
SelectedEventDriverList = JGAAP_API.getEventDrivers();
for (int i = 0; i < SelectedEventDriverList.size(); i++)
{
SelectedEventSetsListBox_Model.addElement(SelectedEventDriverList.get(i).displayName());
}
CheckMinimumRequirements();
}
private void UpdateSelectedEventCullingListBox()
{
SelectedEventCullingListBox_Model.clear();
SelectedEventCullersList = JGAAP_API.getEventCullers();
for (int i = 0; i < SelectedEventCullersList.size(); i++)
{
SelectedEventCullingListBox_Model.addElement(SelectedEventCullersList.get(i).displayName());
}
}
private void UpdateSelectedCanonicizerListBox() {
SelectedCanonicizerListBox_Model.clear();
for (int i = 0; i < SelectedCanonicizerList.size(); i++)
{
SelectedCanonicizerListBox_Model.addElement(SelectedCanonicizerList.get(i).displayName());
}
}
private void UpdateUnknownDocumentsTable() {
UnknownAuthorDocumentsTable_Model.setRowCount(0);
UnknownDocumentList = JGAAP_API.getUnknownDocuments();
for (int i = 0; i < UnknownDocumentList.size(); i++)
{
Object RowData[] = {UnknownDocumentList.get(i).getTitle(), UnknownDocumentList.get(i).getFilePath()};
UnknownAuthorDocumentsTable_Model.addRow(RowData);
}
UpdateDocumentsTable();
}
private void UpdateKnownDocumentsTree() {
DefaultMutableTreeNode root = (DefaultMutableTreeNode) KnownAuthorsTree_Model.getRoot();
for (int i = root.getChildCount() - 1; i >= 0; i--)
{
KnownAuthorsTree_Model.removeNodeFromParent((DefaultMutableTreeNode)root.getChildAt(i));
}
AuthorList = JGAAP_API.getAuthors();
for (int i = 0; i < AuthorList.size(); i++)
{
String AuthorName = AuthorList.get(i);
DefaultMutableTreeNode author = new DefaultMutableTreeNode(AuthorName);
KnownAuthorsTree_Model.insertNodeInto(author, root, i);
//root.add(author);
KnownDocumentList = JGAAP_API.getDocumentsByAuthor(AuthorName);
for (int j = 0; j < KnownDocumentList.size(); j++)
{
//author.add(new DefaultMutableTreeNode(KnownDocumentList.get(j).getTitle() + " - " + KnownDocumentList.get(j).getFilePath()));
DefaultMutableTreeNode temp = new DefaultMutableTreeNode(KnownDocumentList.get(j).getTitle() + " - " + KnownDocumentList.get(j).getFilePath());
KnownAuthorsTree_Model.insertNodeInto(temp, author, j);
}
}
UpdateDocumentsTable();
}
private void UpdateDocumentsTable() {
String CanonPresent = "No";
DocumentsTable_Model.setRowCount(0);
DocumentList = JGAAP_API.getDocuments();
for (int i = 0; i < DocumentList.size(); i++)
{
if (DocumentList.get(i).getCanonicizers().isEmpty())
{
CanonPresent = "No";
}
else
{
CanonPresent = "Yes";
}
Object RowData[] = {DocumentList.get(i).getTitle(), DocumentList.get(i).isAuthorKnown(), DocumentList.get(i).getAuthor(), DocumentList.get(i).getDocType(), CanonPresent};
DocumentsTable_Model.addRow(RowData);
}
CheckMinimumRequirements();
}
private void UpdateCurrentCanonicizerBox() {
int row = CanonicizersPanel_DocumentsTable.getSelectedRow();
if (row >= 0)
{
DocumentList = JGAAP_API.getDocuments();
List<Canonicizer> tempList = DocumentList.get(row).getCanonicizers();
String tempString = "";
for (int i = 0; i < tempList.size(); i++)
{
tempString = tempString + tempList.get(i).displayName() + "\r\n";
}
CanonicizersPanel_DocumentsCurrentCanonicizersTextBox.setText(tempString);
}
}
private void SanatizeMasterLists() {
for (int i = AnalysisDriverMasterList.size() - 1; i >= 0; i--)
{
if (!AnalysisDriverMasterList.get(i).showInGUI())
{
AnalysisDriverMasterList.remove(i);
}
}
for (int i = CanonicizerMasterList.size() - 1; i >= 0; i--)
{
if (!CanonicizerMasterList.get(i).showInGUI())
{
CanonicizerMasterList.remove(i);
}
}
for (int i = EventDriverMasterList.size() - 1; i >= 0; i--)
{
if (!EventDriverMasterList.get(i).showInGUI())
{
EventDriverMasterList.remove(i);
}
}
for (int i = EventCullersMasterList.size() - 1; i >= 0; i--)
{
if (!EventCullersMasterList.get(i).showInGUI())
{
EventCullersMasterList.remove(i);
}
}
for (int i = DistanceFunctionsMasterList.size() - 1; i >= 0; i--)
{
if (!DistanceFunctionsMasterList.get(i).showInGUI())
{
DistanceFunctionsMasterList.remove(i);
}
}
for (int i = LanguagesMasterList.size() - 1; i >= 0; i--)
{
if (!LanguagesMasterList.get(i).showInGUI())
{
LanguagesMasterList.remove(i);
}
}
}
private void SetAnalysisMethodList() {
for (int i = 0; i < AnalysisDriverMasterList.size(); i++)
{
AnalysisMethodListBox_Model.addElement(AnalysisDriverMasterList.get(i).displayName());
}
if (!AnalysisDriverMasterList.isEmpty())
{
AnalysisMethodPanel_AnalysisMethodsListBox.setSelectedIndex(0);
AnalysisMethodPanel_AnalysisMethodDescriptionTextBox.setText(AnalysisDriverMasterList.get(0).longDescription());
}
}
private void SetDistanceFunctionList() {
for (int i = 0; i < DistanceFunctionsMasterList.size(); i++)
{
DistanceFunctionsListBox_Model.addElement(DistanceFunctionsMasterList.get(i).displayName());
}
if (!DistanceFunctionsMasterList.isEmpty())
{
AnalysisMethodPanel_DistanceFunctionsListBox.setSelectedIndex(0);
AnalysisMethodPanel_DistanceFunctionDescriptionTextBox.setText(DistanceFunctionsMasterList.get(0).longDescription());
}
}
private void SetCanonicizerList() {
for (int i = 0; i < CanonicizerMasterList.size(); i++)
{
CanonicizerListBox_Model.addElement(CanonicizerMasterList.get(i).displayName());
}
if (!CanonicizerMasterList.isEmpty())
{
CanonicizersPanel_CanonicizerListBox.setSelectedIndex(0);
CanonicizersPanel_DocumentsCurrentCanonicizersTextBox.setText(CanonicizerMasterList.get(0).longDescription());
}
}
private void SetEventCullingList() {
for (int i = 0; i < EventCullersMasterList.size(); i++)
{
EventCullingListBox_Model.addElement(EventCullersMasterList.get(i).displayName());
}
if (!EventCullersMasterList.isEmpty())
{
EventCullingPanel_EventCullingListBox.setSelectedIndex(0);
EventCullingPanel_EventCullingDescriptionTextbox.setText(EventCullersMasterList.get(0).longDescription());
}
}
private void SetLanguagesList() {
int englishIndex = -1;
for (int i = 0; i < LanguagesMasterList.size(); i++)
{
LanguageComboBox_Model.addElement(LanguagesMasterList.get(i).displayName());
if (LanguagesMasterList.get(i).displayName().equalsIgnoreCase("English"))
{
englishIndex = i;
}
}
if (englishIndex > -1)
{
DocumentsPanel_LanguageComboBox.setSelectedIndex(englishIndex);
}
}
private void SetEventSetList() {
for (int i = 0; i < EventDriverMasterList.size(); i++)
{
EventSetsListBox_Model.addElement(EventDriverMasterList.get(i).displayName());
}
if (!EventDriverMasterList.isEmpty())
{
EventSetsPanel_EventSetListBox.setSelectedIndex(0);
EventSetsPanel_EventSetDescriptionTextBox.setText(EventDriverMasterList.get(0).longDescription());
}
}
private void SetUnknownDocumentColumns() {
UnknownAuthorDocumentsTable_Model.addColumn("Title");
UnknownAuthorDocumentsTable_Model.addColumn("Filepath");
DocumentsPanel_UnknownAuthorsTable.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
DocumentsPanel_UnknownAuthorsTable.setColumnSelectionAllowed(false);
DocumentsPanel_UnknownAuthorsTable.setRowSelectionAllowed(true);
DocumentsPanel_UnknownAuthorsTable.getModel().addTableModelListener(new TableModelListener() {
public void tableChanged(TableModelEvent e)
{
System.out.println("Unknown Documents Table Row: " + e.getFirstRow() + ", Column: " + e.getColumn());
if ((e.getColumn() >= 0) && (e.getFirstRow() >= 0))
{
UnknownDocumentList = JGAAP_API.getUnknownDocuments();
if (e.getColumn() == 0)
{
UnknownDocumentList.get(e.getFirstRow()).setTitle((String)DocumentsPanel_UnknownAuthorsTable.getValueAt(e.getFirstRow(), 0));
}
UpdateDocumentsTable();
}
}
});
}
private void SetKnownDocumentTree() {
DocumentsPanel_KnownAuthorsTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
DocumentsPanel_KnownAuthorsTree.setShowsRootHandles(true);
}
private void SetDocumentColumns() {
DocumentsTable_Model.addColumn("Title");
DocumentsTable_Model.addColumn("Known");
DocumentsTable_Model.addColumn("Author");
DocumentsTable_Model.addColumn("Doc Type");
DocumentsTable_Model.addColumn("Canonicizers?");
CanonicizersPanel_DocumentsTable.setColumnSelectionAllowed(false);
CanonicizersPanel_DocumentsTable.setRowSelectionAllowed(true);
CanonicizersPanel_DocumentsTable.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e)
{
UpdateCurrentCanonicizerBox();
}
});
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new JGAAP_UI_MainForm().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPanel AnalysisMethodPanel_AMParametersPanel;
private javax.swing.JButton AnalysisMethodPanel_AddAllAnalysisMethodsButton;
private javax.swing.JButton AnalysisMethodPanel_AddAnalysisMethodButton;
private javax.swing.JTextArea AnalysisMethodPanel_AnalysisMethodDescriptionTextBox;
private javax.swing.JList AnalysisMethodPanel_AnalysisMethodsListBox;
private javax.swing.JPanel AnalysisMethodPanel_DFParametersPanel;
private javax.swing.JTextArea AnalysisMethodPanel_DistanceFunctionDescriptionTextBox;
private javax.swing.JList AnalysisMethodPanel_DistanceFunctionsListBox;
private javax.swing.JButton AnalysisMethodPanel_NotesButton;
private javax.swing.JButton AnalysisMethodPanel_RemoveAllAnalysisMethodsButton;
private javax.swing.JButton AnalysisMethodPanel_RemoveAnalysisMethodsButton;
private javax.swing.JList AnalysisMethodPanel_SelectedAnalysisMethodsListBox;
private javax.swing.JMenuItem BatchLoadMenuItem;
private javax.swing.JMenuItem BatchSaveMenuItem;
private javax.swing.JButton CanonicizersPanel_AddAllCanonicizersButton;
private javax.swing.JButton CanonicizersPanel_AddCanonicizerButton;
private javax.swing.JList CanonicizersPanel_CanonicizerListBox;
private javax.swing.JTextArea CanonicizersPanel_DocumentsCanonicizerDescriptionTextBox;
private javax.swing.JTextArea CanonicizersPanel_DocumentsCurrentCanonicizersTextBox;
private javax.swing.JTable CanonicizersPanel_DocumentsTable;
private javax.swing.JButton CanonicizersPanel_NotesButton;
private javax.swing.JButton CanonicizersPanel_RemoveAllCanonicizersButton;
private javax.swing.JButton CanonicizersPanel_RemoveCanonicizerButton;
private javax.swing.JList CanonicizersPanel_SelectedCanonicizerListBox;
private javax.swing.JButton CanonicizersPanel_SetToAllDocuments;
private javax.swing.JButton CanonicizersPanel_SetToDocumentButton;
private javax.swing.JButton CanonicizersPanel_SetToDocumentTypeButton;
private javax.swing.JButton DocumentsPanel_AddAuthorButton;
private javax.swing.JButton DocumentsPanel_AddDocumentsButton;
private javax.swing.JButton DocumentsPanel_EditAuthorButton;
private javax.swing.JTree DocumentsPanel_KnownAuthorsTree;
private javax.swing.JComboBox DocumentsPanel_LanguageComboBox;
private javax.swing.JButton DocumentsPanel_NotesButton;
private javax.swing.JButton DocumentsPanel_RemoveAuthorButton;
private javax.swing.JButton DocumentsPanel_RemoveDocumentsButton;
private javax.swing.JTable DocumentsPanel_UnknownAuthorsTable;
private javax.swing.JButton EventCullingPanel_AddAllEventCullingButton;
private javax.swing.JButton EventCullingPanel_AddEventCullingButton;
private javax.swing.JTextArea EventCullingPanel_EventCullingDescriptionTextbox;
private javax.swing.JList EventCullingPanel_EventCullingListBox;
private javax.swing.JButton EventCullingPanel_NotesButton;
private javax.swing.JPanel EventCullingPanel_ParametersPanel;
private javax.swing.JButton EventCullingPanel_RemoveAllEventCullingButton;
private javax.swing.JButton EventCullingPanel_RemoveEventCullingButton;
private javax.swing.JList EventCullingPanel_SelectedEventCullingListBox;
private javax.swing.JButton EventSetsPanel_AddAllEventSetsButton;
private javax.swing.JButton EventSetsPanel_AddEventSetButton;
private javax.swing.JTextArea EventSetsPanel_EventSetDescriptionTextBox;
private javax.swing.JList EventSetsPanel_EventSetListBox;
private javax.swing.JButton EventSetsPanel_NotesButton;
private javax.swing.JPanel EventSetsPanel_ParametersPanel;
private javax.swing.JButton EventSetsPanel_RemoveAllEventSetsButton;
private javax.swing.JButton EventSetsPanel_RemoveEventSetButton;
private javax.swing.JList EventSetsPanel_SelectedEventSetListBox;
private javax.swing.JPanel JGAAP_AnalysisMethodPanel;
private javax.swing.JPanel JGAAP_CanonicizerPanel;
private javax.swing.JPanel JGAAP_DocumentsPanel;
private javax.swing.JPanel JGAAP_EventCullingPanel;
private javax.swing.JPanel JGAAP_EventSetsPanel;
private javax.swing.JMenuBar JGAAP_MenuBar;
private javax.swing.JPanel JGAAP_ReviewPanel;
private javax.swing.JTabbedPane JGAAP_TabbedPane;
private javax.swing.JButton Next_Button;
private javax.swing.JMenuItem ProblemAMenuItem;
private javax.swing.JMenuItem ProblemBMenuItem;
private javax.swing.JMenuItem ProblemCMenuItem;
private javax.swing.JMenuItem ProblemDMenuItem;
private javax.swing.JMenuItem ProblemEMenuItem;
private javax.swing.JMenuItem ProblemFMenuItem;
private javax.swing.JMenuItem ProblemGMenuItem;
private javax.swing.JMenuItem ProblemHMenuItem;
private javax.swing.JMenuItem ProblemIMenuItem;
private javax.swing.JMenuItem ProblemJMenuItem;
private javax.swing.JMenuItem ProblemKMenuItem;
private javax.swing.JMenuItem ProblemLMenuItem;
private javax.swing.JMenuItem ProblemMMenuItem;
private javax.swing.JLabel ReviewPanel_DocumentsLabel;
private javax.swing.JTable ReviewPanel_DocumentsTable;
private javax.swing.JButton ReviewPanel_ProcessButton;
private javax.swing.JLabel ReviewPanel_SelectedAnalysisMethodsLabel;
private javax.swing.JList ReviewPanel_SelectedAnalysisMethodsListBox;
private javax.swing.JLabel ReviewPanel_SelectedEventCullingLabel;
private javax.swing.JList ReviewPanel_SelectedEventCullingListBox;
private javax.swing.JLabel ReviewPanel_SelectedEventSetLabel;
private javax.swing.JList ReviewPanel_SelectedEventSetListBox;
private javax.swing.JButton Review_Button;
private javax.swing.JMenuItem aboutMenuItem;
private javax.swing.JMenuItem exitMenuItem;
private javax.swing.JButton helpCloseButton;
private javax.swing.JDialog helpDialog;
private javax.swing.JMenu helpMenu;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel13;
private javax.swing.JLabel jLabel15;
private javax.swing.JLabel jLabel16;
private javax.swing.JLabel jLabel17;
private javax.swing.JLabel jLabel18;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel20;
private javax.swing.JLabel jLabel21;
private javax.swing.JLabel jLabel22;
private javax.swing.JLabel jLabel23;
private javax.swing.JLabel jLabel24;
private javax.swing.JLabel jLabel25;
private javax.swing.JLabel jLabel26;
private javax.swing.JLabel jLabel27;
private javax.swing.JLabel jLabel28;
private javax.swing.JLabel jLabel29;
private javax.swing.JLabel jLabel30;
private javax.swing.JLabel jLabel31;
private javax.swing.JLabel jLabel32;
private javax.swing.JLabel jLabel33;
private javax.swing.JLabel jLabel34;
private javax.swing.JLabel jLabel35;
private javax.swing.JLabel jLabel36;
private javax.swing.JLabel jLabel37;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenu jMenu4;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane10;
private javax.swing.JScrollPane jScrollPane11;
private javax.swing.JScrollPane jScrollPane12;
private javax.swing.JScrollPane jScrollPane13;
private javax.swing.JScrollPane jScrollPane14;
private javax.swing.JScrollPane jScrollPane15;
private javax.swing.JScrollPane jScrollPane16;
private javax.swing.JScrollPane jScrollPane17;
private javax.swing.JScrollPane jScrollPane18;
private javax.swing.JScrollPane jScrollPane19;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane20;
private javax.swing.JScrollPane jScrollPane21;
private javax.swing.JScrollPane jScrollPane22;
private javax.swing.JScrollPane jScrollPane23;
private javax.swing.JScrollPane jScrollPane24;
private javax.swing.JScrollPane jScrollPane25;
private javax.swing.JScrollPane jScrollPane26;
private javax.swing.JScrollPane jScrollPane27;
private javax.swing.JScrollPane jScrollPane6;
private javax.swing.JScrollPane jScrollPane9;
// End of variables declaration//GEN-END:variables
}
| true | true | private void initComponents() {
helpDialog = new javax.swing.JDialog();
helpCloseButton = new javax.swing.JButton();
jLabel11 = new javax.swing.JLabel();
jLabel12 = new javax.swing.JLabel();
jLabel13 = new javax.swing.JLabel();
jLabel23 = new javax.swing.JLabel();
jLabel24 = new javax.swing.JLabel();
jLabel25 = new javax.swing.JLabel();
jLabel26 = new javax.swing.JLabel();
JGAAP_TabbedPane = new javax.swing.JTabbedPane();
JGAAP_DocumentsPanel = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
DocumentsPanel_UnknownAuthorsTable = new javax.swing.JTable();
jScrollPane2 = new javax.swing.JScrollPane();
DocumentsPanel_KnownAuthorsTree = new javax.swing.JTree();
DocumentsPanel_AddDocumentsButton = new javax.swing.JButton();
DocumentsPanel_RemoveDocumentsButton = new javax.swing.JButton();
DocumentsPanel_AddAuthorButton = new javax.swing.JButton();
DocumentsPanel_EditAuthorButton = new javax.swing.JButton();
DocumentsPanel_RemoveAuthorButton = new javax.swing.JButton();
DocumentsPanel_NotesButton = new javax.swing.JButton();
jLabel10 = new javax.swing.JLabel();
DocumentsPanel_LanguageComboBox = new javax.swing.JComboBox();
JGAAP_CanonicizerPanel = new javax.swing.JPanel();
CanonicizersPanel_RemoveCanonicizerButton = new javax.swing.JButton();
jLabel27 = new javax.swing.JLabel();
CanonicizersPanel_NotesButton = new javax.swing.JButton();
jScrollPane11 = new javax.swing.JScrollPane();
CanonicizersPanel_DocumentsCanonicizerDescriptionTextBox = new javax.swing.JTextArea();
CanonicizersPanel_AddCanonicizerButton = new javax.swing.JButton();
CanonicizersPanel_AddAllCanonicizersButton = new javax.swing.JButton();
jScrollPane12 = new javax.swing.JScrollPane();
CanonicizersPanel_CanonicizerListBox = new javax.swing.JList();
jScrollPane13 = new javax.swing.JScrollPane();
CanonicizersPanel_SelectedCanonicizerListBox = new javax.swing.JList();
CanonicizersPanel_RemoveAllCanonicizersButton = new javax.swing.JButton();
jLabel31 = new javax.swing.JLabel();
jScrollPane20 = new javax.swing.JScrollPane();
CanonicizersPanel_DocumentsTable = new javax.swing.JTable();
jScrollPane21 = new javax.swing.JScrollPane();
CanonicizersPanel_DocumentsCurrentCanonicizersTextBox = new javax.swing.JTextArea();
CanonicizersPanel_SetToDocumentButton = new javax.swing.JButton();
CanonicizersPanel_SetToDocumentTypeButton = new javax.swing.JButton();
CanonicizersPanel_SetToAllDocuments = new javax.swing.JButton();
jLabel29 = new javax.swing.JLabel();
jLabel30 = new javax.swing.JLabel();
jLabel32 = new javax.swing.JLabel();
jLabel33 = new javax.swing.JLabel();
jLabel34 = new javax.swing.JLabel();
JGAAP_EventSetsPanel = new javax.swing.JPanel();
EventSetsPanel_NotesButton = new javax.swing.JButton();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
jScrollPane9 = new javax.swing.JScrollPane();
EventSetsPanel_EventSetListBox = new javax.swing.JList();
jScrollPane10 = new javax.swing.JScrollPane();
EventSetsPanel_SelectedEventSetListBox = new javax.swing.JList();
EventSetsPanel_ParametersPanel = new javax.swing.JPanel();
jScrollPane6 = new javax.swing.JScrollPane();
EventSetsPanel_EventSetDescriptionTextBox = new javax.swing.JTextArea();
EventSetsPanel_AddEventSetButton = new javax.swing.JButton();
EventSetsPanel_RemoveEventSetButton = new javax.swing.JButton();
EventSetsPanel_AddAllEventSetsButton = new javax.swing.JButton();
EventSetsPanel_RemoveAllEventSetsButton = new javax.swing.JButton();
JGAAP_EventCullingPanel = new javax.swing.JPanel();
jLabel15 = new javax.swing.JLabel();
jLabel16 = new javax.swing.JLabel();
jLabel17 = new javax.swing.JLabel();
EventCullingPanel_NotesButton = new javax.swing.JButton();
jScrollPane14 = new javax.swing.JScrollPane();
EventCullingPanel_SelectedEventCullingListBox = new javax.swing.JList();
EventCullingPanel_AddEventCullingButton = new javax.swing.JButton();
EventCullingPanel_RemoveEventCullingButton = new javax.swing.JButton();
EventCullingPanel_AddAllEventCullingButton = new javax.swing.JButton();
EventCullingPanel_RemoveAllEventCullingButton = new javax.swing.JButton();
EventCullingPanel_ParametersPanel = new javax.swing.JPanel();
jScrollPane15 = new javax.swing.JScrollPane();
EventCullingPanel_EventCullingListBox = new javax.swing.JList();
jScrollPane16 = new javax.swing.JScrollPane();
EventCullingPanel_EventCullingDescriptionTextbox = new javax.swing.JTextArea();
jLabel18 = new javax.swing.JLabel();
JGAAP_AnalysisMethodPanel = new javax.swing.JPanel();
jLabel20 = new javax.swing.JLabel();
jLabel21 = new javax.swing.JLabel();
jLabel22 = new javax.swing.JLabel();
AnalysisMethodPanel_NotesButton = new javax.swing.JButton();
jScrollPane17 = new javax.swing.JScrollPane();
AnalysisMethodPanel_SelectedAnalysisMethodsListBox = new javax.swing.JList();
AnalysisMethodPanel_AddAnalysisMethodButton = new javax.swing.JButton();
AnalysisMethodPanel_RemoveAnalysisMethodsButton = new javax.swing.JButton();
AnalysisMethodPanel_AddAllAnalysisMethodsButton = new javax.swing.JButton();
AnalysisMethodPanel_RemoveAllAnalysisMethodsButton = new javax.swing.JButton();
AnalysisMethodPanel_AMParametersPanel = new javax.swing.JPanel();
jScrollPane18 = new javax.swing.JScrollPane();
AnalysisMethodPanel_AnalysisMethodsListBox = new javax.swing.JList();
jLabel28 = new javax.swing.JLabel();
jScrollPane19 = new javax.swing.JScrollPane();
AnalysisMethodPanel_AnalysisMethodDescriptionTextBox = new javax.swing.JTextArea();
jScrollPane22 = new javax.swing.JScrollPane();
AnalysisMethodPanel_DistanceFunctionsListBox = new javax.swing.JList();
jLabel35 = new javax.swing.JLabel();
jScrollPane23 = new javax.swing.JScrollPane();
AnalysisMethodPanel_DistanceFunctionDescriptionTextBox = new javax.swing.JTextArea();
jLabel36 = new javax.swing.JLabel();
AnalysisMethodPanel_DFParametersPanel = new javax.swing.JPanel();
jLabel37 = new javax.swing.JLabel();
JGAAP_ReviewPanel = new javax.swing.JPanel();
ReviewPanel_ProcessButton = new javax.swing.JButton();
ReviewPanel_DocumentsLabel = new javax.swing.JLabel();
jScrollPane24 = new javax.swing.JScrollPane();
ReviewPanel_DocumentsTable = new javax.swing.JTable();
ReviewPanel_SelectedEventSetLabel = new javax.swing.JLabel();
ReviewPanel_SelectedEventCullingLabel = new javax.swing.JLabel();
ReviewPanel_SelectedAnalysisMethodsLabel = new javax.swing.JLabel();
jScrollPane25 = new javax.swing.JScrollPane();
ReviewPanel_SelectedEventSetListBox = new javax.swing.JList();
jScrollPane26 = new javax.swing.JScrollPane();
ReviewPanel_SelectedEventCullingListBox = new javax.swing.JList();
jScrollPane27 = new javax.swing.JScrollPane();
ReviewPanel_SelectedAnalysisMethodsListBox = new javax.swing.JList();
Next_Button = new javax.swing.JButton();
Review_Button = new javax.swing.JButton();
JGAAP_MenuBar = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenu4 = new javax.swing.JMenu();
BatchSaveMenuItem = new javax.swing.JMenuItem();
BatchLoadMenuItem = new javax.swing.JMenuItem();
jMenu2 = new javax.swing.JMenu();
ProblemAMenuItem = new javax.swing.JMenuItem();
ProblemBMenuItem = new javax.swing.JMenuItem();
ProblemCMenuItem = new javax.swing.JMenuItem();
ProblemDMenuItem = new javax.swing.JMenuItem();
ProblemEMenuItem = new javax.swing.JMenuItem();
ProblemFMenuItem = new javax.swing.JMenuItem();
ProblemGMenuItem = new javax.swing.JMenuItem();
ProblemHMenuItem = new javax.swing.JMenuItem();
ProblemIMenuItem = new javax.swing.JMenuItem();
ProblemJMenuItem = new javax.swing.JMenuItem();
ProblemKMenuItem = new javax.swing.JMenuItem();
ProblemLMenuItem = new javax.swing.JMenuItem();
ProblemMMenuItem = new javax.swing.JMenuItem();
exitMenuItem = new javax.swing.JMenuItem();
helpMenu = new javax.swing.JMenu();
aboutMenuItem = new javax.swing.JMenuItem();
helpDialog.setTitle("About");
helpDialog.setMinimumSize(new java.awt.Dimension(520, 300));
helpDialog.setResizable(false);
helpCloseButton.setText("close");
helpCloseButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
helpCloseButtonActionPerformed(evt);
}
});
jLabel11.setFont(new java.awt.Font("Lucida Grande", 0, 24));
jLabel11.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel11.setText("JGAAP 5.0");
jLabel12.setText("<html> JGAAP, the Java Graphical Authorship Attribution Program, <br/>is an opensource author attribution / text classification tool <br/>Developed by the EVL lab (Evaluating Variation in Language Labratory) <br/> Released by Patrick Juola under the GPL v3.0");
jLabel13.setText("©2011 EVL lab");
jLabel23.setForeground(new java.awt.Color(0, 0, 255));
jLabel23.setText("http://evllabs.com");
jLabel23.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel23MouseClicked(evt);
}
});
jLabel24.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/jgaap/ui/resources/jgaap_icon.png"))); // NOI18N
jLabel25.setForeground(new java.awt.Color(0, 0, 255));
jLabel25.setText("http://jgaap.com");
jLabel25.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel25MouseClicked(evt);
}
});
jLabel26.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/jgaap/ui/resources/EVLlab_icon.png"))); // NOI18N
javax.swing.GroupLayout helpDialogLayout = new javax.swing.GroupLayout(helpDialog.getContentPane());
helpDialog.getContentPane().setLayout(helpDialogLayout);
helpDialogLayout.setHorizontalGroup(
helpDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(helpDialogLayout.createSequentialGroup()
.addGroup(helpDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(helpDialogLayout.createSequentialGroup()
.addContainerGap()
.addGroup(helpDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(helpDialogLayout.createSequentialGroup()
.addComponent(jLabel24)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, 153, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel26))
.addComponent(helpCloseButton, javax.swing.GroupLayout.Alignment.TRAILING)))
.addGroup(helpDialogLayout.createSequentialGroup()
.addGap(199, 199, 199)
.addGroup(helpDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel23)
.addGroup(helpDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel13)
.addComponent(jLabel25))))
.addGroup(helpDialogLayout.createSequentialGroup()
.addGap(58, 58, 58)
.addComponent(jLabel12, javax.swing.GroupLayout.PREFERRED_SIZE, 452, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
helpDialogLayout.setVerticalGroup(
helpDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(helpDialogLayout.createSequentialGroup()
.addGroup(helpDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(helpDialogLayout.createSequentialGroup()
.addGroup(helpDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel24)
.addGroup(helpDialogLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel26, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, helpDialogLayout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel11)
.addGap(44, 44, 44)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel12, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel23)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel25)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 8, Short.MAX_VALUE)
.addGroup(helpDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(helpCloseButton)
.addComponent(jLabel13))
.addContainerGap())
);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("JGAAP");
JGAAP_TabbedPane.setName("JGAAP_TabbedPane"); // NOI18N
jLabel1.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24));
jLabel1.setText("Unknown Authors");
jLabel2.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24));
jLabel2.setText("Known Authors");
DocumentsPanel_UnknownAuthorsTable.setModel(UnknownAuthorDocumentsTable_Model);
DocumentsPanel_UnknownAuthorsTable.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_LAST_COLUMN);
DocumentsPanel_UnknownAuthorsTable.setColumnSelectionAllowed(true);
DocumentsPanel_UnknownAuthorsTable.getTableHeader().setReorderingAllowed(false);
jScrollPane1.setViewportView(DocumentsPanel_UnknownAuthorsTable);
DocumentsPanel_UnknownAuthorsTable.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
DocumentsPanel_KnownAuthorsTree.setModel(KnownAuthorsTree_Model);
DocumentsPanel_KnownAuthorsTree.setShowsRootHandles(true);
jScrollPane2.setViewportView(DocumentsPanel_KnownAuthorsTree);
DocumentsPanel_AddDocumentsButton.setText("Add Document");
DocumentsPanel_AddDocumentsButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
DocumentsPanel_AddDocumentsButtonActionPerformed(evt);
}
});
DocumentsPanel_RemoveDocumentsButton.setText("Remove Document");
DocumentsPanel_RemoveDocumentsButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
DocumentsPanel_RemoveDocumentsButtonActionPerformed(evt);
}
});
DocumentsPanel_AddAuthorButton.setLabel("Add Author");
DocumentsPanel_AddAuthorButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
DocumentsPanel_AddAuthorButtonActionPerformed(evt);
}
});
DocumentsPanel_EditAuthorButton.setLabel("Edit Author");
DocumentsPanel_EditAuthorButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
DocumentsPanel_EditAuthorButtonActionPerformed(evt);
}
});
DocumentsPanel_RemoveAuthorButton.setLabel("Remove Author");
DocumentsPanel_RemoveAuthorButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
DocumentsPanel_RemoveAuthorButtonActionPerformed(evt);
}
});
DocumentsPanel_NotesButton.setLabel("Notes");
DocumentsPanel_NotesButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
DocumentsPanel_NotesButtonActionPerformed(evt);
}
});
jLabel10.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24));
jLabel10.setText("Language");
DocumentsPanel_LanguageComboBox.setModel(LanguageComboBox_Model);
DocumentsPanel_LanguageComboBox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
DocumentsPanel_LanguageComboBoxActionPerformed(evt);
}
});
javax.swing.GroupLayout JGAAP_DocumentsPanelLayout = new javax.swing.GroupLayout(JGAAP_DocumentsPanel);
JGAAP_DocumentsPanel.setLayout(JGAAP_DocumentsPanelLayout);
JGAAP_DocumentsPanelLayout.setHorizontalGroup(
JGAAP_DocumentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, JGAAP_DocumentsPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(JGAAP_DocumentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 824, Short.MAX_VALUE)
.addGroup(JGAAP_DocumentsPanelLayout.createSequentialGroup()
.addGroup(JGAAP_DocumentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel10)
.addComponent(DocumentsPanel_LanguageComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 656, Short.MAX_VALUE)
.addComponent(DocumentsPanel_NotesButton))
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 824, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, JGAAP_DocumentsPanelLayout.createSequentialGroup()
.addGroup(JGAAP_DocumentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addGroup(JGAAP_DocumentsPanelLayout.createSequentialGroup()
.addComponent(DocumentsPanel_AddDocumentsButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(DocumentsPanel_RemoveDocumentsButton))
.addComponent(jLabel2))
.addGap(512, 512, 512))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, JGAAP_DocumentsPanelLayout.createSequentialGroup()
.addComponent(DocumentsPanel_AddAuthorButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(DocumentsPanel_EditAuthorButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(DocumentsPanel_RemoveAuthorButton)))
.addContainerGap())
);
JGAAP_DocumentsPanelLayout.setVerticalGroup(
JGAAP_DocumentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(JGAAP_DocumentsPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(JGAAP_DocumentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(DocumentsPanel_NotesButton)
.addGroup(JGAAP_DocumentsPanelLayout.createSequentialGroup()
.addComponent(jLabel10)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(DocumentsPanel_LanguageComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_DocumentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(DocumentsPanel_RemoveDocumentsButton)
.addComponent(DocumentsPanel_AddDocumentsButton))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 191, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_DocumentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(DocumentsPanel_RemoveAuthorButton)
.addComponent(DocumentsPanel_EditAuthorButton)
.addComponent(DocumentsPanel_AddAuthorButton))
.addContainerGap())
);
JGAAP_TabbedPane.addTab("Documents", JGAAP_DocumentsPanel);
CanonicizersPanel_RemoveCanonicizerButton.setText("<");
CanonicizersPanel_RemoveCanonicizerButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CanonicizersPanel_RemoveCanonicizerButtonActionPerformed(evt);
}
});
jLabel27.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N
jLabel27.setText("Documents");
CanonicizersPanel_NotesButton.setLabel("Notes");
CanonicizersPanel_NotesButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CanonicizersPanel_NotesButtonActionPerformed(evt);
}
});
CanonicizersPanel_DocumentsCanonicizerDescriptionTextBox.setColumns(20);
CanonicizersPanel_DocumentsCanonicizerDescriptionTextBox.setLineWrap(true);
CanonicizersPanel_DocumentsCanonicizerDescriptionTextBox.setRows(5);
CanonicizersPanel_DocumentsCanonicizerDescriptionTextBox.setWrapStyleWord(true);
jScrollPane11.setViewportView(CanonicizersPanel_DocumentsCanonicizerDescriptionTextBox);
CanonicizersPanel_AddCanonicizerButton.setText(">");
CanonicizersPanel_AddCanonicizerButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CanonicizersPanel_AddCanonicizerButtonActionPerformed(evt);
}
});
CanonicizersPanel_AddAllCanonicizersButton.setText("All");
CanonicizersPanel_AddAllCanonicizersButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CanonicizersPanel_AddAllCanonicizersButtonActionPerformed(evt);
}
});
CanonicizersPanel_CanonicizerListBox.setModel(CanonicizerListBox_Model);
CanonicizersPanel_CanonicizerListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
CanonicizersPanel_CanonicizerListBox.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
CanonicizersPanel_CanonicizerListBoxMouseClicked(evt);
}
});
CanonicizersPanel_CanonicizerListBox.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseMoved(java.awt.event.MouseEvent evt) {
CanonicizersPanel_CanonicizerListBoxMouseMoved(evt);
}
});
jScrollPane12.setViewportView(CanonicizersPanel_CanonicizerListBox);
CanonicizersPanel_SelectedCanonicizerListBox.setModel(SelectedCanonicizerListBox_Model);
CanonicizersPanel_SelectedCanonicizerListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
CanonicizersPanel_SelectedCanonicizerListBox.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
CanonicizersPanel_SelectedCanonicizerListBoxMouseClicked(evt);
}
});
CanonicizersPanel_SelectedCanonicizerListBox.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseMoved(java.awt.event.MouseEvent evt) {
CanonicizersPanel_SelectedCanonicizerListBoxMouseMoved(evt);
}
});
jScrollPane13.setViewportView(CanonicizersPanel_SelectedCanonicizerListBox);
CanonicizersPanel_RemoveAllCanonicizersButton.setText("Clear");
CanonicizersPanel_RemoveAllCanonicizersButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CanonicizersPanel_RemoveAllCanonicizersButtonActionPerformed(evt);
}
});
jLabel31.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24));
jLabel31.setText("Document's Current Canonicizers");
CanonicizersPanel_DocumentsTable.setModel(DocumentsTable_Model);
jScrollPane20.setViewportView(CanonicizersPanel_DocumentsTable);
CanonicizersPanel_DocumentsCurrentCanonicizersTextBox.setColumns(20);
CanonicizersPanel_DocumentsCurrentCanonicizersTextBox.setLineWrap(true);
CanonicizersPanel_DocumentsCurrentCanonicizersTextBox.setRows(5);
CanonicizersPanel_DocumentsCurrentCanonicizersTextBox.setWrapStyleWord(true);
jScrollPane21.setViewportView(CanonicizersPanel_DocumentsCurrentCanonicizersTextBox);
CanonicizersPanel_SetToDocumentButton.setText("Set to Doc");
CanonicizersPanel_SetToDocumentButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CanonicizersPanel_SetToDocumentButtonActionPerformed(evt);
}
});
CanonicizersPanel_SetToDocumentTypeButton.setText("Set to Doc Type");
CanonicizersPanel_SetToDocumentTypeButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CanonicizersPanel_SetToDocumentTypeButtonActionPerformed(evt);
}
});
CanonicizersPanel_SetToAllDocuments.setText("Set to All Docs");
CanonicizersPanel_SetToAllDocuments.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CanonicizersPanel_SetToAllDocumentsActionPerformed(evt);
}
});
jLabel29.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24));
jLabel29.setText("Selected");
jLabel30.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24));
jLabel30.setText("Canonicizers");
jLabel32.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24));
jLabel32.setText("Canonicizer Description");
jLabel33.setText("Note: These buttons are used to add");
jLabel34.setText("selected canonicizers to documents.");
javax.swing.GroupLayout JGAAP_CanonicizerPanelLayout = new javax.swing.GroupLayout(JGAAP_CanonicizerPanel);
JGAAP_CanonicizerPanel.setLayout(JGAAP_CanonicizerPanelLayout);
JGAAP_CanonicizerPanelLayout.setHorizontalGroup(
JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(JGAAP_CanonicizerPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(JGAAP_CanonicizerPanelLayout.createSequentialGroup()
.addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(JGAAP_CanonicizerPanelLayout.createSequentialGroup()
.addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel30)
.addComponent(jScrollPane12, javax.swing.GroupLayout.DEFAULT_SIZE, 155, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(CanonicizersPanel_AddCanonicizerButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(CanonicizersPanel_RemoveCanonicizerButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(CanonicizersPanel_AddAllCanonicizersButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(CanonicizersPanel_RemoveAllCanonicizersButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
.addComponent(jLabel33)
.addComponent(jLabel34))
.addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(CanonicizersPanel_SetToDocumentTypeButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 153, Short.MAX_VALUE)
.addComponent(jLabel29)
.addComponent(CanonicizersPanel_SetToDocumentButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 153, Short.MAX_VALUE)
.addComponent(jScrollPane13, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 153, Short.MAX_VALUE)
.addComponent(CanonicizersPanel_SetToAllDocuments, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 153, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane20, javax.swing.GroupLayout.DEFAULT_SIZE, 437, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, JGAAP_CanonicizerPanelLayout.createSequentialGroup()
.addComponent(jLabel27)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 255, Short.MAX_VALUE)
.addComponent(CanonicizersPanel_NotesButton))))
.addGroup(JGAAP_CanonicizerPanelLayout.createSequentialGroup()
.addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jScrollPane21, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel31, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel32)
.addComponent(jScrollPane11, javax.swing.GroupLayout.DEFAULT_SIZE, 463, Short.MAX_VALUE))))
.addContainerGap())
);
JGAAP_CanonicizerPanelLayout.setVerticalGroup(
JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, JGAAP_CanonicizerPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel27)
.addComponent(jLabel30)
.addComponent(jLabel29))
.addGroup(JGAAP_CanonicizerPanelLayout.createSequentialGroup()
.addGap(5, 5, 5)
.addComponent(CanonicizersPanel_NotesButton)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane20, javax.swing.GroupLayout.DEFAULT_SIZE, 304, Short.MAX_VALUE)
.addGroup(JGAAP_CanonicizerPanelLayout.createSequentialGroup()
.addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(JGAAP_CanonicizerPanelLayout.createSequentialGroup()
.addComponent(CanonicizersPanel_AddCanonicizerButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(CanonicizersPanel_RemoveCanonicizerButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(CanonicizersPanel_AddAllCanonicizersButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(CanonicizersPanel_RemoveAllCanonicizersButton))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, JGAAP_CanonicizerPanelLayout.createSequentialGroup()
.addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane13, javax.swing.GroupLayout.DEFAULT_SIZE, 217, Short.MAX_VALUE)
.addComponent(jScrollPane12, javax.swing.GroupLayout.DEFAULT_SIZE, 217, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(CanonicizersPanel_SetToDocumentButton)))
.addGap(6, 6, 6)
.addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(JGAAP_CanonicizerPanelLayout.createSequentialGroup()
.addComponent(jLabel33)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel34)
.addGap(18, 18, 18))
.addGroup(JGAAP_CanonicizerPanelLayout.createSequentialGroup()
.addComponent(CanonicizersPanel_SetToDocumentTypeButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(CanonicizersPanel_SetToAllDocuments)))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel31)
.addComponent(jLabel32))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane21, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jScrollPane11, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
JGAAP_TabbedPane.addTab("Canonicizers", JGAAP_CanonicizerPanel);
EventSetsPanel_NotesButton.setLabel("Notes");
EventSetsPanel_NotesButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EventSetsPanel_NotesButtonActionPerformed(evt);
}
});
jLabel6.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N
jLabel6.setText("Event Drivers");
jLabel7.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24));
jLabel7.setText("Parameters");
jLabel8.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24));
jLabel8.setText("Event Driver Description");
jLabel9.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24));
jLabel9.setText("Selected");
EventSetsPanel_EventSetListBox.setModel(EventSetsListBox_Model);
EventSetsPanel_EventSetListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
EventSetsPanel_EventSetListBox.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
EventSetsPanel_EventSetListBoxMouseClicked(evt);
}
});
EventSetsPanel_EventSetListBox.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseMoved(java.awt.event.MouseEvent evt) {
EventSetsPanel_EventSetListBoxMouseMoved(evt);
}
});
jScrollPane9.setViewportView(EventSetsPanel_EventSetListBox);
EventSetsPanel_SelectedEventSetListBox.setModel(SelectedEventSetsListBox_Model);
EventSetsPanel_SelectedEventSetListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
EventSetsPanel_SelectedEventSetListBox.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
EventSetsPanel_SelectedEventSetListBoxMouseClicked(evt);
}
});
EventSetsPanel_SelectedEventSetListBox.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseMoved(java.awt.event.MouseEvent evt) {
EventSetsPanel_SelectedEventSetListBoxMouseMoved(evt);
}
});
jScrollPane10.setViewportView(EventSetsPanel_SelectedEventSetListBox);
EventSetsPanel_ParametersPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder());
javax.swing.GroupLayout EventSetsPanel_ParametersPanelLayout = new javax.swing.GroupLayout(EventSetsPanel_ParametersPanel);
EventSetsPanel_ParametersPanel.setLayout(EventSetsPanel_ParametersPanelLayout);
EventSetsPanel_ParametersPanelLayout.setHorizontalGroup(
EventSetsPanel_ParametersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 344, Short.MAX_VALUE)
);
EventSetsPanel_ParametersPanelLayout.setVerticalGroup(
EventSetsPanel_ParametersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
EventSetsPanel_EventSetDescriptionTextBox.setColumns(20);
EventSetsPanel_EventSetDescriptionTextBox.setLineWrap(true);
EventSetsPanel_EventSetDescriptionTextBox.setRows(5);
EventSetsPanel_EventSetDescriptionTextBox.setWrapStyleWord(true);
jScrollPane6.setViewportView(EventSetsPanel_EventSetDescriptionTextBox);
EventSetsPanel_AddEventSetButton.setText(">");
EventSetsPanel_AddEventSetButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EventSetsPanel_AddEventSetButtonActionPerformed(evt);
}
});
EventSetsPanel_RemoveEventSetButton.setText("<");
EventSetsPanel_RemoveEventSetButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EventSetsPanel_RemoveEventSetButtonActionPerformed(evt);
}
});
EventSetsPanel_AddAllEventSetsButton.setText("All");
EventSetsPanel_AddAllEventSetsButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EventSetsPanel_AddAllEventSetsButtonActionPerformed(evt);
}
});
EventSetsPanel_RemoveAllEventSetsButton.setText("Clear");
EventSetsPanel_RemoveAllEventSetsButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EventSetsPanel_RemoveAllEventSetsButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout JGAAP_EventSetsPanelLayout = new javax.swing.GroupLayout(JGAAP_EventSetsPanel);
JGAAP_EventSetsPanel.setLayout(JGAAP_EventSetsPanelLayout);
JGAAP_EventSetsPanelLayout.setHorizontalGroup(
JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, JGAAP_EventSetsPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane6, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 824, Short.MAX_VALUE)
.addComponent(jLabel8, javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(JGAAP_EventSetsPanelLayout.createSequentialGroup()
.addGroup(JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane9, javax.swing.GroupLayout.PREFERRED_SIZE, 178, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel6))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(EventSetsPanel_RemoveEventSetButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(EventSetsPanel_AddAllEventSetsButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(EventSetsPanel_AddEventSetButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(EventSetsPanel_RemoveAllEventSetsButton, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel9)
.addComponent(jScrollPane10, javax.swing.GroupLayout.PREFERRED_SIZE, 216, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(JGAAP_EventSetsPanelLayout.createSequentialGroup()
.addComponent(jLabel7)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 163, Short.MAX_VALUE)
.addComponent(EventSetsPanel_NotesButton))
.addComponent(EventSetsPanel_ParametersPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
.addContainerGap())
);
JGAAP_EventSetsPanelLayout.setVerticalGroup(
JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(JGAAP_EventSetsPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6)
.addComponent(jLabel9))
.addGroup(JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(EventSetsPanel_NotesButton)
.addComponent(jLabel7)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(EventSetsPanel_ParametersPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane10, javax.swing.GroupLayout.DEFAULT_SIZE, 304, Short.MAX_VALUE)
.addComponent(jScrollPane9, javax.swing.GroupLayout.DEFAULT_SIZE, 304, Short.MAX_VALUE)
.addGroup(JGAAP_EventSetsPanelLayout.createSequentialGroup()
.addComponent(EventSetsPanel_AddEventSetButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(EventSetsPanel_RemoveEventSetButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(EventSetsPanel_AddAllEventSetsButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(EventSetsPanel_RemoveAllEventSetsButton)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel8)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane6, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
JGAAP_TabbedPane.addTab("Event Drivers", JGAAP_EventSetsPanel);
jLabel15.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N
jLabel15.setText("Event Culling");
jLabel16.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24));
jLabel16.setText("Parameters");
jLabel17.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24));
jLabel17.setText("Selected");
EventCullingPanel_NotesButton.setLabel("Notes");
EventCullingPanel_NotesButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EventCullingPanel_NotesButtonActionPerformed(evt);
}
});
EventCullingPanel_SelectedEventCullingListBox.setModel(SelectedEventCullingListBox_Model);
EventCullingPanel_SelectedEventCullingListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
EventCullingPanel_SelectedEventCullingListBox.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
EventCullingPanel_SelectedEventCullingListBoxMouseClicked(evt);
}
});
EventCullingPanel_SelectedEventCullingListBox.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseMoved(java.awt.event.MouseEvent evt) {
EventCullingPanel_SelectedEventCullingListBoxMouseMoved(evt);
}
});
jScrollPane14.setViewportView(EventCullingPanel_SelectedEventCullingListBox);
EventCullingPanel_AddEventCullingButton.setText(">");
EventCullingPanel_AddEventCullingButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EventCullingPanel_AddEventCullingButtonActionPerformed(evt);
}
});
EventCullingPanel_RemoveEventCullingButton.setText("<");
EventCullingPanel_RemoveEventCullingButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EventCullingPanel_RemoveEventCullingButtonActionPerformed(evt);
}
});
EventCullingPanel_AddAllEventCullingButton.setText("All");
EventCullingPanel_AddAllEventCullingButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EventCullingPanel_AddAllEventCullingButtonActionPerformed(evt);
}
});
EventCullingPanel_RemoveAllEventCullingButton.setText("Clear");
EventCullingPanel_RemoveAllEventCullingButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EventCullingPanel_RemoveAllEventCullingButtonActionPerformed(evt);
}
});
EventCullingPanel_ParametersPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder());
javax.swing.GroupLayout EventCullingPanel_ParametersPanelLayout = new javax.swing.GroupLayout(EventCullingPanel_ParametersPanel);
EventCullingPanel_ParametersPanel.setLayout(EventCullingPanel_ParametersPanelLayout);
EventCullingPanel_ParametersPanelLayout.setHorizontalGroup(
EventCullingPanel_ParametersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 343, Short.MAX_VALUE)
);
EventCullingPanel_ParametersPanelLayout.setVerticalGroup(
EventCullingPanel_ParametersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
EventCullingPanel_EventCullingListBox.setModel(EventCullingListBox_Model);
EventCullingPanel_EventCullingListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
EventCullingPanel_EventCullingListBox.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
EventCullingPanel_EventCullingListBoxMouseClicked(evt);
}
});
EventCullingPanel_EventCullingListBox.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseMoved(java.awt.event.MouseEvent evt) {
EventCullingPanel_EventCullingListBoxMouseMoved(evt);
}
});
jScrollPane15.setViewportView(EventCullingPanel_EventCullingListBox);
EventCullingPanel_EventCullingDescriptionTextbox.setColumns(20);
EventCullingPanel_EventCullingDescriptionTextbox.setLineWrap(true);
EventCullingPanel_EventCullingDescriptionTextbox.setRows(5);
EventCullingPanel_EventCullingDescriptionTextbox.setWrapStyleWord(true);
jScrollPane16.setViewportView(EventCullingPanel_EventCullingDescriptionTextbox);
jLabel18.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24));
jLabel18.setText("Event Culling Description");
javax.swing.GroupLayout JGAAP_EventCullingPanelLayout = new javax.swing.GroupLayout(JGAAP_EventCullingPanel);
JGAAP_EventCullingPanel.setLayout(JGAAP_EventCullingPanelLayout);
JGAAP_EventCullingPanelLayout.setHorizontalGroup(
JGAAP_EventCullingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, JGAAP_EventCullingPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(JGAAP_EventCullingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane16, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 824, Short.MAX_VALUE)
.addComponent(jLabel18, javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(JGAAP_EventCullingPanelLayout.createSequentialGroup()
.addGroup(JGAAP_EventCullingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane15, javax.swing.GroupLayout.PREFERRED_SIZE, 178, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel15))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_EventCullingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(EventCullingPanel_RemoveEventCullingButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(EventCullingPanel_AddAllEventCullingButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(EventCullingPanel_AddEventCullingButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(EventCullingPanel_RemoveAllEventCullingButton, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_EventCullingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel17)
.addComponent(jScrollPane14, javax.swing.GroupLayout.PREFERRED_SIZE, 217, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_EventCullingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(JGAAP_EventCullingPanelLayout.createSequentialGroup()
.addComponent(jLabel16)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 162, Short.MAX_VALUE)
.addComponent(EventCullingPanel_NotesButton))
.addComponent(EventCullingPanel_ParametersPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
.addContainerGap())
);
JGAAP_EventCullingPanelLayout.setVerticalGroup(
JGAAP_EventCullingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(JGAAP_EventCullingPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(JGAAP_EventCullingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(JGAAP_EventCullingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel15)
.addComponent(jLabel17)
.addComponent(jLabel16))
.addComponent(EventCullingPanel_NotesButton))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_EventCullingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane14, javax.swing.GroupLayout.DEFAULT_SIZE, 304, Short.MAX_VALUE)
.addComponent(EventCullingPanel_ParametersPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane15, javax.swing.GroupLayout.DEFAULT_SIZE, 304, Short.MAX_VALUE)
.addGroup(JGAAP_EventCullingPanelLayout.createSequentialGroup()
.addComponent(EventCullingPanel_AddEventCullingButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(EventCullingPanel_RemoveEventCullingButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(EventCullingPanel_AddAllEventCullingButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(EventCullingPanel_RemoveAllEventCullingButton)
.addGap(107, 107, 107)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel18)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane16, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
JGAAP_TabbedPane.addTab("Event Culling", JGAAP_EventCullingPanel);
jLabel20.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N
jLabel20.setText("Analysis Methods");
jLabel21.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24));
jLabel21.setText("AM Parameters");
jLabel22.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24));
jLabel22.setText("Selected");
AnalysisMethodPanel_NotesButton.setLabel("Notes");
AnalysisMethodPanel_NotesButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
AnalysisMethodPanel_NotesButtonActionPerformed(evt);
}
});
AnalysisMethodPanel_SelectedAnalysisMethodsListBox.setModel(SelectedAnalysisMethodListBox_Model);
AnalysisMethodPanel_SelectedAnalysisMethodsListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
AnalysisMethodPanel_SelectedAnalysisMethodsListBox.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
AnalysisMethodPanel_SelectedAnalysisMethodsListBoxMouseClicked(evt);
}
});
AnalysisMethodPanel_SelectedAnalysisMethodsListBox.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseMoved(java.awt.event.MouseEvent evt) {
AnalysisMethodPanel_SelectedAnalysisMethodsListBoxMouseMoved(evt);
}
});
jScrollPane17.setViewportView(AnalysisMethodPanel_SelectedAnalysisMethodsListBox);
AnalysisMethodPanel_AddAnalysisMethodButton.setText(">");
AnalysisMethodPanel_AddAnalysisMethodButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
AnalysisMethodPanel_AddAnalysisMethodButtonActionPerformed(evt);
}
});
AnalysisMethodPanel_RemoveAnalysisMethodsButton.setText("<");
AnalysisMethodPanel_RemoveAnalysisMethodsButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
AnalysisMethodPanel_RemoveAnalysisMethodsButtonActionPerformed(evt);
}
});
AnalysisMethodPanel_AddAllAnalysisMethodsButton.setText("All");
AnalysisMethodPanel_AddAllAnalysisMethodsButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
AnalysisMethodPanel_AddAllAnalysisMethodsButtonActionPerformed(evt);
}
});
AnalysisMethodPanel_RemoveAllAnalysisMethodsButton.setText("Clear");
AnalysisMethodPanel_RemoveAllAnalysisMethodsButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
AnalysisMethodPanel_RemoveAllAnalysisMethodsButtonActionPerformed(evt);
}
});
AnalysisMethodPanel_AMParametersPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder());
javax.swing.GroupLayout AnalysisMethodPanel_AMParametersPanelLayout = new javax.swing.GroupLayout(AnalysisMethodPanel_AMParametersPanel);
AnalysisMethodPanel_AMParametersPanel.setLayout(AnalysisMethodPanel_AMParametersPanelLayout);
AnalysisMethodPanel_AMParametersPanelLayout.setHorizontalGroup(
AnalysisMethodPanel_AMParametersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 355, Short.MAX_VALUE)
);
AnalysisMethodPanel_AMParametersPanelLayout.setVerticalGroup(
AnalysisMethodPanel_AMParametersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 125, Short.MAX_VALUE)
);
AnalysisMethodPanel_AnalysisMethodsListBox.setModel(AnalysisMethodListBox_Model);
AnalysisMethodPanel_AnalysisMethodsListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
AnalysisMethodPanel_AnalysisMethodsListBox.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
AnalysisMethodPanel_AnalysisMethodsListBoxMouseClicked(evt);
}
});
AnalysisMethodPanel_AnalysisMethodsListBox.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseMoved(java.awt.event.MouseEvent evt) {
AnalysisMethodPanel_AnalysisMethodsListBoxMouseMoved(evt);
}
});
jScrollPane18.setViewportView(AnalysisMethodPanel_AnalysisMethodsListBox);
jLabel28.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N
jLabel28.setText("Distance Function Description");
AnalysisMethodPanel_AnalysisMethodDescriptionTextBox.setColumns(20);
AnalysisMethodPanel_AnalysisMethodDescriptionTextBox.setLineWrap(true);
AnalysisMethodPanel_AnalysisMethodDescriptionTextBox.setRows(5);
AnalysisMethodPanel_AnalysisMethodDescriptionTextBox.setWrapStyleWord(true);
jScrollPane19.setViewportView(AnalysisMethodPanel_AnalysisMethodDescriptionTextBox);
AnalysisMethodPanel_DistanceFunctionsListBox.setModel(DistanceFunctionsListBox_Model);
AnalysisMethodPanel_DistanceFunctionsListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
AnalysisMethodPanel_DistanceFunctionsListBox.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
AnalysisMethodPanel_DistanceFunctionsListBoxMouseClicked(evt);
}
});
AnalysisMethodPanel_DistanceFunctionsListBox.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseMoved(java.awt.event.MouseEvent evt) {
AnalysisMethodPanel_DistanceFunctionsListBoxMouseMoved(evt);
}
});
jScrollPane22.setViewportView(AnalysisMethodPanel_DistanceFunctionsListBox);
jLabel35.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N
jLabel35.setText("Distance Functions");
AnalysisMethodPanel_DistanceFunctionDescriptionTextBox.setColumns(20);
AnalysisMethodPanel_DistanceFunctionDescriptionTextBox.setLineWrap(true);
AnalysisMethodPanel_DistanceFunctionDescriptionTextBox.setRows(5);
AnalysisMethodPanel_DistanceFunctionDescriptionTextBox.setWrapStyleWord(true);
jScrollPane23.setViewportView(AnalysisMethodPanel_DistanceFunctionDescriptionTextBox);
jLabel36.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N
jLabel36.setText("Analysis Method Description");
AnalysisMethodPanel_DFParametersPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder());
javax.swing.GroupLayout AnalysisMethodPanel_DFParametersPanelLayout = new javax.swing.GroupLayout(AnalysisMethodPanel_DFParametersPanel);
AnalysisMethodPanel_DFParametersPanel.setLayout(AnalysisMethodPanel_DFParametersPanelLayout);
AnalysisMethodPanel_DFParametersPanelLayout.setHorizontalGroup(
AnalysisMethodPanel_DFParametersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 355, Short.MAX_VALUE)
);
AnalysisMethodPanel_DFParametersPanelLayout.setVerticalGroup(
AnalysisMethodPanel_DFParametersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 128, Short.MAX_VALUE)
);
jLabel37.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24));
jLabel37.setText("DF Parameters");
javax.swing.GroupLayout JGAAP_AnalysisMethodPanelLayout = new javax.swing.GroupLayout(JGAAP_AnalysisMethodPanel);
JGAAP_AnalysisMethodPanel.setLayout(JGAAP_AnalysisMethodPanelLayout);
JGAAP_AnalysisMethodPanelLayout.setHorizontalGroup(
JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, JGAAP_AnalysisMethodPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(JGAAP_AnalysisMethodPanelLayout.createSequentialGroup()
.addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel35, javax.swing.GroupLayout.DEFAULT_SIZE, 257, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, JGAAP_AnalysisMethodPanelLayout.createSequentialGroup()
.addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane22, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 187, Short.MAX_VALUE)
.addComponent(jScrollPane18, javax.swing.GroupLayout.Alignment.LEADING, 0, 0, Short.MAX_VALUE)
.addComponent(jLabel20, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(AnalysisMethodPanel_RemoveAnalysisMethodsButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(AnalysisMethodPanel_AddAllAnalysisMethodsButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(AnalysisMethodPanel_AddAnalysisMethodButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(AnalysisMethodPanel_RemoveAllAnalysisMethodsButton, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel22)
.addComponent(jScrollPane17, javax.swing.GroupLayout.PREFERRED_SIZE, 196, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(AnalysisMethodPanel_DFParametersPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(AnalysisMethodPanel_AMParametersPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(JGAAP_AnalysisMethodPanelLayout.createSequentialGroup()
.addComponent(jLabel21)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 133, Short.MAX_VALUE)
.addComponent(AnalysisMethodPanel_NotesButton))
.addComponent(jLabel37)))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, JGAAP_AnalysisMethodPanelLayout.createSequentialGroup()
.addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane19, javax.swing.GroupLayout.PREFERRED_SIZE, 405, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel36))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel28)
.addComponent(jScrollPane23, javax.swing.GroupLayout.DEFAULT_SIZE, 413, Short.MAX_VALUE))))
.addContainerGap())
);
JGAAP_AnalysisMethodPanelLayout.setVerticalGroup(
JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(JGAAP_AnalysisMethodPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel20)
.addComponent(jLabel21)
.addComponent(jLabel22)
.addComponent(AnalysisMethodPanel_NotesButton))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane17, javax.swing.GroupLayout.DEFAULT_SIZE, 301, Short.MAX_VALUE)
.addGroup(JGAAP_AnalysisMethodPanelLayout.createSequentialGroup()
.addComponent(AnalysisMethodPanel_AMParametersPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel37)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(AnalysisMethodPanel_DFParametersPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(JGAAP_AnalysisMethodPanelLayout.createSequentialGroup()
.addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(JGAAP_AnalysisMethodPanelLayout.createSequentialGroup()
.addComponent(AnalysisMethodPanel_AddAnalysisMethodButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(AnalysisMethodPanel_RemoveAnalysisMethodsButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(AnalysisMethodPanel_AddAllAnalysisMethodsButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(AnalysisMethodPanel_RemoveAllAnalysisMethodsButton))
.addComponent(jScrollPane18, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel35)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane22, javax.swing.GroupLayout.DEFAULT_SIZE, 132, Short.MAX_VALUE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel28)
.addComponent(jLabel36))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane19, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jScrollPane23, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
JGAAP_TabbedPane.addTab("Analysis Methods", JGAAP_AnalysisMethodPanel);
ReviewPanel_ProcessButton.setLabel("Process");
ReviewPanel_ProcessButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ReviewPanel_ProcessButtonActionPerformed(evt);
}
});
ReviewPanel_DocumentsLabel.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N
ReviewPanel_DocumentsLabel.setText("Documents");
ReviewPanel_DocumentsLabel.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
ReviewPanel_DocumentsLabelMouseClicked(evt);
}
});
ReviewPanel_DocumentsTable.setModel(DocumentsTable_Model);
ReviewPanel_DocumentsTable.setEnabled(false);
ReviewPanel_DocumentsTable.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
ReviewPanel_DocumentsTableMouseClicked(evt);
}
});
jScrollPane24.setViewportView(ReviewPanel_DocumentsTable);
ReviewPanel_SelectedEventSetLabel.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N
ReviewPanel_SelectedEventSetLabel.setText("Event Driver");
ReviewPanel_SelectedEventSetLabel.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
ReviewPanel_SelectedEventSetLabelMouseClicked(evt);
}
});
ReviewPanel_SelectedEventCullingLabel.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N
ReviewPanel_SelectedEventCullingLabel.setText("Event Culling");
ReviewPanel_SelectedEventCullingLabel.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
ReviewPanel_SelectedEventCullingLabelMouseClicked(evt);
}
});
ReviewPanel_SelectedAnalysisMethodsLabel.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N
ReviewPanel_SelectedAnalysisMethodsLabel.setText("Analysis Methods");
ReviewPanel_SelectedAnalysisMethodsLabel.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
ReviewPanel_SelectedAnalysisMethodsLabelMouseClicked(evt);
}
});
ReviewPanel_SelectedEventSetListBox.setModel(SelectedEventSetsListBox_Model);
ReviewPanel_SelectedEventSetListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
ReviewPanel_SelectedEventSetListBox.setEnabled(false);
ReviewPanel_SelectedEventSetListBox.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
ReviewPanel_SelectedEventSetListBoxMouseClicked(evt);
}
});
jScrollPane25.setViewportView(ReviewPanel_SelectedEventSetListBox);
ReviewPanel_SelectedEventCullingListBox.setModel(SelectedEventCullingListBox_Model);
ReviewPanel_SelectedEventCullingListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
ReviewPanel_SelectedEventCullingListBox.setEnabled(false);
ReviewPanel_SelectedEventCullingListBox.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
ReviewPanel_SelectedEventCullingListBoxMouseClicked(evt);
}
});
jScrollPane26.setViewportView(ReviewPanel_SelectedEventCullingListBox);
ReviewPanel_SelectedAnalysisMethodsListBox.setModel(SelectedAnalysisMethodListBox_Model);
ReviewPanel_SelectedAnalysisMethodsListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
ReviewPanel_SelectedAnalysisMethodsListBox.setEnabled(false);
ReviewPanel_SelectedAnalysisMethodsListBox.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
ReviewPanel_SelectedAnalysisMethodsListBoxMouseClicked(evt);
}
});
jScrollPane27.setViewportView(ReviewPanel_SelectedAnalysisMethodsListBox);
javax.swing.GroupLayout JGAAP_ReviewPanelLayout = new javax.swing.GroupLayout(JGAAP_ReviewPanel);
JGAAP_ReviewPanel.setLayout(JGAAP_ReviewPanelLayout);
JGAAP_ReviewPanelLayout.setHorizontalGroup(
JGAAP_ReviewPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, JGAAP_ReviewPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(JGAAP_ReviewPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane24, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 824, Short.MAX_VALUE)
.addComponent(ReviewPanel_DocumentsLabel, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(ReviewPanel_ProcessButton)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, JGAAP_ReviewPanelLayout.createSequentialGroup()
.addGroup(JGAAP_ReviewPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane25, javax.swing.GroupLayout.PREFERRED_SIZE, 273, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(ReviewPanel_SelectedEventSetLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_ReviewPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(ReviewPanel_SelectedEventCullingLabel)
.addComponent(jScrollPane26, javax.swing.GroupLayout.PREFERRED_SIZE, 268, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_ReviewPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(ReviewPanel_SelectedAnalysisMethodsLabel)
.addComponent(jScrollPane27, javax.swing.GroupLayout.DEFAULT_SIZE, 271, Short.MAX_VALUE))))
.addContainerGap())
);
JGAAP_ReviewPanelLayout.setVerticalGroup(
JGAAP_ReviewPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(JGAAP_ReviewPanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(ReviewPanel_DocumentsLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane24, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_ReviewPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(ReviewPanel_SelectedEventSetLabel)
.addComponent(ReviewPanel_SelectedEventCullingLabel)
.addComponent(ReviewPanel_SelectedAnalysisMethodsLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_ReviewPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane27, javax.swing.GroupLayout.DEFAULT_SIZE, 258, Short.MAX_VALUE)
.addComponent(jScrollPane26, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 258, Short.MAX_VALUE)
.addComponent(jScrollPane25, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 258, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(ReviewPanel_ProcessButton)
.addContainerGap())
);
JGAAP_TabbedPane.addTab("Review & Process", JGAAP_ReviewPanel);
Next_Button.setText("Next >");
Next_Button.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Next_ButtonActionPerformed(evt);
}
});
Review_Button.setText("Finish & Review");
Review_Button.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Review_ButtonActionPerformed(evt);
}
});
jMenu1.setText("File");
jMenu4.setText("Batch Documents");
BatchSaveMenuItem.setText("Save Documents");
BatchSaveMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BatchSaveMenuItemActionPerformed(evt);
}
});
jMenu4.add(BatchSaveMenuItem);
BatchLoadMenuItem.setText("Load Documents");
BatchLoadMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BatchLoadMenuItemActionPerformed(evt);
}
});
jMenu4.add(BatchLoadMenuItem);
jMenu1.add(jMenu4);
jMenu2.setText("AAAC Problems");
ProblemAMenuItem.setText("Problem A");
ProblemAMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ProblemAMenuItemActionPerformed(evt);
}
});
jMenu2.add(ProblemAMenuItem);
ProblemBMenuItem.setText("Problem B");
ProblemBMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ProblemBMenuItemActionPerformed(evt);
}
});
jMenu2.add(ProblemBMenuItem);
ProblemCMenuItem.setText("Problem C");
ProblemCMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ProblemCMenuItemActionPerformed(evt);
}
});
jMenu2.add(ProblemCMenuItem);
ProblemDMenuItem.setText("Problem D");
ProblemDMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ProblemDMenuItemActionPerformed(evt);
}
});
jMenu2.add(ProblemDMenuItem);
ProblemEMenuItem.setText("Problem E");
ProblemEMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ProblemEMenuItemActionPerformed(evt);
}
});
jMenu2.add(ProblemEMenuItem);
ProblemFMenuItem.setText("Problem F");
ProblemFMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ProblemFMenuItemActionPerformed(evt);
}
});
jMenu2.add(ProblemFMenuItem);
ProblemGMenuItem.setText("Problem G");
ProblemGMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ProblemGMenuItemActionPerformed(evt);
}
});
jMenu2.add(ProblemGMenuItem);
ProblemHMenuItem.setText("Problem H");
ProblemHMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ProblemHMenuItemActionPerformed(evt);
}
});
jMenu2.add(ProblemHMenuItem);
ProblemIMenuItem.setText("Problem I");
ProblemIMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ProblemIMenuItemActionPerformed(evt);
}
});
jMenu2.add(ProblemIMenuItem);
ProblemJMenuItem.setText("Problem J");
ProblemJMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ProblemJMenuItemActionPerformed(evt);
}
});
jMenu2.add(ProblemJMenuItem);
ProblemKMenuItem.setText("Problem K");
ProblemKMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ProblemKMenuItemActionPerformed(evt);
}
});
jMenu2.add(ProblemKMenuItem);
ProblemLMenuItem.setText("Problem L");
ProblemLMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ProblemLMenuItemActionPerformed(evt);
}
});
jMenu2.add(ProblemLMenuItem);
ProblemMMenuItem.setText("Problem M");
ProblemMMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ProblemMMenuItemActionPerformed(evt);
}
});
jMenu2.add(ProblemMMenuItem);
jMenu1.add(jMenu2);
exitMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Q, java.awt.event.InputEvent.CTRL_MASK));
exitMenuItem.setText("Exit");
exitMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
exitMenuItemActionPerformed(evt);
}
});
jMenu1.add(exitMenuItem);
JGAAP_MenuBar.add(jMenu1);
helpMenu.setText("Help");
aboutMenuItem.setText("About..");
aboutMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
aboutMenuItemActionPerformed(evt);
}
});
helpMenu.add(aboutMenuItem);
JGAAP_MenuBar.add(helpMenu);
setJMenuBar(JGAAP_MenuBar);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(JGAAP_TabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, 849, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(Review_Button)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(Next_Button)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(JGAAP_TabbedPane, javax.swing.GroupLayout.PREFERRED_SIZE, 529, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(Next_Button)
.addComponent(Review_Button))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
| private void initComponents() {
helpDialog = new javax.swing.JDialog();
helpCloseButton = new javax.swing.JButton();
jLabel11 = new javax.swing.JLabel();
jLabel12 = new javax.swing.JLabel();
jLabel13 = new javax.swing.JLabel();
jLabel23 = new javax.swing.JLabel();
jLabel24 = new javax.swing.JLabel();
jLabel25 = new javax.swing.JLabel();
jLabel26 = new javax.swing.JLabel();
JGAAP_TabbedPane = new javax.swing.JTabbedPane();
JGAAP_DocumentsPanel = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
DocumentsPanel_UnknownAuthorsTable = new javax.swing.JTable();
jScrollPane2 = new javax.swing.JScrollPane();
DocumentsPanel_KnownAuthorsTree = new javax.swing.JTree();
DocumentsPanel_AddDocumentsButton = new javax.swing.JButton();
DocumentsPanel_RemoveDocumentsButton = new javax.swing.JButton();
DocumentsPanel_AddAuthorButton = new javax.swing.JButton();
DocumentsPanel_EditAuthorButton = new javax.swing.JButton();
DocumentsPanel_RemoveAuthorButton = new javax.swing.JButton();
DocumentsPanel_NotesButton = new javax.swing.JButton();
jLabel10 = new javax.swing.JLabel();
DocumentsPanel_LanguageComboBox = new javax.swing.JComboBox();
JGAAP_CanonicizerPanel = new javax.swing.JPanel();
CanonicizersPanel_RemoveCanonicizerButton = new javax.swing.JButton();
jLabel27 = new javax.swing.JLabel();
CanonicizersPanel_NotesButton = new javax.swing.JButton();
jScrollPane11 = new javax.swing.JScrollPane();
CanonicizersPanel_DocumentsCanonicizerDescriptionTextBox = new javax.swing.JTextArea();
CanonicizersPanel_AddCanonicizerButton = new javax.swing.JButton();
CanonicizersPanel_AddAllCanonicizersButton = new javax.swing.JButton();
jScrollPane12 = new javax.swing.JScrollPane();
CanonicizersPanel_CanonicizerListBox = new javax.swing.JList();
jScrollPane13 = new javax.swing.JScrollPane();
CanonicizersPanel_SelectedCanonicizerListBox = new javax.swing.JList();
CanonicizersPanel_RemoveAllCanonicizersButton = new javax.swing.JButton();
jLabel31 = new javax.swing.JLabel();
jScrollPane20 = new javax.swing.JScrollPane();
CanonicizersPanel_DocumentsTable = new javax.swing.JTable();
jScrollPane21 = new javax.swing.JScrollPane();
CanonicizersPanel_DocumentsCurrentCanonicizersTextBox = new javax.swing.JTextArea();
CanonicizersPanel_SetToDocumentButton = new javax.swing.JButton();
CanonicizersPanel_SetToDocumentTypeButton = new javax.swing.JButton();
CanonicizersPanel_SetToAllDocuments = new javax.swing.JButton();
jLabel29 = new javax.swing.JLabel();
jLabel30 = new javax.swing.JLabel();
jLabel32 = new javax.swing.JLabel();
jLabel33 = new javax.swing.JLabel();
jLabel34 = new javax.swing.JLabel();
JGAAP_EventSetsPanel = new javax.swing.JPanel();
EventSetsPanel_NotesButton = new javax.swing.JButton();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
jScrollPane9 = new javax.swing.JScrollPane();
EventSetsPanel_EventSetListBox = new javax.swing.JList();
jScrollPane10 = new javax.swing.JScrollPane();
EventSetsPanel_SelectedEventSetListBox = new javax.swing.JList();
EventSetsPanel_ParametersPanel = new javax.swing.JPanel();
jScrollPane6 = new javax.swing.JScrollPane();
EventSetsPanel_EventSetDescriptionTextBox = new javax.swing.JTextArea();
EventSetsPanel_AddEventSetButton = new javax.swing.JButton();
EventSetsPanel_RemoveEventSetButton = new javax.swing.JButton();
EventSetsPanel_AddAllEventSetsButton = new javax.swing.JButton();
EventSetsPanel_RemoveAllEventSetsButton = new javax.swing.JButton();
JGAAP_EventCullingPanel = new javax.swing.JPanel();
jLabel15 = new javax.swing.JLabel();
jLabel16 = new javax.swing.JLabel();
jLabel17 = new javax.swing.JLabel();
EventCullingPanel_NotesButton = new javax.swing.JButton();
jScrollPane14 = new javax.swing.JScrollPane();
EventCullingPanel_SelectedEventCullingListBox = new javax.swing.JList();
EventCullingPanel_AddEventCullingButton = new javax.swing.JButton();
EventCullingPanel_RemoveEventCullingButton = new javax.swing.JButton();
EventCullingPanel_AddAllEventCullingButton = new javax.swing.JButton();
EventCullingPanel_RemoveAllEventCullingButton = new javax.swing.JButton();
EventCullingPanel_ParametersPanel = new javax.swing.JPanel();
jScrollPane15 = new javax.swing.JScrollPane();
EventCullingPanel_EventCullingListBox = new javax.swing.JList();
jScrollPane16 = new javax.swing.JScrollPane();
EventCullingPanel_EventCullingDescriptionTextbox = new javax.swing.JTextArea();
jLabel18 = new javax.swing.JLabel();
JGAAP_AnalysisMethodPanel = new javax.swing.JPanel();
jLabel20 = new javax.swing.JLabel();
jLabel21 = new javax.swing.JLabel();
jLabel22 = new javax.swing.JLabel();
AnalysisMethodPanel_NotesButton = new javax.swing.JButton();
jScrollPane17 = new javax.swing.JScrollPane();
AnalysisMethodPanel_SelectedAnalysisMethodsListBox = new javax.swing.JList();
AnalysisMethodPanel_AddAnalysisMethodButton = new javax.swing.JButton();
AnalysisMethodPanel_RemoveAnalysisMethodsButton = new javax.swing.JButton();
AnalysisMethodPanel_AddAllAnalysisMethodsButton = new javax.swing.JButton();
AnalysisMethodPanel_RemoveAllAnalysisMethodsButton = new javax.swing.JButton();
AnalysisMethodPanel_AMParametersPanel = new javax.swing.JPanel();
jScrollPane18 = new javax.swing.JScrollPane();
AnalysisMethodPanel_AnalysisMethodsListBox = new javax.swing.JList();
jLabel28 = new javax.swing.JLabel();
jScrollPane19 = new javax.swing.JScrollPane();
AnalysisMethodPanel_AnalysisMethodDescriptionTextBox = new javax.swing.JTextArea();
jScrollPane22 = new javax.swing.JScrollPane();
AnalysisMethodPanel_DistanceFunctionsListBox = new javax.swing.JList();
jLabel35 = new javax.swing.JLabel();
jScrollPane23 = new javax.swing.JScrollPane();
AnalysisMethodPanel_DistanceFunctionDescriptionTextBox = new javax.swing.JTextArea();
jLabel36 = new javax.swing.JLabel();
AnalysisMethodPanel_DFParametersPanel = new javax.swing.JPanel();
jLabel37 = new javax.swing.JLabel();
JGAAP_ReviewPanel = new javax.swing.JPanel();
ReviewPanel_ProcessButton = new javax.swing.JButton();
ReviewPanel_DocumentsLabel = new javax.swing.JLabel();
jScrollPane24 = new javax.swing.JScrollPane();
ReviewPanel_DocumentsTable = new javax.swing.JTable();
ReviewPanel_SelectedEventSetLabel = new javax.swing.JLabel();
ReviewPanel_SelectedEventCullingLabel = new javax.swing.JLabel();
ReviewPanel_SelectedAnalysisMethodsLabel = new javax.swing.JLabel();
jScrollPane25 = new javax.swing.JScrollPane();
ReviewPanel_SelectedEventSetListBox = new javax.swing.JList();
jScrollPane26 = new javax.swing.JScrollPane();
ReviewPanel_SelectedEventCullingListBox = new javax.swing.JList();
jScrollPane27 = new javax.swing.JScrollPane();
ReviewPanel_SelectedAnalysisMethodsListBox = new javax.swing.JList();
Next_Button = new javax.swing.JButton();
Review_Button = new javax.swing.JButton();
JGAAP_MenuBar = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenu4 = new javax.swing.JMenu();
BatchSaveMenuItem = new javax.swing.JMenuItem();
BatchLoadMenuItem = new javax.swing.JMenuItem();
jMenu2 = new javax.swing.JMenu();
ProblemAMenuItem = new javax.swing.JMenuItem();
ProblemBMenuItem = new javax.swing.JMenuItem();
ProblemCMenuItem = new javax.swing.JMenuItem();
ProblemDMenuItem = new javax.swing.JMenuItem();
ProblemEMenuItem = new javax.swing.JMenuItem();
ProblemFMenuItem = new javax.swing.JMenuItem();
ProblemGMenuItem = new javax.swing.JMenuItem();
ProblemHMenuItem = new javax.swing.JMenuItem();
ProblemIMenuItem = new javax.swing.JMenuItem();
ProblemJMenuItem = new javax.swing.JMenuItem();
ProblemKMenuItem = new javax.swing.JMenuItem();
ProblemLMenuItem = new javax.swing.JMenuItem();
ProblemMMenuItem = new javax.swing.JMenuItem();
exitMenuItem = new javax.swing.JMenuItem();
helpMenu = new javax.swing.JMenu();
aboutMenuItem = new javax.swing.JMenuItem();
helpDialog.setTitle("About");
helpDialog.setMinimumSize(new java.awt.Dimension(520, 300));
helpDialog.setResizable(false);
helpCloseButton.setText("close");
helpCloseButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
helpCloseButtonActionPerformed(evt);
}
});
jLabel11.setFont(new java.awt.Font("Lucida Grande", 0, 24));
jLabel11.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel11.setText("JGAAP 5.0");
jLabel12.setText("<html> JGAAP, the Java Graphical Authorship Attribution Program, <br/>is an opensource author attribution / text classification tool <br/>Developed by the EVL lab (Evaluating Variation in Language Labratory) <br/> Released by Patrick Juola under the GPL v3.0");
jLabel13.setText("�2011 EVL lab");
jLabel23.setForeground(new java.awt.Color(0, 0, 255));
jLabel23.setText("http://evllabs.com");
jLabel23.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel23MouseClicked(evt);
}
});
jLabel24.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/jgaap/ui/resources/jgaap_icon.png"))); // NOI18N
jLabel25.setForeground(new java.awt.Color(0, 0, 255));
jLabel25.setText("http://jgaap.com");
jLabel25.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel25MouseClicked(evt);
}
});
jLabel26.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/jgaap/ui/resources/EVLlab_icon.png"))); // NOI18N
javax.swing.GroupLayout helpDialogLayout = new javax.swing.GroupLayout(helpDialog.getContentPane());
helpDialog.getContentPane().setLayout(helpDialogLayout);
helpDialogLayout.setHorizontalGroup(
helpDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(helpDialogLayout.createSequentialGroup()
.addGroup(helpDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(helpDialogLayout.createSequentialGroup()
.addContainerGap()
.addGroup(helpDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(helpDialogLayout.createSequentialGroup()
.addComponent(jLabel24)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, 153, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel26))
.addComponent(helpCloseButton, javax.swing.GroupLayout.Alignment.TRAILING)))
.addGroup(helpDialogLayout.createSequentialGroup()
.addGap(199, 199, 199)
.addGroup(helpDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel23)
.addGroup(helpDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel13)
.addComponent(jLabel25))))
.addGroup(helpDialogLayout.createSequentialGroup()
.addGap(58, 58, 58)
.addComponent(jLabel12, javax.swing.GroupLayout.PREFERRED_SIZE, 452, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
helpDialogLayout.setVerticalGroup(
helpDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(helpDialogLayout.createSequentialGroup()
.addGroup(helpDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(helpDialogLayout.createSequentialGroup()
.addGroup(helpDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel24)
.addGroup(helpDialogLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel26, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, helpDialogLayout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel11)
.addGap(44, 44, 44)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel12, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel23)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel25)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 8, Short.MAX_VALUE)
.addGroup(helpDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(helpCloseButton)
.addComponent(jLabel13))
.addContainerGap())
);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("JGAAP");
JGAAP_TabbedPane.setName("JGAAP_TabbedPane"); // NOI18N
jLabel1.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24));
jLabel1.setText("Unknown Authors");
jLabel2.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24));
jLabel2.setText("Known Authors");
DocumentsPanel_UnknownAuthorsTable.setModel(UnknownAuthorDocumentsTable_Model);
DocumentsPanel_UnknownAuthorsTable.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_LAST_COLUMN);
DocumentsPanel_UnknownAuthorsTable.setColumnSelectionAllowed(true);
DocumentsPanel_UnknownAuthorsTable.getTableHeader().setReorderingAllowed(false);
jScrollPane1.setViewportView(DocumentsPanel_UnknownAuthorsTable);
DocumentsPanel_UnknownAuthorsTable.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
DocumentsPanel_KnownAuthorsTree.setModel(KnownAuthorsTree_Model);
DocumentsPanel_KnownAuthorsTree.setShowsRootHandles(true);
jScrollPane2.setViewportView(DocumentsPanel_KnownAuthorsTree);
DocumentsPanel_AddDocumentsButton.setText("Add Document");
DocumentsPanel_AddDocumentsButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
DocumentsPanel_AddDocumentsButtonActionPerformed(evt);
}
});
DocumentsPanel_RemoveDocumentsButton.setText("Remove Document");
DocumentsPanel_RemoveDocumentsButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
DocumentsPanel_RemoveDocumentsButtonActionPerformed(evt);
}
});
DocumentsPanel_AddAuthorButton.setLabel("Add Author");
DocumentsPanel_AddAuthorButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
DocumentsPanel_AddAuthorButtonActionPerformed(evt);
}
});
DocumentsPanel_EditAuthorButton.setLabel("Edit Author");
DocumentsPanel_EditAuthorButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
DocumentsPanel_EditAuthorButtonActionPerformed(evt);
}
});
DocumentsPanel_RemoveAuthorButton.setLabel("Remove Author");
DocumentsPanel_RemoveAuthorButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
DocumentsPanel_RemoveAuthorButtonActionPerformed(evt);
}
});
DocumentsPanel_NotesButton.setLabel("Notes");
DocumentsPanel_NotesButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
DocumentsPanel_NotesButtonActionPerformed(evt);
}
});
jLabel10.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24));
jLabel10.setText("Language");
DocumentsPanel_LanguageComboBox.setModel(LanguageComboBox_Model);
DocumentsPanel_LanguageComboBox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
DocumentsPanel_LanguageComboBoxActionPerformed(evt);
}
});
javax.swing.GroupLayout JGAAP_DocumentsPanelLayout = new javax.swing.GroupLayout(JGAAP_DocumentsPanel);
JGAAP_DocumentsPanel.setLayout(JGAAP_DocumentsPanelLayout);
JGAAP_DocumentsPanelLayout.setHorizontalGroup(
JGAAP_DocumentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, JGAAP_DocumentsPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(JGAAP_DocumentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 824, Short.MAX_VALUE)
.addGroup(JGAAP_DocumentsPanelLayout.createSequentialGroup()
.addGroup(JGAAP_DocumentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel10)
.addComponent(DocumentsPanel_LanguageComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 656, Short.MAX_VALUE)
.addComponent(DocumentsPanel_NotesButton))
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 824, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, JGAAP_DocumentsPanelLayout.createSequentialGroup()
.addGroup(JGAAP_DocumentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addGroup(JGAAP_DocumentsPanelLayout.createSequentialGroup()
.addComponent(DocumentsPanel_AddDocumentsButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(DocumentsPanel_RemoveDocumentsButton))
.addComponent(jLabel2))
.addGap(512, 512, 512))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, JGAAP_DocumentsPanelLayout.createSequentialGroup()
.addComponent(DocumentsPanel_AddAuthorButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(DocumentsPanel_EditAuthorButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(DocumentsPanel_RemoveAuthorButton)))
.addContainerGap())
);
JGAAP_DocumentsPanelLayout.setVerticalGroup(
JGAAP_DocumentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(JGAAP_DocumentsPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(JGAAP_DocumentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(DocumentsPanel_NotesButton)
.addGroup(JGAAP_DocumentsPanelLayout.createSequentialGroup()
.addComponent(jLabel10)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(DocumentsPanel_LanguageComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_DocumentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(DocumentsPanel_RemoveDocumentsButton)
.addComponent(DocumentsPanel_AddDocumentsButton))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 191, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_DocumentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(DocumentsPanel_RemoveAuthorButton)
.addComponent(DocumentsPanel_EditAuthorButton)
.addComponent(DocumentsPanel_AddAuthorButton))
.addContainerGap())
);
JGAAP_TabbedPane.addTab("Documents", JGAAP_DocumentsPanel);
CanonicizersPanel_RemoveCanonicizerButton.setText("<");
CanonicizersPanel_RemoveCanonicizerButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CanonicizersPanel_RemoveCanonicizerButtonActionPerformed(evt);
}
});
jLabel27.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N
jLabel27.setText("Documents");
CanonicizersPanel_NotesButton.setLabel("Notes");
CanonicizersPanel_NotesButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CanonicizersPanel_NotesButtonActionPerformed(evt);
}
});
CanonicizersPanel_DocumentsCanonicizerDescriptionTextBox.setColumns(20);
CanonicizersPanel_DocumentsCanonicizerDescriptionTextBox.setLineWrap(true);
CanonicizersPanel_DocumentsCanonicizerDescriptionTextBox.setRows(5);
CanonicizersPanel_DocumentsCanonicizerDescriptionTextBox.setWrapStyleWord(true);
jScrollPane11.setViewportView(CanonicizersPanel_DocumentsCanonicizerDescriptionTextBox);
CanonicizersPanel_AddCanonicizerButton.setText(">");
CanonicizersPanel_AddCanonicizerButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CanonicizersPanel_AddCanonicizerButtonActionPerformed(evt);
}
});
CanonicizersPanel_AddAllCanonicizersButton.setText("All");
CanonicizersPanel_AddAllCanonicizersButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CanonicizersPanel_AddAllCanonicizersButtonActionPerformed(evt);
}
});
CanonicizersPanel_CanonicizerListBox.setModel(CanonicizerListBox_Model);
CanonicizersPanel_CanonicizerListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
CanonicizersPanel_CanonicizerListBox.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
CanonicizersPanel_CanonicizerListBoxMouseClicked(evt);
}
});
CanonicizersPanel_CanonicizerListBox.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseMoved(java.awt.event.MouseEvent evt) {
CanonicizersPanel_CanonicizerListBoxMouseMoved(evt);
}
});
jScrollPane12.setViewportView(CanonicizersPanel_CanonicizerListBox);
CanonicizersPanel_SelectedCanonicizerListBox.setModel(SelectedCanonicizerListBox_Model);
CanonicizersPanel_SelectedCanonicizerListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
CanonicizersPanel_SelectedCanonicizerListBox.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
CanonicizersPanel_SelectedCanonicizerListBoxMouseClicked(evt);
}
});
CanonicizersPanel_SelectedCanonicizerListBox.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseMoved(java.awt.event.MouseEvent evt) {
CanonicizersPanel_SelectedCanonicizerListBoxMouseMoved(evt);
}
});
jScrollPane13.setViewportView(CanonicizersPanel_SelectedCanonicizerListBox);
CanonicizersPanel_RemoveAllCanonicizersButton.setText("Clear");
CanonicizersPanel_RemoveAllCanonicizersButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CanonicizersPanel_RemoveAllCanonicizersButtonActionPerformed(evt);
}
});
jLabel31.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24));
jLabel31.setText("Document's Current Canonicizers");
CanonicizersPanel_DocumentsTable.setModel(DocumentsTable_Model);
jScrollPane20.setViewportView(CanonicizersPanel_DocumentsTable);
CanonicizersPanel_DocumentsCurrentCanonicizersTextBox.setColumns(20);
CanonicizersPanel_DocumentsCurrentCanonicizersTextBox.setLineWrap(true);
CanonicizersPanel_DocumentsCurrentCanonicizersTextBox.setRows(5);
CanonicizersPanel_DocumentsCurrentCanonicizersTextBox.setWrapStyleWord(true);
jScrollPane21.setViewportView(CanonicizersPanel_DocumentsCurrentCanonicizersTextBox);
CanonicizersPanel_SetToDocumentButton.setText("Set to Doc");
CanonicizersPanel_SetToDocumentButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CanonicizersPanel_SetToDocumentButtonActionPerformed(evt);
}
});
CanonicizersPanel_SetToDocumentTypeButton.setText("Set to Doc Type");
CanonicizersPanel_SetToDocumentTypeButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CanonicizersPanel_SetToDocumentTypeButtonActionPerformed(evt);
}
});
CanonicizersPanel_SetToAllDocuments.setText("Set to All Docs");
CanonicizersPanel_SetToAllDocuments.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CanonicizersPanel_SetToAllDocumentsActionPerformed(evt);
}
});
jLabel29.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24));
jLabel29.setText("Selected");
jLabel30.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24));
jLabel30.setText("Canonicizers");
jLabel32.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24));
jLabel32.setText("Canonicizer Description");
jLabel33.setText("Note: These buttons are used to add");
jLabel34.setText("selected canonicizers to documents.");
javax.swing.GroupLayout JGAAP_CanonicizerPanelLayout = new javax.swing.GroupLayout(JGAAP_CanonicizerPanel);
JGAAP_CanonicizerPanel.setLayout(JGAAP_CanonicizerPanelLayout);
JGAAP_CanonicizerPanelLayout.setHorizontalGroup(
JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(JGAAP_CanonicizerPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(JGAAP_CanonicizerPanelLayout.createSequentialGroup()
.addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(JGAAP_CanonicizerPanelLayout.createSequentialGroup()
.addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel30)
.addComponent(jScrollPane12, javax.swing.GroupLayout.DEFAULT_SIZE, 155, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(CanonicizersPanel_AddCanonicizerButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(CanonicizersPanel_RemoveCanonicizerButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(CanonicizersPanel_AddAllCanonicizersButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(CanonicizersPanel_RemoveAllCanonicizersButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
.addComponent(jLabel33)
.addComponent(jLabel34))
.addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(CanonicizersPanel_SetToDocumentTypeButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 153, Short.MAX_VALUE)
.addComponent(jLabel29)
.addComponent(CanonicizersPanel_SetToDocumentButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 153, Short.MAX_VALUE)
.addComponent(jScrollPane13, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 153, Short.MAX_VALUE)
.addComponent(CanonicizersPanel_SetToAllDocuments, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 153, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane20, javax.swing.GroupLayout.DEFAULT_SIZE, 437, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, JGAAP_CanonicizerPanelLayout.createSequentialGroup()
.addComponent(jLabel27)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 255, Short.MAX_VALUE)
.addComponent(CanonicizersPanel_NotesButton))))
.addGroup(JGAAP_CanonicizerPanelLayout.createSequentialGroup()
.addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jScrollPane21, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel31, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel32)
.addComponent(jScrollPane11, javax.swing.GroupLayout.DEFAULT_SIZE, 463, Short.MAX_VALUE))))
.addContainerGap())
);
JGAAP_CanonicizerPanelLayout.setVerticalGroup(
JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, JGAAP_CanonicizerPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel27)
.addComponent(jLabel30)
.addComponent(jLabel29))
.addGroup(JGAAP_CanonicizerPanelLayout.createSequentialGroup()
.addGap(5, 5, 5)
.addComponent(CanonicizersPanel_NotesButton)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane20, javax.swing.GroupLayout.DEFAULT_SIZE, 304, Short.MAX_VALUE)
.addGroup(JGAAP_CanonicizerPanelLayout.createSequentialGroup()
.addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(JGAAP_CanonicizerPanelLayout.createSequentialGroup()
.addComponent(CanonicizersPanel_AddCanonicizerButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(CanonicizersPanel_RemoveCanonicizerButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(CanonicizersPanel_AddAllCanonicizersButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(CanonicizersPanel_RemoveAllCanonicizersButton))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, JGAAP_CanonicizerPanelLayout.createSequentialGroup()
.addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane13, javax.swing.GroupLayout.DEFAULT_SIZE, 217, Short.MAX_VALUE)
.addComponent(jScrollPane12, javax.swing.GroupLayout.DEFAULT_SIZE, 217, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(CanonicizersPanel_SetToDocumentButton)))
.addGap(6, 6, 6)
.addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(JGAAP_CanonicizerPanelLayout.createSequentialGroup()
.addComponent(jLabel33)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel34)
.addGap(18, 18, 18))
.addGroup(JGAAP_CanonicizerPanelLayout.createSequentialGroup()
.addComponent(CanonicizersPanel_SetToDocumentTypeButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(CanonicizersPanel_SetToAllDocuments)))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel31)
.addComponent(jLabel32))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane21, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jScrollPane11, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
JGAAP_TabbedPane.addTab("Canonicizers", JGAAP_CanonicizerPanel);
EventSetsPanel_NotesButton.setLabel("Notes");
EventSetsPanel_NotesButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EventSetsPanel_NotesButtonActionPerformed(evt);
}
});
jLabel6.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N
jLabel6.setText("Event Drivers");
jLabel7.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24));
jLabel7.setText("Parameters");
jLabel8.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24));
jLabel8.setText("Event Driver Description");
jLabel9.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24));
jLabel9.setText("Selected");
EventSetsPanel_EventSetListBox.setModel(EventSetsListBox_Model);
EventSetsPanel_EventSetListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
EventSetsPanel_EventSetListBox.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
EventSetsPanel_EventSetListBoxMouseClicked(evt);
}
});
EventSetsPanel_EventSetListBox.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseMoved(java.awt.event.MouseEvent evt) {
EventSetsPanel_EventSetListBoxMouseMoved(evt);
}
});
jScrollPane9.setViewportView(EventSetsPanel_EventSetListBox);
EventSetsPanel_SelectedEventSetListBox.setModel(SelectedEventSetsListBox_Model);
EventSetsPanel_SelectedEventSetListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
EventSetsPanel_SelectedEventSetListBox.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
EventSetsPanel_SelectedEventSetListBoxMouseClicked(evt);
}
});
EventSetsPanel_SelectedEventSetListBox.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseMoved(java.awt.event.MouseEvent evt) {
EventSetsPanel_SelectedEventSetListBoxMouseMoved(evt);
}
});
jScrollPane10.setViewportView(EventSetsPanel_SelectedEventSetListBox);
EventSetsPanel_ParametersPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder());
javax.swing.GroupLayout EventSetsPanel_ParametersPanelLayout = new javax.swing.GroupLayout(EventSetsPanel_ParametersPanel);
EventSetsPanel_ParametersPanel.setLayout(EventSetsPanel_ParametersPanelLayout);
EventSetsPanel_ParametersPanelLayout.setHorizontalGroup(
EventSetsPanel_ParametersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 344, Short.MAX_VALUE)
);
EventSetsPanel_ParametersPanelLayout.setVerticalGroup(
EventSetsPanel_ParametersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
EventSetsPanel_EventSetDescriptionTextBox.setColumns(20);
EventSetsPanel_EventSetDescriptionTextBox.setLineWrap(true);
EventSetsPanel_EventSetDescriptionTextBox.setRows(5);
EventSetsPanel_EventSetDescriptionTextBox.setWrapStyleWord(true);
jScrollPane6.setViewportView(EventSetsPanel_EventSetDescriptionTextBox);
EventSetsPanel_AddEventSetButton.setText(">");
EventSetsPanel_AddEventSetButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EventSetsPanel_AddEventSetButtonActionPerformed(evt);
}
});
EventSetsPanel_RemoveEventSetButton.setText("<");
EventSetsPanel_RemoveEventSetButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EventSetsPanel_RemoveEventSetButtonActionPerformed(evt);
}
});
EventSetsPanel_AddAllEventSetsButton.setText("All");
EventSetsPanel_AddAllEventSetsButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EventSetsPanel_AddAllEventSetsButtonActionPerformed(evt);
}
});
EventSetsPanel_RemoveAllEventSetsButton.setText("Clear");
EventSetsPanel_RemoveAllEventSetsButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EventSetsPanel_RemoveAllEventSetsButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout JGAAP_EventSetsPanelLayout = new javax.swing.GroupLayout(JGAAP_EventSetsPanel);
JGAAP_EventSetsPanel.setLayout(JGAAP_EventSetsPanelLayout);
JGAAP_EventSetsPanelLayout.setHorizontalGroup(
JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, JGAAP_EventSetsPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane6, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 824, Short.MAX_VALUE)
.addComponent(jLabel8, javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(JGAAP_EventSetsPanelLayout.createSequentialGroup()
.addGroup(JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane9, javax.swing.GroupLayout.PREFERRED_SIZE, 178, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel6))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(EventSetsPanel_RemoveEventSetButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(EventSetsPanel_AddAllEventSetsButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(EventSetsPanel_AddEventSetButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(EventSetsPanel_RemoveAllEventSetsButton, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel9)
.addComponent(jScrollPane10, javax.swing.GroupLayout.PREFERRED_SIZE, 216, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(JGAAP_EventSetsPanelLayout.createSequentialGroup()
.addComponent(jLabel7)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 163, Short.MAX_VALUE)
.addComponent(EventSetsPanel_NotesButton))
.addComponent(EventSetsPanel_ParametersPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
.addContainerGap())
);
JGAAP_EventSetsPanelLayout.setVerticalGroup(
JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(JGAAP_EventSetsPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6)
.addComponent(jLabel9))
.addGroup(JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(EventSetsPanel_NotesButton)
.addComponent(jLabel7)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(EventSetsPanel_ParametersPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane10, javax.swing.GroupLayout.DEFAULT_SIZE, 304, Short.MAX_VALUE)
.addComponent(jScrollPane9, javax.swing.GroupLayout.DEFAULT_SIZE, 304, Short.MAX_VALUE)
.addGroup(JGAAP_EventSetsPanelLayout.createSequentialGroup()
.addComponent(EventSetsPanel_AddEventSetButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(EventSetsPanel_RemoveEventSetButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(EventSetsPanel_AddAllEventSetsButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(EventSetsPanel_RemoveAllEventSetsButton)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel8)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane6, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
JGAAP_TabbedPane.addTab("Event Drivers", JGAAP_EventSetsPanel);
jLabel15.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N
jLabel15.setText("Event Culling");
jLabel16.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24));
jLabel16.setText("Parameters");
jLabel17.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24));
jLabel17.setText("Selected");
EventCullingPanel_NotesButton.setLabel("Notes");
EventCullingPanel_NotesButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EventCullingPanel_NotesButtonActionPerformed(evt);
}
});
EventCullingPanel_SelectedEventCullingListBox.setModel(SelectedEventCullingListBox_Model);
EventCullingPanel_SelectedEventCullingListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
EventCullingPanel_SelectedEventCullingListBox.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
EventCullingPanel_SelectedEventCullingListBoxMouseClicked(evt);
}
});
EventCullingPanel_SelectedEventCullingListBox.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseMoved(java.awt.event.MouseEvent evt) {
EventCullingPanel_SelectedEventCullingListBoxMouseMoved(evt);
}
});
jScrollPane14.setViewportView(EventCullingPanel_SelectedEventCullingListBox);
EventCullingPanel_AddEventCullingButton.setText(">");
EventCullingPanel_AddEventCullingButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EventCullingPanel_AddEventCullingButtonActionPerformed(evt);
}
});
EventCullingPanel_RemoveEventCullingButton.setText("<");
EventCullingPanel_RemoveEventCullingButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EventCullingPanel_RemoveEventCullingButtonActionPerformed(evt);
}
});
EventCullingPanel_AddAllEventCullingButton.setText("All");
EventCullingPanel_AddAllEventCullingButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EventCullingPanel_AddAllEventCullingButtonActionPerformed(evt);
}
});
EventCullingPanel_RemoveAllEventCullingButton.setText("Clear");
EventCullingPanel_RemoveAllEventCullingButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EventCullingPanel_RemoveAllEventCullingButtonActionPerformed(evt);
}
});
EventCullingPanel_ParametersPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder());
javax.swing.GroupLayout EventCullingPanel_ParametersPanelLayout = new javax.swing.GroupLayout(EventCullingPanel_ParametersPanel);
EventCullingPanel_ParametersPanel.setLayout(EventCullingPanel_ParametersPanelLayout);
EventCullingPanel_ParametersPanelLayout.setHorizontalGroup(
EventCullingPanel_ParametersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 343, Short.MAX_VALUE)
);
EventCullingPanel_ParametersPanelLayout.setVerticalGroup(
EventCullingPanel_ParametersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
EventCullingPanel_EventCullingListBox.setModel(EventCullingListBox_Model);
EventCullingPanel_EventCullingListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
EventCullingPanel_EventCullingListBox.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
EventCullingPanel_EventCullingListBoxMouseClicked(evt);
}
});
EventCullingPanel_EventCullingListBox.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseMoved(java.awt.event.MouseEvent evt) {
EventCullingPanel_EventCullingListBoxMouseMoved(evt);
}
});
jScrollPane15.setViewportView(EventCullingPanel_EventCullingListBox);
EventCullingPanel_EventCullingDescriptionTextbox.setColumns(20);
EventCullingPanel_EventCullingDescriptionTextbox.setLineWrap(true);
EventCullingPanel_EventCullingDescriptionTextbox.setRows(5);
EventCullingPanel_EventCullingDescriptionTextbox.setWrapStyleWord(true);
jScrollPane16.setViewportView(EventCullingPanel_EventCullingDescriptionTextbox);
jLabel18.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24));
jLabel18.setText("Event Culling Description");
javax.swing.GroupLayout JGAAP_EventCullingPanelLayout = new javax.swing.GroupLayout(JGAAP_EventCullingPanel);
JGAAP_EventCullingPanel.setLayout(JGAAP_EventCullingPanelLayout);
JGAAP_EventCullingPanelLayout.setHorizontalGroup(
JGAAP_EventCullingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, JGAAP_EventCullingPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(JGAAP_EventCullingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane16, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 824, Short.MAX_VALUE)
.addComponent(jLabel18, javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(JGAAP_EventCullingPanelLayout.createSequentialGroup()
.addGroup(JGAAP_EventCullingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane15, javax.swing.GroupLayout.PREFERRED_SIZE, 178, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel15))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_EventCullingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(EventCullingPanel_RemoveEventCullingButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(EventCullingPanel_AddAllEventCullingButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(EventCullingPanel_AddEventCullingButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(EventCullingPanel_RemoveAllEventCullingButton, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_EventCullingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel17)
.addComponent(jScrollPane14, javax.swing.GroupLayout.PREFERRED_SIZE, 217, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_EventCullingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(JGAAP_EventCullingPanelLayout.createSequentialGroup()
.addComponent(jLabel16)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 162, Short.MAX_VALUE)
.addComponent(EventCullingPanel_NotesButton))
.addComponent(EventCullingPanel_ParametersPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
.addContainerGap())
);
JGAAP_EventCullingPanelLayout.setVerticalGroup(
JGAAP_EventCullingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(JGAAP_EventCullingPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(JGAAP_EventCullingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(JGAAP_EventCullingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel15)
.addComponent(jLabel17)
.addComponent(jLabel16))
.addComponent(EventCullingPanel_NotesButton))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_EventCullingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane14, javax.swing.GroupLayout.DEFAULT_SIZE, 304, Short.MAX_VALUE)
.addComponent(EventCullingPanel_ParametersPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane15, javax.swing.GroupLayout.DEFAULT_SIZE, 304, Short.MAX_VALUE)
.addGroup(JGAAP_EventCullingPanelLayout.createSequentialGroup()
.addComponent(EventCullingPanel_AddEventCullingButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(EventCullingPanel_RemoveEventCullingButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(EventCullingPanel_AddAllEventCullingButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(EventCullingPanel_RemoveAllEventCullingButton)
.addGap(107, 107, 107)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel18)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane16, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
JGAAP_TabbedPane.addTab("Event Culling", JGAAP_EventCullingPanel);
jLabel20.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N
jLabel20.setText("Analysis Methods");
jLabel21.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24));
jLabel21.setText("AM Parameters");
jLabel22.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24));
jLabel22.setText("Selected");
AnalysisMethodPanel_NotesButton.setLabel("Notes");
AnalysisMethodPanel_NotesButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
AnalysisMethodPanel_NotesButtonActionPerformed(evt);
}
});
AnalysisMethodPanel_SelectedAnalysisMethodsListBox.setModel(SelectedAnalysisMethodListBox_Model);
AnalysisMethodPanel_SelectedAnalysisMethodsListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
AnalysisMethodPanel_SelectedAnalysisMethodsListBox.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
AnalysisMethodPanel_SelectedAnalysisMethodsListBoxMouseClicked(evt);
}
});
AnalysisMethodPanel_SelectedAnalysisMethodsListBox.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseMoved(java.awt.event.MouseEvent evt) {
AnalysisMethodPanel_SelectedAnalysisMethodsListBoxMouseMoved(evt);
}
});
jScrollPane17.setViewportView(AnalysisMethodPanel_SelectedAnalysisMethodsListBox);
AnalysisMethodPanel_AddAnalysisMethodButton.setText(">");
AnalysisMethodPanel_AddAnalysisMethodButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
AnalysisMethodPanel_AddAnalysisMethodButtonActionPerformed(evt);
}
});
AnalysisMethodPanel_RemoveAnalysisMethodsButton.setText("<");
AnalysisMethodPanel_RemoveAnalysisMethodsButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
AnalysisMethodPanel_RemoveAnalysisMethodsButtonActionPerformed(evt);
}
});
AnalysisMethodPanel_AddAllAnalysisMethodsButton.setText("All");
AnalysisMethodPanel_AddAllAnalysisMethodsButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
AnalysisMethodPanel_AddAllAnalysisMethodsButtonActionPerformed(evt);
}
});
AnalysisMethodPanel_RemoveAllAnalysisMethodsButton.setText("Clear");
AnalysisMethodPanel_RemoveAllAnalysisMethodsButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
AnalysisMethodPanel_RemoveAllAnalysisMethodsButtonActionPerformed(evt);
}
});
AnalysisMethodPanel_AMParametersPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder());
javax.swing.GroupLayout AnalysisMethodPanel_AMParametersPanelLayout = new javax.swing.GroupLayout(AnalysisMethodPanel_AMParametersPanel);
AnalysisMethodPanel_AMParametersPanel.setLayout(AnalysisMethodPanel_AMParametersPanelLayout);
AnalysisMethodPanel_AMParametersPanelLayout.setHorizontalGroup(
AnalysisMethodPanel_AMParametersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 355, Short.MAX_VALUE)
);
AnalysisMethodPanel_AMParametersPanelLayout.setVerticalGroup(
AnalysisMethodPanel_AMParametersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 125, Short.MAX_VALUE)
);
AnalysisMethodPanel_AnalysisMethodsListBox.setModel(AnalysisMethodListBox_Model);
AnalysisMethodPanel_AnalysisMethodsListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
AnalysisMethodPanel_AnalysisMethodsListBox.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
AnalysisMethodPanel_AnalysisMethodsListBoxMouseClicked(evt);
}
});
AnalysisMethodPanel_AnalysisMethodsListBox.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseMoved(java.awt.event.MouseEvent evt) {
AnalysisMethodPanel_AnalysisMethodsListBoxMouseMoved(evt);
}
});
jScrollPane18.setViewportView(AnalysisMethodPanel_AnalysisMethodsListBox);
jLabel28.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N
jLabel28.setText("Distance Function Description");
AnalysisMethodPanel_AnalysisMethodDescriptionTextBox.setColumns(20);
AnalysisMethodPanel_AnalysisMethodDescriptionTextBox.setLineWrap(true);
AnalysisMethodPanel_AnalysisMethodDescriptionTextBox.setRows(5);
AnalysisMethodPanel_AnalysisMethodDescriptionTextBox.setWrapStyleWord(true);
jScrollPane19.setViewportView(AnalysisMethodPanel_AnalysisMethodDescriptionTextBox);
AnalysisMethodPanel_DistanceFunctionsListBox.setModel(DistanceFunctionsListBox_Model);
AnalysisMethodPanel_DistanceFunctionsListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
AnalysisMethodPanel_DistanceFunctionsListBox.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
AnalysisMethodPanel_DistanceFunctionsListBoxMouseClicked(evt);
}
});
AnalysisMethodPanel_DistanceFunctionsListBox.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseMoved(java.awt.event.MouseEvent evt) {
AnalysisMethodPanel_DistanceFunctionsListBoxMouseMoved(evt);
}
});
jScrollPane22.setViewportView(AnalysisMethodPanel_DistanceFunctionsListBox);
jLabel35.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N
jLabel35.setText("Distance Functions");
AnalysisMethodPanel_DistanceFunctionDescriptionTextBox.setColumns(20);
AnalysisMethodPanel_DistanceFunctionDescriptionTextBox.setLineWrap(true);
AnalysisMethodPanel_DistanceFunctionDescriptionTextBox.setRows(5);
AnalysisMethodPanel_DistanceFunctionDescriptionTextBox.setWrapStyleWord(true);
jScrollPane23.setViewportView(AnalysisMethodPanel_DistanceFunctionDescriptionTextBox);
jLabel36.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N
jLabel36.setText("Analysis Method Description");
AnalysisMethodPanel_DFParametersPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder());
javax.swing.GroupLayout AnalysisMethodPanel_DFParametersPanelLayout = new javax.swing.GroupLayout(AnalysisMethodPanel_DFParametersPanel);
AnalysisMethodPanel_DFParametersPanel.setLayout(AnalysisMethodPanel_DFParametersPanelLayout);
AnalysisMethodPanel_DFParametersPanelLayout.setHorizontalGroup(
AnalysisMethodPanel_DFParametersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 355, Short.MAX_VALUE)
);
AnalysisMethodPanel_DFParametersPanelLayout.setVerticalGroup(
AnalysisMethodPanel_DFParametersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 128, Short.MAX_VALUE)
);
jLabel37.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24));
jLabel37.setText("DF Parameters");
javax.swing.GroupLayout JGAAP_AnalysisMethodPanelLayout = new javax.swing.GroupLayout(JGAAP_AnalysisMethodPanel);
JGAAP_AnalysisMethodPanel.setLayout(JGAAP_AnalysisMethodPanelLayout);
JGAAP_AnalysisMethodPanelLayout.setHorizontalGroup(
JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, JGAAP_AnalysisMethodPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(JGAAP_AnalysisMethodPanelLayout.createSequentialGroup()
.addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel35, javax.swing.GroupLayout.DEFAULT_SIZE, 257, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, JGAAP_AnalysisMethodPanelLayout.createSequentialGroup()
.addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane22, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 187, Short.MAX_VALUE)
.addComponent(jScrollPane18, javax.swing.GroupLayout.Alignment.LEADING, 0, 0, Short.MAX_VALUE)
.addComponent(jLabel20, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(AnalysisMethodPanel_RemoveAnalysisMethodsButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(AnalysisMethodPanel_AddAllAnalysisMethodsButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(AnalysisMethodPanel_AddAnalysisMethodButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(AnalysisMethodPanel_RemoveAllAnalysisMethodsButton, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel22)
.addComponent(jScrollPane17, javax.swing.GroupLayout.PREFERRED_SIZE, 196, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(AnalysisMethodPanel_DFParametersPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(AnalysisMethodPanel_AMParametersPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(JGAAP_AnalysisMethodPanelLayout.createSequentialGroup()
.addComponent(jLabel21)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 133, Short.MAX_VALUE)
.addComponent(AnalysisMethodPanel_NotesButton))
.addComponent(jLabel37)))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, JGAAP_AnalysisMethodPanelLayout.createSequentialGroup()
.addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane19, javax.swing.GroupLayout.PREFERRED_SIZE, 405, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel36))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel28)
.addComponent(jScrollPane23, javax.swing.GroupLayout.DEFAULT_SIZE, 413, Short.MAX_VALUE))))
.addContainerGap())
);
JGAAP_AnalysisMethodPanelLayout.setVerticalGroup(
JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(JGAAP_AnalysisMethodPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel20)
.addComponent(jLabel21)
.addComponent(jLabel22)
.addComponent(AnalysisMethodPanel_NotesButton))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane17, javax.swing.GroupLayout.DEFAULT_SIZE, 301, Short.MAX_VALUE)
.addGroup(JGAAP_AnalysisMethodPanelLayout.createSequentialGroup()
.addComponent(AnalysisMethodPanel_AMParametersPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel37)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(AnalysisMethodPanel_DFParametersPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(JGAAP_AnalysisMethodPanelLayout.createSequentialGroup()
.addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(JGAAP_AnalysisMethodPanelLayout.createSequentialGroup()
.addComponent(AnalysisMethodPanel_AddAnalysisMethodButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(AnalysisMethodPanel_RemoveAnalysisMethodsButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(AnalysisMethodPanel_AddAllAnalysisMethodsButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(AnalysisMethodPanel_RemoveAllAnalysisMethodsButton))
.addComponent(jScrollPane18, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel35)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane22, javax.swing.GroupLayout.DEFAULT_SIZE, 132, Short.MAX_VALUE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel28)
.addComponent(jLabel36))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane19, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jScrollPane23, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
JGAAP_TabbedPane.addTab("Analysis Methods", JGAAP_AnalysisMethodPanel);
ReviewPanel_ProcessButton.setLabel("Process");
ReviewPanel_ProcessButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ReviewPanel_ProcessButtonActionPerformed(evt);
}
});
ReviewPanel_DocumentsLabel.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N
ReviewPanel_DocumentsLabel.setText("Documents");
ReviewPanel_DocumentsLabel.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
ReviewPanel_DocumentsLabelMouseClicked(evt);
}
});
ReviewPanel_DocumentsTable.setModel(DocumentsTable_Model);
ReviewPanel_DocumentsTable.setEnabled(false);
ReviewPanel_DocumentsTable.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
ReviewPanel_DocumentsTableMouseClicked(evt);
}
});
jScrollPane24.setViewportView(ReviewPanel_DocumentsTable);
ReviewPanel_SelectedEventSetLabel.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N
ReviewPanel_SelectedEventSetLabel.setText("Event Driver");
ReviewPanel_SelectedEventSetLabel.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
ReviewPanel_SelectedEventSetLabelMouseClicked(evt);
}
});
ReviewPanel_SelectedEventCullingLabel.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N
ReviewPanel_SelectedEventCullingLabel.setText("Event Culling");
ReviewPanel_SelectedEventCullingLabel.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
ReviewPanel_SelectedEventCullingLabelMouseClicked(evt);
}
});
ReviewPanel_SelectedAnalysisMethodsLabel.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N
ReviewPanel_SelectedAnalysisMethodsLabel.setText("Analysis Methods");
ReviewPanel_SelectedAnalysisMethodsLabel.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
ReviewPanel_SelectedAnalysisMethodsLabelMouseClicked(evt);
}
});
ReviewPanel_SelectedEventSetListBox.setModel(SelectedEventSetsListBox_Model);
ReviewPanel_SelectedEventSetListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
ReviewPanel_SelectedEventSetListBox.setEnabled(false);
ReviewPanel_SelectedEventSetListBox.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
ReviewPanel_SelectedEventSetListBoxMouseClicked(evt);
}
});
jScrollPane25.setViewportView(ReviewPanel_SelectedEventSetListBox);
ReviewPanel_SelectedEventCullingListBox.setModel(SelectedEventCullingListBox_Model);
ReviewPanel_SelectedEventCullingListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
ReviewPanel_SelectedEventCullingListBox.setEnabled(false);
ReviewPanel_SelectedEventCullingListBox.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
ReviewPanel_SelectedEventCullingListBoxMouseClicked(evt);
}
});
jScrollPane26.setViewportView(ReviewPanel_SelectedEventCullingListBox);
ReviewPanel_SelectedAnalysisMethodsListBox.setModel(SelectedAnalysisMethodListBox_Model);
ReviewPanel_SelectedAnalysisMethodsListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
ReviewPanel_SelectedAnalysisMethodsListBox.setEnabled(false);
ReviewPanel_SelectedAnalysisMethodsListBox.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
ReviewPanel_SelectedAnalysisMethodsListBoxMouseClicked(evt);
}
});
jScrollPane27.setViewportView(ReviewPanel_SelectedAnalysisMethodsListBox);
javax.swing.GroupLayout JGAAP_ReviewPanelLayout = new javax.swing.GroupLayout(JGAAP_ReviewPanel);
JGAAP_ReviewPanel.setLayout(JGAAP_ReviewPanelLayout);
JGAAP_ReviewPanelLayout.setHorizontalGroup(
JGAAP_ReviewPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, JGAAP_ReviewPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(JGAAP_ReviewPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane24, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 824, Short.MAX_VALUE)
.addComponent(ReviewPanel_DocumentsLabel, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(ReviewPanel_ProcessButton)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, JGAAP_ReviewPanelLayout.createSequentialGroup()
.addGroup(JGAAP_ReviewPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane25, javax.swing.GroupLayout.PREFERRED_SIZE, 273, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(ReviewPanel_SelectedEventSetLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_ReviewPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(ReviewPanel_SelectedEventCullingLabel)
.addComponent(jScrollPane26, javax.swing.GroupLayout.PREFERRED_SIZE, 268, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_ReviewPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(ReviewPanel_SelectedAnalysisMethodsLabel)
.addComponent(jScrollPane27, javax.swing.GroupLayout.DEFAULT_SIZE, 271, Short.MAX_VALUE))))
.addContainerGap())
);
JGAAP_ReviewPanelLayout.setVerticalGroup(
JGAAP_ReviewPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(JGAAP_ReviewPanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(ReviewPanel_DocumentsLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane24, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_ReviewPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(ReviewPanel_SelectedEventSetLabel)
.addComponent(ReviewPanel_SelectedEventCullingLabel)
.addComponent(ReviewPanel_SelectedAnalysisMethodsLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(JGAAP_ReviewPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane27, javax.swing.GroupLayout.DEFAULT_SIZE, 258, Short.MAX_VALUE)
.addComponent(jScrollPane26, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 258, Short.MAX_VALUE)
.addComponent(jScrollPane25, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 258, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(ReviewPanel_ProcessButton)
.addContainerGap())
);
JGAAP_TabbedPane.addTab("Review & Process", JGAAP_ReviewPanel);
Next_Button.setText("Next >");
Next_Button.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Next_ButtonActionPerformed(evt);
}
});
Review_Button.setText("Finish & Review");
Review_Button.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Review_ButtonActionPerformed(evt);
}
});
jMenu1.setText("File");
jMenu4.setText("Batch Documents");
BatchSaveMenuItem.setText("Save Documents");
BatchSaveMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BatchSaveMenuItemActionPerformed(evt);
}
});
jMenu4.add(BatchSaveMenuItem);
BatchLoadMenuItem.setText("Load Documents");
BatchLoadMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BatchLoadMenuItemActionPerformed(evt);
}
});
jMenu4.add(BatchLoadMenuItem);
jMenu1.add(jMenu4);
jMenu2.setText("AAAC Problems");
ProblemAMenuItem.setText("Problem A");
ProblemAMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ProblemAMenuItemActionPerformed(evt);
}
});
jMenu2.add(ProblemAMenuItem);
ProblemBMenuItem.setText("Problem B");
ProblemBMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ProblemBMenuItemActionPerformed(evt);
}
});
jMenu2.add(ProblemBMenuItem);
ProblemCMenuItem.setText("Problem C");
ProblemCMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ProblemCMenuItemActionPerformed(evt);
}
});
jMenu2.add(ProblemCMenuItem);
ProblemDMenuItem.setText("Problem D");
ProblemDMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ProblemDMenuItemActionPerformed(evt);
}
});
jMenu2.add(ProblemDMenuItem);
ProblemEMenuItem.setText("Problem E");
ProblemEMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ProblemEMenuItemActionPerformed(evt);
}
});
jMenu2.add(ProblemEMenuItem);
ProblemFMenuItem.setText("Problem F");
ProblemFMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ProblemFMenuItemActionPerformed(evt);
}
});
jMenu2.add(ProblemFMenuItem);
ProblemGMenuItem.setText("Problem G");
ProblemGMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ProblemGMenuItemActionPerformed(evt);
}
});
jMenu2.add(ProblemGMenuItem);
ProblemHMenuItem.setText("Problem H");
ProblemHMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ProblemHMenuItemActionPerformed(evt);
}
});
jMenu2.add(ProblemHMenuItem);
ProblemIMenuItem.setText("Problem I");
ProblemIMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ProblemIMenuItemActionPerformed(evt);
}
});
jMenu2.add(ProblemIMenuItem);
ProblemJMenuItem.setText("Problem J");
ProblemJMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ProblemJMenuItemActionPerformed(evt);
}
});
jMenu2.add(ProblemJMenuItem);
ProblemKMenuItem.setText("Problem K");
ProblemKMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ProblemKMenuItemActionPerformed(evt);
}
});
jMenu2.add(ProblemKMenuItem);
ProblemLMenuItem.setText("Problem L");
ProblemLMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ProblemLMenuItemActionPerformed(evt);
}
});
jMenu2.add(ProblemLMenuItem);
ProblemMMenuItem.setText("Problem M");
ProblemMMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ProblemMMenuItemActionPerformed(evt);
}
});
jMenu2.add(ProblemMMenuItem);
jMenu1.add(jMenu2);
exitMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Q, java.awt.event.InputEvent.CTRL_MASK));
exitMenuItem.setText("Exit");
exitMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
exitMenuItemActionPerformed(evt);
}
});
jMenu1.add(exitMenuItem);
JGAAP_MenuBar.add(jMenu1);
helpMenu.setText("Help");
aboutMenuItem.setText("About..");
aboutMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
aboutMenuItemActionPerformed(evt);
}
});
helpMenu.add(aboutMenuItem);
JGAAP_MenuBar.add(helpMenu);
setJMenuBar(JGAAP_MenuBar);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(JGAAP_TabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, 849, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(Review_Button)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(Next_Button)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(JGAAP_TabbedPane, javax.swing.GroupLayout.PREFERRED_SIZE, 529, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(Next_Button)
.addComponent(Review_Button))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
|
diff --git a/src/main/java/org/acra/ErrorReporter.java b/src/main/java/org/acra/ErrorReporter.java
index dc01d0b..8904121 100644
--- a/src/main/java/org/acra/ErrorReporter.java
+++ b/src/main/java/org/acra/ErrorReporter.java
@@ -1,889 +1,882 @@
/*
* Copyright 2010 Emmanuel Astier & Kevin Gaudin
*
* 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.acra;
import android.Manifest.permission;
import android.app.Application;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.os.Looper;
import android.text.format.Time;
import android.util.Log;
import android.widget.Toast;
import org.acra.annotation.ReportsCrashes;
import org.acra.collector.ConfigurationCollector;
import org.acra.collector.CrashReportData;
import org.acra.collector.CrashReportDataFactory;
import org.acra.sender.EmailIntentSender;
import org.acra.sender.GoogleFormSender;
import org.acra.sender.HttpPostSender;
import org.acra.sender.ReportSender;
import org.acra.util.PackageManagerWrapper;
import org.acra.util.ToastSender;
import java.io.File;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.acra.ACRA.LOG_TAG;
import static org.acra.ReportField.IS_SILENT;
/**
* <p>
* The ErrorReporter is a Singleton object in charge of collecting crash context
* data and sending crash reports. It registers itself as the Application's
* Thread default {@link UncaughtExceptionHandler}.
* </p>
* <p>
* When a crash occurs, it collects data of the crash context (device, system,
* stack trace...) and writes a report file in the application private
* directory. This report file is then sent :
* <ul>
* <li>immediately if {@link ReportsCrashes#mode} is set to
* {@link ReportingInteractionMode#SILENT} or
* {@link ReportingInteractionMode#TOAST},</li>
* <li>on application start if in the previous case the transmission could not
* technically be made,</li>
* <li>when the user accepts to send it if {@link ReportsCrashes#mode()} is set
* to {@link ReportingInteractionMode#NOTIFICATION}.</li>
* </ul>
* </p>
* <p>
* If an error occurs while sending a report, it is kept for later attempts.
* </p>
*/
public class ErrorReporter implements Thread.UncaughtExceptionHandler {
private boolean enabled = false;
private final Context mContext;
private final SharedPreferences prefs;
/**
* Contains the active {@link ReportSender}s.
*/
private final List<ReportSender> mReportSenders = new ArrayList<ReportSender>();
private final CrashReportDataFactory crashReportDataFactory;
private final CrashReportFileNameParser fileNameParser = new CrashReportFileNameParser();
// A reference to the system's previous default UncaughtExceptionHandler
// kept in order to execute the default exception handling after sending the
// report.
private final Thread.UncaughtExceptionHandler mDfltExceptionHandler;
private Thread brokenThread;
private Throwable unhandledThrowable;
/**
* This is used to wait for the crash toast to end it's display duration
* before killing the Application.
*/
private static boolean toastWaitEnded = true;
/**
* Can only be constructed from within this class.
*
* @param context
* Context for the application in which ACRA is running.
* @param prefs
* SharedPreferences used by ACRA.
* @param enabled
* Whether this ErrorReporter should capture Exceptions and
* forward their reports.
*/
ErrorReporter(Context context, SharedPreferences prefs, boolean enabled) {
this.mContext = context;
this.prefs = prefs;
this.enabled = enabled;
// Store the initial Configuration state.
final String initialConfiguration = ConfigurationCollector.collectConfiguration(mContext);
// Sets the application start date.
// This will be included in the reports, will be helpful compared to
// user_crash date.
final Time appStartDate = new Time();
appStartDate.setToNow();
crashReportDataFactory = new CrashReportDataFactory(mContext, prefs, appStartDate, initialConfiguration);
// If mDfltExceptionHandler is not null, initialization is already done.
// Don't do it twice to avoid losing the original handler.
mDfltExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(this);
// Check for pending reports
checkReportsOnApplicationStart();
}
/**
* @return the current instance of ErrorReporter.
* @throws IllegalStateException
* if {@link ACRA#init(android.app.Application)} has not yet
* been called.
* @deprecated since 4.3.0 Use {@link org.acra.ACRA#getErrorReporter()}
* instead.
*/
public static ErrorReporter getInstance() {
return ACRA.getErrorReporter();
}
/**
* Deprecated. Use {@link #putCustomData(String, String)}.
*
* @param key
* A key for your custom data.
* @param value
* The value associated to your key.
*/
@Deprecated
public void addCustomData(String key, String value) {
crashReportDataFactory.putCustomData(key, value);
}
/**
* <p>
* Use this method to provide the ErrorReporter with data of your running
* application. You should call this at several key places in your code the
* same way as you would output important debug data in a log file. Only the
* latest value is kept for each key (no history of the values is sent in
* the report).
* </p>
* <p>
* The key/value pairs will be stored in the GoogleDoc spreadsheet in the
* "custom" column, as a text containing a 'key = value' pair on each line.
* </p>
*
* @param key
* A key for your custom data.
* @param value
* The value associated to your key.
* @return The previous value for this key if there was one, or null.
* @see #removeCustomData(String)
* @see #getCustomData(String)
*/
public String putCustomData(String key, String value) {
return crashReportDataFactory.putCustomData(key, value);
}
/**
* Removes a key/value pair from your reports custom data field.
*
* @param key
* The key of the data to be removed.
* @return The value for this key before removal.
* @see #putCustomData(String, String)
* @see #getCustomData(String)
*/
public String removeCustomData(String key) {
return crashReportDataFactory.removeCustomData(key);
}
/**
* Gets the current value for a key in your reports custom data field.
*
* @param key
* The key of the data to be retrieved.
* @return The value for this key.
* @see #putCustomData(String, String)
* @see #removeCustomData(String)
*/
public String getCustomData(String key) {
return crashReportDataFactory.getCustomData(key);
}
/**
* Add a {@link ReportSender} to the list of active {@link ReportSender}s.
*
* @param sender
* The {@link ReportSender} to be added.
*/
public void addReportSender(ReportSender sender) {
mReportSenders.add(sender);
}
/**
* Remove a specific instance of {@link ReportSender} from the list of
* active {@link ReportSender}s.
*
* @param sender
* The {@link ReportSender} instance to be removed.
*/
public void removeReportSender(ReportSender sender) {
mReportSenders.remove(sender);
}
/**
* Remove all {@link ReportSender} instances from a specific class.
*
* @param senderClass
* ReportSender class whose instances should be removed.
*/
public void removeReportSenders(Class<?> senderClass) {
if (ReportSender.class.isAssignableFrom(senderClass)) {
for (ReportSender sender : mReportSenders) {
if (senderClass.isInstance(sender)) {
mReportSenders.remove(sender);
}
}
}
}
/**
* Clears the list of active {@link ReportSender}s. You should then call
* {@link #addReportSender(ReportSender)} or ACRA will not send any report
* anymore.
*/
public void removeAllReportSenders() {
mReportSenders.clear();
}
/**
* Removes all previously set {@link ReportSender}s and set the given one as
* the new {@link ReportSender}.
*
* @param sender
* ReportSender to set as the sole sender for this ErrorReporter.
*/
public void setReportSender(ReportSender sender) {
removeAllReportSenders();
addReportSender(sender);
}
/*
* (non-Javadoc)
*
* @see
* java.lang.Thread.UncaughtExceptionHandler#uncaughtException(java.lang
* .Thread, java.lang.Throwable)
*/
public void uncaughtException(Thread t, Throwable e) {
try {
// If we're not enabled then just pass the Exception on to any
// defaultExceptionHandler.
if (!enabled) {
if (mDfltExceptionHandler != null) {
Log.e(ACRA.LOG_TAG, "ACRA is disabled for " + mContext.getPackageName()
+ " - forwarding uncaught Exception on to default ExceptionHandler");
mDfltExceptionHandler.uncaughtException(t, e);
} else {
Log.e(ACRA.LOG_TAG, "ACRA is disabled for " + mContext.getPackageName()
+ " - no default ExceptionHandler");
}
return;
}
brokenThread = t;
unhandledThrowable = e;
Log.e(ACRA.LOG_TAG,
"ACRA caught a " + e.getClass().getSimpleName() + " exception for " + mContext.getPackageName()
+ ". Building report.");
// Generate and send crash report
handleException(e, ACRA.getConfig().mode(), false, true);
} catch (Throwable fatality) {
// ACRA failed. Prevent any recursive call to
// ACRA.uncaughtException(), let the native reporter do its job.
if (mDfltExceptionHandler != null) {
mDfltExceptionHandler.uncaughtException(t, e);
}
}
}
/**
*
*/
private void endApplication() {
if (ACRA.getConfig().mode() == ReportingInteractionMode.SILENT
|| (ACRA.getConfig().mode() == ReportingInteractionMode.TOAST && ACRA.getConfig()
.forceCloseDialogAfterToast())) {
// If using silent mode, let the system default handler do it's job
// and display the force close dialog.
mDfltExceptionHandler.uncaughtException(brokenThread, unhandledThrowable);
} else {
// If ACRA handles user notifications with a Toast or a Notification
// the Force Close dialog is one more notification to the user...
// We choose to close the process ourselves using the same actions.
Log.e(LOG_TAG, mContext.getPackageName() + " fatal error : " + unhandledThrowable.getMessage(),
unhandledThrowable);
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(10);
}
}
/**
* Send a report for this {@link Throwable} silently (forces the use of
* {@link ReportingInteractionMode#SILENT} for this report, whatever is the
* mode set for the application. Very useful for tracking difficult defects.
*
* @param e
* The {@link Throwable} to be reported. If null the report will
* contain a new Exception("Report requested by developer").
*/
public void handleSilentException(Throwable e) {
// Mark this report as silent.
if (enabled) {
handleException(e, ReportingInteractionMode.SILENT, true, false);
Log.d(LOG_TAG, "ACRA sent Silent report.");
return;
}
Log.d(LOG_TAG, "ACRA is disabled. Silent report not sent.");
}
/**
* Enable or disable this ErrorReporter. By default it is enabled.
*
* @param enabled
* Whether this ErrorReporter should capture Exceptions and
* forward them as crash reports.
*/
public void setEnabled(boolean enabled) {
Log.i(ACRA.LOG_TAG, "ACRA is " + (enabled ? "enabled" : "disabled") + " for " + mContext.getPackageName());
this.enabled = enabled;
}
/**
* Starts a Thread to start sending outstanding error reports.
*
* @param onlySendSilentReports
* If true then only send silent reports.
* @param approveReportsFirst
* If true then approve unapproved reports first.
* @return SendWorker that will be sending the report.s
*/
SendWorker startSendingReports(boolean onlySendSilentReports, boolean approveReportsFirst) {
final SendWorker worker = new SendWorker(mContext, mReportSenders, onlySendSilentReports, approveReportsFirst);
worker.start();
return worker;
}
/**
* Delete all report files stored.
*/
void deletePendingReports() {
deletePendingReports(true, true, 0);
}
/**
* This method looks for pending reports and does the action required
* depending on the interaction mode set.
*/
private void checkReportsOnApplicationStart() {
// Delete any old unsent reports if this is a newer version of the app
// than when we last started.
final long lastVersionNr = prefs.getInt(ACRA.PREF_LAST_VERSION_NR, 0);
final PackageManagerWrapper packageManagerWrapper = new PackageManagerWrapper(mContext);
final PackageInfo packageInfo = packageManagerWrapper.getPackageInfo();
final boolean newVersion = (packageInfo != null && packageInfo.versionCode > lastVersionNr);
if (newVersion) {
if (ACRA.getConfig().deleteOldUnsentReportsOnApplicationStart()) {
deletePendingReports();
}
final SharedPreferences.Editor prefsEditor = prefs.edit();
prefsEditor.putInt(ACRA.PREF_LAST_VERSION_NR, packageInfo.versionCode);
prefsEditor.commit();
}
if ((ACRA.getConfig().mode() == ReportingInteractionMode.NOTIFICATION || ACRA.getConfig().mode() == ReportingInteractionMode.DIALOG)
&& ACRA.getConfig().deleteUnapprovedReportsOnApplicationStart()) {
// NOTIFICATION or DIALOG mode, and there are unapproved reports to
// send (latest notification/dialog has been ignored: neither
// accepted
// nor refused). The application developer has decided that
// these reports should not be renotified ==> destroy them all but
// one.
deletePendingNonApprovedReports(true);
}
final CrashReportFinder reportFinder = new CrashReportFinder(mContext);
String[] filesList = reportFinder.getCrashReportFiles();
if (filesList != null && filesList.length > 0) {
// Immediately send reports for SILENT and TOAST modes.
// Immediately send reports in NOTIFICATION mode only if they are
// all silent or approved.
// If there is still one unapproved report in NOTIFICATION mode,
// notify it.
// If there are unapproved reports in DIALOG mode, show the dialog
ReportingInteractionMode reportingInteractionMode = ACRA.getConfig().mode();
filesList = reportFinder.getCrashReportFiles();
final boolean onlySilentOrApprovedReports = containsOnlySilentOrApprovedReports(filesList);
if (reportingInteractionMode == ReportingInteractionMode.SILENT
|| reportingInteractionMode == ReportingInteractionMode.TOAST
|| (onlySilentOrApprovedReports && (reportingInteractionMode == ReportingInteractionMode.NOTIFICATION || reportingInteractionMode == ReportingInteractionMode.DIALOG))) {
if (reportingInteractionMode == ReportingInteractionMode.TOAST && !onlySilentOrApprovedReports) {
// Display the Toast in TOAST mode only if there are
// non-silent reports.
ToastSender.sendToast(mContext, ACRA.getConfig().resToastText(), Toast.LENGTH_LONG);
}
Log.v(ACRA.LOG_TAG, "About to start ReportSenderWorker from #checkReportOnApplicationStart");
startSendingReports(false, false);
} else if (ACRA.getConfig().mode() == ReportingInteractionMode.NOTIFICATION) {
// NOTIFICATION mode there are unapproved reports to send
// Display the notification.
// The user comment will be associated to the latest report
notifySendReport(getLatestNonSilentReport(filesList));
} else if (ACRA.getConfig().mode() == ReportingInteractionMode.DIALOG) {
// DIALOG mode: the dialog is always displayed because it has
// been put on the task stack before killing the app.
// The user can explicitly say Yes or No... or ignore the dialog
// with the back button.
// As there are unapproved reports to send, display the dialog.
// The user comment will be associated to the latest report
notifyDialog(getLatestNonSilentReport(filesList));
}
}
}
/**
* Delete all pending non approved reports.
*
* @param keepOne
* If you need to keep the latest report, set this to true.
*/
void deletePendingNonApprovedReports(boolean keepOne) {
// In NOTIFICATION AND DIALOG mode, we have to keep the latest report
// which
// has been writtent before killing the app.
final int nbReportsToKeep = keepOne ? 1 : 0;
deletePendingReports(false, true, nbReportsToKeep);
}
/**
* Send a report for a {@link Throwable} with the reporting interaction mode
* configured by the developer.
*
* @param e
* The {@link Throwable} to be reported. If null the report will
* contain a new Exception("Report requested by developer").
* @param endApplication
* Set this to true if you want the application to be ended after
* sending the report.
*/
public void handleException(Throwable e, boolean endApplication) {
handleException(e, ACRA.getConfig().mode(), false, endApplication);
}
/**
* Send a report for a {@link Throwable} with the reporting interaction mode
* configured by the developer, the application is then killed and restarted
* by the system.
*
* @param e
* The {@link Throwable} to be reported. If null the report will
* contain a new Exception("Report requested by developer").
*/
public void handleException(Throwable e) {
handleException(e, ACRA.getConfig().mode(), false, false);
}
/**
* Try to send a report, if an error occurs stores a report file for a later
* attempt.
*
* @param e
* Throwable to be reported. If null the report will contain a
* new Exception("Report requested by developer").
* @param reportingInteractionMode
* The desired interaction mode.
* @param forceSilentReport
* This report is to be sent silently, whatever mode has been
* configured.
* @param endApplication
* Whether to end the application once the error has been
* handled.
*/
private void handleException(Throwable e, ReportingInteractionMode reportingInteractionMode,
final boolean forceSilentReport, final boolean endApplication) {
if (!enabled) {
return;
}
boolean sendOnlySilentReports = false;
if (reportingInteractionMode == null) {
// No interaction mode defined, we assume it has been set during
// ACRA.initACRA()
reportingInteractionMode = ACRA.getConfig().mode();
} else {
// An interaction mode has been provided. If ACRA has been
// initialized with a non SILENT mode and this mode is overridden
// with SILENT, then we have to send only reports which have been
// explicitly declared as silent via handleSilentException().
if (reportingInteractionMode == ReportingInteractionMode.SILENT
&& ACRA.getConfig().mode() != ReportingInteractionMode.SILENT) {
sendOnlySilentReports = true;
}
}
if (e == null) {
e = new Exception("Report requested by developer");
}
final boolean shouldDisplayToast = reportingInteractionMode == ReportingInteractionMode.TOAST
|| (ACRA.getConfig().resToastText() != 0 && (reportingInteractionMode == ReportingInteractionMode.NOTIFICATION || reportingInteractionMode == ReportingInteractionMode.DIALOG));
if (shouldDisplayToast) {
new Thread() {
/*
* (non-Javadoc)
*
* @see java.lang.Thread#run()
*/
@Override
public void run() {
Looper.prepare();
ToastSender.sendToast(mContext, ACRA.getConfig().resToastText(), Toast.LENGTH_LONG);
Looper.loop();
}
}.start();
// We will wait a few seconds at the end of the method to be sure
// that the Toast can be read by the user.
}
final CrashReportData crashReportData = crashReportDataFactory.createCrashData(e, forceSilentReport,
brokenThread);
// Always write the report file
final String reportFileName = getReportFileName(crashReportData);
saveCrashReportFile(reportFileName, crashReportData);
SendWorker sender = null;
if (reportingInteractionMode == ReportingInteractionMode.SILENT
|| reportingInteractionMode == ReportingInteractionMode.TOAST
|| prefs.getBoolean(ACRA.PREF_ALWAYS_ACCEPT, false)) {
// Approve and then send reports now
Log.d(ACRA.LOG_TAG, "About to start ReportSenderWorker from #handleException");
sender = startSendingReports(sendOnlySilentReports, true);
} else if (reportingInteractionMode == ReportingInteractionMode.NOTIFICATION) {
// Send reports when user accepts
Log.d(ACRA.LOG_TAG, "About to send status bar notification from #handleException");
notifySendReport(reportFileName);
}
- // } else if (reportingInteractionMode ==
- // ReportingInteractionMode.DIALOG) {
- // // Create a new activity task with the confirmation dialog.
- // // This new task will be persisted on application restart right
- // // after its death.
- // Log.d(ACRA.LOG_TAG, "About to create DIALOG from #handleException");
- // notifyDialog(reportFileName);
- // }
if (shouldDisplayToast) {
// A toast is being displayed, we have to wait for its end before
// doing anything else.
// The toastWaitEnded flag will be checked before any other
// operation.
toastWaitEnded = false;
new Thread() {
@Override
public void run() {
final Time beforeWait = new Time();
final Time currentTime = new Time();
beforeWait.setToNow();
final long beforeWaitInMillis = beforeWait.toMillis(false);
long elapsedTimeInMillis = 0;
while (elapsedTimeInMillis < ACRAConstants.TOAST_WAIT_DURATION) {
try {
// Wait a bit to let the user read the toast
Thread.sleep(ACRAConstants.TOAST_WAIT_DURATION);
} catch (InterruptedException e1) {
Log.d(LOG_TAG, "Interrupted while waiting for Toast to end.", e1);
}
currentTime.setToNow();
elapsedTimeInMillis = currentTime.toMillis(false) - beforeWaitInMillis;
}
toastWaitEnded = true;
}
}.start();
}
// start an AsyncTask waiting for the end of the sender
// call endApplication() in onPostExecute(), only when (toastWaitEnded
// == true)
final SendWorker worker = sender;
- final boolean showDirectDialog = reportingInteractionMode == ReportingInteractionMode.DIALOG;
+ final boolean showDirectDialog = (reportingInteractionMode == ReportingInteractionMode.DIALOG)
+ && !prefs.getBoolean(ACRA.PREF_ALWAYS_ACCEPT, false);
new Thread() {
@Override
public void run() {
// We have to wait for BOTH the toast display wait AND
// the worker job to be completed.
Log.d(LOG_TAG, "Waiting for Toast + worker...");
while (!toastWaitEnded || (worker != null && worker.isAlive())) {
try {
Thread.sleep(100);
} catch (InterruptedException e1) {
Log.e(LOG_TAG, "Error : ", e1);
}
}
if (showDirectDialog) {
// Create a new activity task with the confirmation dialog.
// This new task will be persisted on application restart
// right
// after its death.
Log.d(ACRA.LOG_TAG, "About to create DIALOG from #handleException");
notifyDialog(reportFileName);
}
Log.d(LOG_TAG, "Wait for Toast + worker ended. Kill Application ? " + endApplication);
if (endApplication) {
endApplication();
}
}
}.start();
}
/**
* -------- Function added----- Notify user with a dialog the app has
* crashed, ask permission to send it. {@link CrashReportDialog} Activity.
*
* @param reportFileName
* Name fo the error report to display in the crash report
* dialog.
*/
void notifyDialog(String reportFileName) {
Log.d(LOG_TAG, "Creating Dialog for " + reportFileName);
Intent dialogIntent = new Intent(mContext, CrashReportDialog.class);
dialogIntent.putExtra(ACRAConstants.EXTRA_REPORT_FILE_NAME, reportFileName);
dialogIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(dialogIntent);
}
/**
* Send a status bar notification.
*
* The action triggered when the notification is selected is to start the
* {@link CrashReportDialog} Activity.
*
* @param reportFileName
* Name of the report file to send.
*/
private void notifySendReport(String reportFileName) {
// This notification can't be set to AUTO_CANCEL because after a crash,
// clicking on it restarts the application and this triggers a check
// for pending reports which issues the notification back.
// Notification cancellation is done in the dialog activity displayed
// on notification click.
final NotificationManager notificationManager = (NotificationManager) mContext
.getSystemService(Context.NOTIFICATION_SERVICE);
final ReportsCrashes conf = ACRA.getConfig();
// Default notification icon is the warning symbol
final int icon = conf.resNotifIcon();
final CharSequence tickerText = mContext.getText(conf.resNotifTickerText());
final long when = System.currentTimeMillis();
final Notification notification = new Notification(icon, tickerText, when);
final CharSequence contentTitle = mContext.getText(conf.resNotifTitle());
final CharSequence contentText = mContext.getText(conf.resNotifText());
final Intent notificationIntent = new Intent(mContext, CrashReportDialog.class);
Log.d(LOG_TAG, "Creating Notification for " + reportFileName);
notificationIntent.putExtra(ACRAConstants.EXTRA_REPORT_FILE_NAME, reportFileName);
final PendingIntent contentIntent = PendingIntent.getActivity(mContext, 0, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
notification.setLatestEventInfo(mContext, contentTitle, contentText, contentIntent);
// Send new notification
notificationManager.cancelAll();
notificationManager.notify(ACRAConstants.NOTIF_CRASH_ID, notification);
}
private String getReportFileName(CrashReportData crashData) {
final Time now = new Time();
now.setToNow();
final long timestamp = now.toMillis(false);
final String isSilent = crashData.getProperty(IS_SILENT);
return "" + timestamp + (isSilent != null ? ACRAConstants.SILENT_SUFFIX : "")
+ ACRAConstants.REPORTFILE_EXTENSION;
}
/**
* When a report can't be sent, it is saved here in a file in the root of
* the application private directory.
*
* @param fileName
* In a few rare cases, we write the report again with additional
* data (user comment for example). In such cases, you can
* provide the already existing file name here to overwrite the
* report file. If null, a new file report will be generated
* @param crashData
* Can be used to save an alternative (or previously generated)
* report data. Used to store again a report with the addition of
* user comment. If null, the default current crash data are
* used.
*/
private void saveCrashReportFile(String fileName, CrashReportData crashData) {
try {
Log.d(LOG_TAG, "Writing crash report file " + fileName + ".");
final CrashReportPersister persister = new CrashReportPersister(mContext);
persister.store(crashData, fileName);
} catch (Exception e) {
Log.e(LOG_TAG, "An error occurred while writing the report file...", e);
}
}
/**
* Retrieve the most recently created "non silent" report from an array of
* report file names. A non silent is any report which has not been created
* with {@link #handleSilentException(Throwable)}.
*
* @param filesList
* An array of report file names.
* @return The most recently created "non silent" report file name.
*/
private String getLatestNonSilentReport(String[] filesList) {
if (filesList != null && filesList.length > 0) {
for (int i = filesList.length - 1; i >= 0; i--) {
if (!fileNameParser.isSilent(filesList[i])) {
return filesList[i];
}
}
// We should never have this result, but this should be secure...
return filesList[filesList.length - 1];
} else {
return null;
}
}
/**
* Delete pending reports.
*
* @param deleteApprovedReports
* Set to true to delete approved and silent reports.
* @param deleteNonApprovedReports
* Set to true to delete non approved/silent reports.
* @param nbOfLatestToKeep
* Number of pending reports to retain.
*/
private void deletePendingReports(boolean deleteApprovedReports, boolean deleteNonApprovedReports,
int nbOfLatestToKeep) {
// TODO Check logic and instances where nbOfLatestToKeep = X, because
// that might stop us from deleting any reports.
final CrashReportFinder reportFinder = new CrashReportFinder(mContext);
final String[] filesList = reportFinder.getCrashReportFiles();
Arrays.sort(filesList);
if (filesList != null) {
for (int iFile = 0; iFile < filesList.length - nbOfLatestToKeep; iFile++) {
final String fileName = filesList[iFile];
final boolean isReportApproved = fileNameParser.isApproved(fileName);
if ((isReportApproved && deleteApprovedReports) || (!isReportApproved && deleteNonApprovedReports)) {
final File fileToDelete = new File(mContext.getFilesDir(), fileName);
if (!fileToDelete.delete()) {
Log.e(ACRA.LOG_TAG, "Could not delete report : " + fileToDelete);
}
}
}
}
}
/**
* Checks if an array of reports files names contains only silent or
* approved reports.
*
* @param reportFileNames
* Array of report locations to check.
* @return True if there are only silent or approved reports. False if there
* is at least one non-approved report.
*/
private boolean containsOnlySilentOrApprovedReports(String[] reportFileNames) {
for (String reportFileName : reportFileNames) {
if (!fileNameParser.isApproved(reportFileName)) {
return false;
}
}
return true;
}
/**
* Sets relevant ReportSenders to the ErrorReporter, replacing any
* previously set ReportSender.
*/
public void setDefaultReportSenders() {
ReportsCrashes conf = ACRA.getConfig();
Application mApplication = ACRA.getApplication();
removeAllReportSenders();
// Try to send by mail. If a mailTo address is provided, do not add
// other senders.
if (!"".equals(conf.mailTo())) {
Log.w(LOG_TAG, mApplication.getPackageName() + " reports will be sent by email (if accepted by user).");
setReportSender(new EmailIntentSender(mApplication));
return;
}
final PackageManagerWrapper pm = new PackageManagerWrapper(mApplication);
if (!pm.hasPermission(permission.INTERNET)) {
// NB If the PackageManager has died then this will erroneously log
// the error that the App doesn't have Internet (even though it
// does).
// I think that is a small price to pay to ensure that ACRA doesn't
// crash if the PackageManager has died.
Log.e(LOG_TAG,
mApplication.getPackageName()
+ " should be granted permission "
+ permission.INTERNET
+ " if you want your crash reports to be sent. If you don't want to add this permission to your application you can also enable sending reports by email. If this is your will then provide your email address in @ReportsCrashes(mailTo=\"[email protected]\"");
return;
}
// If formUri is set, instantiate a sender for a generic HTTP POST form
// with default mapping.
if (conf.formUri() != null && !"".equals(conf.formUri())) {
setReportSender(new HttpPostSender(null));
return;
}
// The default behavior is to use the formKey for a Google Docs Form. If
// a formUri was also provided, we keep its sender.
if (conf.formKey() != null && !"".equals(conf.formKey().trim())) {
addReportSender(new GoogleFormSender());
}
}
}
| false | true | private void handleException(Throwable e, ReportingInteractionMode reportingInteractionMode,
final boolean forceSilentReport, final boolean endApplication) {
if (!enabled) {
return;
}
boolean sendOnlySilentReports = false;
if (reportingInteractionMode == null) {
// No interaction mode defined, we assume it has been set during
// ACRA.initACRA()
reportingInteractionMode = ACRA.getConfig().mode();
} else {
// An interaction mode has been provided. If ACRA has been
// initialized with a non SILENT mode and this mode is overridden
// with SILENT, then we have to send only reports which have been
// explicitly declared as silent via handleSilentException().
if (reportingInteractionMode == ReportingInteractionMode.SILENT
&& ACRA.getConfig().mode() != ReportingInteractionMode.SILENT) {
sendOnlySilentReports = true;
}
}
if (e == null) {
e = new Exception("Report requested by developer");
}
final boolean shouldDisplayToast = reportingInteractionMode == ReportingInteractionMode.TOAST
|| (ACRA.getConfig().resToastText() != 0 && (reportingInteractionMode == ReportingInteractionMode.NOTIFICATION || reportingInteractionMode == ReportingInteractionMode.DIALOG));
if (shouldDisplayToast) {
new Thread() {
/*
* (non-Javadoc)
*
* @see java.lang.Thread#run()
*/
@Override
public void run() {
Looper.prepare();
ToastSender.sendToast(mContext, ACRA.getConfig().resToastText(), Toast.LENGTH_LONG);
Looper.loop();
}
}.start();
// We will wait a few seconds at the end of the method to be sure
// that the Toast can be read by the user.
}
final CrashReportData crashReportData = crashReportDataFactory.createCrashData(e, forceSilentReport,
brokenThread);
// Always write the report file
final String reportFileName = getReportFileName(crashReportData);
saveCrashReportFile(reportFileName, crashReportData);
SendWorker sender = null;
if (reportingInteractionMode == ReportingInteractionMode.SILENT
|| reportingInteractionMode == ReportingInteractionMode.TOAST
|| prefs.getBoolean(ACRA.PREF_ALWAYS_ACCEPT, false)) {
// Approve and then send reports now
Log.d(ACRA.LOG_TAG, "About to start ReportSenderWorker from #handleException");
sender = startSendingReports(sendOnlySilentReports, true);
} else if (reportingInteractionMode == ReportingInteractionMode.NOTIFICATION) {
// Send reports when user accepts
Log.d(ACRA.LOG_TAG, "About to send status bar notification from #handleException");
notifySendReport(reportFileName);
}
// } else if (reportingInteractionMode ==
// ReportingInteractionMode.DIALOG) {
// // Create a new activity task with the confirmation dialog.
// // This new task will be persisted on application restart right
// // after its death.
// Log.d(ACRA.LOG_TAG, "About to create DIALOG from #handleException");
// notifyDialog(reportFileName);
// }
if (shouldDisplayToast) {
// A toast is being displayed, we have to wait for its end before
// doing anything else.
// The toastWaitEnded flag will be checked before any other
// operation.
toastWaitEnded = false;
new Thread() {
@Override
public void run() {
final Time beforeWait = new Time();
final Time currentTime = new Time();
beforeWait.setToNow();
final long beforeWaitInMillis = beforeWait.toMillis(false);
long elapsedTimeInMillis = 0;
while (elapsedTimeInMillis < ACRAConstants.TOAST_WAIT_DURATION) {
try {
// Wait a bit to let the user read the toast
Thread.sleep(ACRAConstants.TOAST_WAIT_DURATION);
} catch (InterruptedException e1) {
Log.d(LOG_TAG, "Interrupted while waiting for Toast to end.", e1);
}
currentTime.setToNow();
elapsedTimeInMillis = currentTime.toMillis(false) - beforeWaitInMillis;
}
toastWaitEnded = true;
}
}.start();
}
// start an AsyncTask waiting for the end of the sender
// call endApplication() in onPostExecute(), only when (toastWaitEnded
// == true)
final SendWorker worker = sender;
final boolean showDirectDialog = reportingInteractionMode == ReportingInteractionMode.DIALOG;
new Thread() {
@Override
public void run() {
// We have to wait for BOTH the toast display wait AND
// the worker job to be completed.
Log.d(LOG_TAG, "Waiting for Toast + worker...");
while (!toastWaitEnded || (worker != null && worker.isAlive())) {
try {
Thread.sleep(100);
} catch (InterruptedException e1) {
Log.e(LOG_TAG, "Error : ", e1);
}
}
if (showDirectDialog) {
// Create a new activity task with the confirmation dialog.
// This new task will be persisted on application restart
// right
// after its death.
Log.d(ACRA.LOG_TAG, "About to create DIALOG from #handleException");
notifyDialog(reportFileName);
}
Log.d(LOG_TAG, "Wait for Toast + worker ended. Kill Application ? " + endApplication);
if (endApplication) {
endApplication();
}
}
}.start();
}
| private void handleException(Throwable e, ReportingInteractionMode reportingInteractionMode,
final boolean forceSilentReport, final boolean endApplication) {
if (!enabled) {
return;
}
boolean sendOnlySilentReports = false;
if (reportingInteractionMode == null) {
// No interaction mode defined, we assume it has been set during
// ACRA.initACRA()
reportingInteractionMode = ACRA.getConfig().mode();
} else {
// An interaction mode has been provided. If ACRA has been
// initialized with a non SILENT mode and this mode is overridden
// with SILENT, then we have to send only reports which have been
// explicitly declared as silent via handleSilentException().
if (reportingInteractionMode == ReportingInteractionMode.SILENT
&& ACRA.getConfig().mode() != ReportingInteractionMode.SILENT) {
sendOnlySilentReports = true;
}
}
if (e == null) {
e = new Exception("Report requested by developer");
}
final boolean shouldDisplayToast = reportingInteractionMode == ReportingInteractionMode.TOAST
|| (ACRA.getConfig().resToastText() != 0 && (reportingInteractionMode == ReportingInteractionMode.NOTIFICATION || reportingInteractionMode == ReportingInteractionMode.DIALOG));
if (shouldDisplayToast) {
new Thread() {
/*
* (non-Javadoc)
*
* @see java.lang.Thread#run()
*/
@Override
public void run() {
Looper.prepare();
ToastSender.sendToast(mContext, ACRA.getConfig().resToastText(), Toast.LENGTH_LONG);
Looper.loop();
}
}.start();
// We will wait a few seconds at the end of the method to be sure
// that the Toast can be read by the user.
}
final CrashReportData crashReportData = crashReportDataFactory.createCrashData(e, forceSilentReport,
brokenThread);
// Always write the report file
final String reportFileName = getReportFileName(crashReportData);
saveCrashReportFile(reportFileName, crashReportData);
SendWorker sender = null;
if (reportingInteractionMode == ReportingInteractionMode.SILENT
|| reportingInteractionMode == ReportingInteractionMode.TOAST
|| prefs.getBoolean(ACRA.PREF_ALWAYS_ACCEPT, false)) {
// Approve and then send reports now
Log.d(ACRA.LOG_TAG, "About to start ReportSenderWorker from #handleException");
sender = startSendingReports(sendOnlySilentReports, true);
} else if (reportingInteractionMode == ReportingInteractionMode.NOTIFICATION) {
// Send reports when user accepts
Log.d(ACRA.LOG_TAG, "About to send status bar notification from #handleException");
notifySendReport(reportFileName);
}
if (shouldDisplayToast) {
// A toast is being displayed, we have to wait for its end before
// doing anything else.
// The toastWaitEnded flag will be checked before any other
// operation.
toastWaitEnded = false;
new Thread() {
@Override
public void run() {
final Time beforeWait = new Time();
final Time currentTime = new Time();
beforeWait.setToNow();
final long beforeWaitInMillis = beforeWait.toMillis(false);
long elapsedTimeInMillis = 0;
while (elapsedTimeInMillis < ACRAConstants.TOAST_WAIT_DURATION) {
try {
// Wait a bit to let the user read the toast
Thread.sleep(ACRAConstants.TOAST_WAIT_DURATION);
} catch (InterruptedException e1) {
Log.d(LOG_TAG, "Interrupted while waiting for Toast to end.", e1);
}
currentTime.setToNow();
elapsedTimeInMillis = currentTime.toMillis(false) - beforeWaitInMillis;
}
toastWaitEnded = true;
}
}.start();
}
// start an AsyncTask waiting for the end of the sender
// call endApplication() in onPostExecute(), only when (toastWaitEnded
// == true)
final SendWorker worker = sender;
final boolean showDirectDialog = (reportingInteractionMode == ReportingInteractionMode.DIALOG)
&& !prefs.getBoolean(ACRA.PREF_ALWAYS_ACCEPT, false);
new Thread() {
@Override
public void run() {
// We have to wait for BOTH the toast display wait AND
// the worker job to be completed.
Log.d(LOG_TAG, "Waiting for Toast + worker...");
while (!toastWaitEnded || (worker != null && worker.isAlive())) {
try {
Thread.sleep(100);
} catch (InterruptedException e1) {
Log.e(LOG_TAG, "Error : ", e1);
}
}
if (showDirectDialog) {
// Create a new activity task with the confirmation dialog.
// This new task will be persisted on application restart
// right
// after its death.
Log.d(ACRA.LOG_TAG, "About to create DIALOG from #handleException");
notifyDialog(reportFileName);
}
Log.d(LOG_TAG, "Wait for Toast + worker ended. Kill Application ? " + endApplication);
if (endApplication) {
endApplication();
}
}
}.start();
}
|
diff --git a/src/net/milkbowl/combatevents/listeners/CombatEntityListener.java b/src/net/milkbowl/combatevents/listeners/CombatEntityListener.java
index 15c25a6..15f5ac6 100644
--- a/src/net/milkbowl/combatevents/listeners/CombatEntityListener.java
+++ b/src/net/milkbowl/combatevents/listeners/CombatEntityListener.java
@@ -1,294 +1,294 @@
package net.milkbowl.combatevents.listeners;
import java.util.Iterator;
import net.milkbowl.combatevents.Camper;
import net.milkbowl.combatevents.CombatEventsCore;
import net.milkbowl.combatevents.CombatPlayer;
import net.milkbowl.combatevents.CombatReason;
import net.milkbowl.combatevents.Config;
import net.milkbowl.combatevents.KillType;
import net.milkbowl.combatevents.LeaveCombatReason;
import net.milkbowl.combatevents.Utility;
import net.milkbowl.combatevents.events.EntityKilledByEntityEvent;
import net.milkbowl.combatevents.events.PlayerEnterCombatEvent;
import net.milkbowl.combatevents.events.PlayerLeaveCombatEvent;
import org.bukkit.Location;
import org.bukkit.entity.Creature;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.entity.Tameable;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.entity.EntityListener;
import org.bukkit.event.entity.EntityTargetEvent;
public class CombatEntityListener extends EntityListener {
private CombatEventsCore plugin;
public CombatEntityListener(CombatEventsCore plugin) {
this.plugin = plugin;
}
public void OnEntityTarget(EntityTargetEvent event) {
if (event.isCancelled() || !(event.getTarget() instanceof Player) || !(event.getEntity() instanceof Creature) || !Config.isTargetTriggersCombat() )
return;
Player player = (Player) event.getTarget();
Creature cEntity = (Creature) event.getEntity();
//If this target is a Player and within the proper distance fire our EnterCombatEvent
if (Utility.getDistance(player.getLocation(), cEntity.getLocation()) <= Config.getTargetTriggerRange()) {
plugin.getServer().getPluginManager().callEvent(new PlayerEnterCombatEvent(player, CombatReason.TARGETED_BY_MOB));
plugin.enterCombat(player, new CombatPlayer(player, CombatReason.TARGETED_BY_MOB, cEntity, plugin), cEntity, CombatReason.TARGETED_BY_MOB);
}
}
public void onEntityDamage(EntityDamageEvent event) {
//Disregard this event?
if (event.isCancelled() || !isValidEntity(event.getEntity()))
return;
//Convert the entity.
LivingEntity cEntity = (LivingEntity) event.getEntity();
//Don't even think about trying to pop into combat against a dead entity.
if (cEntity.getHealth() <= 0)
return;
//Reasons to pop us into combat
CombatReason reason = null;
Player player = null;
Entity rEntity = null;
Player pvpPlayer = null;
if (event instanceof EntityDamageByEntityEvent) {
EntityDamageByEntityEvent subEvent = (EntityDamageByEntityEvent) event;
if (subEvent.getDamager() instanceof Tameable && Config.isPetTriggersCombat()) {
player = getOwner((Tameable) subEvent.getDamager());
if (player != null) {
reason = CombatReason.PET_ATTACKED;
rEntity = subEvent.getEntity();
}
} else if (subEvent.getEntity() instanceof Tameable && Config.isPetTriggersCombat()) {
player = getOwner((Tameable) subEvent.getEntity());
if (player != null) {
reason = CombatReason.PET_TOOK_DAMAGE;
rEntity = subEvent.getDamager();
}
} else if (subEvent.getEntity() instanceof Player) {
player = (Player) subEvent.getEntity();
if (subEvent.getDamager() instanceof Player) {
rEntity = subEvent.getDamager();
pvpPlayer = (Player) subEvent.getDamager();
reason = CombatReason.DAMAGED_BY_PLAYER;
} else if (subEvent.getDamager() instanceof Projectile) {
Projectile proj = (Projectile) subEvent.getDamager();
if (proj.getShooter() instanceof Player) {
pvpPlayer = (Player) proj.getShooter();
reason = CombatReason.DAMAGED_BY_PLAYER;
} else {
rEntity = proj.getShooter();
reason = CombatReason.DAMAGED_BY_MOB;
}
} else {
rEntity = subEvent.getDamager();
reason = CombatReason.DAMAGED_BY_MOB;
}
} else if (subEvent.getDamager() instanceof Player && !(subEvent.getEntity() instanceof Player)) {
player = (Player) subEvent.getDamager();
reason = CombatReason.ATTACKED_MOB;
rEntity = subEvent.getEntity();
}
}
if (reason != null && player != null) {
CombatPlayer cPlayer = new CombatPlayer(player, reason, rEntity, plugin);
plugin.enterCombat(player, cPlayer, rEntity, reason);
//If this is a PvP event lets tag the other player as in-combat or update their times
if (reason.equals(CombatReason.DAMAGED_BY_PLAYER)) {
plugin.enterCombat(pvpPlayer, new CombatPlayer(pvpPlayer, CombatReason.ATTACKED_PLAYER, rEntity, plugin), player, CombatReason.ATTACKED_PLAYER);
}
}
}
public void onEntityDeath (EntityDeathEvent event) {
//Reasons to disregard this event
if ( !isValidEntity(event.getEntity()) )
return;
LivingEntity cEntity = (LivingEntity) event.getEntity();
/**
* Removes the dying entity from the KillMap if they are in it
* and fires the appropriate event.
*
* This new Event WILL override the EntityKilled events drops if
* the drops are changed in the sub-event
*
*/
LivingEntity attacker = null;
KillType killType = null;
if (event.getEntity().getLastDamageCause() instanceof EntityDamageByEntityEvent) {
EntityDamageByEntityEvent subEvent = (EntityDamageByEntityEvent) event.getEntity().getLastDamageCause();
if (subEvent.getDamager() instanceof LivingEntity) {
attacker = (LivingEntity) subEvent.getDamager();
killType = KillType.NORMAL;
} else if (subEvent.getDamager() instanceof Projectile) {
attacker = ((Projectile) subEvent.getDamager()).getShooter();
killType = KillType.PROJECTILE;
}
}
if ( attacker != null ) {
//Lets check if this player is camping and adjust the Kill Reason appropriately
if (attacker instanceof Player && !(event.getEntity() instanceof Player) && Config.isAntiCamp()) {
Player p = (Player) attacker;
Camper campPlayer;
if (plugin.getCampMap().containsKey(p.getName())) {
campPlayer = plugin.getCampMap().get(p.getName());
plugin.getServer().getScheduler().cancelTask(campPlayer.getCampTask());
if (Utility.getDistance(p.getLocation(), campPlayer.getSpawner()) > Config.getCampRange() * 2) {
plugin.getCampMap().remove(p);
} else {
campPlayer.addKill();
campPlayer.setCampTask(plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new CampRemover(p), Config.getCampTime() * 20));
if (campPlayer.getKills() > Config.getCampKills())
killType = KillType.CAMPING;
if (campPlayer.getKills() >= Config.getCampKills())
p.sendMessage(Config.getCampMessage());
}
} else {
//If this player is near a spawner lets add them to the camp detector
Location spawnLoc = Utility.findSpawner(p.getLocation());
if (spawnLoc != null) {
campPlayer = new Camper(spawnLoc);
campPlayer.setCampTask(plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new CampRemover(p), Config.getCampTime() * 20));
}
}
}
EntityKilledByEntityEvent kEvent = new EntityKilledByEntityEvent(attacker, cEntity, event.getDrops(), killType);
plugin.getServer().getPluginManager().callEvent(kEvent);
} else {
return;
}
/**
* If this is a player, lets run our checks and remove them from combat with any other
* players.
*
*/
if (cEntity instanceof Player) {
Player player = (Player) cEntity;
//If this player is in the camp map, lets remove them
plugin.getCampMap().remove(player);
- if (plugin.getCombatPlayer(player).getReasonMap() == null || plugin.getCombatPlayer(player).getReasonMap().isEmpty()) {
+ if (plugin.getCombatPlayer(player) == null || plugin.getCombatPlayer(player).getReasonMap() == null || plugin.getCombatPlayer(player).getReasonMap().isEmpty()) {
return;
}
//Check
Iterator<Entity> iter = plugin.getCombatPlayer(player).getReasonMap().keySet().iterator();
while (iter.hasNext()) {
Entity entity = iter.next();
if (entity instanceof Player) {
Player p = (Player) entity;
if (plugin.getCombatPlayer(p) == null) continue;
CombatReason lastReason = plugin.getCombatPlayer(p).removeReason(player);
if (plugin.getCombatPlayer(p).getReasonMap().isEmpty()) {
//If the mapping is empty lets leave combat.
if (throwPlayerLeaveCombatEvent(p, LeaveCombatReason.TARGET_DIED, new CombatReason[] {lastReason}))
plugin.getServer().getScheduler().cancelTask(plugin.getCombatTask(p));
plugin.leaveCombat(p);
}
break;
}
}
/**
* remove the Killed player from combat and remove their combat reasons.
*
*/
if (throwPlayerLeaveCombatEvent(player, LeaveCombatReason.DEATH, plugin.getCombatPlayer(player).getReasons())) {
plugin.getCombatPlayer(player).clearReasons();
//Cancel the task and remove the player from the combat map and send our leave combat message
plugin.getServer().getScheduler().cancelTask(plugin.getCombatTask(player));
}
plugin.leaveCombat(player);
}
/**
* if a player didn't die lets run a check and remove the entity from any other player
* combat maps.
*/
else {
for ( Player p : plugin.getServer().getOnlinePlayers() ) {
if (plugin.getCombatPlayer(p) == null)
continue;
CombatReason[] lastReasons = null;
if (plugin.getCombatPlayer(p).getReasons().length == 1)
lastReasons = plugin.getCombatPlayer(p).getReasons();
Iterator<Entity> iter = plugin.getCombatPlayer(p).getReasonMap().keySet().iterator();
while (iter.hasNext()) {
Entity entity = iter.next();
if (entity == null) continue;
if (entity.equals(cEntity)) {
iter.remove();
break;
}
}
/**
* After we removed the entity, lets kick the player out of combat if
* they have no more reasons to be in combat
*/
if (plugin.getCombatPlayer(p).getReasonMap().isEmpty()) {
//If the mapping is empty lets leave combat.
if (throwPlayerLeaveCombatEvent(p, LeaveCombatReason.TARGET_DIED, lastReasons))
plugin.getServer().getScheduler().cancelTask(plugin.getCombatTask(p));
plugin.leaveCombat(p);
}
}
}
}
private boolean throwPlayerLeaveCombatEvent(Player player, LeaveCombatReason leaveReason, CombatReason[] reasons) {
PlayerLeaveCombatEvent event = new PlayerLeaveCombatEvent(player, leaveReason, reasons);
plugin.getServer().getPluginManager().callEvent(event);
//Return if the event was successful
return !event.isCancelled();
}
private Player getOwner (Tameable tEntity) {
if (tEntity.isTamed())
if (tEntity.getOwner() instanceof Player)
return (Player) tEntity.getOwner();
return null;
}
private boolean isValidEntity (Entity thisEntity) {
if ( !(thisEntity instanceof LivingEntity) )
return false;
return true;
}
public class CampRemover implements Runnable {
Player player;
CampRemover(Player player) {
this.player = player;
}
@Override
public void run() {
plugin.getCampMap().remove(player);
}
}
}
| true | true | public void onEntityDeath (EntityDeathEvent event) {
//Reasons to disregard this event
if ( !isValidEntity(event.getEntity()) )
return;
LivingEntity cEntity = (LivingEntity) event.getEntity();
/**
* Removes the dying entity from the KillMap if they are in it
* and fires the appropriate event.
*
* This new Event WILL override the EntityKilled events drops if
* the drops are changed in the sub-event
*
*/
LivingEntity attacker = null;
KillType killType = null;
if (event.getEntity().getLastDamageCause() instanceof EntityDamageByEntityEvent) {
EntityDamageByEntityEvent subEvent = (EntityDamageByEntityEvent) event.getEntity().getLastDamageCause();
if (subEvent.getDamager() instanceof LivingEntity) {
attacker = (LivingEntity) subEvent.getDamager();
killType = KillType.NORMAL;
} else if (subEvent.getDamager() instanceof Projectile) {
attacker = ((Projectile) subEvent.getDamager()).getShooter();
killType = KillType.PROJECTILE;
}
}
if ( attacker != null ) {
//Lets check if this player is camping and adjust the Kill Reason appropriately
if (attacker instanceof Player && !(event.getEntity() instanceof Player) && Config.isAntiCamp()) {
Player p = (Player) attacker;
Camper campPlayer;
if (plugin.getCampMap().containsKey(p.getName())) {
campPlayer = plugin.getCampMap().get(p.getName());
plugin.getServer().getScheduler().cancelTask(campPlayer.getCampTask());
if (Utility.getDistance(p.getLocation(), campPlayer.getSpawner()) > Config.getCampRange() * 2) {
plugin.getCampMap().remove(p);
} else {
campPlayer.addKill();
campPlayer.setCampTask(plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new CampRemover(p), Config.getCampTime() * 20));
if (campPlayer.getKills() > Config.getCampKills())
killType = KillType.CAMPING;
if (campPlayer.getKills() >= Config.getCampKills())
p.sendMessage(Config.getCampMessage());
}
} else {
//If this player is near a spawner lets add them to the camp detector
Location spawnLoc = Utility.findSpawner(p.getLocation());
if (spawnLoc != null) {
campPlayer = new Camper(spawnLoc);
campPlayer.setCampTask(plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new CampRemover(p), Config.getCampTime() * 20));
}
}
}
EntityKilledByEntityEvent kEvent = new EntityKilledByEntityEvent(attacker, cEntity, event.getDrops(), killType);
plugin.getServer().getPluginManager().callEvent(kEvent);
} else {
return;
}
/**
* If this is a player, lets run our checks and remove them from combat with any other
* players.
*
*/
if (cEntity instanceof Player) {
Player player = (Player) cEntity;
//If this player is in the camp map, lets remove them
plugin.getCampMap().remove(player);
if (plugin.getCombatPlayer(player).getReasonMap() == null || plugin.getCombatPlayer(player).getReasonMap().isEmpty()) {
return;
}
//Check
Iterator<Entity> iter = plugin.getCombatPlayer(player).getReasonMap().keySet().iterator();
while (iter.hasNext()) {
Entity entity = iter.next();
if (entity instanceof Player) {
Player p = (Player) entity;
if (plugin.getCombatPlayer(p) == null) continue;
CombatReason lastReason = plugin.getCombatPlayer(p).removeReason(player);
if (plugin.getCombatPlayer(p).getReasonMap().isEmpty()) {
//If the mapping is empty lets leave combat.
if (throwPlayerLeaveCombatEvent(p, LeaveCombatReason.TARGET_DIED, new CombatReason[] {lastReason}))
plugin.getServer().getScheduler().cancelTask(plugin.getCombatTask(p));
plugin.leaveCombat(p);
}
break;
}
}
/**
* remove the Killed player from combat and remove their combat reasons.
*
*/
if (throwPlayerLeaveCombatEvent(player, LeaveCombatReason.DEATH, plugin.getCombatPlayer(player).getReasons())) {
plugin.getCombatPlayer(player).clearReasons();
//Cancel the task and remove the player from the combat map and send our leave combat message
plugin.getServer().getScheduler().cancelTask(plugin.getCombatTask(player));
}
plugin.leaveCombat(player);
}
/**
* if a player didn't die lets run a check and remove the entity from any other player
* combat maps.
*/
else {
for ( Player p : plugin.getServer().getOnlinePlayers() ) {
if (plugin.getCombatPlayer(p) == null)
continue;
CombatReason[] lastReasons = null;
if (plugin.getCombatPlayer(p).getReasons().length == 1)
lastReasons = plugin.getCombatPlayer(p).getReasons();
Iterator<Entity> iter = plugin.getCombatPlayer(p).getReasonMap().keySet().iterator();
while (iter.hasNext()) {
Entity entity = iter.next();
if (entity == null) continue;
if (entity.equals(cEntity)) {
iter.remove();
break;
}
}
/**
* After we removed the entity, lets kick the player out of combat if
* they have no more reasons to be in combat
*/
if (plugin.getCombatPlayer(p).getReasonMap().isEmpty()) {
//If the mapping is empty lets leave combat.
if (throwPlayerLeaveCombatEvent(p, LeaveCombatReason.TARGET_DIED, lastReasons))
plugin.getServer().getScheduler().cancelTask(plugin.getCombatTask(p));
plugin.leaveCombat(p);
}
}
}
}
| public void onEntityDeath (EntityDeathEvent event) {
//Reasons to disregard this event
if ( !isValidEntity(event.getEntity()) )
return;
LivingEntity cEntity = (LivingEntity) event.getEntity();
/**
* Removes the dying entity from the KillMap if they are in it
* and fires the appropriate event.
*
* This new Event WILL override the EntityKilled events drops if
* the drops are changed in the sub-event
*
*/
LivingEntity attacker = null;
KillType killType = null;
if (event.getEntity().getLastDamageCause() instanceof EntityDamageByEntityEvent) {
EntityDamageByEntityEvent subEvent = (EntityDamageByEntityEvent) event.getEntity().getLastDamageCause();
if (subEvent.getDamager() instanceof LivingEntity) {
attacker = (LivingEntity) subEvent.getDamager();
killType = KillType.NORMAL;
} else if (subEvent.getDamager() instanceof Projectile) {
attacker = ((Projectile) subEvent.getDamager()).getShooter();
killType = KillType.PROJECTILE;
}
}
if ( attacker != null ) {
//Lets check if this player is camping and adjust the Kill Reason appropriately
if (attacker instanceof Player && !(event.getEntity() instanceof Player) && Config.isAntiCamp()) {
Player p = (Player) attacker;
Camper campPlayer;
if (plugin.getCampMap().containsKey(p.getName())) {
campPlayer = plugin.getCampMap().get(p.getName());
plugin.getServer().getScheduler().cancelTask(campPlayer.getCampTask());
if (Utility.getDistance(p.getLocation(), campPlayer.getSpawner()) > Config.getCampRange() * 2) {
plugin.getCampMap().remove(p);
} else {
campPlayer.addKill();
campPlayer.setCampTask(plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new CampRemover(p), Config.getCampTime() * 20));
if (campPlayer.getKills() > Config.getCampKills())
killType = KillType.CAMPING;
if (campPlayer.getKills() >= Config.getCampKills())
p.sendMessage(Config.getCampMessage());
}
} else {
//If this player is near a spawner lets add them to the camp detector
Location spawnLoc = Utility.findSpawner(p.getLocation());
if (spawnLoc != null) {
campPlayer = new Camper(spawnLoc);
campPlayer.setCampTask(plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new CampRemover(p), Config.getCampTime() * 20));
}
}
}
EntityKilledByEntityEvent kEvent = new EntityKilledByEntityEvent(attacker, cEntity, event.getDrops(), killType);
plugin.getServer().getPluginManager().callEvent(kEvent);
} else {
return;
}
/**
* If this is a player, lets run our checks and remove them from combat with any other
* players.
*
*/
if (cEntity instanceof Player) {
Player player = (Player) cEntity;
//If this player is in the camp map, lets remove them
plugin.getCampMap().remove(player);
if (plugin.getCombatPlayer(player) == null || plugin.getCombatPlayer(player).getReasonMap() == null || plugin.getCombatPlayer(player).getReasonMap().isEmpty()) {
return;
}
//Check
Iterator<Entity> iter = plugin.getCombatPlayer(player).getReasonMap().keySet().iterator();
while (iter.hasNext()) {
Entity entity = iter.next();
if (entity instanceof Player) {
Player p = (Player) entity;
if (plugin.getCombatPlayer(p) == null) continue;
CombatReason lastReason = plugin.getCombatPlayer(p).removeReason(player);
if (plugin.getCombatPlayer(p).getReasonMap().isEmpty()) {
//If the mapping is empty lets leave combat.
if (throwPlayerLeaveCombatEvent(p, LeaveCombatReason.TARGET_DIED, new CombatReason[] {lastReason}))
plugin.getServer().getScheduler().cancelTask(plugin.getCombatTask(p));
plugin.leaveCombat(p);
}
break;
}
}
/**
* remove the Killed player from combat and remove their combat reasons.
*
*/
if (throwPlayerLeaveCombatEvent(player, LeaveCombatReason.DEATH, plugin.getCombatPlayer(player).getReasons())) {
plugin.getCombatPlayer(player).clearReasons();
//Cancel the task and remove the player from the combat map and send our leave combat message
plugin.getServer().getScheduler().cancelTask(plugin.getCombatTask(player));
}
plugin.leaveCombat(player);
}
/**
* if a player didn't die lets run a check and remove the entity from any other player
* combat maps.
*/
else {
for ( Player p : plugin.getServer().getOnlinePlayers() ) {
if (plugin.getCombatPlayer(p) == null)
continue;
CombatReason[] lastReasons = null;
if (plugin.getCombatPlayer(p).getReasons().length == 1)
lastReasons = plugin.getCombatPlayer(p).getReasons();
Iterator<Entity> iter = plugin.getCombatPlayer(p).getReasonMap().keySet().iterator();
while (iter.hasNext()) {
Entity entity = iter.next();
if (entity == null) continue;
if (entity.equals(cEntity)) {
iter.remove();
break;
}
}
/**
* After we removed the entity, lets kick the player out of combat if
* they have no more reasons to be in combat
*/
if (plugin.getCombatPlayer(p).getReasonMap().isEmpty()) {
//If the mapping is empty lets leave combat.
if (throwPlayerLeaveCombatEvent(p, LeaveCombatReason.TARGET_DIED, lastReasons))
plugin.getServer().getScheduler().cancelTask(plugin.getCombatTask(p));
plugin.leaveCombat(p);
}
}
}
}
|
diff --git a/publicMAIN/src/org/publicmain/gui/GUI.java b/publicMAIN/src/org/publicmain/gui/GUI.java
index b5964bb..d7567aa 100644
--- a/publicMAIN/src/org/publicmain/gui/GUI.java
+++ b/publicMAIN/src/org/publicmain/gui/GUI.java
@@ -1,621 +1,621 @@
package org.publicmain.gui;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import java.util.Vector;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JTabbedPane;
import javax.swing.JToggleButton;
import javax.swing.SwingUtilities;
import javax.swing.UIDefaults;
import javax.swing.UIManager;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.images.Help;
import org.publicmain.chatengine.ChatEngine;
import org.publicmain.chatengine.GruppenKanal;
import org.publicmain.chatengine.KnotenKanal;
import org.publicmain.common.LogEngine;
import org.publicmain.common.Node;
import org.publicmain.sql.DBConnection;
import com.nilo.plaf.nimrod.NimRODLookAndFeel;
/**
* @author ATRM
*
*/
public class GUI extends JFrame implements Observer , ChangeListener{
// Deklarationen:
ChatEngine ce;
LogEngine log;
private static GUI me;
private List<Node> nodes;
private List<ChatWindow> chatList;
private JMenuBar menuBar;
private JMenu fileMenu;
private JMenu configMenu;
private JMenu helpMenu;
private JMenuItem aboutPMAIN;
private JMenuItem helpContents;
private JMenuItem menuItemRequestFile;
private JMenu lafMenu;
private ButtonGroup btnGrp;
private JMenuItem lafNimROD;
private DragableJTabbedPane jTabbedPane;
private JToggleButton userListBtn;
private boolean userListActive;
private UserList userListWin;
private pMTrayIcon trayIcon;
private DBConnection db;
/**
* Konstruktor f�r GUI
*/
private GUI() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
log.log(ex);
}
// Initialisierungen:
try {
if(ChatEngine.getCE()==null){
this.ce = new ChatEngine();
} else {
ce=ChatEngine.getCE();
}
} catch (Exception e) {
log.log(e);
}
this.me = this;
this.log = new LogEngine();
// this.db = DBConnection.getDBConnection(); // bei bedarf einbinden!
this.menuBar = new JMenuBar();
this.fileMenu = new JMenu("File");
this.configMenu = new JMenu("Settings");
this.helpMenu = new JMenu("Help");
this.aboutPMAIN = new JMenuItem("About pMAIN");
- this.helpContents = new JMenuItem("Help Contents", new ImageIcon(getClass().getResource("HelpContentsIcon.png"))); // evtl. noch anderes Icon w�hlen
+ this.helpContents = new JMenuItem("Help Contents", new ImageIcon(getClass().getResource("helpContentsIcon.png"))); // evtl. noch anderes Icon w�hlen
this.menuItemRequestFile = new JMenuItem("Test(request_File)");
this.lafMenu = new JMenu("Switch Design");
this.btnGrp = new ButtonGroup();
this.chatList = new ArrayList<ChatWindow>();
this.jTabbedPane = new DragableJTabbedPane();
this.userListBtn = new JToggleButton(new ImageIcon(getClass().getResource("UserListAusklappen.png")));
this.userListActive = false;
this.lafNimROD = new JRadioButtonMenuItem("NimROD");
this.trayIcon = new pMTrayIcon();
// Anlegen der Men�eintr�ge f�r Designwechsel (installierte
// LookAndFeels)
// + hinzuf�gen zum lafMenu ("Designwechsel")
// + hinzuf�gen der ActionListener (lafController)
for (UIManager.LookAndFeelInfo laf : UIManager.getInstalledLookAndFeels()) {
JRadioButtonMenuItem tempJMenuItem = new JRadioButtonMenuItem(laf.getName());
if((laf.getName().equals("Windows")) &&
(UIManager.getSystemLookAndFeelClassName().equals("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"))){
tempJMenuItem.setSelected(true);
}
lafMenu.add(tempJMenuItem);
btnGrp.add(tempJMenuItem);
tempJMenuItem.addActionListener(new lafController(lafMenu, laf));
}
// Anlegen ben�tigter Controller und Listener:
// WindowListener f�r das GUI-Fenster:
this.addWindowListener(new winController());
// ChangeListener f�r Focus auf Eingabefeld
this.jTabbedPane.addChangeListener(this);
// ActionListener f�r Menu's:
this.menuItemRequestFile.addActionListener(new menuContoller());
this.aboutPMAIN.addActionListener(new menuContoller());
this.helpContents.addActionListener(new menuContoller());
this.lafNimROD.addActionListener(new lafController(lafNimROD, null));
// Konfiguration userListBtn:
this.userListBtn.setMargin(new Insets(2, 3, 2, 3));
this.userListBtn.setToolTipText("Userlist einblenden");
this.userListBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JToggleButton source = (JToggleButton) e.getSource();
if (source.isSelected()) {
userListAufklappen();
} else {
userListZuklappen();
}
}
});
// Men�s hinzuf�gen:
this.btnGrp.add(lafNimROD);
this.lafMenu.add(lafNimROD);
this.configMenu.add(lafMenu);
this.fileMenu.add(menuItemRequestFile);
this.helpMenu.add(aboutPMAIN);
this.helpMenu.add(helpContents);
this.menuBar.add(userListBtn);
this.menuBar.add(fileMenu);
this.menuBar.add(configMenu);
this.menuBar.add(helpMenu);
// GUI Komponenten hinzuf�gen:
this.setJMenuBar(menuBar);
this.add(jTabbedPane);
this.addChat(new ChatWindow("public"));
this.addChat(new ChatWindow("grupp1"));
this.addChat(new ChatWindow(123 ,"private1"));
// GUI JFrame Einstellungen:
this.setIconImage(new ImageIcon(getClass().getResource("pM_Logo2.png")).getImage());
this.pack();
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("publicMAIN");
this.setVisible(true);
chatList.get(0).focusEingabefeld();
}
/**
* Diese Methode klappt die Userliste auf
*
*
*/
private void userListAufklappen(){
if(!userListActive){
this.userListBtn.setToolTipText("Userlist ausblenden");
this.userListBtn.setIcon(new ImageIcon(getClass().getResource("UserListEinklappen.png")));
this.userListBtn.setSelected(true);
this.userListWin = new UserList(GUI.me);
this.userListWin.repaint();
this.userListWin.setVisible(true);
userListActive = true;
}
}
/**
* Diese Methode klappt die Userliste zu
*
*
*/
private void userListZuklappen(){
if(userListActive){
this.userListBtn.setToolTipText("Userlist einblenden");
this.userListBtn.setIcon(new ImageIcon(getClass().getResource("UserListAusklappen.png")));
this.userListBtn.setSelected(false);
this.userListWin.setVisible(false);
this.userListActive = false;
}
}
/**
* Diese Methode f�gt ein ChatWindow hinzu
*
* Diese Methode f�gt ein ChatWindow zu GUI hinzu und setzt dessen
* Komponenten
*
* @param cw
*/
public void addChat(final ChatWindow cw) {
// TODO: evtl. noch Typunterscheidung hinzuf�gen (Methode
// getCwTyp():String)
String title = cw.getChatWindowName();
// neues ChatWindow (cw) zur Chatliste (ArrayList<ChatWindow>)
// hinzuf�gen:
this.chatList.add(cw);
// erzeugen von neuem Tab f�r neues ChatWindow:
this.jTabbedPane.addTab(title, cw);
// ChatWindow am NachrichtenListener (MSGListener) anmelden:
// ce.group_join(title);
ce.add_MSGListener(cw, title);
// Index vom ChatWindow im JTabbedPane holen um am richtigen Ort
// einzuf�gen:
int index = jTabbedPane.indexOfComponent(cw);
// den neuen Tab an die Stelle von index setzen:
this.jTabbedPane.setTabComponentAt(index, cw.getWindowTab());
}
/**
* Diese Methode entfernt ein ChatWindow
*
* Diese Methode sorgt daf�r das ChatWindows aus der ArrayList "chatList"
* entfernt werden und im GUI nicht mehr angezeigt werden.
*
* @param ChatWindow
*/
public void delChat(ChatWindow cw) {
// ChatWindow (cw) aus jTabbedPane entfernen:
this.jTabbedPane.remove(cw);
// ChatWindow aus Chatliste entfernen:
this.chatList.remove(cw);
// ChatWindow aus Gruppe entfernen (MSGListener abschalten):
ce.remove_MSGListener(cw);
// Falls keine ChatWindows mehr wird public ge�ffnet:
if (chatList.isEmpty()) {
// TODO: Hier evtl. noch anderen Programmablauf implementier
// z.B. schlie�en des Programms wenn letztes ChatWindow geschlossen
// wird
addChat(new ChatWindow("public"));
}
}
/**
* F�hrt das Programm ordnungsgem�� runter
*/
void shutdown(){
//TODO: ordentlicher shutdown
System.exit(0);
}
/**
* Diese Methode wird in einem privaten ChatWindow zum versenden der Nachricht verwendet
* @param empfUID long Empf�ngerUID
* @param msg String die Nachricht
* @param cw ChatWindow das aufrufende ChatWindow
*/
void privSend(long empfUID,String msg, ChatWindow cw){
ce.send_private(empfUID, msg);
}
/**
* Diese Methode sendet eine private Nachricht durch /w
*
* Diese Methode wird vom ChatWindow durch die Eingabe von /w aufgerufen
* zun�chst wird gepr�ft ob schon ein ChatWindow f�r den privaten Chat existiert
* falls nicht wird eines angelegt und die private nachricht an die UID versendet
* @param empfAlias String Empf�nger Alias
* @param msg String die Nachricht
* @param cw ChatWindow das aufrufende ChatWindow
*/
void privSend(String empfAlias, String msg, ChatWindow cw){
boolean cwExist = false;
long tmpUID;
for(ChatWindow x : chatList){
if(x.getChatWindowName().equals(cw.getChatWindowName())){
cwExist = true;
}
}
for(Node x : nodes){
if(x.getAlias().equals(empfAlias)){
tmpUID = x.getNodeID();
if(!cwExist){
addChat(new ChatWindow(tmpUID, empfAlias));
}
ce.send_private(tmpUID, msg);
}
}
}
/**
* Diese Methode wird f�r das Senden von Gruppennachrichten verwendet
* Falls noch kein ChatWindow f�r diese Gruppe besteht wird eines erzeugt.
* @param empfGrp String Empf�ngergruppe
* @param msg String die Nachricht/Msg
* @param cw ChatWindow das aufrufende ChatWindow
*/
void groupSend(String empfGrp, String msg, ChatWindow cw){
boolean cwExist = false;
for(ChatWindow x : chatList){
if(x.getChatWindowName().equals(empfGrp)){
cwExist = true;
}
}
if(!cwExist){
addChat(new ChatWindow(empfGrp));
}
ce.send_group(empfGrp, msg);
}
/**
* Diese Methode ist f�r das Ignorien eines users
* @param alias String Alias des Users
* @returns true Wenn User gefunden
*/
boolean ignoreUser(String alias){
long tmpUID;
for(Node x : nodes){
if(x.getAlias().equals(alias)){
tmpUID = x.getUserID();
ce.ignore_user(tmpUID);
return true;
}
}
return false;
}
/**
* Diese Methode ist f�r das nicht weitere Ignorieren eines users
* @param alias String Alias des Users
* @return true Wenn User gefunden
*/
boolean unignoreUser(String alias){
long tmpUID;
for(Node x : nodes){
if(x.getAlias().equals(alias)){
tmpUID = x.getUserID();
ce.unignore_user(tmpUID);
return true;
}
}
return false;
}
/**
* Diese Methode liefert ein Fileobjekt
*
* Diese Methode bittet die GUI(den Nutzer) um ein Fileobjekt zur Ablage der
* empfangenen Datei
*
* @return File
*/
public File request_File() {
// TODO: hier stimmt noch nix! sp�ter �berarbeiten!
JFileChooser fileChooser = new JFileChooser();
int returnVal = fileChooser.showSaveDialog(me);
if (returnVal == JFileChooser.APPROVE_OPTION) {
System.out.println("You chose to save this file: " + fileChooser.getSelectedFile().getName());
}
return fileChooser.getSelectedFile();
}
/**
* Diese Methode soll �ber �nderungen informieren
*/
public void notifyGUI() {
// TODO:
// da muss noch was gemacht werden !!!
// evtl fliegt die Methode auch raus wenn wir das
// mit den Observerpattern machen...
}
/*
* (non-Javadoc)
*
* @see java.util.Observer#update(java.util.Observable, java.lang.Object)
*/
@Override
public void update(Observable o, Object arg) {
if (o instanceof GruppenKanal){
if (o.countObservers()==1){
//erzeuge gruppenfenster f�ge nachricht ein sei happy
}
else{
//
}
}
if(o instanceof KnotenKanal&&o.countObservers()==1){
//erzeuge gruppen
}
// TODO Auto-generated method stub
}
/**
* Diese Methode stellt das Node bereit
*
* Diese Methode ist ein Getter f�r das Node
*
* @param sender
* @return Node
*/
public Node getNode(long sender) {
for (Node x : nodes)
if (x.getNodeID() == sender)
return x;
return null;
}
/**
* Diese Methode stellt das GUI bereit
*
* Diese Methode stellt das GUI f�r andere Klassen bereit um einen Zugriff
* auf GUI Attribute zu erm�glichen
*
* @return GUI
*/
public static GUI getGUI() {
if (me == null) {
me = new GUI();
}
return me;
}
/**
* @return
*/
JTabbedPane getTabbedPane(){
return this.jTabbedPane;
}
/**
* ActionListener f�r Design wechsel (LookAndFeel)
*
* hier wird das Umschalten des LookAndFeels im laufenden Betrieb erm�glicht
*
* @author ABerthold
*
*/
class lafController implements ActionListener {
private JMenuItem lafMenu;
private UIManager.LookAndFeelInfo laf;
private boolean userListWasActive;
public lafController(JMenuItem lafMenu, UIManager.LookAndFeelInfo laf) {
this.lafMenu = lafMenu;
this.laf = laf;
}
@Override
public void actionPerformed(ActionEvent e) {
userListWasActive = userListActive;
JMenuItem source = (JMenuItem)e.getSource();
userListZuklappen();
if(source.getText().equals("NimROD")){
try{
UIManager.setLookAndFeel(new NimRODLookAndFeel());
} catch (Exception ex){
LogEngine.log(ex);
}
} else {
try {
UIManager.setLookAndFeel(laf.getClassName());
} catch (Exception ex) {
LogEngine.log(ex);
}
}
SwingUtilities.updateComponentTreeUI(GUI.me);
GUI.me.pack();
if(userListWasActive)userListAufklappen();
}
}
/**
* ActionListener f�r Menu's
*
* @author ABerthold
*
*/
class menuContoller implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
JMenuItem source = (JMenuItem)e.getSource();
switch(source.getText()){
case "Test(request_File)":
request_File();
break;
case "About pMAIN":
new AboutPublicMAIN(me, "About publicMAIN", true);
break;
case "Help Contents":
//TODO: HelpContents HTML schreiben
new HelpContents();
break;
}
}
}
/**
* WindowListener f�r GUI
*
*
*
* @author ABerthold
*
*/
class winController implements WindowListener{
public void windowOpened(WindowEvent arg0) {
// TODO Auto-generated method stub
}
@Override
// Wird das GUI minimiert wird die Userlist zugeklappt und der
// userListBtn zur�ckgesetzt:
public void windowIconified(WindowEvent arg0) {
if (userListBtn.isSelected()) {
userListZuklappen();
}
}
@Override
public void windowDeiconified(WindowEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void windowDeactivated(WindowEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void windowClosing(WindowEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void windowClosed(WindowEvent arg0) {
// Object[] eventCache =
// {"super, so ne scheisse","deine Mama liegt im Systemtray"};
// Object anchor = true;
// JOptionPane.showInputDialog(me,
// "pMAIN wird ins Systemtray gelegt!",
// "pMAIN -> Systemtray", JOptionPane.PLAIN_MESSAGE, new
// ImageIcon("media/pM16x16.png"), eventCache, anchor);
}
@Override
public void windowActivated(WindowEvent arg0) {
if (userListBtn.isSelected()) {
userListWin.toFront();
}
}
}
/**
* Diese Methode gibt die Default Settings des aktuellen L&F in der Console aus
*/
private void getLookAndFeelDefaultsToConsole(){
UIDefaults def = UIManager.getLookAndFeelDefaults();
Vector<?> vec = new Vector<Object>(def.keySet());
Collections.sort(vec, new Comparator<Object>() {
public int compare(Object arg0, Object arg1) {
return arg0.toString().compareTo(arg1.toString());
}
});
for (Object obj : vec) {
System.out.println(obj + "\n\t" + def.get(obj));
}
}
@Override
public void stateChanged(ChangeEvent e) {
((ChatWindow)jTabbedPane.getSelectedComponent()).focusEingabefeld();
}
}
| true | true | private GUI() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
log.log(ex);
}
// Initialisierungen:
try {
if(ChatEngine.getCE()==null){
this.ce = new ChatEngine();
} else {
ce=ChatEngine.getCE();
}
} catch (Exception e) {
log.log(e);
}
this.me = this;
this.log = new LogEngine();
// this.db = DBConnection.getDBConnection(); // bei bedarf einbinden!
this.menuBar = new JMenuBar();
this.fileMenu = new JMenu("File");
this.configMenu = new JMenu("Settings");
this.helpMenu = new JMenu("Help");
this.aboutPMAIN = new JMenuItem("About pMAIN");
this.helpContents = new JMenuItem("Help Contents", new ImageIcon(getClass().getResource("HelpContentsIcon.png"))); // evtl. noch anderes Icon w�hlen
this.menuItemRequestFile = new JMenuItem("Test(request_File)");
this.lafMenu = new JMenu("Switch Design");
this.btnGrp = new ButtonGroup();
this.chatList = new ArrayList<ChatWindow>();
this.jTabbedPane = new DragableJTabbedPane();
this.userListBtn = new JToggleButton(new ImageIcon(getClass().getResource("UserListAusklappen.png")));
this.userListActive = false;
this.lafNimROD = new JRadioButtonMenuItem("NimROD");
this.trayIcon = new pMTrayIcon();
// Anlegen der Men�eintr�ge f�r Designwechsel (installierte
// LookAndFeels)
// + hinzuf�gen zum lafMenu ("Designwechsel")
// + hinzuf�gen der ActionListener (lafController)
for (UIManager.LookAndFeelInfo laf : UIManager.getInstalledLookAndFeels()) {
JRadioButtonMenuItem tempJMenuItem = new JRadioButtonMenuItem(laf.getName());
if((laf.getName().equals("Windows")) &&
(UIManager.getSystemLookAndFeelClassName().equals("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"))){
tempJMenuItem.setSelected(true);
}
lafMenu.add(tempJMenuItem);
btnGrp.add(tempJMenuItem);
tempJMenuItem.addActionListener(new lafController(lafMenu, laf));
}
// Anlegen ben�tigter Controller und Listener:
// WindowListener f�r das GUI-Fenster:
this.addWindowListener(new winController());
// ChangeListener f�r Focus auf Eingabefeld
this.jTabbedPane.addChangeListener(this);
// ActionListener f�r Menu's:
this.menuItemRequestFile.addActionListener(new menuContoller());
this.aboutPMAIN.addActionListener(new menuContoller());
this.helpContents.addActionListener(new menuContoller());
this.lafNimROD.addActionListener(new lafController(lafNimROD, null));
// Konfiguration userListBtn:
this.userListBtn.setMargin(new Insets(2, 3, 2, 3));
this.userListBtn.setToolTipText("Userlist einblenden");
this.userListBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JToggleButton source = (JToggleButton) e.getSource();
if (source.isSelected()) {
userListAufklappen();
} else {
userListZuklappen();
}
}
});
// Men�s hinzuf�gen:
this.btnGrp.add(lafNimROD);
this.lafMenu.add(lafNimROD);
this.configMenu.add(lafMenu);
this.fileMenu.add(menuItemRequestFile);
this.helpMenu.add(aboutPMAIN);
this.helpMenu.add(helpContents);
this.menuBar.add(userListBtn);
this.menuBar.add(fileMenu);
this.menuBar.add(configMenu);
this.menuBar.add(helpMenu);
// GUI Komponenten hinzuf�gen:
this.setJMenuBar(menuBar);
this.add(jTabbedPane);
this.addChat(new ChatWindow("public"));
this.addChat(new ChatWindow("grupp1"));
this.addChat(new ChatWindow(123 ,"private1"));
// GUI JFrame Einstellungen:
this.setIconImage(new ImageIcon(getClass().getResource("pM_Logo2.png")).getImage());
this.pack();
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("publicMAIN");
this.setVisible(true);
chatList.get(0).focusEingabefeld();
}
| private GUI() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
log.log(ex);
}
// Initialisierungen:
try {
if(ChatEngine.getCE()==null){
this.ce = new ChatEngine();
} else {
ce=ChatEngine.getCE();
}
} catch (Exception e) {
log.log(e);
}
this.me = this;
this.log = new LogEngine();
// this.db = DBConnection.getDBConnection(); // bei bedarf einbinden!
this.menuBar = new JMenuBar();
this.fileMenu = new JMenu("File");
this.configMenu = new JMenu("Settings");
this.helpMenu = new JMenu("Help");
this.aboutPMAIN = new JMenuItem("About pMAIN");
this.helpContents = new JMenuItem("Help Contents", new ImageIcon(getClass().getResource("helpContentsIcon.png"))); // evtl. noch anderes Icon w�hlen
this.menuItemRequestFile = new JMenuItem("Test(request_File)");
this.lafMenu = new JMenu("Switch Design");
this.btnGrp = new ButtonGroup();
this.chatList = new ArrayList<ChatWindow>();
this.jTabbedPane = new DragableJTabbedPane();
this.userListBtn = new JToggleButton(new ImageIcon(getClass().getResource("UserListAusklappen.png")));
this.userListActive = false;
this.lafNimROD = new JRadioButtonMenuItem("NimROD");
this.trayIcon = new pMTrayIcon();
// Anlegen der Men�eintr�ge f�r Designwechsel (installierte
// LookAndFeels)
// + hinzuf�gen zum lafMenu ("Designwechsel")
// + hinzuf�gen der ActionListener (lafController)
for (UIManager.LookAndFeelInfo laf : UIManager.getInstalledLookAndFeels()) {
JRadioButtonMenuItem tempJMenuItem = new JRadioButtonMenuItem(laf.getName());
if((laf.getName().equals("Windows")) &&
(UIManager.getSystemLookAndFeelClassName().equals("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"))){
tempJMenuItem.setSelected(true);
}
lafMenu.add(tempJMenuItem);
btnGrp.add(tempJMenuItem);
tempJMenuItem.addActionListener(new lafController(lafMenu, laf));
}
// Anlegen ben�tigter Controller und Listener:
// WindowListener f�r das GUI-Fenster:
this.addWindowListener(new winController());
// ChangeListener f�r Focus auf Eingabefeld
this.jTabbedPane.addChangeListener(this);
// ActionListener f�r Menu's:
this.menuItemRequestFile.addActionListener(new menuContoller());
this.aboutPMAIN.addActionListener(new menuContoller());
this.helpContents.addActionListener(new menuContoller());
this.lafNimROD.addActionListener(new lafController(lafNimROD, null));
// Konfiguration userListBtn:
this.userListBtn.setMargin(new Insets(2, 3, 2, 3));
this.userListBtn.setToolTipText("Userlist einblenden");
this.userListBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JToggleButton source = (JToggleButton) e.getSource();
if (source.isSelected()) {
userListAufklappen();
} else {
userListZuklappen();
}
}
});
// Men�s hinzuf�gen:
this.btnGrp.add(lafNimROD);
this.lafMenu.add(lafNimROD);
this.configMenu.add(lafMenu);
this.fileMenu.add(menuItemRequestFile);
this.helpMenu.add(aboutPMAIN);
this.helpMenu.add(helpContents);
this.menuBar.add(userListBtn);
this.menuBar.add(fileMenu);
this.menuBar.add(configMenu);
this.menuBar.add(helpMenu);
// GUI Komponenten hinzuf�gen:
this.setJMenuBar(menuBar);
this.add(jTabbedPane);
this.addChat(new ChatWindow("public"));
this.addChat(new ChatWindow("grupp1"));
this.addChat(new ChatWindow(123 ,"private1"));
// GUI JFrame Einstellungen:
this.setIconImage(new ImageIcon(getClass().getResource("pM_Logo2.png")).getImage());
this.pack();
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("publicMAIN");
this.setVisible(true);
chatList.get(0).focusEingabefeld();
}
|
diff --git a/components/dotnet-executable/src/main/java/npanday/executable/compiler/impl/DefaultCompiler.java b/components/dotnet-executable/src/main/java/npanday/executable/compiler/impl/DefaultCompiler.java
index bc0ec634..f6242a2e 100644
--- a/components/dotnet-executable/src/main/java/npanday/executable/compiler/impl/DefaultCompiler.java
+++ b/components/dotnet-executable/src/main/java/npanday/executable/compiler/impl/DefaultCompiler.java
@@ -1,266 +1,266 @@
/*
* 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 npanday.executable.compiler.impl;
import org.apache.maven.artifact.Artifact;
import org.codehaus.plexus.util.FileUtils;
import java.util.Date;
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
import java.io.File;
import npanday.executable.CommandFilter;
import npanday.executable.ExecutionException;
import npanday.vendor.Vendor;
import npanday.executable.compiler.CompilerConfig;
/**
* A default compiler that can be used in most cases.
*
* @author Shane Isbell
*/
public final class DefaultCompiler
extends BaseCompiler
{
public boolean failOnErrorOutput()
{
//MONO writes warnings to standard error: this turns off failing builds on warnings for MONO
return !compilerContext.getCompilerRequirement().getVendor().equals( Vendor.MONO );
}
public List<String> getCommands()
throws ExecutionException
{
if ( compilerContext == null )
{
throw new ExecutionException( "NPANDAY-068-000: Compiler has not been initialized with a context" );
}
CompilerConfig config = compilerContext.getNetCompilerConfig();
List<Artifact> references = compilerContext.getLibraryDependencies();
List<Artifact> modules = compilerContext.getDirectModuleDependencies();
String sourceDirectory = compilerContext.getSourceDirectoryName();
String artifactFilePath = compilerContext.getArtifact().getAbsolutePath();
String targetArtifactType = config.getArtifactType().getTargetCompileType();
compilerContext.getCompilerRequirement().getFrameworkVersion();
List<String> commands = new ArrayList<String>();
if(config.getOutputDirectory() != null)
{
File f = new File(config.getOutputDirectory(), compilerContext.getArtifact().getName());
artifactFilePath = f.getAbsolutePath();
}
if(artifactFilePath!=null && artifactFilePath.toLowerCase().endsWith(".zip"))
{
artifactFilePath = artifactFilePath.substring(0, artifactFilePath.length() - 3) + "dll";
}
commands.add( "/out:" + artifactFilePath );
commands.add( "/target:" + targetArtifactType );
if(config.getIncludeSources() == null || config.getIncludeSources().isEmpty() )
{
commands.add( "/recurse:" + sourceDirectory + File.separator + "**" );
}
if ( modules != null && !modules.isEmpty() )
{
StringBuffer sb = new StringBuffer();
for ( Iterator i = modules.iterator(); i.hasNext(); )
{
Artifact artifact = (Artifact) i.next();
String path = artifact.getFile().getAbsolutePath();
sb.append( path );
if ( i.hasNext() )
{
sb.append( ";" );
}
}
commands.add( "/addmodule:" + sb.toString() );
}
if ( !references.isEmpty() )
{
for ( Artifact artifact : references )
{
String path = artifact.getFile().getAbsolutePath();
commands.add( "/reference:" + path );
}
}
for ( File file : compilerContext.getEmbeddedResources() )
{
commands.add( "/resource:" + file.getAbsolutePath() );
}
for ( File file : compilerContext.getLinkedResources() )
{
commands.add( "/linkresource:" + file.getAbsolutePath() );
}
for ( File file : compilerContext.getWin32Resources() )
{
commands.add( "/win32res:" + file.getAbsolutePath() );
}
if ( compilerContext.getWin32Icon() != null )
{
commands.add( "/win32icon:" + compilerContext.getWin32Icon().getAbsolutePath() );
}
if ( compilerContext.getCompilerRequirement().getVendor().equals( Vendor.MICROSOFT ) )
{
commands.add( "/nologo" );
}
if ( compilerContext.getCompilerRequirement().getVendor().equals( Vendor.MICROSOFT ) &&
compilerContext.getCompilerRequirement().getFrameworkVersion().equals( "3.0" ) )
{
String wcfRef = "/reference:" + System.getenv( "SystemRoot" ) +
"\\Microsoft.NET\\Framework\\v3.0\\Windows Communication Foundation\\";
//TODO: This is a hard-coded path: Don't have a registry value either.
commands.add( wcfRef + "System.ServiceModel.dll" );
commands.add( wcfRef + "Microsoft.Transactions.Bridge.dll" );
commands.add( wcfRef + "Microsoft.Transactions.Bridge.Dtc.dll" );
commands.add( wcfRef + "System.ServiceModel.Install.dll" );
commands.add( wcfRef + "System.ServiceModel.WasHosting.dll" );
commands.add( wcfRef + "System.Runtime.Serialization.dll" );
commands.add( wcfRef + "SMDiagnostics.dll" );
}
if ( compilerContext.getCompilerRequirement().getVendor().equals( Vendor.MICROSOFT ) &&
compilerContext.getCompilerRequirement().getFrameworkVersion().equals( "3.5" ) )
{
String wcfRef = "/reference:" + System.getenv( "SystemRoot" ) +
"\\Microsoft.NET\\Framework\\v3.5\\";
//TODO: This is a hard-coded path: Don't have a registry value either.
commands.add( wcfRef + "Microsoft.Build.Tasks.v3.5.dll" );
commands.add( wcfRef + "Microsoft.CompactFramework.Build.Tasks.dll" );
commands.add( wcfRef + "Microsoft.Data.Entity.Build.Tasks.dll" );
commands.add( wcfRef + "Microsoft.VisualC.STLCLR.dll" );
}
if ( compilerContext.getKeyInfo().getKeyFileUri() != null )
{
commands.add( "/keyfile:" + compilerContext.getKeyInfo().getKeyFileUri() );
}
else if ( compilerContext.getKeyInfo().getKeyContainerName() != null )
{
commands.add( "/keycontainer:" + compilerContext.getKeyInfo().getKeyContainerName() );
}
if ( config.getCommands() != null )
{
commands.addAll( config.getCommands() );
}
commands.add( "/warnaserror-" );
//commands.add( "/nowarn" );
if ( compilerContext.getCompilerRequirement().getVendor().equals( Vendor.MONO ) )
{
commands.add( "/reference:System.Drawing" );
commands.add( "/reference:System.Windows.Forms" );
commands.add( "/reference:System.Web.Services" );
}
if ( !compilerContext.getNetCompilerConfig().isTestCompile() )
{
commands.add(
"/doc:" + new File( compilerContext.getTargetDirectory(), "comments.xml" ).getAbsolutePath() );
}
CommandFilter filter = compilerContext.getCommandFilter();
List<String> filteredCommands = filter.filter( commands );
//Include Sources code is being copied to temporary folder for the recurse option
String fileExt = "";
String frameWorkVer = ""+compilerContext.getCompilerRequirement().getFrameworkVersion();
String TempDir = "";
String targetDir = ""+compilerContext.getTargetDirectory();
Date date = new Date();
String Now =""+date.getDate()+date.getHours()+date.getMinutes()+date.getSeconds();
- TempDir = targetDir+"\\"+Now;
+ TempDir = targetDir+File.separator+Now;
try
{
FileUtils.deleteDirectory( TempDir );
}
catch(Exception e)
{
//Does Precautionary delete for tempDir
}
FileUtils.mkdir(TempDir);
if(config.getIncludeSources() != null && !config.getIncludeSources().isEmpty() )
{
int folderCtr=0;
for(String includeSource : config.getIncludeSources())
{
- String[] sourceTokens = includeSource.split("\\\\");
+ String[] sourceTokens = includeSource.split(File.separator+File.separator);
String lastToken = sourceTokens[sourceTokens.length-1];
if(fileExt=="")
{
String[] extToken = lastToken.split( "\\." );
fileExt = "."+extToken[extToken.length-1];
}
try
{
- String fileToCheck = TempDir+"\\"+lastToken;
+ String fileToCheck = TempDir+File.separator+lastToken;
if(FileUtils.fileExists( fileToCheck ))
{
- String subTempDir = TempDir+"\\"+folderCtr+"\\";
+ String subTempDir = TempDir+File.separator+folderCtr+File.separator;
FileUtils.mkdir( subTempDir );
FileUtils.copyFileToDirectory( includeSource, subTempDir);
folderCtr++;
}
else
{
FileUtils.copyFileToDirectory( includeSource, TempDir);
}
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
//part of original code.
//filteredCommands.add(includeSource);
}
- String recurseCmd = "/recurse:"+TempDir+"\\*"+fileExt;
+ String recurseCmd = "/recurse:"+TempDir+File.separator+"*"+fileExt;
filteredCommands.add(recurseCmd);
}
return filteredCommands;
}
public void resetCommands( List<String> commands )
{
}
}
| false | true | public List<String> getCommands()
throws ExecutionException
{
if ( compilerContext == null )
{
throw new ExecutionException( "NPANDAY-068-000: Compiler has not been initialized with a context" );
}
CompilerConfig config = compilerContext.getNetCompilerConfig();
List<Artifact> references = compilerContext.getLibraryDependencies();
List<Artifact> modules = compilerContext.getDirectModuleDependencies();
String sourceDirectory = compilerContext.getSourceDirectoryName();
String artifactFilePath = compilerContext.getArtifact().getAbsolutePath();
String targetArtifactType = config.getArtifactType().getTargetCompileType();
compilerContext.getCompilerRequirement().getFrameworkVersion();
List<String> commands = new ArrayList<String>();
if(config.getOutputDirectory() != null)
{
File f = new File(config.getOutputDirectory(), compilerContext.getArtifact().getName());
artifactFilePath = f.getAbsolutePath();
}
if(artifactFilePath!=null && artifactFilePath.toLowerCase().endsWith(".zip"))
{
artifactFilePath = artifactFilePath.substring(0, artifactFilePath.length() - 3) + "dll";
}
commands.add( "/out:" + artifactFilePath );
commands.add( "/target:" + targetArtifactType );
if(config.getIncludeSources() == null || config.getIncludeSources().isEmpty() )
{
commands.add( "/recurse:" + sourceDirectory + File.separator + "**" );
}
if ( modules != null && !modules.isEmpty() )
{
StringBuffer sb = new StringBuffer();
for ( Iterator i = modules.iterator(); i.hasNext(); )
{
Artifact artifact = (Artifact) i.next();
String path = artifact.getFile().getAbsolutePath();
sb.append( path );
if ( i.hasNext() )
{
sb.append( ";" );
}
}
commands.add( "/addmodule:" + sb.toString() );
}
if ( !references.isEmpty() )
{
for ( Artifact artifact : references )
{
String path = artifact.getFile().getAbsolutePath();
commands.add( "/reference:" + path );
}
}
for ( File file : compilerContext.getEmbeddedResources() )
{
commands.add( "/resource:" + file.getAbsolutePath() );
}
for ( File file : compilerContext.getLinkedResources() )
{
commands.add( "/linkresource:" + file.getAbsolutePath() );
}
for ( File file : compilerContext.getWin32Resources() )
{
commands.add( "/win32res:" + file.getAbsolutePath() );
}
if ( compilerContext.getWin32Icon() != null )
{
commands.add( "/win32icon:" + compilerContext.getWin32Icon().getAbsolutePath() );
}
if ( compilerContext.getCompilerRequirement().getVendor().equals( Vendor.MICROSOFT ) )
{
commands.add( "/nologo" );
}
if ( compilerContext.getCompilerRequirement().getVendor().equals( Vendor.MICROSOFT ) &&
compilerContext.getCompilerRequirement().getFrameworkVersion().equals( "3.0" ) )
{
String wcfRef = "/reference:" + System.getenv( "SystemRoot" ) +
"\\Microsoft.NET\\Framework\\v3.0\\Windows Communication Foundation\\";
//TODO: This is a hard-coded path: Don't have a registry value either.
commands.add( wcfRef + "System.ServiceModel.dll" );
commands.add( wcfRef + "Microsoft.Transactions.Bridge.dll" );
commands.add( wcfRef + "Microsoft.Transactions.Bridge.Dtc.dll" );
commands.add( wcfRef + "System.ServiceModel.Install.dll" );
commands.add( wcfRef + "System.ServiceModel.WasHosting.dll" );
commands.add( wcfRef + "System.Runtime.Serialization.dll" );
commands.add( wcfRef + "SMDiagnostics.dll" );
}
if ( compilerContext.getCompilerRequirement().getVendor().equals( Vendor.MICROSOFT ) &&
compilerContext.getCompilerRequirement().getFrameworkVersion().equals( "3.5" ) )
{
String wcfRef = "/reference:" + System.getenv( "SystemRoot" ) +
"\\Microsoft.NET\\Framework\\v3.5\\";
//TODO: This is a hard-coded path: Don't have a registry value either.
commands.add( wcfRef + "Microsoft.Build.Tasks.v3.5.dll" );
commands.add( wcfRef + "Microsoft.CompactFramework.Build.Tasks.dll" );
commands.add( wcfRef + "Microsoft.Data.Entity.Build.Tasks.dll" );
commands.add( wcfRef + "Microsoft.VisualC.STLCLR.dll" );
}
if ( compilerContext.getKeyInfo().getKeyFileUri() != null )
{
commands.add( "/keyfile:" + compilerContext.getKeyInfo().getKeyFileUri() );
}
else if ( compilerContext.getKeyInfo().getKeyContainerName() != null )
{
commands.add( "/keycontainer:" + compilerContext.getKeyInfo().getKeyContainerName() );
}
if ( config.getCommands() != null )
{
commands.addAll( config.getCommands() );
}
commands.add( "/warnaserror-" );
//commands.add( "/nowarn" );
if ( compilerContext.getCompilerRequirement().getVendor().equals( Vendor.MONO ) )
{
commands.add( "/reference:System.Drawing" );
commands.add( "/reference:System.Windows.Forms" );
commands.add( "/reference:System.Web.Services" );
}
if ( !compilerContext.getNetCompilerConfig().isTestCompile() )
{
commands.add(
"/doc:" + new File( compilerContext.getTargetDirectory(), "comments.xml" ).getAbsolutePath() );
}
CommandFilter filter = compilerContext.getCommandFilter();
List<String> filteredCommands = filter.filter( commands );
//Include Sources code is being copied to temporary folder for the recurse option
String fileExt = "";
String frameWorkVer = ""+compilerContext.getCompilerRequirement().getFrameworkVersion();
String TempDir = "";
String targetDir = ""+compilerContext.getTargetDirectory();
Date date = new Date();
String Now =""+date.getDate()+date.getHours()+date.getMinutes()+date.getSeconds();
TempDir = targetDir+"\\"+Now;
try
{
FileUtils.deleteDirectory( TempDir );
}
catch(Exception e)
{
//Does Precautionary delete for tempDir
}
FileUtils.mkdir(TempDir);
if(config.getIncludeSources() != null && !config.getIncludeSources().isEmpty() )
{
int folderCtr=0;
for(String includeSource : config.getIncludeSources())
{
String[] sourceTokens = includeSource.split("\\\\");
String lastToken = sourceTokens[sourceTokens.length-1];
if(fileExt=="")
{
String[] extToken = lastToken.split( "\\." );
fileExt = "."+extToken[extToken.length-1];
}
try
{
String fileToCheck = TempDir+"\\"+lastToken;
if(FileUtils.fileExists( fileToCheck ))
{
String subTempDir = TempDir+"\\"+folderCtr+"\\";
FileUtils.mkdir( subTempDir );
FileUtils.copyFileToDirectory( includeSource, subTempDir);
folderCtr++;
}
else
{
FileUtils.copyFileToDirectory( includeSource, TempDir);
}
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
//part of original code.
//filteredCommands.add(includeSource);
}
String recurseCmd = "/recurse:"+TempDir+"\\*"+fileExt;
filteredCommands.add(recurseCmd);
}
return filteredCommands;
}
| public List<String> getCommands()
throws ExecutionException
{
if ( compilerContext == null )
{
throw new ExecutionException( "NPANDAY-068-000: Compiler has not been initialized with a context" );
}
CompilerConfig config = compilerContext.getNetCompilerConfig();
List<Artifact> references = compilerContext.getLibraryDependencies();
List<Artifact> modules = compilerContext.getDirectModuleDependencies();
String sourceDirectory = compilerContext.getSourceDirectoryName();
String artifactFilePath = compilerContext.getArtifact().getAbsolutePath();
String targetArtifactType = config.getArtifactType().getTargetCompileType();
compilerContext.getCompilerRequirement().getFrameworkVersion();
List<String> commands = new ArrayList<String>();
if(config.getOutputDirectory() != null)
{
File f = new File(config.getOutputDirectory(), compilerContext.getArtifact().getName());
artifactFilePath = f.getAbsolutePath();
}
if(artifactFilePath!=null && artifactFilePath.toLowerCase().endsWith(".zip"))
{
artifactFilePath = artifactFilePath.substring(0, artifactFilePath.length() - 3) + "dll";
}
commands.add( "/out:" + artifactFilePath );
commands.add( "/target:" + targetArtifactType );
if(config.getIncludeSources() == null || config.getIncludeSources().isEmpty() )
{
commands.add( "/recurse:" + sourceDirectory + File.separator + "**" );
}
if ( modules != null && !modules.isEmpty() )
{
StringBuffer sb = new StringBuffer();
for ( Iterator i = modules.iterator(); i.hasNext(); )
{
Artifact artifact = (Artifact) i.next();
String path = artifact.getFile().getAbsolutePath();
sb.append( path );
if ( i.hasNext() )
{
sb.append( ";" );
}
}
commands.add( "/addmodule:" + sb.toString() );
}
if ( !references.isEmpty() )
{
for ( Artifact artifact : references )
{
String path = artifact.getFile().getAbsolutePath();
commands.add( "/reference:" + path );
}
}
for ( File file : compilerContext.getEmbeddedResources() )
{
commands.add( "/resource:" + file.getAbsolutePath() );
}
for ( File file : compilerContext.getLinkedResources() )
{
commands.add( "/linkresource:" + file.getAbsolutePath() );
}
for ( File file : compilerContext.getWin32Resources() )
{
commands.add( "/win32res:" + file.getAbsolutePath() );
}
if ( compilerContext.getWin32Icon() != null )
{
commands.add( "/win32icon:" + compilerContext.getWin32Icon().getAbsolutePath() );
}
if ( compilerContext.getCompilerRequirement().getVendor().equals( Vendor.MICROSOFT ) )
{
commands.add( "/nologo" );
}
if ( compilerContext.getCompilerRequirement().getVendor().equals( Vendor.MICROSOFT ) &&
compilerContext.getCompilerRequirement().getFrameworkVersion().equals( "3.0" ) )
{
String wcfRef = "/reference:" + System.getenv( "SystemRoot" ) +
"\\Microsoft.NET\\Framework\\v3.0\\Windows Communication Foundation\\";
//TODO: This is a hard-coded path: Don't have a registry value either.
commands.add( wcfRef + "System.ServiceModel.dll" );
commands.add( wcfRef + "Microsoft.Transactions.Bridge.dll" );
commands.add( wcfRef + "Microsoft.Transactions.Bridge.Dtc.dll" );
commands.add( wcfRef + "System.ServiceModel.Install.dll" );
commands.add( wcfRef + "System.ServiceModel.WasHosting.dll" );
commands.add( wcfRef + "System.Runtime.Serialization.dll" );
commands.add( wcfRef + "SMDiagnostics.dll" );
}
if ( compilerContext.getCompilerRequirement().getVendor().equals( Vendor.MICROSOFT ) &&
compilerContext.getCompilerRequirement().getFrameworkVersion().equals( "3.5" ) )
{
String wcfRef = "/reference:" + System.getenv( "SystemRoot" ) +
"\\Microsoft.NET\\Framework\\v3.5\\";
//TODO: This is a hard-coded path: Don't have a registry value either.
commands.add( wcfRef + "Microsoft.Build.Tasks.v3.5.dll" );
commands.add( wcfRef + "Microsoft.CompactFramework.Build.Tasks.dll" );
commands.add( wcfRef + "Microsoft.Data.Entity.Build.Tasks.dll" );
commands.add( wcfRef + "Microsoft.VisualC.STLCLR.dll" );
}
if ( compilerContext.getKeyInfo().getKeyFileUri() != null )
{
commands.add( "/keyfile:" + compilerContext.getKeyInfo().getKeyFileUri() );
}
else if ( compilerContext.getKeyInfo().getKeyContainerName() != null )
{
commands.add( "/keycontainer:" + compilerContext.getKeyInfo().getKeyContainerName() );
}
if ( config.getCommands() != null )
{
commands.addAll( config.getCommands() );
}
commands.add( "/warnaserror-" );
//commands.add( "/nowarn" );
if ( compilerContext.getCompilerRequirement().getVendor().equals( Vendor.MONO ) )
{
commands.add( "/reference:System.Drawing" );
commands.add( "/reference:System.Windows.Forms" );
commands.add( "/reference:System.Web.Services" );
}
if ( !compilerContext.getNetCompilerConfig().isTestCompile() )
{
commands.add(
"/doc:" + new File( compilerContext.getTargetDirectory(), "comments.xml" ).getAbsolutePath() );
}
CommandFilter filter = compilerContext.getCommandFilter();
List<String> filteredCommands = filter.filter( commands );
//Include Sources code is being copied to temporary folder for the recurse option
String fileExt = "";
String frameWorkVer = ""+compilerContext.getCompilerRequirement().getFrameworkVersion();
String TempDir = "";
String targetDir = ""+compilerContext.getTargetDirectory();
Date date = new Date();
String Now =""+date.getDate()+date.getHours()+date.getMinutes()+date.getSeconds();
TempDir = targetDir+File.separator+Now;
try
{
FileUtils.deleteDirectory( TempDir );
}
catch(Exception e)
{
//Does Precautionary delete for tempDir
}
FileUtils.mkdir(TempDir);
if(config.getIncludeSources() != null && !config.getIncludeSources().isEmpty() )
{
int folderCtr=0;
for(String includeSource : config.getIncludeSources())
{
String[] sourceTokens = includeSource.split(File.separator+File.separator);
String lastToken = sourceTokens[sourceTokens.length-1];
if(fileExt=="")
{
String[] extToken = lastToken.split( "\\." );
fileExt = "."+extToken[extToken.length-1];
}
try
{
String fileToCheck = TempDir+File.separator+lastToken;
if(FileUtils.fileExists( fileToCheck ))
{
String subTempDir = TempDir+File.separator+folderCtr+File.separator;
FileUtils.mkdir( subTempDir );
FileUtils.copyFileToDirectory( includeSource, subTempDir);
folderCtr++;
}
else
{
FileUtils.copyFileToDirectory( includeSource, TempDir);
}
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
//part of original code.
//filteredCommands.add(includeSource);
}
String recurseCmd = "/recurse:"+TempDir+File.separator+"*"+fileExt;
filteredCommands.add(recurseCmd);
}
return filteredCommands;
}
|
diff --git a/src/ca/mcgill/hs/classifiers/location/MotionStateClusterer.java b/src/ca/mcgill/hs/classifiers/location/MotionStateClusterer.java
index 62ed732..c4901d2 100644
--- a/src/ca/mcgill/hs/classifiers/location/MotionStateClusterer.java
+++ b/src/ca/mcgill/hs/classifiers/location/MotionStateClusterer.java
@@ -1,326 +1,326 @@
package ca.mcgill.hs.classifiers.location;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Timer;
import java.util.TimerTask;
import android.util.Log;
public class MotionStateClusterer {
// Contains the timestamp for the observation as well as the index in the
// distance matrix for that observation.
private static final class Tuple {
public final double timestamp;
public final int index;
public Tuple(final double timestamp, final int index) {
this.timestamp = timestamp;
this.index = index;
}
}
private static final int RESET_MOVEMENT_STATE_TIME_IN_SECONDS = 10;
private BufferedWriter outputLog = null;
private static final String RESET_MOVEMENT_STATE_TIMER_NAME = "reset movement state timer";
private static final String TAG = "MotionStateClusterer";
private final SignificantLocationClusterer slClusterer;
private final LocationSet locations;
private Timer resetMovementTimer;
private long current_cluster = -1;
// Maintain a queue of the Tuples for the observations that are
// currently being clustered.
private final LinkedList<Tuple> pool = new LinkedList<Tuple>();
// Window length, in seconds.
private final boolean TIME_BASED_WINDOW;
private final int WINDOW_LENGTH;
// Delta from the paper. This value represents the percentage of the points
// in the pool that must neighbours of a point for it to be considered to be
// part of a cluster
private final float DELTA;
// Maintain a lookup table between timestamps and observations, which
// are sets of measurements taken at an instance in time.
private final HashMap<Double, Observation> observations;
private final double[][] dist_matrix;
// True if the previous window was labelled as stationary.
private boolean previouslyMoving = true;
private boolean currentlyMoving = false;
// True if the current window was labelled as stationary.
// private boolean curStationaryStatus = false;
private final SimpleDateFormat dfm = new SimpleDateFormat("HH:mm:ss");
private int timerDelay = 1000 * RESET_MOVEMENT_STATE_TIME_IN_SECONDS;
public MotionStateClusterer(final LocationSet locations) {
TIME_BASED_WINDOW = locations.usesTimeBasedWindow();
WINDOW_LENGTH = locations.getWindowLength();
DELTA = locations.pctOfWindowRequiredToBeStationary();
dist_matrix = new double[WINDOW_LENGTH][WINDOW_LENGTH];
observations = new HashMap<Double, Observation>(
(int) (WINDOW_LENGTH / 0.75f), 0.75f);
for (int i = 0; i < WINDOW_LENGTH; i++) {
for (int j = 0; j < WINDOW_LENGTH; j++) {
dist_matrix[i][j] = -1;
}
}
slClusterer = new SignificantLocationClusterer(locations);
this.locations = locations;
resetMovementTimer = new Timer(RESET_MOVEMENT_STATE_TIMER_NAME);
final Date d = new Date(System.currentTimeMillis());
final SimpleDateFormat dfm = new SimpleDateFormat("yy-MM-dd-HHmmss");
final File f = new File("/sdcard/hsandroidapp/data/recent/"
+ dfm.format(d) + "-clusters.log");
try {
outputLog = new BufferedWriter(new FileWriter(f));
} catch (final IOException e) {
e.printStackTrace();
}
}
// Adds a new observation to the pool, does some clustering, and then
// returns the statuses of each point in the pool.
public void addObservation(double timestamp, final Observation observation) {
// Delete observation outside MAX_TIME window.
deleteOldObservations(timestamp);
int index = getAvailableIndex();
// Update distance matrix
for (final Tuple tuple : pool) {
dist_matrix[index][tuple.index] = dist_matrix[tuple.index][index] = observation
.distanceFrom(observations.get(tuple.timestamp));
}
observations.put(timestamp, observation);
pool.addLast(new Tuple(timestamp, index));
final int pool_size = pool.size();
/*
* If it's a time-based window, then don't cluster if there's only one
* sample in the pool, otherwise if it's not a time-based window, then
* don't cluster until the pool is full.
*/
if ((TIME_BASED_WINDOW && pool_size <= 1)
|| (!TIME_BASED_WINDOW && pool_size < WINDOW_LENGTH)) {
return;
}
// Perform the clustering
final boolean[] cluster_status = new boolean[WINDOW_LENGTH];
for (int i = 0; i < WINDOW_LENGTH; i++) {
// Set initial cluster status to false
cluster_status[i] = false;
}
for (final Tuple tuple : pool) {
final int i = tuple.index;
// Not the most efficient way to do things, but not too bad
// First we check how many neighbours are within epsilon
int neighbours = 0;
for (final Tuple tuple2 : pool) {
final int j = tuple2.index;
if (i != j && dist_matrix[i][j] < observation.getEPS()
&& dist_matrix[i][j] > 0.0) {
neighbours += 1;
}
}
// Then, if enough neighbours exist, set ourself and our neighbours
// to be in a cluster
if (neighbours >= (int) (DELTA * (double) pool_size)) {
cluster_status[i] = true;
for (int j = 0; j < WINDOW_LENGTH; j++) {
if (dist_matrix[i][j] < observation.getEPS()
&& dist_matrix[i][j] > 0.0) {
cluster_status[j] = true;
}
}
}
}
// And finally, update the statuses
Location location = null;
int clustered_points = 0;
int status = 0;
for (final Tuple tuple : pool) {
timestamp = tuple.timestamp;
index = tuple.index;
if (cluster_status[index]) {
status -= 1; // Vote for stationarity
clustered_points += 1;
/*
* If we were moving on the last step and now we've stopped,
* create a new significant location candidate.
*/
if (previouslyMoving) {
if (location == null) {
location = locations.newLocation(timestamp);
}
location.addObservation(observations.get(timestamp));
}
} else {
status += 1; // Vote for motion.
}
}
Log.d(TAG, "Clustered " + clustered_points + " of " + pool_size
+ " points.");
if (location != null) {
current_cluster = slClusterer.addNewLocation(location);
currentlyMoving = false;
Log.d(TAG,
"WifiClusterer thinks we're stationary and in location: "
+ current_cluster);
if (current_cluster > 0) {
/*
* The purpose of this timer is to avoid continually updating
* the location if the user remains stationary in a known
* location. We start with a timer that resets the motion state
* every RESET_UPDATE_STATUS_TIME_IN_SECONDS seconds, and then
* after an update we double the time before the next update.
*/
resetMovementTimer.schedule(new TimerTask() {
@Override
public void run() {
previouslyMoving = true;
}
}, timerDelay);
timerDelay *= 2;
previouslyMoving = false;
}
- } else if (!previouslyMoving) {
+ } else if (!previouslyMoving && clustered_points == 0) {
/*
* If we were stationary, but now we are moving, then we cancel the
* timer that should only be running if we're stationary.
*/
current_cluster = -1;
timerDelay = RESET_MOVEMENT_STATE_TIME_IN_SECONDS * 1000;
previouslyMoving = true;
currentlyMoving = true;
resetMovementTimer.cancel();
resetMovementTimer.purge();
resetMovementTimer = new Timer(RESET_MOVEMENT_STATE_TIMER_NAME);
- } else {
+ } else if (clustered_points == 0) {
/* User was moving previously, and is still moving */
current_cluster = -1;
currentlyMoving = true;
}
final Date d = new Date(System.currentTimeMillis());
LocationStatusWidget.updateText("Update at: " + dfm.format(d)
+ "\nClustered " + clustered_points + " of " + pool_size
+ " points.\nCurrently in location: " + current_cluster + "\n");
try {
if (outputLog != null) {
outputLog.write(dfm.format(d) + "," + current_cluster + "\n");
}
} catch (final IOException e) {
e.printStackTrace();
}
}
public void close() {
try {
if (outputLog != null) {
Log.d(TAG, "Computing Statistics");
final File f = new File("/sdcard/hsandroidapp/clusters.dat");
BufferedWriter statsDmp = null;
try {
statsDmp = new BufferedWriter(new FileWriter(f, false));
statsDmp.write(slClusterer.toString());
statsDmp.flush();
} catch (final IOException e) {
e.printStackTrace();
} finally {
statsDmp.close();
}
outputLog.close();
}
} catch (final IOException e) {
e.printStackTrace();
}
}
// Deletes the oldest observation from the pool and returns the index
// for that point in the distance matrix, so that it can be reused.
private void deleteOldObservations(final double timestamp) {
// Delete anything older than WINDOW_LENGTH seconds
if (TIME_BASED_WINDOW) {
while (pool.size() > 0
&& (timestamp - pool.getFirst().timestamp > WINDOW_LENGTH || pool
.size() >= WINDOW_LENGTH)) {
final Tuple first = pool.getFirst();
observations.remove(first.timestamp);
final int idx = first.index;
for (int i = 0; i < WINDOW_LENGTH; i++) {
dist_matrix[i][idx] = -1;
dist_matrix[idx][i] = -1;
}
pool.removeFirst();
}
}
// Only delete the one oldest observation (ie., fixed length sliding
// window)
else {
if (!pool.isEmpty() && pool.size() >= WINDOW_LENGTH) {
final Tuple first = pool.getFirst();
observations.remove(first.timestamp);
final int idx = first.index;
for (int i = 0; i < WINDOW_LENGTH; i++) {
dist_matrix[i][idx] = -1;
dist_matrix[idx][i] = -1;
}
pool.removeFirst();
}
}
}
// Returns the first available index in the distance matrix.
public int getAvailableIndex() {
int idx = 0;
while (dist_matrix[0][idx] >= 0) {
idx++;
}
return idx;
}
public String getClusterStatus() {
return slClusterer.toString();
}
public int getMaxTime() {
return WINDOW_LENGTH;
}
public int getPoolSize() {
return pool.size();
}
public boolean lastObservationWasMoving() {
return currentlyMoving;
}
}
| false | true | public void addObservation(double timestamp, final Observation observation) {
// Delete observation outside MAX_TIME window.
deleteOldObservations(timestamp);
int index = getAvailableIndex();
// Update distance matrix
for (final Tuple tuple : pool) {
dist_matrix[index][tuple.index] = dist_matrix[tuple.index][index] = observation
.distanceFrom(observations.get(tuple.timestamp));
}
observations.put(timestamp, observation);
pool.addLast(new Tuple(timestamp, index));
final int pool_size = pool.size();
/*
* If it's a time-based window, then don't cluster if there's only one
* sample in the pool, otherwise if it's not a time-based window, then
* don't cluster until the pool is full.
*/
if ((TIME_BASED_WINDOW && pool_size <= 1)
|| (!TIME_BASED_WINDOW && pool_size < WINDOW_LENGTH)) {
return;
}
// Perform the clustering
final boolean[] cluster_status = new boolean[WINDOW_LENGTH];
for (int i = 0; i < WINDOW_LENGTH; i++) {
// Set initial cluster status to false
cluster_status[i] = false;
}
for (final Tuple tuple : pool) {
final int i = tuple.index;
// Not the most efficient way to do things, but not too bad
// First we check how many neighbours are within epsilon
int neighbours = 0;
for (final Tuple tuple2 : pool) {
final int j = tuple2.index;
if (i != j && dist_matrix[i][j] < observation.getEPS()
&& dist_matrix[i][j] > 0.0) {
neighbours += 1;
}
}
// Then, if enough neighbours exist, set ourself and our neighbours
// to be in a cluster
if (neighbours >= (int) (DELTA * (double) pool_size)) {
cluster_status[i] = true;
for (int j = 0; j < WINDOW_LENGTH; j++) {
if (dist_matrix[i][j] < observation.getEPS()
&& dist_matrix[i][j] > 0.0) {
cluster_status[j] = true;
}
}
}
}
// And finally, update the statuses
Location location = null;
int clustered_points = 0;
int status = 0;
for (final Tuple tuple : pool) {
timestamp = tuple.timestamp;
index = tuple.index;
if (cluster_status[index]) {
status -= 1; // Vote for stationarity
clustered_points += 1;
/*
* If we were moving on the last step and now we've stopped,
* create a new significant location candidate.
*/
if (previouslyMoving) {
if (location == null) {
location = locations.newLocation(timestamp);
}
location.addObservation(observations.get(timestamp));
}
} else {
status += 1; // Vote for motion.
}
}
Log.d(TAG, "Clustered " + clustered_points + " of " + pool_size
+ " points.");
if (location != null) {
current_cluster = slClusterer.addNewLocation(location);
currentlyMoving = false;
Log.d(TAG,
"WifiClusterer thinks we're stationary and in location: "
+ current_cluster);
if (current_cluster > 0) {
/*
* The purpose of this timer is to avoid continually updating
* the location if the user remains stationary in a known
* location. We start with a timer that resets the motion state
* every RESET_UPDATE_STATUS_TIME_IN_SECONDS seconds, and then
* after an update we double the time before the next update.
*/
resetMovementTimer.schedule(new TimerTask() {
@Override
public void run() {
previouslyMoving = true;
}
}, timerDelay);
timerDelay *= 2;
previouslyMoving = false;
}
} else if (!previouslyMoving) {
/*
* If we were stationary, but now we are moving, then we cancel the
* timer that should only be running if we're stationary.
*/
current_cluster = -1;
timerDelay = RESET_MOVEMENT_STATE_TIME_IN_SECONDS * 1000;
previouslyMoving = true;
currentlyMoving = true;
resetMovementTimer.cancel();
resetMovementTimer.purge();
resetMovementTimer = new Timer(RESET_MOVEMENT_STATE_TIMER_NAME);
} else {
/* User was moving previously, and is still moving */
current_cluster = -1;
currentlyMoving = true;
}
final Date d = new Date(System.currentTimeMillis());
LocationStatusWidget.updateText("Update at: " + dfm.format(d)
+ "\nClustered " + clustered_points + " of " + pool_size
+ " points.\nCurrently in location: " + current_cluster + "\n");
try {
if (outputLog != null) {
outputLog.write(dfm.format(d) + "," + current_cluster + "\n");
}
} catch (final IOException e) {
e.printStackTrace();
}
}
| public void addObservation(double timestamp, final Observation observation) {
// Delete observation outside MAX_TIME window.
deleteOldObservations(timestamp);
int index = getAvailableIndex();
// Update distance matrix
for (final Tuple tuple : pool) {
dist_matrix[index][tuple.index] = dist_matrix[tuple.index][index] = observation
.distanceFrom(observations.get(tuple.timestamp));
}
observations.put(timestamp, observation);
pool.addLast(new Tuple(timestamp, index));
final int pool_size = pool.size();
/*
* If it's a time-based window, then don't cluster if there's only one
* sample in the pool, otherwise if it's not a time-based window, then
* don't cluster until the pool is full.
*/
if ((TIME_BASED_WINDOW && pool_size <= 1)
|| (!TIME_BASED_WINDOW && pool_size < WINDOW_LENGTH)) {
return;
}
// Perform the clustering
final boolean[] cluster_status = new boolean[WINDOW_LENGTH];
for (int i = 0; i < WINDOW_LENGTH; i++) {
// Set initial cluster status to false
cluster_status[i] = false;
}
for (final Tuple tuple : pool) {
final int i = tuple.index;
// Not the most efficient way to do things, but not too bad
// First we check how many neighbours are within epsilon
int neighbours = 0;
for (final Tuple tuple2 : pool) {
final int j = tuple2.index;
if (i != j && dist_matrix[i][j] < observation.getEPS()
&& dist_matrix[i][j] > 0.0) {
neighbours += 1;
}
}
// Then, if enough neighbours exist, set ourself and our neighbours
// to be in a cluster
if (neighbours >= (int) (DELTA * (double) pool_size)) {
cluster_status[i] = true;
for (int j = 0; j < WINDOW_LENGTH; j++) {
if (dist_matrix[i][j] < observation.getEPS()
&& dist_matrix[i][j] > 0.0) {
cluster_status[j] = true;
}
}
}
}
// And finally, update the statuses
Location location = null;
int clustered_points = 0;
int status = 0;
for (final Tuple tuple : pool) {
timestamp = tuple.timestamp;
index = tuple.index;
if (cluster_status[index]) {
status -= 1; // Vote for stationarity
clustered_points += 1;
/*
* If we were moving on the last step and now we've stopped,
* create a new significant location candidate.
*/
if (previouslyMoving) {
if (location == null) {
location = locations.newLocation(timestamp);
}
location.addObservation(observations.get(timestamp));
}
} else {
status += 1; // Vote for motion.
}
}
Log.d(TAG, "Clustered " + clustered_points + " of " + pool_size
+ " points.");
if (location != null) {
current_cluster = slClusterer.addNewLocation(location);
currentlyMoving = false;
Log.d(TAG,
"WifiClusterer thinks we're stationary and in location: "
+ current_cluster);
if (current_cluster > 0) {
/*
* The purpose of this timer is to avoid continually updating
* the location if the user remains stationary in a known
* location. We start with a timer that resets the motion state
* every RESET_UPDATE_STATUS_TIME_IN_SECONDS seconds, and then
* after an update we double the time before the next update.
*/
resetMovementTimer.schedule(new TimerTask() {
@Override
public void run() {
previouslyMoving = true;
}
}, timerDelay);
timerDelay *= 2;
previouslyMoving = false;
}
} else if (!previouslyMoving && clustered_points == 0) {
/*
* If we were stationary, but now we are moving, then we cancel the
* timer that should only be running if we're stationary.
*/
current_cluster = -1;
timerDelay = RESET_MOVEMENT_STATE_TIME_IN_SECONDS * 1000;
previouslyMoving = true;
currentlyMoving = true;
resetMovementTimer.cancel();
resetMovementTimer.purge();
resetMovementTimer = new Timer(RESET_MOVEMENT_STATE_TIMER_NAME);
} else if (clustered_points == 0) {
/* User was moving previously, and is still moving */
current_cluster = -1;
currentlyMoving = true;
}
final Date d = new Date(System.currentTimeMillis());
LocationStatusWidget.updateText("Update at: " + dfm.format(d)
+ "\nClustered " + clustered_points + " of " + pool_size
+ " points.\nCurrently in location: " + current_cluster + "\n");
try {
if (outputLog != null) {
outputLog.write(dfm.format(d) + "," + current_cluster + "\n");
}
} catch (final IOException e) {
e.printStackTrace();
}
}
|
diff --git a/src/com/division/battlegrounds/mech/BattlegroundQueueManager.java b/src/com/division/battlegrounds/mech/BattlegroundQueueManager.java
index 508af4f..0974f95 100644
--- a/src/com/division/battlegrounds/mech/BattlegroundQueueManager.java
+++ b/src/com/division/battlegrounds/mech/BattlegroundQueueManager.java
@@ -1,107 +1,110 @@
package com.division.battlegrounds.mech;
import com.division.battlegrounds.core.Battleground;
import com.division.battlegrounds.core.BattlegroundCore;
import com.division.battlegrounds.event.EnteredQueueEvent;
import com.division.battlegrounds.event.LeftQueueEvent;
import com.division.battlegrounds.event.RoundStartEvent;
import java.util.Collection;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
/**
*
* @author Evan
*/
public class BattlegroundQueueManager implements Listener {
private final BattlegroundRegistrar bgr;
private final String bgaFormat = ChatColor.RED + "[" + ChatColor.YELLOW + "BGAnnouncer" + ChatColor.RED + "]" + ChatColor.YELLOW + " %s of %s players in queue for %s";
public BattlegroundQueueManager(BattlegroundRegistrar bgr) {
this.bgr = bgr;
Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask(BattlegroundCore.getInstance(), new queueRunner(), 100L, 100L);
}
@EventHandler(priority = EventPriority.MONITOR)
public void onEnteredQueue(EnteredQueueEvent evt) {
int minPlayers = evt.getBattleground().getMinPlayers();
int curPlayers = evt.getBattleground().getQueueSize();
if (evt.getBattleground().isPlayerInBattleground(evt.getPlayer())) {
return;
}
if (evt.getBattleground().isActive()) {
if (evt.getBattleground().isDynamic() && !evt.getBattleground().isFull()) {
evt.getBattleground().addPlayerToBattleground(evt.getPlayer());
return;
}
}
if (evt.getBattleground().isBroadcasting()) {
broadcastQueueStatus(evt.getBattleground().getName(), curPlayers, minPlayers);
}
}
@EventHandler(priority = EventPriority.MONITOR)
public void onLeftQueue(LeftQueueEvent evt) {
int minPlayers = evt.getBattleground().getMinPlayers();
int curPlayers = evt.getBattleground().getQueueSize();
broadcastQueueStatus(evt.getBattleground().getName(), curPlayers, minPlayers);
}
@EventHandler(priority = EventPriority.MONITOR)
public void onRoundStart(RoundStartEvent evt) {
Bukkit.getServer().broadcastMessage(String.format(BattlegroundCore.logFormat, "Battleground: " + evt.getBattleground().getName() + " has started."));
}
private void broadcastQueueStatus(String name, int curPlayers, int minPlayers) {
Bukkit.getServer().broadcastMessage(String.format(bgaFormat, curPlayers, minPlayers, name));
}
private class queueRunner implements Runnable {
@Override
public void run() {
Collection<Battleground> bgList = bgr.getRegistrar().values();
for (Battleground bg : bgList) {
+ if(bg.getQueue().isEmpty()){
+ continue;
+ }
if (bg.isActive()) {
if (bg.isDynamic() && !bg.isFull()) {
bg.addPlayerToBattleground(bg.getQueue().get(0));
bg.getQueue().remove(0);
}
return;
}
if (bg.getQueueSize() >= bg.getMinPlayers()) {
if (bg.getQueueSize() >= bg.getMaxPlayers()) {
Bukkit.getServer().getPluginManager().callEvent(new RoundStartEvent(bg, bg.getQueue().subList(0, bg.getMaxPlayers())));
} else {
Bukkit.getServer().getPluginManager().callEvent(new RoundStartEvent(bg, bg.getQueue()));
}
}
}
}
}
public boolean isInQueue(Player player) {
Collection<Battleground> bgList = bgr.getRegistrar().values();
for (Battleground bg : bgList) {
if (bg.getQueue().contains(player)) {
return true;
}
}
return false;
}
public Battleground getQueuedBG(Player player) {
Collection<Battleground> bgList = bgr.getRegistrar().values();
for (Battleground bg : bgList) {
if (bg.getQueue().contains(player)) {
return bg;
}
}
return null;
}
}
| true | true | public void run() {
Collection<Battleground> bgList = bgr.getRegistrar().values();
for (Battleground bg : bgList) {
if (bg.isActive()) {
if (bg.isDynamic() && !bg.isFull()) {
bg.addPlayerToBattleground(bg.getQueue().get(0));
bg.getQueue().remove(0);
}
return;
}
if (bg.getQueueSize() >= bg.getMinPlayers()) {
if (bg.getQueueSize() >= bg.getMaxPlayers()) {
Bukkit.getServer().getPluginManager().callEvent(new RoundStartEvent(bg, bg.getQueue().subList(0, bg.getMaxPlayers())));
} else {
Bukkit.getServer().getPluginManager().callEvent(new RoundStartEvent(bg, bg.getQueue()));
}
}
}
}
| public void run() {
Collection<Battleground> bgList = bgr.getRegistrar().values();
for (Battleground bg : bgList) {
if(bg.getQueue().isEmpty()){
continue;
}
if (bg.isActive()) {
if (bg.isDynamic() && !bg.isFull()) {
bg.addPlayerToBattleground(bg.getQueue().get(0));
bg.getQueue().remove(0);
}
return;
}
if (bg.getQueueSize() >= bg.getMinPlayers()) {
if (bg.getQueueSize() >= bg.getMaxPlayers()) {
Bukkit.getServer().getPluginManager().callEvent(new RoundStartEvent(bg, bg.getQueue().subList(0, bg.getMaxPlayers())));
} else {
Bukkit.getServer().getPluginManager().callEvent(new RoundStartEvent(bg, bg.getQueue()));
}
}
}
}
|
diff --git a/src/java/drbd/gui/resources/HostInfo.java b/src/java/drbd/gui/resources/HostInfo.java
index 53598166..7e1a1622 100644
--- a/src/java/drbd/gui/resources/HostInfo.java
+++ b/src/java/drbd/gui/resources/HostInfo.java
@@ -1,867 +1,867 @@
/*
* This file is part of DRBD Management Console by LINBIT HA-Solutions GmbH
* written by Rasto Levrinc.
*
* Copyright (C) 2009-2010, LINBIT HA-Solutions GmbH.
* Copyright (C) 2009-2010, Rasto Levrinc
*
* DRBD Management Console is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as published
* by the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* DRBD Management Console is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with drbd; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package drbd.gui.resources;
import drbd.EditHostDialog;
import drbd.gui.Browser;
import drbd.gui.HostBrowser;
import drbd.gui.ClusterBrowser;
import drbd.gui.SpringUtilities;
import drbd.data.Host;
import drbd.data.Cluster;
import drbd.utilities.UpdatableItem;
import drbd.data.Subtext;
import drbd.data.ClusterStatus;
import drbd.data.ConfigData;
import drbd.data.AccessMode;
import drbd.utilities.Tools;
import drbd.utilities.MyButton;
import drbd.utilities.ExecCallback;
import drbd.utilities.MyMenu;
import drbd.utilities.MyMenuItem;
import drbd.utilities.CRM;
import drbd.utilities.SSH;
import drbd.utilities.Corosync;
import drbd.utilities.Openais;
import drbd.utilities.Heartbeat;
import java.util.List;
import java.util.ArrayList;
import java.awt.Font;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Color;
import javax.swing.BoxLayout;
import javax.swing.JComponent;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.SpringLayout;
import javax.swing.JScrollPane;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JColorChooser;
/**
* This class holds info data for a host.
* It shows host view, just like in the host tab.
*/
public final class HostInfo extends Info {
/** Host data. */
private final Host host;
/** Host standby icon. */
private static final ImageIcon HOST_STANDBY_ICON =
Tools.createImageIcon(Tools.getDefault("HeartbeatGraph.HostStandbyIcon"));
/** Host standby off icon. */
private static final ImageIcon HOST_STANDBY_OFF_ICON =
Tools.createImageIcon(
Tools.getDefault("HeartbeatGraph.HostStandbyOffIcon"));
/** Stop comm layer icon. */
private static final ImageIcon HOST_STOP_COMM_LAYER_ICON =
Tools.createImageIcon(
Tools.getDefault("HeartbeatGraph.HostStopCommLayerIcon"));
/** Start comm layer icon. */
private static final ImageIcon HOST_START_COMM_LAYER_ICON =
Tools.createImageIcon(
Tools.getDefault("HeartbeatGraph.HostStartCommLayerIcon"));
/** Offline subtext. */
private static final Subtext OFFLINE_SUBTEXT =
new Subtext("offline", null, Color.BLUE);
/** Pending subtext. */
private static final Subtext PENDING_SUBTEXT =
new Subtext("pending", null, Color.BLUE);
/** Fenced/unclean subtext. */
private static final Subtext FENCED_SUBTEXT =
new Subtext("fencing...", null, Color.RED);
/** Stopped subtext. */
private static final Subtext STOPPED_SUBTEXT =
new Subtext("stopped", null, Color.RED);
/** Unknown subtext. */
private static final Subtext UNKNOWN_SUBTEXT =
new Subtext("wait...", null, Color.BLUE);
/** Online subtext. */
private static final Subtext ONLINE_SUBTEXT =
new Subtext("online", null, Color.BLUE);
/** Standby subtext. */
private static final Subtext STANDBY_SUBTEXT =
new Subtext("STANDBY", null, Color.RED);
/** Stopping subtext. */
private static final Subtext STOPPING_SUBTEXT =
new Subtext("stopping...", null, Color.RED);
/** Starting subtext. */
private static final Subtext STARTING_SUBTEXT =
new Subtext("starting...", null, Color.BLUE);
/** String that is displayed as a tool tip for disabled menu item. */
private static final String NO_PCMK_STATUS_STRING =
"cluster status is not available";
/** Prepares a new <code>HostInfo</code> object. */
public HostInfo(final Host host, final Browser browser) {
super(host.getName(), browser);
this.host = host;
}
/** Returns browser object of this info. */
@Override protected HostBrowser getBrowser() {
return (HostBrowser) super.getBrowser();
}
/** Returns a host icon for the menu. */
@Override public ImageIcon getMenuIcon(final boolean testOnly) {
final Cluster cl = host.getCluster();
if (cl != null) {
return HostBrowser.HOST_IN_CLUSTER_ICON_RIGHT_SMALL;
}
return HostBrowser.HOST_ICON;
}
/** Returns id, which is name of the host. */
@Override public String getId() {
return host.getName();
}
/** Returns a host icon for the category in the menu. */
@Override public ImageIcon getCategoryIcon(final boolean testOnly) {
return HostBrowser.HOST_ICON;
}
/** Returns tooltip for the host. */
@Override public String getToolTipForGraph(final boolean testOnly) {
return getBrowser().getHostToolTip(host);
}
/** Returns info panel. */
@Override public JComponent getInfoPanel() {
final Font f = new Font("Monospaced", Font.PLAIN, 12);
final JTextArea ta = new JTextArea();
ta.setFont(f);
final String stacktrace = Tools.getStackTrace();
final ExecCallback execCallback =
new ExecCallback() {
@Override public void done(final String ans) {
ta.setText(ans);
}
@Override public void doneError(final String ans,
final int exitCode) {
ta.setText("error");
Tools.sshError(host, "", ans, stacktrace, exitCode);
}
};
final MyButton crmMonButton = new MyButton("crm_mon");
crmMonButton.addActionListener(new ActionListener() {
@Override public void actionPerformed(final ActionEvent e) {
host.execCommand("HostBrowser.getCrmMon",
execCallback,
null, /* ConvertCmdCallback */
true, /* outputVisible */
SSH.DEFAULT_COMMAND_TIMEOUT);
}
});
host.registerEnableOnConnect(crmMonButton);
final MyButton crmConfigureShowButton =
new MyButton("crm configure show");
crmConfigureShowButton.addActionListener(new ActionListener() {
@Override public void actionPerformed(final ActionEvent e) {
host.execCommand("HostBrowser.getCrmConfigureShow",
execCallback,
null, /* ConvertCmdCallback */
true, /* outputVisible */
SSH.DEFAULT_COMMAND_TIMEOUT);
}
});
host.registerEnableOnConnect(crmConfigureShowButton);
final JPanel mainPanel = new JPanel();
mainPanel.setBackground(HostBrowser.PANEL_BACKGROUND);
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
final JPanel buttonPanel = new JPanel(new BorderLayout());
buttonPanel.setBackground(HostBrowser.STATUS_BACKGROUND);
buttonPanel.setMinimumSize(new Dimension(0, 50));
buttonPanel.setPreferredSize(new Dimension(0, 50));
buttonPanel.setMaximumSize(new Dimension(Short.MAX_VALUE, 50));
mainPanel.add(buttonPanel);
/* Actions */
final JMenuBar mb = new JMenuBar();
mb.setBackground(HostBrowser.PANEL_BACKGROUND);
final JMenu serviceCombo = getActionsMenu();
mb.add(serviceCombo);
buttonPanel.add(mb, BorderLayout.EAST);
final JPanel p = new JPanel(new SpringLayout());
p.setBackground(HostBrowser.STATUS_BACKGROUND);
p.add(crmMonButton);
p.add(crmConfigureShowButton);
SpringUtilities.makeCompactGrid(p, 2, 1, // rows, cols
1, 1, // initX, initY
1, 1); // xPad, yPad
mainPanel.setMinimumSize(new Dimension(
Tools.getDefaultInt("HostBrowser.ResourceInfoArea.Width"),
Tools.getDefaultInt("HostBrowser.ResourceInfoArea.Height")));
mainPanel.setPreferredSize(new Dimension(
Tools.getDefaultInt("HostBrowser.ResourceInfoArea.Width"),
Tools.getDefaultInt("HostBrowser.ResourceInfoArea.Height")));
buttonPanel.add(p);
mainPanel.add(new JScrollPane(ta));
return mainPanel;
}
/** Gets host. */
public Host getHost() {
return host;
}
/**
* Compares this host info name with specified hostinfo's name.
*
* @param otherHI
* other host info
* @return true if they are equal
*/
boolean equals(final HostInfo otherHI) {
if (otherHI == null) {
return false;
}
return otherHI.toString().equals(host.getName());
}
/** Returns string representation of the host. It's same as name. */
@Override public String toString() {
return host.getName();
}
/** Returns name of the host. */
@Override public String getName() {
return host.getName();
}
/** Creates the popup for the host. */
@Override public List<UpdatableItem> createPopup() {
final List<UpdatableItem> items = new ArrayList<UpdatableItem>();
final boolean testOnly = false;
/* host wizard */
final MyMenuItem hostWizardItem =
new MyMenuItem(Tools.getString("HostBrowser.HostWizard"),
HostBrowser.HOST_ICON_LARGE,
"",
new AccessMode(ConfigData.AccessType.RO, false),
new AccessMode(ConfigData.AccessType.RO, false)) {
private static final long serialVersionUID = 1L;
@Override public String enablePredicate() {
return null;
}
@Override public void action() {
final EditHostDialog dialog = new EditHostDialog(host);
dialog.showDialogs();
}
};
items.add(hostWizardItem);
Tools.getGUIData().registerAddHostButton(hostWizardItem);
/* cluster manager standby on/off */
final HostInfo thisClass = this;
final MyMenuItem standbyItem =
new MyMenuItem(Tools.getString("HostBrowser.CRM.StandByOn"),
HOST_STANDBY_ICON,
ClusterBrowser.STARTING_PTEST_TOOLTIP,
Tools.getString("HostBrowser.CRM.StandByOff"),
HOST_STANDBY_OFF_ICON,
ClusterBrowser.STARTING_PTEST_TOOLTIP,
new AccessMode(ConfigData.AccessType.OP, false),
new AccessMode(ConfigData.AccessType.OP, false)) {
private static final long serialVersionUID = 1L;
@Override public boolean predicate() {
return !isStandby(testOnly);
}
@Override public String enablePredicate() {
if (!getHost().isClStatus()) {
return NO_PCMK_STATUS_STRING;
}
return null;
}
@Override public void action() {
if (isStandby(testOnly)) {
CRM.standByOff(host, testOnly);
} else {
CRM.standByOn(host, testOnly);
}
}
};
final ClusterBrowser cb = getBrowser().getClusterBrowser();
if (cb != null) {
final ClusterBrowser.ClMenuItemCallback standbyItemCallback =
cb.new ClMenuItemCallback(standbyItem, host) {
@Override public void action(final Host host) {
if (isStandby(false)) {
CRM.standByOff(host, true);
} else {
CRM.standByOn(host, true);
}
}
};
addMouseOverListener(standbyItem, standbyItemCallback);
}
items.add(standbyItem);
/* Migrate all services from this host. */
final MyMenuItem allMigrateFromItem =
new MyMenuItem(Tools.getString("HostInfo.CRM.AllMigrateFrom"),
HOST_STANDBY_ICON,
ClusterBrowser.STARTING_PTEST_TOOLTIP,
new AccessMode(ConfigData.AccessType.OP, false),
new AccessMode(ConfigData.AccessType.OP, false)) {
private static final long serialVersionUID = 1L;
@Override public boolean predicate() {
return true;
}
@Override public String enablePredicate() {
if (!getHost().isClStatus()) {
return NO_PCMK_STATUS_STRING;
}
if (getBrowser().getClusterBrowser()
.getExistingServiceList(null).isEmpty()) {
return "there are no services to migrate";
}
return null;
}
@Override public void action() {
for (final ServiceInfo si
: cb.getExistingServiceList(null)) {
if (!si.isConstraintPH()
&& si.getGroupInfo() == null
&& si.getCloneInfo() == null) {
final List<String> runningOnNodes =
si.getRunningOnNodes(false);
if (runningOnNodes != null
&& runningOnNodes.contains(
getHost().getName())) {
final Host dcHost = getHost();
si.migrateFromResource(dcHost,
getHost().getName(),
false);
}
}
}
}
};
if (cb != null) {
final ClusterBrowser.ClMenuItemCallback allMigrateFromItemCallback =
cb.new ClMenuItemCallback(allMigrateFromItem, host) {
@Override public void action(final Host dcHost) {
for (final ServiceInfo si
: cb.getExistingServiceList(null)) {
if (!si.isConstraintPH() && si.getGroupInfo() == null) {
final List<String> runningOnNodes =
si.getRunningOnNodes(false);
if (runningOnNodes != null
&& runningOnNodes.contains(
host.getName())) {
si.migrateFromResource(dcHost,
host.getName(),
true);
}
}
}
}
};
addMouseOverListener(allMigrateFromItem,
allMigrateFromItemCallback);
}
items.add(allMigrateFromItem);
/* Stop corosync/openais. */
final MyMenuItem stopCorosyncItem =
new MyMenuItem(Tools.getString("HostInfo.StopCorosync"),
HOST_STOP_COMM_LAYER_ICON,
ClusterBrowser.STARTING_PTEST_TOOLTIP,
Tools.getString("HostInfo.StopOpenais"),
HOST_STOP_COMM_LAYER_ICON,
ClusterBrowser.STARTING_PTEST_TOOLTIP,
new AccessMode(ConfigData.AccessType.ADMIN, true),
new AccessMode(ConfigData.AccessType.ADMIN, false)) {
private static final long serialVersionUID = 1L;
@Override public boolean predicate() {
/* when both are running it's openais. */
return getHost().isCsRunning() && !getHost().isAisRunning();
}
@Override public boolean visiblePredicate() {
return getHost().isCsRunning()
|| getHost().isAisRunning();
}
@Override public void action() {
if (Tools.confirmDialog(
Tools.getString("HostInfo.confirmCorosyncStop.Title"),
Tools.getString("HostInfo.confirmCorosyncStop.Desc"),
Tools.getString("HostInfo.confirmCorosyncStop.Yes"),
Tools.getString("HostInfo.confirmCorosyncStop.No"))) {
final Host host = getHost();
host.setCommLayerStopping(true);
if (host.getPcmkServiceVersion() > 0
&& host.isPcmkInit()
&& host.isPcmkRunning()) {
Corosync.stopCorosyncWithPcmk(host);
} else {
Corosync.stopCorosync(host);
}
getBrowser().getClusterBrowser().updateHWInfo(host);
}
}
};
if (cb != null) {
final ClusterBrowser.ClMenuItemCallback stopCorosyncItemCallback =
cb.new ClMenuItemCallback(stopCorosyncItem, host) {
@Override public void action(final Host host) {
if (!isStandby(false)) {
CRM.standByOn(host, true);
}
}
};
addMouseOverListener(stopCorosyncItem,
stopCorosyncItemCallback);
}
items.add(stopCorosyncItem);
/* Stop heartbeat. */
final MyMenuItem stopHeartbeatItem =
new MyMenuItem(Tools.getString("HostInfo.StopHeartbeat"),
HOST_STOP_COMM_LAYER_ICON,
ClusterBrowser.STARTING_PTEST_TOOLTIP,
new AccessMode(ConfigData.AccessType.ADMIN, true),
new AccessMode(ConfigData.AccessType.ADMIN, false)) {
private static final long serialVersionUID = 1L;
@Override public boolean visiblePredicate() {
return getHost().isHeartbeatRunning();
}
@Override public void action() {
if (Tools.confirmDialog(
Tools.getString("HostInfo.confirmHeartbeatStop.Title"),
Tools.getString("HostInfo.confirmHeartbeatStop.Desc"),
Tools.getString("HostInfo.confirmHeartbeatStop.Yes"),
Tools.getString("HostInfo.confirmHeartbeatStop.No"))) {
getHost().setCommLayerStopping(true);
Heartbeat.stopHeartbeat(getHost());
getBrowser().getClusterBrowser().updateHWInfo(host);
}
}
};
if (cb != null) {
final ClusterBrowser.ClMenuItemCallback stopHeartbeatItemCallback =
cb.new ClMenuItemCallback(stopHeartbeatItem, host) {
@Override public void action(final Host host) {
if (!isStandby(false)) {
CRM.standByOn(host, true);
}
}
};
addMouseOverListener(stopHeartbeatItem,
stopHeartbeatItemCallback);
}
items.add(stopHeartbeatItem);
/* Start corosync. */
final MyMenuItem startCorosyncItem =
new MyMenuItem(Tools.getString("HostInfo.StartCorosync"),
HOST_START_COMM_LAYER_ICON,
ClusterBrowser.STARTING_PTEST_TOOLTIP,
new AccessMode(ConfigData.AccessType.ADMIN, false),
new AccessMode(ConfigData.AccessType.ADMIN, false)) {
private static final long serialVersionUID = 1L;
@Override public boolean visiblePredicate() {
final Host h = getHost();
return h.isCorosync()
&& h.isCsInit()
&& h.isCsAisConf()
&& !h.isCsRunning()
&& !h.isAisRunning()
&& !h.isHeartbeatRunning()
&& !h.isHeartbeatRc();
}
@Override public String enablePredicate() {
final Host h = getHost();
if (h.isAisRc() && !h.isCsRc()) {
return "Openais is in rc.d";
}
return null;
}
@Override public void action() {
getHost().setCommLayerStarting(true);
if (getHost().isPcmkRc()) {
Corosync.startCorosyncWithPcmk(getHost());
} else {
Corosync.startCorosync(getHost());
}
getBrowser().getClusterBrowser().updateHWInfo(host);
}
};
if (cb != null) {
final ClusterBrowser.ClMenuItemCallback startCorosyncItemCallback =
cb.new ClMenuItemCallback(startCorosyncItem, host) {
@Override public void action(final Host host) {
//TODO
}
};
addMouseOverListener(startCorosyncItem,
startCorosyncItemCallback);
}
items.add(startCorosyncItem);
/* Start openais. */
final MyMenuItem startOpenaisItem =
new MyMenuItem(Tools.getString("HostInfo.StartOpenais"),
HOST_START_COMM_LAYER_ICON,
ClusterBrowser.STARTING_PTEST_TOOLTIP,
new AccessMode(ConfigData.AccessType.ADMIN, false),
new AccessMode(ConfigData.AccessType.ADMIN, false)) {
private static final long serialVersionUID = 1L;
@Override public boolean visiblePredicate() {
final Host h = getHost();
return h.isAisInit()
&& h.isCsAisConf()
&& !h.isCsRunning()
&& !h.isAisRunning()
&& !h.isHeartbeatRunning()
&& !h.isHeartbeatRc();
}
@Override public String enablePredicate() {
final Host h = getHost();
if (h.isCsRc() && !h.isAisRc()) {
return "Corosync is in rc.d";
}
return null;
}
@Override public void action() {
getHost().setCommLayerStarting(true);
Openais.startOpenais(getHost());
getBrowser().getClusterBrowser().updateHWInfo(host);
}
};
if (cb != null) {
final ClusterBrowser.ClMenuItemCallback startOpenaisItemCallback =
cb.new ClMenuItemCallback(startOpenaisItem, host) {
@Override public void action(final Host host) {
//TODO
}
};
addMouseOverListener(startOpenaisItem,
startOpenaisItemCallback);
}
items.add(startOpenaisItem);
/* Start heartbeat. */
final MyMenuItem startHeartbeatItem =
new MyMenuItem(Tools.getString("HostInfo.StartHeartbeat"),
HOST_START_COMM_LAYER_ICON,
ClusterBrowser.STARTING_PTEST_TOOLTIP,
new AccessMode(ConfigData.AccessType.ADMIN, false),
new AccessMode(ConfigData.AccessType.ADMIN, false)) {
private static final long serialVersionUID = 1L;
@Override public boolean visiblePredicate() {
final Host h = getHost();
return h.isHeartbeatInit()
&& h.isHeartbeatConf()
&& !h.isCsRunning()
&& !h.isAisRunning()
&& !h.isHeartbeatRunning();
//&& !h.isAisRc()
//&& !h.isCsRc(); TODO should check /etc/defaults/
}
@Override public void action() {
getHost().setCommLayerStarting(true);
Heartbeat.startHeartbeat(getHost());
getBrowser().getClusterBrowser().updateHWInfo(host);
}
};
if (cb != null) {
final ClusterBrowser.ClMenuItemCallback startHeartbeatItemCallback =
cb.new ClMenuItemCallback(startHeartbeatItem, host) {
@Override public void action(final Host host) {
//TODO
}
};
addMouseOverListener(startHeartbeatItem,
startHeartbeatItemCallback);
}
items.add(startHeartbeatItem);
/* Start pacemaker. */
final MyMenuItem startPcmkItem =
new MyMenuItem(Tools.getString("HostInfo.StartPacemaker"),
HOST_START_COMM_LAYER_ICON,
ClusterBrowser.STARTING_PTEST_TOOLTIP,
new AccessMode(ConfigData.AccessType.ADMIN, false),
new AccessMode(ConfigData.AccessType.ADMIN, false)) {
private static final long serialVersionUID = 1L;
@Override public boolean visiblePredicate() {
final Host h = getHost();
return h.getPcmkServiceVersion() > 0
&& !h.isPcmkRunning()
&& (h.isCsRunning()
|| h.isAisRunning())
&& !h.isHeartbeatRunning();
}
@Override public String enablePredicate() {
return null;
}
@Override public void action() {
Corosync.startPacemaker(getHost());
getBrowser().getClusterBrowser().updateHWInfo(host);
}
};
if (cb != null) {
final ClusterBrowser.ClMenuItemCallback startPcmkItemCallback =
cb.new ClMenuItemCallback(startPcmkItem, host) {
@Override public void action(final Host host) {
//TODO
}
};
addMouseOverListener(startPcmkItem,
startPcmkItemCallback);
}
items.add(startPcmkItem);
/* change host color */
final MyMenuItem changeHostColorItem =
new MyMenuItem(Tools.getString("HostBrowser.Drbd.ChangeHostColor"),
null,
"",
new AccessMode(ConfigData.AccessType.RO, false),
new AccessMode(ConfigData.AccessType.RO, false)) {
private static final long serialVersionUID = 1L;
@Override public String enablePredicate() {
return null;
}
@Override public void action() {
final Color newColor = JColorChooser.showDialog(
Tools.getGUIData().getMainFrame(),
"Choose " + host.getName()
+ " color",
host.getPmColors()[0]);
if (newColor != null) {
host.setSavedColor(newColor);
}
}
};
items.add(changeHostColorItem);
/* view logs */
final MyMenuItem viewLogsItem =
new MyMenuItem(Tools.getString("HostBrowser.Drbd.ViewLogs"),
LOGFILE_ICON,
"",
new AccessMode(ConfigData.AccessType.RO, false),
new AccessMode(ConfigData.AccessType.RO, false)) {
private static final long serialVersionUID = 1L;
@Override public String enablePredicate() {
if (!getHost().isConnected()) {
return Host.NOT_CONNECTED_STRING;
}
return null;
}
@Override public void action() {
drbd.gui.dialog.HostLogs l =
new drbd.gui.dialog.HostLogs(host);
l.showDialog();
}
};
items.add(viewLogsItem);
/* advacend options */
final MyMenu hostAdvancedSubmenu = new MyMenu(
Tools.getString("HostBrowser.AdvancedSubmenu"),
new AccessMode(ConfigData.AccessType.OP, false),
new AccessMode(ConfigData.AccessType.OP, false)) {
private static final long serialVersionUID = 1L;
@Override public String enablePredicate() {
if (!host.isConnected()) {
return Host.NOT_CONNECTED_STRING;
}
return null;
}
@Override public void update() {
super.update();
getBrowser().addAdvancedMenu(this);
}
};
items.add(hostAdvancedSubmenu);
/* remove host from gui */
final MyMenuItem removeHostItem =
new MyMenuItem(Tools.getString("HostBrowser.RemoveHost"),
HostBrowser.HOST_REMOVE_ICON,
- "",
+ Tools.getString("HostBrowser.RemoveHost"),
new AccessMode(ConfigData.AccessType.RO, false),
new AccessMode(ConfigData.AccessType.RO, false)) {
private static final long serialVersionUID = 1L;
@Override public String enablePredicate() {
if (getHost().getCluster() != null) {
return "it is a member of a cluster";
}
return null;
}
@Override public void action() {
getHost().disconnect();
Tools.getConfigData().removeHostFromHosts(getHost());
Tools.getGUIData().allHostsUpdate();
}
};
items.add(removeHostItem);
return items;
}
/** Returns grahical view if there is any. */
@Override public JPanel getGraphicalView() {
final ClusterBrowser b = getBrowser().getClusterBrowser();
if (b == null) {
return null;
}
return b.getServicesInfo().getGraphicalView();
}
/** Returns how much of this is used. */
public int getUsed() {
// TODO: maybe the load?
return -1;
}
/**
* Returns subtexts that appears in the host vertex in the cluster graph.
*/
public Subtext[] getSubtextsForGraph(final boolean testOnly) {
final List<Subtext> texts = new ArrayList<Subtext>();
if (getHost().isConnected()) {
if (!getHost().isClStatus()) {
texts.add(new Subtext("waiting for cluster status...",
null,
Color.BLACK));
}
} else {
texts.add(new Subtext("connecting...", null, Color.BLACK));
}
return texts.toArray(new Subtext[texts.size()]);
}
/** Returns text that appears above the icon in the graph. */
public String getIconTextForGraph(final boolean testOnly) {
if (!getHost().isConnected()) {
return Tools.getString("HostBrowser.Hb.NoInfoAvailable");
}
return null;
}
/** Returns whether this host is in stand by. */
public boolean isStandby(final boolean testOnly) {
final ClusterBrowser b = getBrowser().getClusterBrowser();
if (b == null) {
return false;
}
return b.isStandby(host, testOnly);
}
/** Returns cluster status. */
ClusterStatus getClusterStatus() {
final ClusterBrowser b = getBrowser().getClusterBrowser();
if (b == null) {
return null;
}
return b.getClusterStatus();
}
/** Returns text that appears in the corner of the graph. */
public Subtext getRightCornerTextForGraph(final boolean testOnly) {
if (getHost().isCommLayerStopping()) {
return STOPPING_SUBTEXT;
} else if (getHost().isCommLayerStarting()) {
return STARTING_SUBTEXT;
}
final ClusterStatus cs = getClusterStatus();
if (cs != null && cs.isFencedNode(host.getName())) {
return FENCED_SUBTEXT;
} else if (getHost().isClStatus()) {
if (isStandby(testOnly)) {
return STANDBY_SUBTEXT;
} else {
return ONLINE_SUBTEXT;
}
} else if (getHost().isConnected()) {
final Boolean running = getHost().getCorosyncHeartbeatRunning();
if (running == null) {
return UNKNOWN_SUBTEXT;
} else if (!running) {
return STOPPED_SUBTEXT;
}
if (cs != null && cs.isPendingNode(host.getName())) {
return PENDING_SUBTEXT;
} else if (cs != null
&& "no".equals(cs.isOnlineNode(host.getName()))) {
return OFFLINE_SUBTEXT;
} else {
return UNKNOWN_SUBTEXT;
}
}
return null;
}
/** Selects the node in the menu and reloads everything underneath. */
@Override public void selectMyself() {
super.selectMyself();
getBrowser().nodeChanged(getNode());
}
}
| true | true | @Override public List<UpdatableItem> createPopup() {
final List<UpdatableItem> items = new ArrayList<UpdatableItem>();
final boolean testOnly = false;
/* host wizard */
final MyMenuItem hostWizardItem =
new MyMenuItem(Tools.getString("HostBrowser.HostWizard"),
HostBrowser.HOST_ICON_LARGE,
"",
new AccessMode(ConfigData.AccessType.RO, false),
new AccessMode(ConfigData.AccessType.RO, false)) {
private static final long serialVersionUID = 1L;
@Override public String enablePredicate() {
return null;
}
@Override public void action() {
final EditHostDialog dialog = new EditHostDialog(host);
dialog.showDialogs();
}
};
items.add(hostWizardItem);
Tools.getGUIData().registerAddHostButton(hostWizardItem);
/* cluster manager standby on/off */
final HostInfo thisClass = this;
final MyMenuItem standbyItem =
new MyMenuItem(Tools.getString("HostBrowser.CRM.StandByOn"),
HOST_STANDBY_ICON,
ClusterBrowser.STARTING_PTEST_TOOLTIP,
Tools.getString("HostBrowser.CRM.StandByOff"),
HOST_STANDBY_OFF_ICON,
ClusterBrowser.STARTING_PTEST_TOOLTIP,
new AccessMode(ConfigData.AccessType.OP, false),
new AccessMode(ConfigData.AccessType.OP, false)) {
private static final long serialVersionUID = 1L;
@Override public boolean predicate() {
return !isStandby(testOnly);
}
@Override public String enablePredicate() {
if (!getHost().isClStatus()) {
return NO_PCMK_STATUS_STRING;
}
return null;
}
@Override public void action() {
if (isStandby(testOnly)) {
CRM.standByOff(host, testOnly);
} else {
CRM.standByOn(host, testOnly);
}
}
};
final ClusterBrowser cb = getBrowser().getClusterBrowser();
if (cb != null) {
final ClusterBrowser.ClMenuItemCallback standbyItemCallback =
cb.new ClMenuItemCallback(standbyItem, host) {
@Override public void action(final Host host) {
if (isStandby(false)) {
CRM.standByOff(host, true);
} else {
CRM.standByOn(host, true);
}
}
};
addMouseOverListener(standbyItem, standbyItemCallback);
}
items.add(standbyItem);
/* Migrate all services from this host. */
final MyMenuItem allMigrateFromItem =
new MyMenuItem(Tools.getString("HostInfo.CRM.AllMigrateFrom"),
HOST_STANDBY_ICON,
ClusterBrowser.STARTING_PTEST_TOOLTIP,
new AccessMode(ConfigData.AccessType.OP, false),
new AccessMode(ConfigData.AccessType.OP, false)) {
private static final long serialVersionUID = 1L;
@Override public boolean predicate() {
return true;
}
@Override public String enablePredicate() {
if (!getHost().isClStatus()) {
return NO_PCMK_STATUS_STRING;
}
if (getBrowser().getClusterBrowser()
.getExistingServiceList(null).isEmpty()) {
return "there are no services to migrate";
}
return null;
}
@Override public void action() {
for (final ServiceInfo si
: cb.getExistingServiceList(null)) {
if (!si.isConstraintPH()
&& si.getGroupInfo() == null
&& si.getCloneInfo() == null) {
final List<String> runningOnNodes =
si.getRunningOnNodes(false);
if (runningOnNodes != null
&& runningOnNodes.contains(
getHost().getName())) {
final Host dcHost = getHost();
si.migrateFromResource(dcHost,
getHost().getName(),
false);
}
}
}
}
};
if (cb != null) {
final ClusterBrowser.ClMenuItemCallback allMigrateFromItemCallback =
cb.new ClMenuItemCallback(allMigrateFromItem, host) {
@Override public void action(final Host dcHost) {
for (final ServiceInfo si
: cb.getExistingServiceList(null)) {
if (!si.isConstraintPH() && si.getGroupInfo() == null) {
final List<String> runningOnNodes =
si.getRunningOnNodes(false);
if (runningOnNodes != null
&& runningOnNodes.contains(
host.getName())) {
si.migrateFromResource(dcHost,
host.getName(),
true);
}
}
}
}
};
addMouseOverListener(allMigrateFromItem,
allMigrateFromItemCallback);
}
items.add(allMigrateFromItem);
/* Stop corosync/openais. */
final MyMenuItem stopCorosyncItem =
new MyMenuItem(Tools.getString("HostInfo.StopCorosync"),
HOST_STOP_COMM_LAYER_ICON,
ClusterBrowser.STARTING_PTEST_TOOLTIP,
Tools.getString("HostInfo.StopOpenais"),
HOST_STOP_COMM_LAYER_ICON,
ClusterBrowser.STARTING_PTEST_TOOLTIP,
new AccessMode(ConfigData.AccessType.ADMIN, true),
new AccessMode(ConfigData.AccessType.ADMIN, false)) {
private static final long serialVersionUID = 1L;
@Override public boolean predicate() {
/* when both are running it's openais. */
return getHost().isCsRunning() && !getHost().isAisRunning();
}
@Override public boolean visiblePredicate() {
return getHost().isCsRunning()
|| getHost().isAisRunning();
}
@Override public void action() {
if (Tools.confirmDialog(
Tools.getString("HostInfo.confirmCorosyncStop.Title"),
Tools.getString("HostInfo.confirmCorosyncStop.Desc"),
Tools.getString("HostInfo.confirmCorosyncStop.Yes"),
Tools.getString("HostInfo.confirmCorosyncStop.No"))) {
final Host host = getHost();
host.setCommLayerStopping(true);
if (host.getPcmkServiceVersion() > 0
&& host.isPcmkInit()
&& host.isPcmkRunning()) {
Corosync.stopCorosyncWithPcmk(host);
} else {
Corosync.stopCorosync(host);
}
getBrowser().getClusterBrowser().updateHWInfo(host);
}
}
};
if (cb != null) {
final ClusterBrowser.ClMenuItemCallback stopCorosyncItemCallback =
cb.new ClMenuItemCallback(stopCorosyncItem, host) {
@Override public void action(final Host host) {
if (!isStandby(false)) {
CRM.standByOn(host, true);
}
}
};
addMouseOverListener(stopCorosyncItem,
stopCorosyncItemCallback);
}
items.add(stopCorosyncItem);
/* Stop heartbeat. */
final MyMenuItem stopHeartbeatItem =
new MyMenuItem(Tools.getString("HostInfo.StopHeartbeat"),
HOST_STOP_COMM_LAYER_ICON,
ClusterBrowser.STARTING_PTEST_TOOLTIP,
new AccessMode(ConfigData.AccessType.ADMIN, true),
new AccessMode(ConfigData.AccessType.ADMIN, false)) {
private static final long serialVersionUID = 1L;
@Override public boolean visiblePredicate() {
return getHost().isHeartbeatRunning();
}
@Override public void action() {
if (Tools.confirmDialog(
Tools.getString("HostInfo.confirmHeartbeatStop.Title"),
Tools.getString("HostInfo.confirmHeartbeatStop.Desc"),
Tools.getString("HostInfo.confirmHeartbeatStop.Yes"),
Tools.getString("HostInfo.confirmHeartbeatStop.No"))) {
getHost().setCommLayerStopping(true);
Heartbeat.stopHeartbeat(getHost());
getBrowser().getClusterBrowser().updateHWInfo(host);
}
}
};
if (cb != null) {
final ClusterBrowser.ClMenuItemCallback stopHeartbeatItemCallback =
cb.new ClMenuItemCallback(stopHeartbeatItem, host) {
@Override public void action(final Host host) {
if (!isStandby(false)) {
CRM.standByOn(host, true);
}
}
};
addMouseOverListener(stopHeartbeatItem,
stopHeartbeatItemCallback);
}
items.add(stopHeartbeatItem);
/* Start corosync. */
final MyMenuItem startCorosyncItem =
new MyMenuItem(Tools.getString("HostInfo.StartCorosync"),
HOST_START_COMM_LAYER_ICON,
ClusterBrowser.STARTING_PTEST_TOOLTIP,
new AccessMode(ConfigData.AccessType.ADMIN, false),
new AccessMode(ConfigData.AccessType.ADMIN, false)) {
private static final long serialVersionUID = 1L;
@Override public boolean visiblePredicate() {
final Host h = getHost();
return h.isCorosync()
&& h.isCsInit()
&& h.isCsAisConf()
&& !h.isCsRunning()
&& !h.isAisRunning()
&& !h.isHeartbeatRunning()
&& !h.isHeartbeatRc();
}
@Override public String enablePredicate() {
final Host h = getHost();
if (h.isAisRc() && !h.isCsRc()) {
return "Openais is in rc.d";
}
return null;
}
@Override public void action() {
getHost().setCommLayerStarting(true);
if (getHost().isPcmkRc()) {
Corosync.startCorosyncWithPcmk(getHost());
} else {
Corosync.startCorosync(getHost());
}
getBrowser().getClusterBrowser().updateHWInfo(host);
}
};
if (cb != null) {
final ClusterBrowser.ClMenuItemCallback startCorosyncItemCallback =
cb.new ClMenuItemCallback(startCorosyncItem, host) {
@Override public void action(final Host host) {
//TODO
}
};
addMouseOverListener(startCorosyncItem,
startCorosyncItemCallback);
}
items.add(startCorosyncItem);
/* Start openais. */
final MyMenuItem startOpenaisItem =
new MyMenuItem(Tools.getString("HostInfo.StartOpenais"),
HOST_START_COMM_LAYER_ICON,
ClusterBrowser.STARTING_PTEST_TOOLTIP,
new AccessMode(ConfigData.AccessType.ADMIN, false),
new AccessMode(ConfigData.AccessType.ADMIN, false)) {
private static final long serialVersionUID = 1L;
@Override public boolean visiblePredicate() {
final Host h = getHost();
return h.isAisInit()
&& h.isCsAisConf()
&& !h.isCsRunning()
&& !h.isAisRunning()
&& !h.isHeartbeatRunning()
&& !h.isHeartbeatRc();
}
@Override public String enablePredicate() {
final Host h = getHost();
if (h.isCsRc() && !h.isAisRc()) {
return "Corosync is in rc.d";
}
return null;
}
@Override public void action() {
getHost().setCommLayerStarting(true);
Openais.startOpenais(getHost());
getBrowser().getClusterBrowser().updateHWInfo(host);
}
};
if (cb != null) {
final ClusterBrowser.ClMenuItemCallback startOpenaisItemCallback =
cb.new ClMenuItemCallback(startOpenaisItem, host) {
@Override public void action(final Host host) {
//TODO
}
};
addMouseOverListener(startOpenaisItem,
startOpenaisItemCallback);
}
items.add(startOpenaisItem);
/* Start heartbeat. */
final MyMenuItem startHeartbeatItem =
new MyMenuItem(Tools.getString("HostInfo.StartHeartbeat"),
HOST_START_COMM_LAYER_ICON,
ClusterBrowser.STARTING_PTEST_TOOLTIP,
new AccessMode(ConfigData.AccessType.ADMIN, false),
new AccessMode(ConfigData.AccessType.ADMIN, false)) {
private static final long serialVersionUID = 1L;
@Override public boolean visiblePredicate() {
final Host h = getHost();
return h.isHeartbeatInit()
&& h.isHeartbeatConf()
&& !h.isCsRunning()
&& !h.isAisRunning()
&& !h.isHeartbeatRunning();
//&& !h.isAisRc()
//&& !h.isCsRc(); TODO should check /etc/defaults/
}
@Override public void action() {
getHost().setCommLayerStarting(true);
Heartbeat.startHeartbeat(getHost());
getBrowser().getClusterBrowser().updateHWInfo(host);
}
};
if (cb != null) {
final ClusterBrowser.ClMenuItemCallback startHeartbeatItemCallback =
cb.new ClMenuItemCallback(startHeartbeatItem, host) {
@Override public void action(final Host host) {
//TODO
}
};
addMouseOverListener(startHeartbeatItem,
startHeartbeatItemCallback);
}
items.add(startHeartbeatItem);
/* Start pacemaker. */
final MyMenuItem startPcmkItem =
new MyMenuItem(Tools.getString("HostInfo.StartPacemaker"),
HOST_START_COMM_LAYER_ICON,
ClusterBrowser.STARTING_PTEST_TOOLTIP,
new AccessMode(ConfigData.AccessType.ADMIN, false),
new AccessMode(ConfigData.AccessType.ADMIN, false)) {
private static final long serialVersionUID = 1L;
@Override public boolean visiblePredicate() {
final Host h = getHost();
return h.getPcmkServiceVersion() > 0
&& !h.isPcmkRunning()
&& (h.isCsRunning()
|| h.isAisRunning())
&& !h.isHeartbeatRunning();
}
@Override public String enablePredicate() {
return null;
}
@Override public void action() {
Corosync.startPacemaker(getHost());
getBrowser().getClusterBrowser().updateHWInfo(host);
}
};
if (cb != null) {
final ClusterBrowser.ClMenuItemCallback startPcmkItemCallback =
cb.new ClMenuItemCallback(startPcmkItem, host) {
@Override public void action(final Host host) {
//TODO
}
};
addMouseOverListener(startPcmkItem,
startPcmkItemCallback);
}
items.add(startPcmkItem);
/* change host color */
final MyMenuItem changeHostColorItem =
new MyMenuItem(Tools.getString("HostBrowser.Drbd.ChangeHostColor"),
null,
"",
new AccessMode(ConfigData.AccessType.RO, false),
new AccessMode(ConfigData.AccessType.RO, false)) {
private static final long serialVersionUID = 1L;
@Override public String enablePredicate() {
return null;
}
@Override public void action() {
final Color newColor = JColorChooser.showDialog(
Tools.getGUIData().getMainFrame(),
"Choose " + host.getName()
+ " color",
host.getPmColors()[0]);
if (newColor != null) {
host.setSavedColor(newColor);
}
}
};
items.add(changeHostColorItem);
/* view logs */
final MyMenuItem viewLogsItem =
new MyMenuItem(Tools.getString("HostBrowser.Drbd.ViewLogs"),
LOGFILE_ICON,
"",
new AccessMode(ConfigData.AccessType.RO, false),
new AccessMode(ConfigData.AccessType.RO, false)) {
private static final long serialVersionUID = 1L;
@Override public String enablePredicate() {
if (!getHost().isConnected()) {
return Host.NOT_CONNECTED_STRING;
}
return null;
}
@Override public void action() {
drbd.gui.dialog.HostLogs l =
new drbd.gui.dialog.HostLogs(host);
l.showDialog();
}
};
items.add(viewLogsItem);
/* advacend options */
final MyMenu hostAdvancedSubmenu = new MyMenu(
Tools.getString("HostBrowser.AdvancedSubmenu"),
new AccessMode(ConfigData.AccessType.OP, false),
new AccessMode(ConfigData.AccessType.OP, false)) {
private static final long serialVersionUID = 1L;
@Override public String enablePredicate() {
if (!host.isConnected()) {
return Host.NOT_CONNECTED_STRING;
}
return null;
}
@Override public void update() {
super.update();
getBrowser().addAdvancedMenu(this);
}
};
items.add(hostAdvancedSubmenu);
/* remove host from gui */
final MyMenuItem removeHostItem =
new MyMenuItem(Tools.getString("HostBrowser.RemoveHost"),
HostBrowser.HOST_REMOVE_ICON,
"",
new AccessMode(ConfigData.AccessType.RO, false),
new AccessMode(ConfigData.AccessType.RO, false)) {
private static final long serialVersionUID = 1L;
@Override public String enablePredicate() {
if (getHost().getCluster() != null) {
return "it is a member of a cluster";
}
return null;
}
@Override public void action() {
getHost().disconnect();
Tools.getConfigData().removeHostFromHosts(getHost());
Tools.getGUIData().allHostsUpdate();
}
};
items.add(removeHostItem);
return items;
}
| @Override public List<UpdatableItem> createPopup() {
final List<UpdatableItem> items = new ArrayList<UpdatableItem>();
final boolean testOnly = false;
/* host wizard */
final MyMenuItem hostWizardItem =
new MyMenuItem(Tools.getString("HostBrowser.HostWizard"),
HostBrowser.HOST_ICON_LARGE,
"",
new AccessMode(ConfigData.AccessType.RO, false),
new AccessMode(ConfigData.AccessType.RO, false)) {
private static final long serialVersionUID = 1L;
@Override public String enablePredicate() {
return null;
}
@Override public void action() {
final EditHostDialog dialog = new EditHostDialog(host);
dialog.showDialogs();
}
};
items.add(hostWizardItem);
Tools.getGUIData().registerAddHostButton(hostWizardItem);
/* cluster manager standby on/off */
final HostInfo thisClass = this;
final MyMenuItem standbyItem =
new MyMenuItem(Tools.getString("HostBrowser.CRM.StandByOn"),
HOST_STANDBY_ICON,
ClusterBrowser.STARTING_PTEST_TOOLTIP,
Tools.getString("HostBrowser.CRM.StandByOff"),
HOST_STANDBY_OFF_ICON,
ClusterBrowser.STARTING_PTEST_TOOLTIP,
new AccessMode(ConfigData.AccessType.OP, false),
new AccessMode(ConfigData.AccessType.OP, false)) {
private static final long serialVersionUID = 1L;
@Override public boolean predicate() {
return !isStandby(testOnly);
}
@Override public String enablePredicate() {
if (!getHost().isClStatus()) {
return NO_PCMK_STATUS_STRING;
}
return null;
}
@Override public void action() {
if (isStandby(testOnly)) {
CRM.standByOff(host, testOnly);
} else {
CRM.standByOn(host, testOnly);
}
}
};
final ClusterBrowser cb = getBrowser().getClusterBrowser();
if (cb != null) {
final ClusterBrowser.ClMenuItemCallback standbyItemCallback =
cb.new ClMenuItemCallback(standbyItem, host) {
@Override public void action(final Host host) {
if (isStandby(false)) {
CRM.standByOff(host, true);
} else {
CRM.standByOn(host, true);
}
}
};
addMouseOverListener(standbyItem, standbyItemCallback);
}
items.add(standbyItem);
/* Migrate all services from this host. */
final MyMenuItem allMigrateFromItem =
new MyMenuItem(Tools.getString("HostInfo.CRM.AllMigrateFrom"),
HOST_STANDBY_ICON,
ClusterBrowser.STARTING_PTEST_TOOLTIP,
new AccessMode(ConfigData.AccessType.OP, false),
new AccessMode(ConfigData.AccessType.OP, false)) {
private static final long serialVersionUID = 1L;
@Override public boolean predicate() {
return true;
}
@Override public String enablePredicate() {
if (!getHost().isClStatus()) {
return NO_PCMK_STATUS_STRING;
}
if (getBrowser().getClusterBrowser()
.getExistingServiceList(null).isEmpty()) {
return "there are no services to migrate";
}
return null;
}
@Override public void action() {
for (final ServiceInfo si
: cb.getExistingServiceList(null)) {
if (!si.isConstraintPH()
&& si.getGroupInfo() == null
&& si.getCloneInfo() == null) {
final List<String> runningOnNodes =
si.getRunningOnNodes(false);
if (runningOnNodes != null
&& runningOnNodes.contains(
getHost().getName())) {
final Host dcHost = getHost();
si.migrateFromResource(dcHost,
getHost().getName(),
false);
}
}
}
}
};
if (cb != null) {
final ClusterBrowser.ClMenuItemCallback allMigrateFromItemCallback =
cb.new ClMenuItemCallback(allMigrateFromItem, host) {
@Override public void action(final Host dcHost) {
for (final ServiceInfo si
: cb.getExistingServiceList(null)) {
if (!si.isConstraintPH() && si.getGroupInfo() == null) {
final List<String> runningOnNodes =
si.getRunningOnNodes(false);
if (runningOnNodes != null
&& runningOnNodes.contains(
host.getName())) {
si.migrateFromResource(dcHost,
host.getName(),
true);
}
}
}
}
};
addMouseOverListener(allMigrateFromItem,
allMigrateFromItemCallback);
}
items.add(allMigrateFromItem);
/* Stop corosync/openais. */
final MyMenuItem stopCorosyncItem =
new MyMenuItem(Tools.getString("HostInfo.StopCorosync"),
HOST_STOP_COMM_LAYER_ICON,
ClusterBrowser.STARTING_PTEST_TOOLTIP,
Tools.getString("HostInfo.StopOpenais"),
HOST_STOP_COMM_LAYER_ICON,
ClusterBrowser.STARTING_PTEST_TOOLTIP,
new AccessMode(ConfigData.AccessType.ADMIN, true),
new AccessMode(ConfigData.AccessType.ADMIN, false)) {
private static final long serialVersionUID = 1L;
@Override public boolean predicate() {
/* when both are running it's openais. */
return getHost().isCsRunning() && !getHost().isAisRunning();
}
@Override public boolean visiblePredicate() {
return getHost().isCsRunning()
|| getHost().isAisRunning();
}
@Override public void action() {
if (Tools.confirmDialog(
Tools.getString("HostInfo.confirmCorosyncStop.Title"),
Tools.getString("HostInfo.confirmCorosyncStop.Desc"),
Tools.getString("HostInfo.confirmCorosyncStop.Yes"),
Tools.getString("HostInfo.confirmCorosyncStop.No"))) {
final Host host = getHost();
host.setCommLayerStopping(true);
if (host.getPcmkServiceVersion() > 0
&& host.isPcmkInit()
&& host.isPcmkRunning()) {
Corosync.stopCorosyncWithPcmk(host);
} else {
Corosync.stopCorosync(host);
}
getBrowser().getClusterBrowser().updateHWInfo(host);
}
}
};
if (cb != null) {
final ClusterBrowser.ClMenuItemCallback stopCorosyncItemCallback =
cb.new ClMenuItemCallback(stopCorosyncItem, host) {
@Override public void action(final Host host) {
if (!isStandby(false)) {
CRM.standByOn(host, true);
}
}
};
addMouseOverListener(stopCorosyncItem,
stopCorosyncItemCallback);
}
items.add(stopCorosyncItem);
/* Stop heartbeat. */
final MyMenuItem stopHeartbeatItem =
new MyMenuItem(Tools.getString("HostInfo.StopHeartbeat"),
HOST_STOP_COMM_LAYER_ICON,
ClusterBrowser.STARTING_PTEST_TOOLTIP,
new AccessMode(ConfigData.AccessType.ADMIN, true),
new AccessMode(ConfigData.AccessType.ADMIN, false)) {
private static final long serialVersionUID = 1L;
@Override public boolean visiblePredicate() {
return getHost().isHeartbeatRunning();
}
@Override public void action() {
if (Tools.confirmDialog(
Tools.getString("HostInfo.confirmHeartbeatStop.Title"),
Tools.getString("HostInfo.confirmHeartbeatStop.Desc"),
Tools.getString("HostInfo.confirmHeartbeatStop.Yes"),
Tools.getString("HostInfo.confirmHeartbeatStop.No"))) {
getHost().setCommLayerStopping(true);
Heartbeat.stopHeartbeat(getHost());
getBrowser().getClusterBrowser().updateHWInfo(host);
}
}
};
if (cb != null) {
final ClusterBrowser.ClMenuItemCallback stopHeartbeatItemCallback =
cb.new ClMenuItemCallback(stopHeartbeatItem, host) {
@Override public void action(final Host host) {
if (!isStandby(false)) {
CRM.standByOn(host, true);
}
}
};
addMouseOverListener(stopHeartbeatItem,
stopHeartbeatItemCallback);
}
items.add(stopHeartbeatItem);
/* Start corosync. */
final MyMenuItem startCorosyncItem =
new MyMenuItem(Tools.getString("HostInfo.StartCorosync"),
HOST_START_COMM_LAYER_ICON,
ClusterBrowser.STARTING_PTEST_TOOLTIP,
new AccessMode(ConfigData.AccessType.ADMIN, false),
new AccessMode(ConfigData.AccessType.ADMIN, false)) {
private static final long serialVersionUID = 1L;
@Override public boolean visiblePredicate() {
final Host h = getHost();
return h.isCorosync()
&& h.isCsInit()
&& h.isCsAisConf()
&& !h.isCsRunning()
&& !h.isAisRunning()
&& !h.isHeartbeatRunning()
&& !h.isHeartbeatRc();
}
@Override public String enablePredicate() {
final Host h = getHost();
if (h.isAisRc() && !h.isCsRc()) {
return "Openais is in rc.d";
}
return null;
}
@Override public void action() {
getHost().setCommLayerStarting(true);
if (getHost().isPcmkRc()) {
Corosync.startCorosyncWithPcmk(getHost());
} else {
Corosync.startCorosync(getHost());
}
getBrowser().getClusterBrowser().updateHWInfo(host);
}
};
if (cb != null) {
final ClusterBrowser.ClMenuItemCallback startCorosyncItemCallback =
cb.new ClMenuItemCallback(startCorosyncItem, host) {
@Override public void action(final Host host) {
//TODO
}
};
addMouseOverListener(startCorosyncItem,
startCorosyncItemCallback);
}
items.add(startCorosyncItem);
/* Start openais. */
final MyMenuItem startOpenaisItem =
new MyMenuItem(Tools.getString("HostInfo.StartOpenais"),
HOST_START_COMM_LAYER_ICON,
ClusterBrowser.STARTING_PTEST_TOOLTIP,
new AccessMode(ConfigData.AccessType.ADMIN, false),
new AccessMode(ConfigData.AccessType.ADMIN, false)) {
private static final long serialVersionUID = 1L;
@Override public boolean visiblePredicate() {
final Host h = getHost();
return h.isAisInit()
&& h.isCsAisConf()
&& !h.isCsRunning()
&& !h.isAisRunning()
&& !h.isHeartbeatRunning()
&& !h.isHeartbeatRc();
}
@Override public String enablePredicate() {
final Host h = getHost();
if (h.isCsRc() && !h.isAisRc()) {
return "Corosync is in rc.d";
}
return null;
}
@Override public void action() {
getHost().setCommLayerStarting(true);
Openais.startOpenais(getHost());
getBrowser().getClusterBrowser().updateHWInfo(host);
}
};
if (cb != null) {
final ClusterBrowser.ClMenuItemCallback startOpenaisItemCallback =
cb.new ClMenuItemCallback(startOpenaisItem, host) {
@Override public void action(final Host host) {
//TODO
}
};
addMouseOverListener(startOpenaisItem,
startOpenaisItemCallback);
}
items.add(startOpenaisItem);
/* Start heartbeat. */
final MyMenuItem startHeartbeatItem =
new MyMenuItem(Tools.getString("HostInfo.StartHeartbeat"),
HOST_START_COMM_LAYER_ICON,
ClusterBrowser.STARTING_PTEST_TOOLTIP,
new AccessMode(ConfigData.AccessType.ADMIN, false),
new AccessMode(ConfigData.AccessType.ADMIN, false)) {
private static final long serialVersionUID = 1L;
@Override public boolean visiblePredicate() {
final Host h = getHost();
return h.isHeartbeatInit()
&& h.isHeartbeatConf()
&& !h.isCsRunning()
&& !h.isAisRunning()
&& !h.isHeartbeatRunning();
//&& !h.isAisRc()
//&& !h.isCsRc(); TODO should check /etc/defaults/
}
@Override public void action() {
getHost().setCommLayerStarting(true);
Heartbeat.startHeartbeat(getHost());
getBrowser().getClusterBrowser().updateHWInfo(host);
}
};
if (cb != null) {
final ClusterBrowser.ClMenuItemCallback startHeartbeatItemCallback =
cb.new ClMenuItemCallback(startHeartbeatItem, host) {
@Override public void action(final Host host) {
//TODO
}
};
addMouseOverListener(startHeartbeatItem,
startHeartbeatItemCallback);
}
items.add(startHeartbeatItem);
/* Start pacemaker. */
final MyMenuItem startPcmkItem =
new MyMenuItem(Tools.getString("HostInfo.StartPacemaker"),
HOST_START_COMM_LAYER_ICON,
ClusterBrowser.STARTING_PTEST_TOOLTIP,
new AccessMode(ConfigData.AccessType.ADMIN, false),
new AccessMode(ConfigData.AccessType.ADMIN, false)) {
private static final long serialVersionUID = 1L;
@Override public boolean visiblePredicate() {
final Host h = getHost();
return h.getPcmkServiceVersion() > 0
&& !h.isPcmkRunning()
&& (h.isCsRunning()
|| h.isAisRunning())
&& !h.isHeartbeatRunning();
}
@Override public String enablePredicate() {
return null;
}
@Override public void action() {
Corosync.startPacemaker(getHost());
getBrowser().getClusterBrowser().updateHWInfo(host);
}
};
if (cb != null) {
final ClusterBrowser.ClMenuItemCallback startPcmkItemCallback =
cb.new ClMenuItemCallback(startPcmkItem, host) {
@Override public void action(final Host host) {
//TODO
}
};
addMouseOverListener(startPcmkItem,
startPcmkItemCallback);
}
items.add(startPcmkItem);
/* change host color */
final MyMenuItem changeHostColorItem =
new MyMenuItem(Tools.getString("HostBrowser.Drbd.ChangeHostColor"),
null,
"",
new AccessMode(ConfigData.AccessType.RO, false),
new AccessMode(ConfigData.AccessType.RO, false)) {
private static final long serialVersionUID = 1L;
@Override public String enablePredicate() {
return null;
}
@Override public void action() {
final Color newColor = JColorChooser.showDialog(
Tools.getGUIData().getMainFrame(),
"Choose " + host.getName()
+ " color",
host.getPmColors()[0]);
if (newColor != null) {
host.setSavedColor(newColor);
}
}
};
items.add(changeHostColorItem);
/* view logs */
final MyMenuItem viewLogsItem =
new MyMenuItem(Tools.getString("HostBrowser.Drbd.ViewLogs"),
LOGFILE_ICON,
"",
new AccessMode(ConfigData.AccessType.RO, false),
new AccessMode(ConfigData.AccessType.RO, false)) {
private static final long serialVersionUID = 1L;
@Override public String enablePredicate() {
if (!getHost().isConnected()) {
return Host.NOT_CONNECTED_STRING;
}
return null;
}
@Override public void action() {
drbd.gui.dialog.HostLogs l =
new drbd.gui.dialog.HostLogs(host);
l.showDialog();
}
};
items.add(viewLogsItem);
/* advacend options */
final MyMenu hostAdvancedSubmenu = new MyMenu(
Tools.getString("HostBrowser.AdvancedSubmenu"),
new AccessMode(ConfigData.AccessType.OP, false),
new AccessMode(ConfigData.AccessType.OP, false)) {
private static final long serialVersionUID = 1L;
@Override public String enablePredicate() {
if (!host.isConnected()) {
return Host.NOT_CONNECTED_STRING;
}
return null;
}
@Override public void update() {
super.update();
getBrowser().addAdvancedMenu(this);
}
};
items.add(hostAdvancedSubmenu);
/* remove host from gui */
final MyMenuItem removeHostItem =
new MyMenuItem(Tools.getString("HostBrowser.RemoveHost"),
HostBrowser.HOST_REMOVE_ICON,
Tools.getString("HostBrowser.RemoveHost"),
new AccessMode(ConfigData.AccessType.RO, false),
new AccessMode(ConfigData.AccessType.RO, false)) {
private static final long serialVersionUID = 1L;
@Override public String enablePredicate() {
if (getHost().getCluster() != null) {
return "it is a member of a cluster";
}
return null;
}
@Override public void action() {
getHost().disconnect();
Tools.getConfigData().removeHostFromHosts(getHost());
Tools.getGUIData().allHostsUpdate();
}
};
items.add(removeHostItem);
return items;
}
|
diff --git a/podd-api/src/test/java/com/github/podd/api/test/AbstractPoddArtifactManagerTest.java b/podd-api/src/test/java/com/github/podd/api/test/AbstractPoddArtifactManagerTest.java
index a37acb33..5406195f 100644
--- a/podd-api/src/test/java/com/github/podd/api/test/AbstractPoddArtifactManagerTest.java
+++ b/podd-api/src/test/java/com/github/podd/api/test/AbstractPoddArtifactManagerTest.java
@@ -1,422 +1,422 @@
/**
*
*/
package com.github.podd.api.test;
import java.io.InputStream;
import java.util.Collections;
import java.util.Iterator;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.openrdf.model.Graph;
import org.openrdf.model.Statement;
import org.openrdf.model.URI;
import org.openrdf.model.impl.GraphImpl;
import org.openrdf.model.impl.ValueFactoryImpl;
import org.openrdf.model.vocabulary.RDF;
import org.openrdf.query.GraphQuery;
import org.openrdf.query.GraphQueryResult;
import org.openrdf.query.QueryLanguage;
import org.openrdf.query.impl.DatasetImpl;
import org.openrdf.repository.RepositoryConnection;
import org.openrdf.rio.RDFFormat;
import org.openrdf.rio.Rio;
import org.semanticweb.owlapi.formats.OWLOntologyFormatFactoryRegistry;
import org.semanticweb.owlapi.formats.RioRDFOntologyFormatFactory;
import org.semanticweb.owlapi.model.IRI;
import org.semanticweb.owlapi.model.OWLOntology;
import org.semanticweb.owlapi.model.OWLOntologyID;
import org.semanticweb.owlapi.profiles.OWLProfileReport;
import org.semanticweb.owlapi.reasoner.OWLReasoner;
import org.semanticweb.owlapi.reasoner.OWLReasonerFactory;
import org.semanticweb.owlapi.rio.RioMemoryTripleSource;
import org.semanticweb.owlapi.rio.RioParser;
import org.semanticweb.owlapi.rio.RioParserImpl;
import com.github.podd.api.PoddArtifactManager;
import com.github.podd.api.PoddOWLManager;
import com.github.podd.api.PoddProcessorStage;
import com.github.podd.api.PoddSchemaManager;
import com.github.podd.api.file.PoddFileReference;
import com.github.podd.api.file.PoddFileReferenceManager;
import com.github.podd.api.file.PoddFileReferenceProcessor;
import com.github.podd.api.file.PoddFileReferenceProcessorFactory;
import com.github.podd.api.file.PoddFileReferenceProcessorFactoryRegistry;
import com.github.podd.api.purl.PoddPurlManager;
import com.github.podd.api.purl.PoddPurlProcessor;
import com.github.podd.api.purl.PoddPurlProcessorFactory;
import com.github.podd.api.purl.PoddPurlProcessorFactoryRegistry;
import com.github.podd.api.purl.PoddPurlReference;
import com.github.podd.utils.InferredOWLOntologyID;
/**
* @author Peter Ansell [email protected]
*
*/
public abstract class AbstractPoddArtifactManagerTest
{
protected abstract PoddArtifactManager getNewArtifactManager();
protected abstract PoddPurlProcessorFactory getNewDoiPurlProcessorFactory();
protected abstract PoddFileReferenceManager getNewFileReferenceManager();
protected abstract PoddPurlProcessorFactory getNewHandlePurlProcessorFactory();
protected abstract PoddFileReferenceProcessorFactory getNewHttpFileReferenceProcessorFactory();
protected abstract PoddOWLManager getNewOWLManager();
protected abstract PoddPurlManager getNewPurlManager();
protected abstract OWLReasonerFactory getNewReasonerFactory();
protected abstract PoddSchemaManager getNewSchemaManager();
protected abstract PoddFileReferenceProcessorFactory getNewSSHFileReferenceProcessorFactory();
protected abstract PoddPurlProcessorFactory getNewUUIDPurlProcessorFactory();
/**
* @throws java.lang.Exception
*/
@SuppressWarnings("null")
@Before
public void setUp() throws Exception
{
// FIXME: This needs to be a constant
final URI poddFileReferenceType =
ValueFactoryImpl.getInstance().createURI("http://purl.org/podd/ns/poddBase#PoddFileReference");
final PoddFileReferenceProcessorFactoryRegistry testFileRegistry =
new PoddFileReferenceProcessorFactoryRegistry();
// clear any automatically added entries that may come from META-INF/services entries on the
// classpath
testFileRegistry.clear();
// In practice, the following factories would be automatically added to the registry,
// however for testing we want to explicitly add the ones we want to support for each test
testFileRegistry.add(this.getNewSSHFileReferenceProcessorFactory());
testFileRegistry.add(this.getNewHttpFileReferenceProcessorFactory());
final PoddPurlProcessorFactoryRegistry testPurlRegistry = new PoddPurlProcessorFactoryRegistry();
testPurlRegistry.clear();
testPurlRegistry.add(this.getNewDoiPurlProcessorFactory());
testPurlRegistry.add(this.getNewHandlePurlProcessorFactory());
testPurlRegistry.add(this.getNewUUIDPurlProcessorFactory());
final PoddFileReferenceManager testFileReferenceManager = this.getNewFileReferenceManager();
testFileReferenceManager.setProcessorFactoryRegistry(testFileRegistry);
final PoddPurlManager testPurlManager = this.getNewPurlManager();
testPurlManager.setPurlProcessorFactoryRegistry(testPurlRegistry);
final PoddOWLManager testOWLManager = this.getNewOWLManager();
testOWLManager.setReasonerFactory(this.getNewReasonerFactory());
final PoddArtifactManager testArtifactManager = this.getNewArtifactManager();
testArtifactManager.setFileReferenceManager(testFileReferenceManager);
testArtifactManager.setPurlManager(testPurlManager);
testArtifactManager.setOwlManager(testOWLManager);
final PoddSchemaManager testSchemaManager = this.getNewSchemaManager();
testSchemaManager.setOwlManager(testOWLManager);
final InputStream inputStream = this.getClass().getResourceAsStream("/testArtifact.rdf");
// MIME type should be either given by the user, detected from the content type on the
// request, or autodetected using the Any23 Mime Detector
final String mimeType = "application/rdf+xml";
final RDFFormat format = Rio.getParserFormatForMIMEType(mimeType, RDFFormat.RDFXML);
final InferredOWLOntologyID resultArtifactId = testArtifactManager.loadArtifact(inputStream, format);
// INSIDE the loadArtifact method...
// connection to the temporary repository that the artifact RDF triples will be stored while
// they are initially parsed by OWLAPI.
final RepositoryConnection temporaryRepositoryConnection = null;
final URI randomContext = ValueFactoryImpl.getInstance().createURI(UUID.randomUUID().toString());
// Load the artifact RDF triples into a random context in the temp repository, which may be
// shared between different uploads
temporaryRepositoryConnection.add(inputStream, "", format, randomContext);
// TODO: SPARQL query to extract the Ontology IRI and Version IRI from the
// temporaryRepositoryConnection
// Create an initial OWLOntologyID for the uploaded ontology, after checking that the
// Version IRI is distinct for the given Ontology IRI
final OWLOntologyID tempArtifactId = null;
// TODO If the OWLOntologyID is not distinct, then modify it to be distinct
// return the results, setting the results variable to be the same as the internalResults
// variable from inside of extractFileReferences
// Ie, return internalResults; results = internalResults;
final Set<PoddPurlReference> purlResults =
testArtifactManager.getPurlManager().extractPurlReferences(temporaryRepositoryConnection,
tempArtifactId.getVersionIRI().toOpenRDFURI());
// perform the conversion of the URIs, possibly in bulk, as they are all given to this
// method together
testArtifactManager.getPurlManager().convertTemporaryUris(purlResults, temporaryRepositoryConnection,
tempArtifactId.getVersionIRI().toOpenRDFURI());
// Then work on the file references
// calls, to setup the results collection
final Set<PoddFileReference> fileReferenceResults =
testArtifactManager.getFileReferenceManager().extractFileReferences(temporaryRepositoryConnection,
tempArtifactId.getVersionIRI().toOpenRDFURI());
// INSIDE the extractFileReferences method....
final Set<PoddFileReference> internalFileReferenceResults =
Collections.newSetFromMap(new ConcurrentHashMap<PoddFileReference, Boolean>());
for(final PoddFileReferenceProcessorFactory nextProcessorFactory : testArtifactManager
- .getFileReferenceManager().getProcessorFactoryRegistry().getByStage(PoddProcessorStage.RDF_PARSING))
+ .getFileReferenceManager().getFileProcessorFactoryRegistry().getByStage(PoddProcessorStage.RDF_PARSING))
{
final StringBuilder sparqlQuery = new StringBuilder();
sparqlQuery.append("CONSTRUCT { ");
sparqlQuery.append(nextProcessorFactory.getSPARQLConstructBGP());
sparqlQuery.append(" } WHERE { ");
sparqlQuery.append(nextProcessorFactory.getSPARQLConstructWhere());
sparqlQuery.append(" } ");
if(!nextProcessorFactory.getSPARQLGroupBy().isEmpty())
{
sparqlQuery.append(" GROUP BY ");
sparqlQuery.append(nextProcessorFactory.getSPARQLGroupBy());
}
final GraphQuery graphQuery =
temporaryRepositoryConnection.prepareGraphQuery(QueryLanguage.SPARQL, sparqlQuery.toString());
// Create a new dataset to specify the contexts that the query will be allowed to access
final DatasetImpl dataset = new DatasetImpl();
// The following URIs are passed in as the context to the
// extractFileReferences(RepositoryConnection,URI...) method
final URI artifactGraphUri = null;
// for(URI artifactGraphUri : contexts)
dataset.addDefaultGraph(artifactGraphUri);
dataset.addNamedGraph(artifactGraphUri);
// end for loop
// if the stage is after inferencing, the inferred graph URI would be one of the
// contexts as well
final URI artifactInferredGraphUri = null;
dataset.addDefaultGraph(artifactInferredGraphUri);
dataset.addNamedGraph(artifactInferredGraphUri);
// set the dataset for the query to be our artificially constructed dataset
graphQuery.setDataset(dataset);
final GraphQueryResult queryResult = graphQuery.evaluate();
// If the query matched anything, then for each of the file references in the resulting
// construct statements, we create a file reference and add it to the results
if(!queryResult.hasNext())
{
final Graph graph = new GraphImpl();
while(queryResult.hasNext())
{
graph.add(queryResult.next());
}
final Iterator<Statement> match = graph.match(null, RDF.TYPE, poddFileReferenceType);
while(match.hasNext())
{
final Statement nextStatement = match.next();
final Graph fileReferenceGraph = new GraphImpl();
// For generality, in practice for now, use graph.match as below...
nextProcessorFactory.getSPARQLConstructWhere((URI)nextStatement.getSubject());
final Iterator<Statement> match2 = graph.match(nextStatement.getSubject(), null, null);
while(match2.hasNext())
{
fileReferenceGraph.add(match2.next());
}
// This processor factory matches the graph that we wish to use, so we create a
// processor instance now to create the file reference
// NOTE: This object cannot be shared as we do not specify that it needs to be
// threadsafe
final PoddFileReferenceProcessor processor = nextProcessorFactory.getProcessor();
// create a reference out of the resulting graph
internalFileReferenceResults.add(processor.createReference(fileReferenceGraph));
}
}
}
// optionally verify the file references
testArtifactManager.getFileReferenceManager().verifyFileReferences(fileReferenceResults,
temporaryRepositoryConnection, tempArtifactId.getVersionIRI().toOpenRDFURI());
// TODO: Optionally remove invalid file references or mark them as invalid using RDF
// statements/OWL Classes
// Before loading the statements into OWLAPI, ensure that the schema ontologies are cached
// in memory
// TODO: For each OWL:IMPORTS statement, call the following
final IRI schemaOntologyIRI = null;
// Get the current version
final InferredOWLOntologyID ontologyVersion =
testSchemaManager.getCurrentSchemaOntologyVersion(schemaOntologyIRI);
// Make sure it is cached in memory. This will not attempt to load the ontology again if it
// is already cached or already being loaded
testArtifactManager.getOWLManager().cacheSchemaOntology(ontologyVersion, temporaryRepositoryConnection);
// Load the statements into an OWLAPI OWLOntology
final RioMemoryTripleSource owlSource =
new RioMemoryTripleSource(temporaryRepositoryConnection.getStatements(null, null, null, true,
tempArtifactId.getVersionIRI().toOpenRDFURI()));
owlSource.setNamespaces(temporaryRepositoryConnection.getNamespaces());
final OWLOntology nextOntology = testArtifactManager.getOWLManager().loadOntology(owlSource);
// Inside of PoddOWLManager.loadOntology().....
final RioParser owlParser =
new RioParserImpl((RioRDFOntologyFormatFactory)OWLOntologyFormatFactoryRegistry.getInstance()
.getByMIMEType(mimeType));
// nextOntology = this.manager.createOntology();
owlParser.parse(owlSource, nextOntology);
// Check the OWLAPI OWLOntology against an OWLProfile to make sure it is in profile
final OWLProfileReport profileReport =
testArtifactManager.getOWLManager().getReasonerProfile().checkOntology(nextOntology);
if(!profileReport.isInProfile())
{
testArtifactManager.getOWLManager().removeCache(nextOntology.getOntologyID());
}
// create an OWL Reasoner using the Pellet library and ensure that the reasoner thinks the
// ontology is consistent so far
// Use the factory that we found to create a reasoner over the ontology
final OWLReasoner nextReasoner = testArtifactManager.getOWLManager().createReasoner(nextOntology);
// Test that the ontology was consistent with this reasoner
// This ensures in the case of Pellet that it is in the OWL2-DL profile
// if(!nextReasoner.isConsistent() || nextReasoner.getUnsatisfiableClasses().getSize() > 0)
// Check the OWLAPI OWLOntology using a reasoner for .isConsistent
if(!nextReasoner.isConsistent())
{
testArtifactManager.getOWLManager().removeCache(nextOntology.getOntologyID());
}
// Once the reasoner determines that the ontology is consistent, copy the statements to a
// permanent repository connection
final RepositoryConnection permanentRepositoryConnection = null;
// TODO: Copy the statements to permanentRepositoryConnection
// NOTE: At this stage, a client could be notified, and the artifact could be streamed back
// to them from permanentRepositoryConnection
final InferredOWLOntologyID inferredOWLOntologyID =
testArtifactManager.getOWLManager().generateInferredOntologyID(nextOntology.getOntologyID());
// Use an OWLAPI InferredAxiomGenerator together with the reasoner to create inferred
// axioms to store in the database
// Serialise the inferred statements back to a different context in the permanent
// repository connection
// The contexts to use within the permanent repository connection are all encapsulated in
// the InferredOWLOntologyID object
testArtifactManager.getOWLManager().inferStatements(inferredOWLOntologyID, permanentRepositoryConnection);
// make sure in a finally block to remove the cache for the ontology
testArtifactManager.getOWLManager().removeCache(inferredOWLOntologyID);
// return InferredOWLOntologyID() with the context of the inferred statements
}
/**
* @throws java.lang.Exception
*/
@After
public void tearDown() throws Exception
{
}
/**
* Test method for
* {@link com.github.podd.api.PoddArtifactManager#deregisterProcessor(com.github.podd.api.PoddProcessorFactory, com.github.podd.api.PoddProcessorStage)}
* .
*/
@Test
public final void testDeregisterProcessor()
{
Assert.fail("Not yet implemented"); // TODO
}
/**
* Test method for
* {@link com.github.podd.api.PoddArtifactManager#getProcessors(com.github.podd.api.PoddProcessorStage)}
* .
*/
@Test
public final void testGetProcessors()
{
Assert.fail("Not yet implemented"); // TODO
}
/**
* Test method for
* {@link com.github.podd.api.PoddArtifactManager#loadArtifact(java.io.InputStream, org.openrdf.rio.RDFFormat)}
* .
*/
@Test
public final void testLoadArtifact()
{
Assert.fail("Not yet implemented"); // TODO
}
/**
* Test method for
* {@link com.github.podd.api.PoddArtifactManager#publishArtifact(org.semanticweb.owlapi.model.OWLOntologyID)}
* .
*/
@Test
public final void testPublishArtifact()
{
Assert.fail("Not yet implemented"); // TODO
}
/**
* Test method for
* {@link com.github.podd.api.PoddArtifactManager#registerProcessor(com.github.podd.api.PoddProcessorFactory, com.github.podd.api.PoddProcessorStage)}
* .
*/
@Test
public final void testRegisterProcessor()
{
Assert.fail("Not yet implemented"); // TODO
}
/**
* Test method for
* {@link com.github.podd.api.PoddArtifactManager#updateSchemaImport(org.semanticweb.owlapi.model.OWLOntologyID, org.semanticweb.owlapi.model.OWLOntologyID)}
* .
*/
@Test
public final void testUpdateSchemaImport()
{
Assert.fail("Not yet implemented"); // TODO
}
}
| true | true | public void setUp() throws Exception
{
// FIXME: This needs to be a constant
final URI poddFileReferenceType =
ValueFactoryImpl.getInstance().createURI("http://purl.org/podd/ns/poddBase#PoddFileReference");
final PoddFileReferenceProcessorFactoryRegistry testFileRegistry =
new PoddFileReferenceProcessorFactoryRegistry();
// clear any automatically added entries that may come from META-INF/services entries on the
// classpath
testFileRegistry.clear();
// In practice, the following factories would be automatically added to the registry,
// however for testing we want to explicitly add the ones we want to support for each test
testFileRegistry.add(this.getNewSSHFileReferenceProcessorFactory());
testFileRegistry.add(this.getNewHttpFileReferenceProcessorFactory());
final PoddPurlProcessorFactoryRegistry testPurlRegistry = new PoddPurlProcessorFactoryRegistry();
testPurlRegistry.clear();
testPurlRegistry.add(this.getNewDoiPurlProcessorFactory());
testPurlRegistry.add(this.getNewHandlePurlProcessorFactory());
testPurlRegistry.add(this.getNewUUIDPurlProcessorFactory());
final PoddFileReferenceManager testFileReferenceManager = this.getNewFileReferenceManager();
testFileReferenceManager.setProcessorFactoryRegistry(testFileRegistry);
final PoddPurlManager testPurlManager = this.getNewPurlManager();
testPurlManager.setPurlProcessorFactoryRegistry(testPurlRegistry);
final PoddOWLManager testOWLManager = this.getNewOWLManager();
testOWLManager.setReasonerFactory(this.getNewReasonerFactory());
final PoddArtifactManager testArtifactManager = this.getNewArtifactManager();
testArtifactManager.setFileReferenceManager(testFileReferenceManager);
testArtifactManager.setPurlManager(testPurlManager);
testArtifactManager.setOwlManager(testOWLManager);
final PoddSchemaManager testSchemaManager = this.getNewSchemaManager();
testSchemaManager.setOwlManager(testOWLManager);
final InputStream inputStream = this.getClass().getResourceAsStream("/testArtifact.rdf");
// MIME type should be either given by the user, detected from the content type on the
// request, or autodetected using the Any23 Mime Detector
final String mimeType = "application/rdf+xml";
final RDFFormat format = Rio.getParserFormatForMIMEType(mimeType, RDFFormat.RDFXML);
final InferredOWLOntologyID resultArtifactId = testArtifactManager.loadArtifact(inputStream, format);
// INSIDE the loadArtifact method...
// connection to the temporary repository that the artifact RDF triples will be stored while
// they are initially parsed by OWLAPI.
final RepositoryConnection temporaryRepositoryConnection = null;
final URI randomContext = ValueFactoryImpl.getInstance().createURI(UUID.randomUUID().toString());
// Load the artifact RDF triples into a random context in the temp repository, which may be
// shared between different uploads
temporaryRepositoryConnection.add(inputStream, "", format, randomContext);
// TODO: SPARQL query to extract the Ontology IRI and Version IRI from the
// temporaryRepositoryConnection
// Create an initial OWLOntologyID for the uploaded ontology, after checking that the
// Version IRI is distinct for the given Ontology IRI
final OWLOntologyID tempArtifactId = null;
// TODO If the OWLOntologyID is not distinct, then modify it to be distinct
// return the results, setting the results variable to be the same as the internalResults
// variable from inside of extractFileReferences
// Ie, return internalResults; results = internalResults;
final Set<PoddPurlReference> purlResults =
testArtifactManager.getPurlManager().extractPurlReferences(temporaryRepositoryConnection,
tempArtifactId.getVersionIRI().toOpenRDFURI());
// perform the conversion of the URIs, possibly in bulk, as they are all given to this
// method together
testArtifactManager.getPurlManager().convertTemporaryUris(purlResults, temporaryRepositoryConnection,
tempArtifactId.getVersionIRI().toOpenRDFURI());
// Then work on the file references
// calls, to setup the results collection
final Set<PoddFileReference> fileReferenceResults =
testArtifactManager.getFileReferenceManager().extractFileReferences(temporaryRepositoryConnection,
tempArtifactId.getVersionIRI().toOpenRDFURI());
// INSIDE the extractFileReferences method....
final Set<PoddFileReference> internalFileReferenceResults =
Collections.newSetFromMap(new ConcurrentHashMap<PoddFileReference, Boolean>());
for(final PoddFileReferenceProcessorFactory nextProcessorFactory : testArtifactManager
.getFileReferenceManager().getProcessorFactoryRegistry().getByStage(PoddProcessorStage.RDF_PARSING))
{
final StringBuilder sparqlQuery = new StringBuilder();
sparqlQuery.append("CONSTRUCT { ");
sparqlQuery.append(nextProcessorFactory.getSPARQLConstructBGP());
sparqlQuery.append(" } WHERE { ");
sparqlQuery.append(nextProcessorFactory.getSPARQLConstructWhere());
sparqlQuery.append(" } ");
if(!nextProcessorFactory.getSPARQLGroupBy().isEmpty())
{
sparqlQuery.append(" GROUP BY ");
sparqlQuery.append(nextProcessorFactory.getSPARQLGroupBy());
}
final GraphQuery graphQuery =
temporaryRepositoryConnection.prepareGraphQuery(QueryLanguage.SPARQL, sparqlQuery.toString());
// Create a new dataset to specify the contexts that the query will be allowed to access
final DatasetImpl dataset = new DatasetImpl();
// The following URIs are passed in as the context to the
// extractFileReferences(RepositoryConnection,URI...) method
final URI artifactGraphUri = null;
// for(URI artifactGraphUri : contexts)
dataset.addDefaultGraph(artifactGraphUri);
dataset.addNamedGraph(artifactGraphUri);
// end for loop
// if the stage is after inferencing, the inferred graph URI would be one of the
// contexts as well
final URI artifactInferredGraphUri = null;
dataset.addDefaultGraph(artifactInferredGraphUri);
dataset.addNamedGraph(artifactInferredGraphUri);
// set the dataset for the query to be our artificially constructed dataset
graphQuery.setDataset(dataset);
final GraphQueryResult queryResult = graphQuery.evaluate();
// If the query matched anything, then for each of the file references in the resulting
// construct statements, we create a file reference and add it to the results
if(!queryResult.hasNext())
{
final Graph graph = new GraphImpl();
while(queryResult.hasNext())
{
graph.add(queryResult.next());
}
final Iterator<Statement> match = graph.match(null, RDF.TYPE, poddFileReferenceType);
while(match.hasNext())
{
final Statement nextStatement = match.next();
final Graph fileReferenceGraph = new GraphImpl();
// For generality, in practice for now, use graph.match as below...
nextProcessorFactory.getSPARQLConstructWhere((URI)nextStatement.getSubject());
final Iterator<Statement> match2 = graph.match(nextStatement.getSubject(), null, null);
while(match2.hasNext())
{
fileReferenceGraph.add(match2.next());
}
// This processor factory matches the graph that we wish to use, so we create a
// processor instance now to create the file reference
// NOTE: This object cannot be shared as we do not specify that it needs to be
// threadsafe
final PoddFileReferenceProcessor processor = nextProcessorFactory.getProcessor();
// create a reference out of the resulting graph
internalFileReferenceResults.add(processor.createReference(fileReferenceGraph));
}
}
}
// optionally verify the file references
testArtifactManager.getFileReferenceManager().verifyFileReferences(fileReferenceResults,
temporaryRepositoryConnection, tempArtifactId.getVersionIRI().toOpenRDFURI());
// TODO: Optionally remove invalid file references or mark them as invalid using RDF
// statements/OWL Classes
// Before loading the statements into OWLAPI, ensure that the schema ontologies are cached
// in memory
// TODO: For each OWL:IMPORTS statement, call the following
final IRI schemaOntologyIRI = null;
// Get the current version
final InferredOWLOntologyID ontologyVersion =
testSchemaManager.getCurrentSchemaOntologyVersion(schemaOntologyIRI);
// Make sure it is cached in memory. This will not attempt to load the ontology again if it
// is already cached or already being loaded
testArtifactManager.getOWLManager().cacheSchemaOntology(ontologyVersion, temporaryRepositoryConnection);
// Load the statements into an OWLAPI OWLOntology
final RioMemoryTripleSource owlSource =
new RioMemoryTripleSource(temporaryRepositoryConnection.getStatements(null, null, null, true,
tempArtifactId.getVersionIRI().toOpenRDFURI()));
owlSource.setNamespaces(temporaryRepositoryConnection.getNamespaces());
final OWLOntology nextOntology = testArtifactManager.getOWLManager().loadOntology(owlSource);
// Inside of PoddOWLManager.loadOntology().....
final RioParser owlParser =
new RioParserImpl((RioRDFOntologyFormatFactory)OWLOntologyFormatFactoryRegistry.getInstance()
.getByMIMEType(mimeType));
// nextOntology = this.manager.createOntology();
owlParser.parse(owlSource, nextOntology);
// Check the OWLAPI OWLOntology against an OWLProfile to make sure it is in profile
final OWLProfileReport profileReport =
testArtifactManager.getOWLManager().getReasonerProfile().checkOntology(nextOntology);
if(!profileReport.isInProfile())
{
testArtifactManager.getOWLManager().removeCache(nextOntology.getOntologyID());
}
// create an OWL Reasoner using the Pellet library and ensure that the reasoner thinks the
// ontology is consistent so far
// Use the factory that we found to create a reasoner over the ontology
final OWLReasoner nextReasoner = testArtifactManager.getOWLManager().createReasoner(nextOntology);
// Test that the ontology was consistent with this reasoner
// This ensures in the case of Pellet that it is in the OWL2-DL profile
// if(!nextReasoner.isConsistent() || nextReasoner.getUnsatisfiableClasses().getSize() > 0)
// Check the OWLAPI OWLOntology using a reasoner for .isConsistent
if(!nextReasoner.isConsistent())
{
testArtifactManager.getOWLManager().removeCache(nextOntology.getOntologyID());
}
// Once the reasoner determines that the ontology is consistent, copy the statements to a
// permanent repository connection
final RepositoryConnection permanentRepositoryConnection = null;
// TODO: Copy the statements to permanentRepositoryConnection
// NOTE: At this stage, a client could be notified, and the artifact could be streamed back
// to them from permanentRepositoryConnection
final InferredOWLOntologyID inferredOWLOntologyID =
testArtifactManager.getOWLManager().generateInferredOntologyID(nextOntology.getOntologyID());
// Use an OWLAPI InferredAxiomGenerator together with the reasoner to create inferred
// axioms to store in the database
// Serialise the inferred statements back to a different context in the permanent
// repository connection
// The contexts to use within the permanent repository connection are all encapsulated in
// the InferredOWLOntologyID object
testArtifactManager.getOWLManager().inferStatements(inferredOWLOntologyID, permanentRepositoryConnection);
// make sure in a finally block to remove the cache for the ontology
testArtifactManager.getOWLManager().removeCache(inferredOWLOntologyID);
// return InferredOWLOntologyID() with the context of the inferred statements
}
| public void setUp() throws Exception
{
// FIXME: This needs to be a constant
final URI poddFileReferenceType =
ValueFactoryImpl.getInstance().createURI("http://purl.org/podd/ns/poddBase#PoddFileReference");
final PoddFileReferenceProcessorFactoryRegistry testFileRegistry =
new PoddFileReferenceProcessorFactoryRegistry();
// clear any automatically added entries that may come from META-INF/services entries on the
// classpath
testFileRegistry.clear();
// In practice, the following factories would be automatically added to the registry,
// however for testing we want to explicitly add the ones we want to support for each test
testFileRegistry.add(this.getNewSSHFileReferenceProcessorFactory());
testFileRegistry.add(this.getNewHttpFileReferenceProcessorFactory());
final PoddPurlProcessorFactoryRegistry testPurlRegistry = new PoddPurlProcessorFactoryRegistry();
testPurlRegistry.clear();
testPurlRegistry.add(this.getNewDoiPurlProcessorFactory());
testPurlRegistry.add(this.getNewHandlePurlProcessorFactory());
testPurlRegistry.add(this.getNewUUIDPurlProcessorFactory());
final PoddFileReferenceManager testFileReferenceManager = this.getNewFileReferenceManager();
testFileReferenceManager.setProcessorFactoryRegistry(testFileRegistry);
final PoddPurlManager testPurlManager = this.getNewPurlManager();
testPurlManager.setPurlProcessorFactoryRegistry(testPurlRegistry);
final PoddOWLManager testOWLManager = this.getNewOWLManager();
testOWLManager.setReasonerFactory(this.getNewReasonerFactory());
final PoddArtifactManager testArtifactManager = this.getNewArtifactManager();
testArtifactManager.setFileReferenceManager(testFileReferenceManager);
testArtifactManager.setPurlManager(testPurlManager);
testArtifactManager.setOwlManager(testOWLManager);
final PoddSchemaManager testSchemaManager = this.getNewSchemaManager();
testSchemaManager.setOwlManager(testOWLManager);
final InputStream inputStream = this.getClass().getResourceAsStream("/testArtifact.rdf");
// MIME type should be either given by the user, detected from the content type on the
// request, or autodetected using the Any23 Mime Detector
final String mimeType = "application/rdf+xml";
final RDFFormat format = Rio.getParserFormatForMIMEType(mimeType, RDFFormat.RDFXML);
final InferredOWLOntologyID resultArtifactId = testArtifactManager.loadArtifact(inputStream, format);
// INSIDE the loadArtifact method...
// connection to the temporary repository that the artifact RDF triples will be stored while
// they are initially parsed by OWLAPI.
final RepositoryConnection temporaryRepositoryConnection = null;
final URI randomContext = ValueFactoryImpl.getInstance().createURI(UUID.randomUUID().toString());
// Load the artifact RDF triples into a random context in the temp repository, which may be
// shared between different uploads
temporaryRepositoryConnection.add(inputStream, "", format, randomContext);
// TODO: SPARQL query to extract the Ontology IRI and Version IRI from the
// temporaryRepositoryConnection
// Create an initial OWLOntologyID for the uploaded ontology, after checking that the
// Version IRI is distinct for the given Ontology IRI
final OWLOntologyID tempArtifactId = null;
// TODO If the OWLOntologyID is not distinct, then modify it to be distinct
// return the results, setting the results variable to be the same as the internalResults
// variable from inside of extractFileReferences
// Ie, return internalResults; results = internalResults;
final Set<PoddPurlReference> purlResults =
testArtifactManager.getPurlManager().extractPurlReferences(temporaryRepositoryConnection,
tempArtifactId.getVersionIRI().toOpenRDFURI());
// perform the conversion of the URIs, possibly in bulk, as they are all given to this
// method together
testArtifactManager.getPurlManager().convertTemporaryUris(purlResults, temporaryRepositoryConnection,
tempArtifactId.getVersionIRI().toOpenRDFURI());
// Then work on the file references
// calls, to setup the results collection
final Set<PoddFileReference> fileReferenceResults =
testArtifactManager.getFileReferenceManager().extractFileReferences(temporaryRepositoryConnection,
tempArtifactId.getVersionIRI().toOpenRDFURI());
// INSIDE the extractFileReferences method....
final Set<PoddFileReference> internalFileReferenceResults =
Collections.newSetFromMap(new ConcurrentHashMap<PoddFileReference, Boolean>());
for(final PoddFileReferenceProcessorFactory nextProcessorFactory : testArtifactManager
.getFileReferenceManager().getFileProcessorFactoryRegistry().getByStage(PoddProcessorStage.RDF_PARSING))
{
final StringBuilder sparqlQuery = new StringBuilder();
sparqlQuery.append("CONSTRUCT { ");
sparqlQuery.append(nextProcessorFactory.getSPARQLConstructBGP());
sparqlQuery.append(" } WHERE { ");
sparqlQuery.append(nextProcessorFactory.getSPARQLConstructWhere());
sparqlQuery.append(" } ");
if(!nextProcessorFactory.getSPARQLGroupBy().isEmpty())
{
sparqlQuery.append(" GROUP BY ");
sparqlQuery.append(nextProcessorFactory.getSPARQLGroupBy());
}
final GraphQuery graphQuery =
temporaryRepositoryConnection.prepareGraphQuery(QueryLanguage.SPARQL, sparqlQuery.toString());
// Create a new dataset to specify the contexts that the query will be allowed to access
final DatasetImpl dataset = new DatasetImpl();
// The following URIs are passed in as the context to the
// extractFileReferences(RepositoryConnection,URI...) method
final URI artifactGraphUri = null;
// for(URI artifactGraphUri : contexts)
dataset.addDefaultGraph(artifactGraphUri);
dataset.addNamedGraph(artifactGraphUri);
// end for loop
// if the stage is after inferencing, the inferred graph URI would be one of the
// contexts as well
final URI artifactInferredGraphUri = null;
dataset.addDefaultGraph(artifactInferredGraphUri);
dataset.addNamedGraph(artifactInferredGraphUri);
// set the dataset for the query to be our artificially constructed dataset
graphQuery.setDataset(dataset);
final GraphQueryResult queryResult = graphQuery.evaluate();
// If the query matched anything, then for each of the file references in the resulting
// construct statements, we create a file reference and add it to the results
if(!queryResult.hasNext())
{
final Graph graph = new GraphImpl();
while(queryResult.hasNext())
{
graph.add(queryResult.next());
}
final Iterator<Statement> match = graph.match(null, RDF.TYPE, poddFileReferenceType);
while(match.hasNext())
{
final Statement nextStatement = match.next();
final Graph fileReferenceGraph = new GraphImpl();
// For generality, in practice for now, use graph.match as below...
nextProcessorFactory.getSPARQLConstructWhere((URI)nextStatement.getSubject());
final Iterator<Statement> match2 = graph.match(nextStatement.getSubject(), null, null);
while(match2.hasNext())
{
fileReferenceGraph.add(match2.next());
}
// This processor factory matches the graph that we wish to use, so we create a
// processor instance now to create the file reference
// NOTE: This object cannot be shared as we do not specify that it needs to be
// threadsafe
final PoddFileReferenceProcessor processor = nextProcessorFactory.getProcessor();
// create a reference out of the resulting graph
internalFileReferenceResults.add(processor.createReference(fileReferenceGraph));
}
}
}
// optionally verify the file references
testArtifactManager.getFileReferenceManager().verifyFileReferences(fileReferenceResults,
temporaryRepositoryConnection, tempArtifactId.getVersionIRI().toOpenRDFURI());
// TODO: Optionally remove invalid file references or mark them as invalid using RDF
// statements/OWL Classes
// Before loading the statements into OWLAPI, ensure that the schema ontologies are cached
// in memory
// TODO: For each OWL:IMPORTS statement, call the following
final IRI schemaOntologyIRI = null;
// Get the current version
final InferredOWLOntologyID ontologyVersion =
testSchemaManager.getCurrentSchemaOntologyVersion(schemaOntologyIRI);
// Make sure it is cached in memory. This will not attempt to load the ontology again if it
// is already cached or already being loaded
testArtifactManager.getOWLManager().cacheSchemaOntology(ontologyVersion, temporaryRepositoryConnection);
// Load the statements into an OWLAPI OWLOntology
final RioMemoryTripleSource owlSource =
new RioMemoryTripleSource(temporaryRepositoryConnection.getStatements(null, null, null, true,
tempArtifactId.getVersionIRI().toOpenRDFURI()));
owlSource.setNamespaces(temporaryRepositoryConnection.getNamespaces());
final OWLOntology nextOntology = testArtifactManager.getOWLManager().loadOntology(owlSource);
// Inside of PoddOWLManager.loadOntology().....
final RioParser owlParser =
new RioParserImpl((RioRDFOntologyFormatFactory)OWLOntologyFormatFactoryRegistry.getInstance()
.getByMIMEType(mimeType));
// nextOntology = this.manager.createOntology();
owlParser.parse(owlSource, nextOntology);
// Check the OWLAPI OWLOntology against an OWLProfile to make sure it is in profile
final OWLProfileReport profileReport =
testArtifactManager.getOWLManager().getReasonerProfile().checkOntology(nextOntology);
if(!profileReport.isInProfile())
{
testArtifactManager.getOWLManager().removeCache(nextOntology.getOntologyID());
}
// create an OWL Reasoner using the Pellet library and ensure that the reasoner thinks the
// ontology is consistent so far
// Use the factory that we found to create a reasoner over the ontology
final OWLReasoner nextReasoner = testArtifactManager.getOWLManager().createReasoner(nextOntology);
// Test that the ontology was consistent with this reasoner
// This ensures in the case of Pellet that it is in the OWL2-DL profile
// if(!nextReasoner.isConsistent() || nextReasoner.getUnsatisfiableClasses().getSize() > 0)
// Check the OWLAPI OWLOntology using a reasoner for .isConsistent
if(!nextReasoner.isConsistent())
{
testArtifactManager.getOWLManager().removeCache(nextOntology.getOntologyID());
}
// Once the reasoner determines that the ontology is consistent, copy the statements to a
// permanent repository connection
final RepositoryConnection permanentRepositoryConnection = null;
// TODO: Copy the statements to permanentRepositoryConnection
// NOTE: At this stage, a client could be notified, and the artifact could be streamed back
// to them from permanentRepositoryConnection
final InferredOWLOntologyID inferredOWLOntologyID =
testArtifactManager.getOWLManager().generateInferredOntologyID(nextOntology.getOntologyID());
// Use an OWLAPI InferredAxiomGenerator together with the reasoner to create inferred
// axioms to store in the database
// Serialise the inferred statements back to a different context in the permanent
// repository connection
// The contexts to use within the permanent repository connection are all encapsulated in
// the InferredOWLOntologyID object
testArtifactManager.getOWLManager().inferStatements(inferredOWLOntologyID, permanentRepositoryConnection);
// make sure in a finally block to remove the cache for the ontology
testArtifactManager.getOWLManager().removeCache(inferredOWLOntologyID);
// return InferredOWLOntologyID() with the context of the inferred statements
}
|
diff --git a/org.eclipse.gef3d.examples.uml2/src/java/org/eclipse/gef3d/examples/uml2/clazz/providers/UMLClassEditPartProvider3D.java b/org.eclipse.gef3d.examples.uml2/src/java/org/eclipse/gef3d/examples/uml2/clazz/providers/UMLClassEditPartProvider3D.java
index 314b2a7..3161b0f 100644
--- a/org.eclipse.gef3d.examples.uml2/src/java/org/eclipse/gef3d/examples/uml2/clazz/providers/UMLClassEditPartProvider3D.java
+++ b/org.eclipse.gef3d.examples.uml2/src/java/org/eclipse/gef3d/examples/uml2/clazz/providers/UMLClassEditPartProvider3D.java
@@ -1,135 +1,135 @@
/*******************************************************************************
* Copyright (c) 2009 Jens von Pilgrim 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:
* Jens von Pilgrim, Kristian Duske - initial API and implementation
******************************************************************************/
package org.eclipse.gef3d.examples.uml2.clazz.providers;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.eclipse.gef.RootEditPart;
import org.eclipse.gef3d.examples.uml2.clazz.edit.parts.UMLEditPartFactory3D;
import org.eclipse.gef3d.examples.uml2.clazz.part.UMLClassDiagramEditor3D;
import org.eclipse.gef3d.examples.uml2.usecase.part.UMLUseCaseDiagramEditor3D;
import org.eclipse.gef3d.gmf.runtime.core.service.ProviderAcceptor;
import org.eclipse.gef3d.gmf.runtime.diagram.ui.editparts.DiagramRootEditPart3D;
import org.eclipse.gef3d.gmf.runtime.diagram.ui.services.editpart.DiagramRootEditPart3DProvider;
import org.eclipse.gmf.runtime.common.core.service.IOperation;
import org.eclipse.gmf.runtime.diagram.ui.services.editpart.CreateGraphicEditPartOperation;
import org.eclipse.gmf.runtime.notation.Diagram;
import org.eclipse.uml2.diagram.clazz.providers.UMLEditPartProvider;
/**
* UMLEditPartProvider3D There should really be more documentation here.
*
* @author Jens von Pilgrim
* @author Kristian Duske
* @version $Revision$
* @since Apr 7, 2009
*/
public class UMLClassEditPartProvider3D extends UMLEditPartProvider {
public static String[] SUPPORTED_EDITORS =
{ UMLClassDiagramEditor3D.class.getName() };
/**
* Logger for this class
*/
private static final Logger log =
Logger.getLogger(UMLClassEditPartProvider3D.class.getName());
/**
*
*/
public UMLClassEditPartProvider3D() {
super(); // sets 2D factory
setFactory(new UMLEditPartFactory3D());
setAllowCaching(false);
}
/**
* Returns true if editor is accepts this provider, this is evaluated using
* the {@link ProviderAcceptor} retrieved from the operation. The
* {@link ProviderAcceptor} must have set flag
* {@link #CLASSDIAGRAM_3D_ACCEPTED}.
*
* @see org.eclipse.uml2.diagram.clazz.providers.UMLEditPartProvider#provides(org.eclipse.gmf.runtime.common.core.service.IOperation)
*/
@Override
public synchronized boolean provides(IOperation i_operation) {
if (i_operation instanceof CreateGraphicEditPartOperation) {
ProviderAcceptor providerAcceptor =
ProviderAcceptor.retrieveProviderAcceptor(i_operation);
boolean bIsAccepted =
ProviderAcceptor.evaluate3DAcceptance(this, i_operation);
boolean bIsSupported = isSupported();
CreateGraphicEditPartOperation op = (CreateGraphicEditPartOperation) i_operation;
bIsAccepted &= super.provides(i_operation);
- if (bIsAccepted!=bIsSupported) {
- if (log.isLoggable(Level.INFO)) {
- log.info("Warning, isSupported = " + bIsSupported +
- ", acceptor says " + bIsAccepted +
- ", acceptor: " + providerAcceptor +
- ", model: " + op.getView().getElement()
- ); //$NON-NLS-1$
- }
- }
+// if (bIsAccepted!=bIsSupported) {
+// if (log.isLoggable(Level.INFO)) {
+// log.info("Warning, isSupported = " + bIsSupported +
+// ", acceptor says " + bIsAccepted +
+// ", acceptor: " + providerAcceptor +
+// ", model: " + op.getView().getElement()
+// ); //$NON-NLS-1$
+// }
+// }
return bIsAccepted;
}
return false;
}
/**
* Tests if the editor using this provider is supported. This method
* actually is a hack and we have to find a better solution.
*
* @return
*/
public boolean isSupported() {
Exception ex = new Exception();
// ex.printStackTrace();
String name;
for (StackTraceElement element : ex.getStackTrace()) {
name = element.getClassName();
if (name.startsWith("org.eclipse.ui"))
break;
for (int i = 0; i < SUPPORTED_EDITORS.length; i++) {
if (name.equals(SUPPORTED_EDITORS[i]))
return true;
}
}
return false;
}
/**
* Returns null as the root edit part is expected to be created by a
* different provider in case of 3D, i.e. by {@link
* DiagramRootEditPart3DProvider.}
*
* @see org.eclipse.gmf.runtime.diagram.ui.services.editpart.AbstractEditPartProvider#createRootEditPart(org.eclipse.gmf.runtime.notation.Diagram)
*/
@Override
public RootEditPart createRootEditPart(Diagram i_diagram) {
if (log.isLoggable(Level.INFO)) {
log.info("I don't want to create a root"); //$NON-NLS-1$
}
return null;
}
}
| true | true | public synchronized boolean provides(IOperation i_operation) {
if (i_operation instanceof CreateGraphicEditPartOperation) {
ProviderAcceptor providerAcceptor =
ProviderAcceptor.retrieveProviderAcceptor(i_operation);
boolean bIsAccepted =
ProviderAcceptor.evaluate3DAcceptance(this, i_operation);
boolean bIsSupported = isSupported();
CreateGraphicEditPartOperation op = (CreateGraphicEditPartOperation) i_operation;
bIsAccepted &= super.provides(i_operation);
if (bIsAccepted!=bIsSupported) {
if (log.isLoggable(Level.INFO)) {
log.info("Warning, isSupported = " + bIsSupported +
", acceptor says " + bIsAccepted +
", acceptor: " + providerAcceptor +
", model: " + op.getView().getElement()
); //$NON-NLS-1$
}
}
return bIsAccepted;
}
return false;
}
| public synchronized boolean provides(IOperation i_operation) {
if (i_operation instanceof CreateGraphicEditPartOperation) {
ProviderAcceptor providerAcceptor =
ProviderAcceptor.retrieveProviderAcceptor(i_operation);
boolean bIsAccepted =
ProviderAcceptor.evaluate3DAcceptance(this, i_operation);
boolean bIsSupported = isSupported();
CreateGraphicEditPartOperation op = (CreateGraphicEditPartOperation) i_operation;
bIsAccepted &= super.provides(i_operation);
// if (bIsAccepted!=bIsSupported) {
// if (log.isLoggable(Level.INFO)) {
// log.info("Warning, isSupported = " + bIsSupported +
// ", acceptor says " + bIsAccepted +
// ", acceptor: " + providerAcceptor +
// ", model: " + op.getView().getElement()
// ); //$NON-NLS-1$
// }
// }
return bIsAccepted;
}
return false;
}
|
diff --git a/src/com/yahoo/platform/yui/compressor/CssCompressor.java b/src/com/yahoo/platform/yui/compressor/CssCompressor.java
index f1e2672..0202d8e 100644
--- a/src/com/yahoo/platform/yui/compressor/CssCompressor.java
+++ b/src/com/yahoo/platform/yui/compressor/CssCompressor.java
@@ -1,394 +1,396 @@
/*
* YUI Compressor
* http://developer.yahoo.com/yui/compressor/
* Author: Julien Lecomte - http://www.julienlecomte.net/
* Author: Isaac Schlueter - http://foohack.com/
* Author: Stoyan Stefanov - http://phpied.com/
* Copyright (c) 2011 Yahoo! Inc. All rights reserved.
* The copyrights embodied in the content of this file are licensed
* by Yahoo! Inc. under the BSD (revised) open source license.
*/
package com.yahoo.platform.yui.compressor;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.ArrayList;
public class CssCompressor {
private StringBuffer srcsb = new StringBuffer();
public CssCompressor(Reader in) throws IOException {
// Read the stream...
int c;
while ((c = in.read()) != -1) {
srcsb.append((char) c);
}
}
// Leave data urls alone to increase parse performance.
protected String extractDataUrls(String css, ArrayList preservedTokens) {
int maxIndex = css.length() - 1;
int appendIndex = 0;
StringBuffer sb = new StringBuffer();
Pattern p = Pattern.compile("url\\(\\s*([\"']?)data\\:");
Matcher m = p.matcher(css);
/*
* Since we need to account for non-base64 data urls, we need to handle
* ' and ) being part of the data string. Hence switching to indexOf,
* to determine whether or not we have matching string terminators and
* handling sb appends directly, instead of using matcher.append* methods.
*/
while (m.find()) {
int startIndex = m.start() + 4; // "url(".length()
String terminator = m.group(1); // ', " or empty (not quoted)
if (terminator.length() == 0) {
terminator = ")";
}
boolean foundTerminator = false;
int endIndex = m.end() - 1;
while(foundTerminator == false && endIndex+1 <= maxIndex) {
endIndex = css.indexOf(terminator, endIndex+1);
if ((endIndex > 0) && (css.charAt(endIndex-1) != '\\')) {
foundTerminator = true;
if (!")".equals(terminator)) {
endIndex = css.indexOf(")", endIndex);
}
}
}
// Enough searching, start moving stuff over to the buffer
sb.append(css.substring(appendIndex, m.start()));
if (foundTerminator) {
String token = css.substring(startIndex, endIndex);
token = token.replaceAll("\\s+", "");
preservedTokens.add(token);
String preserver = "url(___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___)";
sb.append(preserver);
appendIndex = endIndex + 1;
} else {
// No end terminator found, re-add the whole match. Should we throw/warn here?
sb.append(css.substring(m.start(), m.end()));
appendIndex = m.end();
}
}
sb.append(css.substring(appendIndex));
return sb.toString();
}
public void compress(Writer out, int linebreakpos)
throws IOException {
Pattern p;
Matcher m;
String css = srcsb.toString();
int startIndex = 0;
int endIndex = 0;
int i = 0;
int max = 0;
ArrayList preservedTokens = new ArrayList(0);
ArrayList comments = new ArrayList(0);
String token;
int totallen = css.length();
String placeholder;
css = this.extractDataUrls(css, preservedTokens);
StringBuffer sb = new StringBuffer(css);
// collect all comment blocks...
while ((startIndex = sb.indexOf("/*", startIndex)) >= 0) {
endIndex = sb.indexOf("*/", startIndex + 2);
if (endIndex < 0) {
endIndex = totallen;
}
token = sb.substring(startIndex + 2, endIndex);
comments.add(token);
sb.replace(startIndex + 2, endIndex, "___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + (comments.size() - 1) + "___");
startIndex += 2;
}
css = sb.toString();
// preserve strings so their content doesn't get accidentally minified
sb = new StringBuffer();
p = Pattern.compile("(\"([^\\\\\"]|\\\\.|\\\\)*\")|(\'([^\\\\\']|\\\\.|\\\\)*\')");
m = p.matcher(css);
while (m.find()) {
token = m.group();
char quote = token.charAt(0);
token = token.substring(1, token.length() - 1);
// maybe the string contains a comment-like substring?
// one, maybe more? put'em back then
if (token.indexOf("___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_") >= 0) {
for (i = 0, max = comments.size(); i < max; i += 1) {
token = token.replace("___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + i + "___", comments.get(i).toString());
}
}
// minify alpha opacity in filter strings
token = token.replaceAll("(?i)progid:DXImageTransform.Microsoft.Alpha\\(Opacity=", "alpha(opacity=");
preservedTokens.add(token);
String preserver = quote + "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___" + quote;
m.appendReplacement(sb, preserver);
}
m.appendTail(sb);
css = sb.toString();
// strings are safe, now wrestle the comments
for (i = 0, max = comments.size(); i < max; i += 1) {
token = comments.get(i).toString();
placeholder = "___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + i + "___";
// ! in the first position of the comment means preserve
// so push to the preserved tokens while stripping the !
if (token.startsWith("!")) {
preservedTokens.add(token);
css = css.replace(placeholder, "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___");
continue;
}
// \ in the last position looks like hack for Mac/IE5
// shorten that to /*\*/ and the next one to /**/
if (token.endsWith("\\")) {
preservedTokens.add("\\");
css = css.replace(placeholder, "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___");
i = i + 1; // attn: advancing the loop
preservedTokens.add("");
css = css.replace("___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + i + "___", "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___");
continue;
}
// keep empty comments after child selectors (IE7 hack)
// e.g. html >/**/ body
if (token.length() == 0) {
startIndex = css.indexOf(placeholder);
if (startIndex > 2) {
if (css.charAt(startIndex - 3) == '>') {
preservedTokens.add("");
css = css.replace(placeholder, "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___");
}
}
}
// in all other cases kill the comment
css = css.replace("/*" + placeholder + "*/", "");
}
// Normalize all whitespace strings to single spaces. Easier to work with that way.
css = css.replaceAll("\\s+", " ");
// Remove the spaces before the things that should not have spaces before them.
// But, be careful not to turn "p :link {...}" into "p:link{...}"
// Swap out any pseudo-class colons with the token, and then swap back.
sb = new StringBuffer();
p = Pattern.compile("(^|\\})(([^\\{:])+:)+([^\\{]*\\{)");
m = p.matcher(css);
while (m.find()) {
String s = m.group();
s = s.replaceAll(":", "___YUICSSMIN_PSEUDOCLASSCOLON___");
s = s.replaceAll( "\\\\", "\\\\\\\\" ).replaceAll( "\\$", "\\\\\\$" );
m.appendReplacement(sb, s);
}
m.appendTail(sb);
css = sb.toString();
// Remove spaces before the things that should not have spaces before them.
css = css.replaceAll("\\s+([!{};:>+\\(\\)\\],])", "$1");
+ // Restore spaces for !important
+ css = css.replaceAll("!important", " !important");
// bring back the colon
css = css.replaceAll("___YUICSSMIN_PSEUDOCLASSCOLON___", ":");
// retain space for special IE6 cases
css = css.replaceAll(":first\\-(line|letter)(\\{|,)", ":first-$1 $2");
// no space after the end of a preserved comment
css = css.replaceAll("\\*/ ", "*/");
// If there is a @charset, then only allow one, and push to the top of the file.
css = css.replaceAll("^(.*)(@charset \"[^\"]*\";)", "$2$1");
css = css.replaceAll("^(\\s*@charset [^;]+;\\s*)+", "$1");
// Put the space back in some cases, to support stuff like
// @media screen and (-webkit-min-device-pixel-ratio:0){
css = css.replaceAll("\\band\\(", "and (");
// Remove the spaces after the things that should not have spaces after them.
css = css.replaceAll("([!{}:;>+\\(\\[,])\\s+", "$1");
// remove unnecessary semicolons
css = css.replaceAll(";+}", "}");
// Replace 0(px,em,%) with 0.
css = css.replaceAll("([\\s:])(0)(px|em|%|in|cm|mm|pc|pt|ex)", "$1$2");
// Replace 0 0 0 0; with 0.
css = css.replaceAll(":0 0 0 0(;|})", ":0$1");
css = css.replaceAll(":0 0 0(;|})", ":0$1");
css = css.replaceAll(":0 0(;|})", ":0$1");
// Replace background-position:0; with background-position:0 0;
// same for transform-origin
sb = new StringBuffer();
p = Pattern.compile("(?i)(background-position|webkit-mask-position|transform-origin|webkit-transform-origin|moz-transform-origin|o-transform-origin|ms-transform-origin):0(;|})");
m = p.matcher(css);
while (m.find()) {
m.appendReplacement(sb, m.group(1).toLowerCase() + ":0 0" + m.group(2));
}
m.appendTail(sb);
css = sb.toString();
// Replace 0.6 to .6, but only when preceded by : or a white-space
css = css.replaceAll("(:|\\s)0+\\.(\\d+)", "$1.$2");
// Shorten colors from rgb(51,102,153) to #336699
// This makes it more likely that it'll get further compressed in the next step.
p = Pattern.compile("rgb\\s*\\(\\s*([0-9,\\s]+)\\s*\\)");
m = p.matcher(css);
sb = new StringBuffer();
while (m.find()) {
String[] rgbcolors = m.group(1).split(",");
StringBuffer hexcolor = new StringBuffer("#");
for (i = 0; i < rgbcolors.length; i++) {
int val = Integer.parseInt(rgbcolors[i]);
if (val < 16) {
hexcolor.append("0");
}
hexcolor.append(Integer.toHexString(val));
}
m.appendReplacement(sb, hexcolor.toString());
}
m.appendTail(sb);
css = sb.toString();
// Shorten colors from #AABBCC to #ABC. Note that we want to make sure
// the color is not preceded by either ", " or =. Indeed, the property
// filter: chroma(color="#FFFFFF");
// would become
// filter: chroma(color="#FFF");
// which makes the filter break in IE.
// We also want to make sure we're only compressing #AABBCC patterns inside { }, not id selectors ( #FAABAC {} )
// We also want to avoid compressing invalid values (e.g. #AABBCCD to #ABCD)
p = Pattern.compile("(\\=\\s*?[\"']?)?" + "#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])" + "(:?\\}|[^0-9a-fA-F{][^{]*?\\})");
m = p.matcher(css);
sb = new StringBuffer();
int index = 0;
while (m.find(index)) {
sb.append(css.substring(index, m.start()));
boolean isFilter = (m.group(1) != null && !"".equals(m.group(1)));
if (isFilter) {
// Restore, as is. Compression will break filters
sb.append(m.group(1) + "#" + m.group(2) + m.group(3) + m.group(4) + m.group(5) + m.group(6) + m.group(7));
} else {
if( m.group(2).equalsIgnoreCase(m.group(3)) &&
m.group(4).equalsIgnoreCase(m.group(5)) &&
m.group(6).equalsIgnoreCase(m.group(7))) {
// #AABBCC pattern
sb.append("#" + (m.group(3) + m.group(5) + m.group(7)).toLowerCase());
} else {
// Non-compressible color, restore, but lower case.
sb.append("#" + (m.group(2) + m.group(3) + m.group(4) + m.group(5) + m.group(6) + m.group(7)).toLowerCase());
}
}
index = m.end(7);
}
sb.append(css.substring(index));
css = sb.toString();
// Replace #f00 -> red
css = css.replaceAll("(:|\\s)(#f00)(;|})", "$1red$3");
// Replace other short color keywords
css = css.replaceAll("(:|\\s)(#000080)(;|})", "$1navy$3");
css = css.replaceAll("(:|\\s)(#808080)(;|})", "$1gray$3");
css = css.replaceAll("(:|\\s)(#808000)(;|})", "$1olive$3");
css = css.replaceAll("(:|\\s)(#800080)(;|})", "$1purple$3");
css = css.replaceAll("(:|\\s)(#c0c0c0)(;|})", "$1silver$3");
css = css.replaceAll("(:|\\s)(#008080)(;|})", "$1teal$3");
css = css.replaceAll("(:|\\s)(#ffa500)(;|})", "$1orange$3");
css = css.replaceAll("(:|\\s)(#800000)(;|})", "$1maroon$3");
// border: none -> border:0
sb = new StringBuffer();
p = Pattern.compile("(?i)(border|border-top|border-right|border-bottom|border-left|outline|background):none(;|})");
m = p.matcher(css);
while (m.find()) {
m.appendReplacement(sb, m.group(1).toLowerCase() + ":0" + m.group(2));
}
m.appendTail(sb);
css = sb.toString();
// shorter opacity IE filter
css = css.replaceAll("(?i)progid:DXImageTransform.Microsoft.Alpha\\(Opacity=", "alpha(opacity=");
// Remove empty rules.
css = css.replaceAll("[^\\}\\{/;]+\\{\\}", "");
// TODO: Should this be after we re-insert tokens. These could alter the break points. However then
// we'd need to make sure we don't break in the middle of a string etc.
if (linebreakpos >= 0) {
// Some source control tools don't like it when files containing lines longer
// than, say 8000 characters, are checked in. The linebreak option is used in
// that case to split long lines after a specific column.
i = 0;
int linestartpos = 0;
sb = new StringBuffer(css);
while (i < sb.length()) {
char c = sb.charAt(i++);
if (c == '}' && i - linestartpos > linebreakpos) {
sb.insert(i, '\n');
linestartpos = i;
}
}
css = sb.toString();
}
// Replace multiple semi-colons in a row by a single one
// See SF bug #1980989
css = css.replaceAll(";;+", ";");
// restore preserved comments and strings
for(i = 0, max = preservedTokens.size(); i < max; i++) {
css = css.replace("___YUICSSMIN_PRESERVED_TOKEN_" + i + "___", preservedTokens.get(i).toString());
}
// Trim the final string (for any leading or trailing white spaces)
css = css.trim();
// Write the output...
out.write(css);
}
}
| true | true | public void compress(Writer out, int linebreakpos)
throws IOException {
Pattern p;
Matcher m;
String css = srcsb.toString();
int startIndex = 0;
int endIndex = 0;
int i = 0;
int max = 0;
ArrayList preservedTokens = new ArrayList(0);
ArrayList comments = new ArrayList(0);
String token;
int totallen = css.length();
String placeholder;
css = this.extractDataUrls(css, preservedTokens);
StringBuffer sb = new StringBuffer(css);
// collect all comment blocks...
while ((startIndex = sb.indexOf("/*", startIndex)) >= 0) {
endIndex = sb.indexOf("*/", startIndex + 2);
if (endIndex < 0) {
endIndex = totallen;
}
token = sb.substring(startIndex + 2, endIndex);
comments.add(token);
sb.replace(startIndex + 2, endIndex, "___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + (comments.size() - 1) + "___");
startIndex += 2;
}
css = sb.toString();
// preserve strings so their content doesn't get accidentally minified
sb = new StringBuffer();
p = Pattern.compile("(\"([^\\\\\"]|\\\\.|\\\\)*\")|(\'([^\\\\\']|\\\\.|\\\\)*\')");
m = p.matcher(css);
while (m.find()) {
token = m.group();
char quote = token.charAt(0);
token = token.substring(1, token.length() - 1);
// maybe the string contains a comment-like substring?
// one, maybe more? put'em back then
if (token.indexOf("___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_") >= 0) {
for (i = 0, max = comments.size(); i < max; i += 1) {
token = token.replace("___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + i + "___", comments.get(i).toString());
}
}
// minify alpha opacity in filter strings
token = token.replaceAll("(?i)progid:DXImageTransform.Microsoft.Alpha\\(Opacity=", "alpha(opacity=");
preservedTokens.add(token);
String preserver = quote + "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___" + quote;
m.appendReplacement(sb, preserver);
}
m.appendTail(sb);
css = sb.toString();
// strings are safe, now wrestle the comments
for (i = 0, max = comments.size(); i < max; i += 1) {
token = comments.get(i).toString();
placeholder = "___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + i + "___";
// ! in the first position of the comment means preserve
// so push to the preserved tokens while stripping the !
if (token.startsWith("!")) {
preservedTokens.add(token);
css = css.replace(placeholder, "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___");
continue;
}
// \ in the last position looks like hack for Mac/IE5
// shorten that to /*\*/ and the next one to /**/
if (token.endsWith("\\")) {
preservedTokens.add("\\");
css = css.replace(placeholder, "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___");
i = i + 1; // attn: advancing the loop
preservedTokens.add("");
css = css.replace("___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + i + "___", "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___");
continue;
}
// keep empty comments after child selectors (IE7 hack)
// e.g. html >/**/ body
if (token.length() == 0) {
startIndex = css.indexOf(placeholder);
if (startIndex > 2) {
if (css.charAt(startIndex - 3) == '>') {
preservedTokens.add("");
css = css.replace(placeholder, "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___");
}
}
}
// in all other cases kill the comment
css = css.replace("/*" + placeholder + "*/", "");
}
// Normalize all whitespace strings to single spaces. Easier to work with that way.
css = css.replaceAll("\\s+", " ");
// Remove the spaces before the things that should not have spaces before them.
// But, be careful not to turn "p :link {...}" into "p:link{...}"
// Swap out any pseudo-class colons with the token, and then swap back.
sb = new StringBuffer();
p = Pattern.compile("(^|\\})(([^\\{:])+:)+([^\\{]*\\{)");
m = p.matcher(css);
while (m.find()) {
String s = m.group();
s = s.replaceAll(":", "___YUICSSMIN_PSEUDOCLASSCOLON___");
s = s.replaceAll( "\\\\", "\\\\\\\\" ).replaceAll( "\\$", "\\\\\\$" );
m.appendReplacement(sb, s);
}
m.appendTail(sb);
css = sb.toString();
// Remove spaces before the things that should not have spaces before them.
css = css.replaceAll("\\s+([!{};:>+\\(\\)\\],])", "$1");
// bring back the colon
css = css.replaceAll("___YUICSSMIN_PSEUDOCLASSCOLON___", ":");
// retain space for special IE6 cases
css = css.replaceAll(":first\\-(line|letter)(\\{|,)", ":first-$1 $2");
// no space after the end of a preserved comment
css = css.replaceAll("\\*/ ", "*/");
// If there is a @charset, then only allow one, and push to the top of the file.
css = css.replaceAll("^(.*)(@charset \"[^\"]*\";)", "$2$1");
css = css.replaceAll("^(\\s*@charset [^;]+;\\s*)+", "$1");
// Put the space back in some cases, to support stuff like
// @media screen and (-webkit-min-device-pixel-ratio:0){
css = css.replaceAll("\\band\\(", "and (");
// Remove the spaces after the things that should not have spaces after them.
css = css.replaceAll("([!{}:;>+\\(\\[,])\\s+", "$1");
// remove unnecessary semicolons
css = css.replaceAll(";+}", "}");
// Replace 0(px,em,%) with 0.
css = css.replaceAll("([\\s:])(0)(px|em|%|in|cm|mm|pc|pt|ex)", "$1$2");
// Replace 0 0 0 0; with 0.
css = css.replaceAll(":0 0 0 0(;|})", ":0$1");
css = css.replaceAll(":0 0 0(;|})", ":0$1");
css = css.replaceAll(":0 0(;|})", ":0$1");
// Replace background-position:0; with background-position:0 0;
// same for transform-origin
sb = new StringBuffer();
p = Pattern.compile("(?i)(background-position|webkit-mask-position|transform-origin|webkit-transform-origin|moz-transform-origin|o-transform-origin|ms-transform-origin):0(;|})");
m = p.matcher(css);
while (m.find()) {
m.appendReplacement(sb, m.group(1).toLowerCase() + ":0 0" + m.group(2));
}
m.appendTail(sb);
css = sb.toString();
// Replace 0.6 to .6, but only when preceded by : or a white-space
css = css.replaceAll("(:|\\s)0+\\.(\\d+)", "$1.$2");
// Shorten colors from rgb(51,102,153) to #336699
// This makes it more likely that it'll get further compressed in the next step.
p = Pattern.compile("rgb\\s*\\(\\s*([0-9,\\s]+)\\s*\\)");
m = p.matcher(css);
sb = new StringBuffer();
while (m.find()) {
String[] rgbcolors = m.group(1).split(",");
StringBuffer hexcolor = new StringBuffer("#");
for (i = 0; i < rgbcolors.length; i++) {
int val = Integer.parseInt(rgbcolors[i]);
if (val < 16) {
hexcolor.append("0");
}
hexcolor.append(Integer.toHexString(val));
}
m.appendReplacement(sb, hexcolor.toString());
}
m.appendTail(sb);
css = sb.toString();
// Shorten colors from #AABBCC to #ABC. Note that we want to make sure
// the color is not preceded by either ", " or =. Indeed, the property
// filter: chroma(color="#FFFFFF");
// would become
// filter: chroma(color="#FFF");
// which makes the filter break in IE.
// We also want to make sure we're only compressing #AABBCC patterns inside { }, not id selectors ( #FAABAC {} )
// We also want to avoid compressing invalid values (e.g. #AABBCCD to #ABCD)
p = Pattern.compile("(\\=\\s*?[\"']?)?" + "#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])" + "(:?\\}|[^0-9a-fA-F{][^{]*?\\})");
m = p.matcher(css);
sb = new StringBuffer();
int index = 0;
while (m.find(index)) {
sb.append(css.substring(index, m.start()));
boolean isFilter = (m.group(1) != null && !"".equals(m.group(1)));
if (isFilter) {
// Restore, as is. Compression will break filters
sb.append(m.group(1) + "#" + m.group(2) + m.group(3) + m.group(4) + m.group(5) + m.group(6) + m.group(7));
} else {
if( m.group(2).equalsIgnoreCase(m.group(3)) &&
m.group(4).equalsIgnoreCase(m.group(5)) &&
m.group(6).equalsIgnoreCase(m.group(7))) {
// #AABBCC pattern
sb.append("#" + (m.group(3) + m.group(5) + m.group(7)).toLowerCase());
} else {
// Non-compressible color, restore, but lower case.
sb.append("#" + (m.group(2) + m.group(3) + m.group(4) + m.group(5) + m.group(6) + m.group(7)).toLowerCase());
}
}
index = m.end(7);
}
sb.append(css.substring(index));
css = sb.toString();
// Replace #f00 -> red
css = css.replaceAll("(:|\\s)(#f00)(;|})", "$1red$3");
// Replace other short color keywords
css = css.replaceAll("(:|\\s)(#000080)(;|})", "$1navy$3");
css = css.replaceAll("(:|\\s)(#808080)(;|})", "$1gray$3");
css = css.replaceAll("(:|\\s)(#808000)(;|})", "$1olive$3");
css = css.replaceAll("(:|\\s)(#800080)(;|})", "$1purple$3");
css = css.replaceAll("(:|\\s)(#c0c0c0)(;|})", "$1silver$3");
css = css.replaceAll("(:|\\s)(#008080)(;|})", "$1teal$3");
css = css.replaceAll("(:|\\s)(#ffa500)(;|})", "$1orange$3");
css = css.replaceAll("(:|\\s)(#800000)(;|})", "$1maroon$3");
// border: none -> border:0
sb = new StringBuffer();
p = Pattern.compile("(?i)(border|border-top|border-right|border-bottom|border-left|outline|background):none(;|})");
m = p.matcher(css);
while (m.find()) {
m.appendReplacement(sb, m.group(1).toLowerCase() + ":0" + m.group(2));
}
m.appendTail(sb);
css = sb.toString();
// shorter opacity IE filter
css = css.replaceAll("(?i)progid:DXImageTransform.Microsoft.Alpha\\(Opacity=", "alpha(opacity=");
// Remove empty rules.
css = css.replaceAll("[^\\}\\{/;]+\\{\\}", "");
// TODO: Should this be after we re-insert tokens. These could alter the break points. However then
// we'd need to make sure we don't break in the middle of a string etc.
if (linebreakpos >= 0) {
// Some source control tools don't like it when files containing lines longer
// than, say 8000 characters, are checked in. The linebreak option is used in
// that case to split long lines after a specific column.
i = 0;
int linestartpos = 0;
sb = new StringBuffer(css);
while (i < sb.length()) {
char c = sb.charAt(i++);
if (c == '}' && i - linestartpos > linebreakpos) {
sb.insert(i, '\n');
linestartpos = i;
}
}
css = sb.toString();
}
// Replace multiple semi-colons in a row by a single one
// See SF bug #1980989
css = css.replaceAll(";;+", ";");
// restore preserved comments and strings
for(i = 0, max = preservedTokens.size(); i < max; i++) {
css = css.replace("___YUICSSMIN_PRESERVED_TOKEN_" + i + "___", preservedTokens.get(i).toString());
}
// Trim the final string (for any leading or trailing white spaces)
css = css.trim();
// Write the output...
out.write(css);
}
| public void compress(Writer out, int linebreakpos)
throws IOException {
Pattern p;
Matcher m;
String css = srcsb.toString();
int startIndex = 0;
int endIndex = 0;
int i = 0;
int max = 0;
ArrayList preservedTokens = new ArrayList(0);
ArrayList comments = new ArrayList(0);
String token;
int totallen = css.length();
String placeholder;
css = this.extractDataUrls(css, preservedTokens);
StringBuffer sb = new StringBuffer(css);
// collect all comment blocks...
while ((startIndex = sb.indexOf("/*", startIndex)) >= 0) {
endIndex = sb.indexOf("*/", startIndex + 2);
if (endIndex < 0) {
endIndex = totallen;
}
token = sb.substring(startIndex + 2, endIndex);
comments.add(token);
sb.replace(startIndex + 2, endIndex, "___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + (comments.size() - 1) + "___");
startIndex += 2;
}
css = sb.toString();
// preserve strings so their content doesn't get accidentally minified
sb = new StringBuffer();
p = Pattern.compile("(\"([^\\\\\"]|\\\\.|\\\\)*\")|(\'([^\\\\\']|\\\\.|\\\\)*\')");
m = p.matcher(css);
while (m.find()) {
token = m.group();
char quote = token.charAt(0);
token = token.substring(1, token.length() - 1);
// maybe the string contains a comment-like substring?
// one, maybe more? put'em back then
if (token.indexOf("___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_") >= 0) {
for (i = 0, max = comments.size(); i < max; i += 1) {
token = token.replace("___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + i + "___", comments.get(i).toString());
}
}
// minify alpha opacity in filter strings
token = token.replaceAll("(?i)progid:DXImageTransform.Microsoft.Alpha\\(Opacity=", "alpha(opacity=");
preservedTokens.add(token);
String preserver = quote + "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___" + quote;
m.appendReplacement(sb, preserver);
}
m.appendTail(sb);
css = sb.toString();
// strings are safe, now wrestle the comments
for (i = 0, max = comments.size(); i < max; i += 1) {
token = comments.get(i).toString();
placeholder = "___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + i + "___";
// ! in the first position of the comment means preserve
// so push to the preserved tokens while stripping the !
if (token.startsWith("!")) {
preservedTokens.add(token);
css = css.replace(placeholder, "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___");
continue;
}
// \ in the last position looks like hack for Mac/IE5
// shorten that to /*\*/ and the next one to /**/
if (token.endsWith("\\")) {
preservedTokens.add("\\");
css = css.replace(placeholder, "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___");
i = i + 1; // attn: advancing the loop
preservedTokens.add("");
css = css.replace("___YUICSSMIN_PRESERVE_CANDIDATE_COMMENT_" + i + "___", "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___");
continue;
}
// keep empty comments after child selectors (IE7 hack)
// e.g. html >/**/ body
if (token.length() == 0) {
startIndex = css.indexOf(placeholder);
if (startIndex > 2) {
if (css.charAt(startIndex - 3) == '>') {
preservedTokens.add("");
css = css.replace(placeholder, "___YUICSSMIN_PRESERVED_TOKEN_" + (preservedTokens.size() - 1) + "___");
}
}
}
// in all other cases kill the comment
css = css.replace("/*" + placeholder + "*/", "");
}
// Normalize all whitespace strings to single spaces. Easier to work with that way.
css = css.replaceAll("\\s+", " ");
// Remove the spaces before the things that should not have spaces before them.
// But, be careful not to turn "p :link {...}" into "p:link{...}"
// Swap out any pseudo-class colons with the token, and then swap back.
sb = new StringBuffer();
p = Pattern.compile("(^|\\})(([^\\{:])+:)+([^\\{]*\\{)");
m = p.matcher(css);
while (m.find()) {
String s = m.group();
s = s.replaceAll(":", "___YUICSSMIN_PSEUDOCLASSCOLON___");
s = s.replaceAll( "\\\\", "\\\\\\\\" ).replaceAll( "\\$", "\\\\\\$" );
m.appendReplacement(sb, s);
}
m.appendTail(sb);
css = sb.toString();
// Remove spaces before the things that should not have spaces before them.
css = css.replaceAll("\\s+([!{};:>+\\(\\)\\],])", "$1");
// Restore spaces for !important
css = css.replaceAll("!important", " !important");
// bring back the colon
css = css.replaceAll("___YUICSSMIN_PSEUDOCLASSCOLON___", ":");
// retain space for special IE6 cases
css = css.replaceAll(":first\\-(line|letter)(\\{|,)", ":first-$1 $2");
// no space after the end of a preserved comment
css = css.replaceAll("\\*/ ", "*/");
// If there is a @charset, then only allow one, and push to the top of the file.
css = css.replaceAll("^(.*)(@charset \"[^\"]*\";)", "$2$1");
css = css.replaceAll("^(\\s*@charset [^;]+;\\s*)+", "$1");
// Put the space back in some cases, to support stuff like
// @media screen and (-webkit-min-device-pixel-ratio:0){
css = css.replaceAll("\\band\\(", "and (");
// Remove the spaces after the things that should not have spaces after them.
css = css.replaceAll("([!{}:;>+\\(\\[,])\\s+", "$1");
// remove unnecessary semicolons
css = css.replaceAll(";+}", "}");
// Replace 0(px,em,%) with 0.
css = css.replaceAll("([\\s:])(0)(px|em|%|in|cm|mm|pc|pt|ex)", "$1$2");
// Replace 0 0 0 0; with 0.
css = css.replaceAll(":0 0 0 0(;|})", ":0$1");
css = css.replaceAll(":0 0 0(;|})", ":0$1");
css = css.replaceAll(":0 0(;|})", ":0$1");
// Replace background-position:0; with background-position:0 0;
// same for transform-origin
sb = new StringBuffer();
p = Pattern.compile("(?i)(background-position|webkit-mask-position|transform-origin|webkit-transform-origin|moz-transform-origin|o-transform-origin|ms-transform-origin):0(;|})");
m = p.matcher(css);
while (m.find()) {
m.appendReplacement(sb, m.group(1).toLowerCase() + ":0 0" + m.group(2));
}
m.appendTail(sb);
css = sb.toString();
// Replace 0.6 to .6, but only when preceded by : or a white-space
css = css.replaceAll("(:|\\s)0+\\.(\\d+)", "$1.$2");
// Shorten colors from rgb(51,102,153) to #336699
// This makes it more likely that it'll get further compressed in the next step.
p = Pattern.compile("rgb\\s*\\(\\s*([0-9,\\s]+)\\s*\\)");
m = p.matcher(css);
sb = new StringBuffer();
while (m.find()) {
String[] rgbcolors = m.group(1).split(",");
StringBuffer hexcolor = new StringBuffer("#");
for (i = 0; i < rgbcolors.length; i++) {
int val = Integer.parseInt(rgbcolors[i]);
if (val < 16) {
hexcolor.append("0");
}
hexcolor.append(Integer.toHexString(val));
}
m.appendReplacement(sb, hexcolor.toString());
}
m.appendTail(sb);
css = sb.toString();
// Shorten colors from #AABBCC to #ABC. Note that we want to make sure
// the color is not preceded by either ", " or =. Indeed, the property
// filter: chroma(color="#FFFFFF");
// would become
// filter: chroma(color="#FFF");
// which makes the filter break in IE.
// We also want to make sure we're only compressing #AABBCC patterns inside { }, not id selectors ( #FAABAC {} )
// We also want to avoid compressing invalid values (e.g. #AABBCCD to #ABCD)
p = Pattern.compile("(\\=\\s*?[\"']?)?" + "#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])" + "(:?\\}|[^0-9a-fA-F{][^{]*?\\})");
m = p.matcher(css);
sb = new StringBuffer();
int index = 0;
while (m.find(index)) {
sb.append(css.substring(index, m.start()));
boolean isFilter = (m.group(1) != null && !"".equals(m.group(1)));
if (isFilter) {
// Restore, as is. Compression will break filters
sb.append(m.group(1) + "#" + m.group(2) + m.group(3) + m.group(4) + m.group(5) + m.group(6) + m.group(7));
} else {
if( m.group(2).equalsIgnoreCase(m.group(3)) &&
m.group(4).equalsIgnoreCase(m.group(5)) &&
m.group(6).equalsIgnoreCase(m.group(7))) {
// #AABBCC pattern
sb.append("#" + (m.group(3) + m.group(5) + m.group(7)).toLowerCase());
} else {
// Non-compressible color, restore, but lower case.
sb.append("#" + (m.group(2) + m.group(3) + m.group(4) + m.group(5) + m.group(6) + m.group(7)).toLowerCase());
}
}
index = m.end(7);
}
sb.append(css.substring(index));
css = sb.toString();
// Replace #f00 -> red
css = css.replaceAll("(:|\\s)(#f00)(;|})", "$1red$3");
// Replace other short color keywords
css = css.replaceAll("(:|\\s)(#000080)(;|})", "$1navy$3");
css = css.replaceAll("(:|\\s)(#808080)(;|})", "$1gray$3");
css = css.replaceAll("(:|\\s)(#808000)(;|})", "$1olive$3");
css = css.replaceAll("(:|\\s)(#800080)(;|})", "$1purple$3");
css = css.replaceAll("(:|\\s)(#c0c0c0)(;|})", "$1silver$3");
css = css.replaceAll("(:|\\s)(#008080)(;|})", "$1teal$3");
css = css.replaceAll("(:|\\s)(#ffa500)(;|})", "$1orange$3");
css = css.replaceAll("(:|\\s)(#800000)(;|})", "$1maroon$3");
// border: none -> border:0
sb = new StringBuffer();
p = Pattern.compile("(?i)(border|border-top|border-right|border-bottom|border-left|outline|background):none(;|})");
m = p.matcher(css);
while (m.find()) {
m.appendReplacement(sb, m.group(1).toLowerCase() + ":0" + m.group(2));
}
m.appendTail(sb);
css = sb.toString();
// shorter opacity IE filter
css = css.replaceAll("(?i)progid:DXImageTransform.Microsoft.Alpha\\(Opacity=", "alpha(opacity=");
// Remove empty rules.
css = css.replaceAll("[^\\}\\{/;]+\\{\\}", "");
// TODO: Should this be after we re-insert tokens. These could alter the break points. However then
// we'd need to make sure we don't break in the middle of a string etc.
if (linebreakpos >= 0) {
// Some source control tools don't like it when files containing lines longer
// than, say 8000 characters, are checked in. The linebreak option is used in
// that case to split long lines after a specific column.
i = 0;
int linestartpos = 0;
sb = new StringBuffer(css);
while (i < sb.length()) {
char c = sb.charAt(i++);
if (c == '}' && i - linestartpos > linebreakpos) {
sb.insert(i, '\n');
linestartpos = i;
}
}
css = sb.toString();
}
// Replace multiple semi-colons in a row by a single one
// See SF bug #1980989
css = css.replaceAll(";;+", ";");
// restore preserved comments and strings
for(i = 0, max = preservedTokens.size(); i < max; i++) {
css = css.replace("___YUICSSMIN_PRESERVED_TOKEN_" + i + "___", preservedTokens.get(i).toString());
}
// Trim the final string (for any leading or trailing white spaces)
css = css.trim();
// Write the output...
out.write(css);
}
|
diff --git a/openejb3/container/openejb-core/src/main/java/org/apache/openejb/persistence/JtaEntityManagerRegistry.java b/openejb3/container/openejb-core/src/main/java/org/apache/openejb/persistence/JtaEntityManagerRegistry.java
index 2dfd371f2..98ef0c77e 100644
--- a/openejb3/container/openejb-core/src/main/java/org/apache/openejb/persistence/JtaEntityManagerRegistry.java
+++ b/openejb3/container/openejb-core/src/main/java/org/apache/openejb/persistence/JtaEntityManagerRegistry.java
@@ -1,297 +1,297 @@
/**
*
* 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.openejb.persistence;
import java.util.Map;
import java.util.HashMap;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.TransactionRequiredException;
import javax.transaction.Status;
import javax.transaction.Synchronization;
import javax.transaction.TransactionSynchronizationRegistry;
/**
* The JtaEntityManagerRegistry tracks JTA entity managers for transation and extended scoped
* entity managers. A signle instance of this object should be created and shared by all
* JtaEntityManagers in the server instance. Failure to do this will result in multiple entity
* managers being created for a single persistence until, and that will result in cache
* incoherence.
*/
public class JtaEntityManagerRegistry {
/**
* Registry of transaction associated entity managers.
*/
private final TransactionSynchronizationRegistry transactionRegistry;
/**
* Registry of entended context entity managers.
*/
private final ThreadLocal<ExtendedRegistry> extendedRegistry = new ThreadLocal<ExtendedRegistry>() {
protected ExtendedRegistry initialValue() {
return new ExtendedRegistry();
}
};
/**
* Creates a JtaEntityManagerRegistry using the specified transactionSynchronizationRegistry for the registry
* if transaction associated entity managers.
*/
public JtaEntityManagerRegistry(TransactionSynchronizationRegistry transactionSynchronizationRegistry) {
this.transactionRegistry = transactionSynchronizationRegistry;
}
/**
* Gets an entity manager instance from the transaction registry, extended regitry or for a transaction scoped
* entity manager, creates a new one when an exisitng instance is not found.
* </p>
* It is important that a component adds extended scoped entity managers to this registry when the component is
* entered and removes them when exited. If this registration is not preformed, an IllegalStateException will
* be thrown when entity manger is fetched.
* @param entityManagerFactory the entity manager factory from which an entity manager is required
* @param properties the properties passed to the entity manager factory when an entity manager is created
* @param extended is the entity manager an extended context
* @return the new entity manager
* @throws IllegalStateException if the entity manger is extended and there is not an existing entity manager
* instance already registered
*/
public EntityManager getEntityManager(EntityManagerFactory entityManagerFactory, Map properties, boolean extended) throws IllegalStateException {
if (entityManagerFactory == null) throw new NullPointerException("entityManagerFactory is null");
EntityManagerTxKey txKey = new EntityManagerTxKey(entityManagerFactory);
boolean transactionActive = isTransactionActive();
// if we have an active transaction, check the tx registry
if (transactionActive) {
EntityManager entityManager = (EntityManager) transactionRegistry.getResource(txKey);
if (entityManager != null) {
return entityManager;
}
}
// if extended context, there must be an entity manager already registered with the tx
if (extended) {
EntityManager entityManager = getInheritedEntityManager(entityManagerFactory);
if (entityManager == null) {
- throw new IllegalStateException("InternalError: an entity manager should already be registered for this entended persistence unit");
+ throw new IllegalStateException("InternalError: an entity manager should already be registered for this extended persistence unit");
}
// if transaction is active, we need to register the entity manager with the transaction manager
if (transactionActive) {
entityManager.joinTransaction();
transactionRegistry.putResource(txKey, entityManager);
}
return entityManager;
} else {
// create a new entity manager
EntityManager entityManager;
if (properties != null) {
entityManager = entityManagerFactory.createEntityManager(properties);
} else {
entityManager = entityManagerFactory.createEntityManager();
}
// if we are in a transaction associate the entity manager with the transaction; otherwise it is
// expected the caller will close this entity manager after use
if (transactionActive) {
transactionRegistry.registerInterposedSynchronization(new CloseEntityManager(entityManager));
transactionRegistry.putResource(txKey, entityManager);
}
return entityManager;
}
}
/**
* Adds the entity managers for the specified component to the registry. This should be called when the component
* is entered.
* @param deploymentId the id of the component
* @param entityManagers the entity managers to register
* @throws EntityManagerAlreadyRegisteredException if an entity manager is already registered with the transaction
* for one of the supplied entity manager factories; for EJBs this should be caught and rethown as an EJBException
*/
public void addEntityManagers(String deploymentId, Object primaryKey, Map<EntityManagerFactory, EntityManager> entityManagers) throws EntityManagerAlreadyRegisteredException {
extendedRegistry.get().addEntityManagers(new InstanceId(deploymentId, primaryKey), entityManagers);
}
/**
* Removed the registered entity managers for the specified component.
* @param deploymentId the id of the component
*/
public void removeEntityManagers(String deploymentId, Object primaryKey) {
extendedRegistry.get().removeEntityManagers(new InstanceId(deploymentId, primaryKey));
}
/**
* Gets an exiting extended entity manager created by a component down the call stack.
* @param entityManagerFactory the entity manager factory from which an entity manager is needed
* @return the existing entity manager or null if one is not found
*/
public EntityManager getInheritedEntityManager(EntityManagerFactory entityManagerFactory) {
return extendedRegistry.get().getInheritedEntityManager(entityManagerFactory);
}
/**
* Notifies the registry that a user transaction has been started or the specified component. When a transaction
* is started for a component with registered extended entity managers, the entity managers are enrolled in the
* transaction.
* @param deploymentId the id of the component
*/
public void transactionStarted(String deploymentId, Object primaryKey) {
extendedRegistry.get().transactionStarted(new InstanceId(deploymentId, primaryKey));
}
/**
* Is a transaction active?
* @return true if a transaction is active; false otherwise
*/
public boolean isTransactionActive() {
int txStatus = transactionRegistry.getTransactionStatus();
boolean transactionActive = txStatus == Status.STATUS_ACTIVE || txStatus == Status.STATUS_MARKED_ROLLBACK;
return transactionActive;
}
private class ExtendedRegistry {
private final Map<InstanceId, Map<EntityManagerFactory, EntityManager>> entityManagersByDeploymentId =
new HashMap<InstanceId, Map<EntityManagerFactory, EntityManager>>();
private void addEntityManagers(InstanceId instanceId, Map<EntityManagerFactory, EntityManager> entityManagers) throws EntityManagerAlreadyRegisteredException {
if (instanceId == null) {
throw new NullPointerException("instanceId is null");
}
if (entityManagers == null) {
throw new NullPointerException("entityManagers is null");
}
if (isTransactionActive()) {
for (Map.Entry<EntityManagerFactory, EntityManager> entry : entityManagers.entrySet()) {
EntityManagerFactory entityManagerFactory = entry.getKey();
EntityManager entityManager = entry.getValue();
EntityManagerTxKey txKey = new EntityManagerTxKey(entityManagerFactory);
EntityManager oldEntityManager = (EntityManager) transactionRegistry.getResource(txKey);
if (entityManager == oldEntityManager) {
break;
}
if (oldEntityManager != null) {
throw new EntityManagerAlreadyRegisteredException("Another entity manager is already registered for this persistence unit");
}
entityManager.joinTransaction();
transactionRegistry.putResource(txKey, entityManager);
}
}
entityManagersByDeploymentId.put(instanceId, entityManagers);
}
private void removeEntityManagers(InstanceId instanceId) {
if (instanceId == null) {
throw new NullPointerException("InstanceId is null");
}
entityManagersByDeploymentId.remove(instanceId);
}
private EntityManager getInheritedEntityManager(EntityManagerFactory entityManagerFactory) {
if (entityManagerFactory == null) {
throw new NullPointerException("entityManagerFactory is null");
}
for (Map<EntityManagerFactory, EntityManager> entityManagers : entityManagersByDeploymentId.values()) {
EntityManager entityManager = entityManagers.get(entityManagerFactory);
if (entityManager != null) {
return entityManager;
}
}
return null;
}
private void transactionStarted(InstanceId instanceId) {
if (instanceId == null) {
throw new NullPointerException("instanceId is null");
}
if (!isTransactionActive()) {
throw new TransactionRequiredException();
}
Map<EntityManagerFactory, EntityManager> entityManagers = entityManagersByDeploymentId.get(instanceId);
if (entityManagers == null) {
return;
}
for (Map.Entry<EntityManagerFactory, EntityManager> entry : entityManagers.entrySet()) {
EntityManagerFactory entityManagerFactory = entry.getKey();
EntityManager entityManager = entry.getValue();
entityManager.joinTransaction();
EntityManagerTxKey txKey = new EntityManagerTxKey(entityManagerFactory);
transactionRegistry.putResource(txKey, entityManager);
}
}
}
private static class InstanceId {
private final String deploymentId;
private final Object primaryKey;
public InstanceId(String deploymentId, Object primaryKey) {
if (deploymentId == null) {
throw new NullPointerException("deploymentId is null");
}
if (primaryKey == null) {
throw new NullPointerException("primaryKey is null");
}
this.deploymentId = deploymentId;
this.primaryKey = primaryKey;
}
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final InstanceId that = (InstanceId) o;
return deploymentId.equals(that.deploymentId) &&
primaryKey.equals(that.primaryKey);
}
public int hashCode() {
int result;
result = deploymentId.hashCode();
result = 29 * result + primaryKey.hashCode();
return result;
}
}
private static class CloseEntityManager implements Synchronization {
private final EntityManager entityManager;
public CloseEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
public void beforeCompletion() {
}
public void afterCompletion(int i) {
entityManager.close();
}
}
}
| true | true | public EntityManager getEntityManager(EntityManagerFactory entityManagerFactory, Map properties, boolean extended) throws IllegalStateException {
if (entityManagerFactory == null) throw new NullPointerException("entityManagerFactory is null");
EntityManagerTxKey txKey = new EntityManagerTxKey(entityManagerFactory);
boolean transactionActive = isTransactionActive();
// if we have an active transaction, check the tx registry
if (transactionActive) {
EntityManager entityManager = (EntityManager) transactionRegistry.getResource(txKey);
if (entityManager != null) {
return entityManager;
}
}
// if extended context, there must be an entity manager already registered with the tx
if (extended) {
EntityManager entityManager = getInheritedEntityManager(entityManagerFactory);
if (entityManager == null) {
throw new IllegalStateException("InternalError: an entity manager should already be registered for this entended persistence unit");
}
// if transaction is active, we need to register the entity manager with the transaction manager
if (transactionActive) {
entityManager.joinTransaction();
transactionRegistry.putResource(txKey, entityManager);
}
return entityManager;
} else {
// create a new entity manager
EntityManager entityManager;
if (properties != null) {
entityManager = entityManagerFactory.createEntityManager(properties);
} else {
entityManager = entityManagerFactory.createEntityManager();
}
// if we are in a transaction associate the entity manager with the transaction; otherwise it is
// expected the caller will close this entity manager after use
if (transactionActive) {
transactionRegistry.registerInterposedSynchronization(new CloseEntityManager(entityManager));
transactionRegistry.putResource(txKey, entityManager);
}
return entityManager;
}
}
| public EntityManager getEntityManager(EntityManagerFactory entityManagerFactory, Map properties, boolean extended) throws IllegalStateException {
if (entityManagerFactory == null) throw new NullPointerException("entityManagerFactory is null");
EntityManagerTxKey txKey = new EntityManagerTxKey(entityManagerFactory);
boolean transactionActive = isTransactionActive();
// if we have an active transaction, check the tx registry
if (transactionActive) {
EntityManager entityManager = (EntityManager) transactionRegistry.getResource(txKey);
if (entityManager != null) {
return entityManager;
}
}
// if extended context, there must be an entity manager already registered with the tx
if (extended) {
EntityManager entityManager = getInheritedEntityManager(entityManagerFactory);
if (entityManager == null) {
throw new IllegalStateException("InternalError: an entity manager should already be registered for this extended persistence unit");
}
// if transaction is active, we need to register the entity manager with the transaction manager
if (transactionActive) {
entityManager.joinTransaction();
transactionRegistry.putResource(txKey, entityManager);
}
return entityManager;
} else {
// create a new entity manager
EntityManager entityManager;
if (properties != null) {
entityManager = entityManagerFactory.createEntityManager(properties);
} else {
entityManager = entityManagerFactory.createEntityManager();
}
// if we are in a transaction associate the entity manager with the transaction; otherwise it is
// expected the caller will close this entity manager after use
if (transactionActive) {
transactionRegistry.registerInterposedSynchronization(new CloseEntityManager(entityManager));
transactionRegistry.putResource(txKey, entityManager);
}
return entityManager;
}
}
|
diff --git a/MPAnalyzer/src/jp/ac/osaka_u/ist/sdl/mpanalyzer/gui/rlist/RList.java b/MPAnalyzer/src/jp/ac/osaka_u/ist/sdl/mpanalyzer/gui/rlist/RList.java
index fd90371..ea80c68 100644
--- a/MPAnalyzer/src/jp/ac/osaka_u/ist/sdl/mpanalyzer/gui/rlist/RList.java
+++ b/MPAnalyzer/src/jp/ac/osaka_u/ist/sdl/mpanalyzer/gui/rlist/RList.java
@@ -1,96 +1,103 @@
package jp.ac.osaka_u.ist.sdl.mpanalyzer.gui.rlist;
import java.awt.Color;
import java.awt.GridLayout;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.SortedSet;
import java.util.TreeSet;
import javax.swing.ButtonGroup;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;
import jp.ac.osaka_u.ist.sdl.mpanalyzer.data.Revision;
import jp.ac.osaka_u.ist.sdl.mpanalyzer.db.ReadOnlyDAO;
public class RList extends JPanel {
final public JScrollPane scrollPane;
final ButtonGroup group;
final Map<JRadioButton, Revision> buttonRevisionMap;
public RList() {
super();
this.group = new ButtonGroup();
this.buttonRevisionMap = new HashMap<JRadioButton, Revision>();
try {
final SortedSet<Revision> revisions = new TreeSet<Revision>(
new Comparator<Revision>() {
@Override
public int compare(final Revision r1, final Revision r2) {
if (r1.number < r2.number) {
return 1;
} else if (r1.number > r2.number) {
return -1;
} else {
return 0;
}
}
});
+ final int threshold = 100;
revisions.addAll(ReadOnlyDAO.getInstance().getRevisions());
- this.setLayout(new GridLayout(revisions.size(), 1));
+ this.setLayout(new GridLayout(
+ revisions.size() < threshold ? revisions.size() : threshold,
+ 1));
+ int number = 0;
for (final Revision revision : revisions) {
final StringBuilder text = new StringBuilder();
text.append(revision.number);
text.append(" (");
text.append(revision.date);
text.append(")");
final JRadioButton button = new JRadioButton(text.toString(),
true);
this.group.add(button);
this.add(button);
this.buttonRevisionMap.put(button, revision);
+ if (100 < ++number) {
+ break;
+ }
}
} catch (final Exception e) {
this.add(new JLabel("Error happened in getting revisions."));
}
this.scrollPane = new JScrollPane();
this.scrollPane.setViewportView(this);
this.scrollPane
.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
this.scrollPane
.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
this.scrollPane.setBorder(new TitledBorder(new LineBorder(Color.black),
"Revisions"));
}
public final long getSelectedRevision() {
for (final Entry<JRadioButton, Revision> entry : this.buttonRevisionMap
.entrySet()) {
if (entry.getKey().isSelected()) {
return entry.getValue().number;
}
}
return 0;
// Object[] selectedObjects = this.group.getSelection()
// .getSelectedObjects();
// if (null != selectedObjects) {
// return Long.parseLong((String) selectedObjects[0]);
// } else {
// return 0;
// }
}
}
| false | true | public RList() {
super();
this.group = new ButtonGroup();
this.buttonRevisionMap = new HashMap<JRadioButton, Revision>();
try {
final SortedSet<Revision> revisions = new TreeSet<Revision>(
new Comparator<Revision>() {
@Override
public int compare(final Revision r1, final Revision r2) {
if (r1.number < r2.number) {
return 1;
} else if (r1.number > r2.number) {
return -1;
} else {
return 0;
}
}
});
revisions.addAll(ReadOnlyDAO.getInstance().getRevisions());
this.setLayout(new GridLayout(revisions.size(), 1));
for (final Revision revision : revisions) {
final StringBuilder text = new StringBuilder();
text.append(revision.number);
text.append(" (");
text.append(revision.date);
text.append(")");
final JRadioButton button = new JRadioButton(text.toString(),
true);
this.group.add(button);
this.add(button);
this.buttonRevisionMap.put(button, revision);
}
} catch (final Exception e) {
this.add(new JLabel("Error happened in getting revisions."));
}
this.scrollPane = new JScrollPane();
this.scrollPane.setViewportView(this);
this.scrollPane
.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
this.scrollPane
.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
this.scrollPane.setBorder(new TitledBorder(new LineBorder(Color.black),
"Revisions"));
}
| public RList() {
super();
this.group = new ButtonGroup();
this.buttonRevisionMap = new HashMap<JRadioButton, Revision>();
try {
final SortedSet<Revision> revisions = new TreeSet<Revision>(
new Comparator<Revision>() {
@Override
public int compare(final Revision r1, final Revision r2) {
if (r1.number < r2.number) {
return 1;
} else if (r1.number > r2.number) {
return -1;
} else {
return 0;
}
}
});
final int threshold = 100;
revisions.addAll(ReadOnlyDAO.getInstance().getRevisions());
this.setLayout(new GridLayout(
revisions.size() < threshold ? revisions.size() : threshold,
1));
int number = 0;
for (final Revision revision : revisions) {
final StringBuilder text = new StringBuilder();
text.append(revision.number);
text.append(" (");
text.append(revision.date);
text.append(")");
final JRadioButton button = new JRadioButton(text.toString(),
true);
this.group.add(button);
this.add(button);
this.buttonRevisionMap.put(button, revision);
if (100 < ++number) {
break;
}
}
} catch (final Exception e) {
this.add(new JLabel("Error happened in getting revisions."));
}
this.scrollPane = new JScrollPane();
this.scrollPane.setViewportView(this);
this.scrollPane
.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
this.scrollPane
.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
this.scrollPane.setBorder(new TitledBorder(new LineBorder(Color.black),
"Revisions"));
}
|
diff --git a/src/com/eteks/sweethome3d/tools/ExtensionsClassLoader.java b/src/com/eteks/sweethome3d/tools/ExtensionsClassLoader.java
index 2f49ebf8..1bd6314d 100644
--- a/src/com/eteks/sweethome3d/tools/ExtensionsClassLoader.java
+++ b/src/com/eteks/sweethome3d/tools/ExtensionsClassLoader.java
@@ -1,353 +1,353 @@
/*
* ExtensionsClassLoader.java 2 sept. 2007
*
* Sweet Home 3D, Copyright (c) 2007-2008 Emmanuel PUYBARET / eTeks <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package com.eteks.sweethome3d.tools;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.security.ProtectionDomain;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
/**
* Class loader able to load classes and DLLs with a higher priority from a given set of JARs.
* Its bytecode is Java 1.1 compatible to be loadable by old JVMs.
* @author Emmanuel Puybaret
*/
public class ExtensionsClassLoader extends ClassLoader {
private final ProtectionDomain protectionDomain;
private final String [] applicationPackages;
private final Map extensionDlls = new HashMap();
private JarFile [] extensionJars = null;
/**
* Creates a class loader. It will consider JARs and DLLs of <code>extensionJarsAndDlls</code> accessed as resources
* as classpath and libclasspath elements with a higher priority than the ones of default classpath,
* and will load itself all the classes belonging to packages of <code>applicationPackages</code>.
* No cache will be used.
*/
public ExtensionsClassLoader(ClassLoader parent,
ProtectionDomain protectionDomain,
String [] extensionJarsAndDlls,
String [] applicationPackages) {
this(parent, protectionDomain, extensionJarsAndDlls, new URL [0], applicationPackages, null, null);
}
/**
* Creates a class loader. It will consider JARs and DLLs of <code>extensionJarAndDllResources</code>
* and <code>extensionJarAndDllUrls</code> as classpath and libclasspath elements with a higher priority
* than the ones of default classpath, and will load itself all the classes belonging to packages of
* <code>applicationPackages</code>.<br>
* Copies of <code>extensionJarAndDllResources</code> and <code>extensionJarAndDllUrls</code> will be stored
* in the given cache folder, each file being prefixed by <code>cachedFilesPrefix</code>.
*/
public ExtensionsClassLoader(ClassLoader parent,
ProtectionDomain protectionDomain,
String [] extensionJarAndDllResources,
URL [] extensionJarAndDllUrls,
String [] applicationPackages,
File cacheFolder,
String cachedFilesPrefix) {
super(parent);
this.protectionDomain = protectionDomain;
this.applicationPackages = applicationPackages;
String extensionPrefix = cachedFilesPrefix == null ? "" : cachedFilesPrefix;
// Compute DLLs prefix and suffix
String dllSuffix;
String dllPrefix;
String osName = System.getProperty("os.name");
if (osName.startsWith("Windows")) {
dllSuffix = ".dll";
dllPrefix = "";
} else if (osName.startsWith("Mac OS X")) {
dllSuffix = ".jnilib";
dllPrefix = "lib";
} else {
dllSuffix = ".so";
dllPrefix = "lib";
}
// Create a list containing only URLs
ArrayList extensionJarsAndDlls = new ArrayList();
for (int i = 0; i < extensionJarAndDllResources.length; i++) {
URL extensionJarOrDllUrl = getResource(extensionJarAndDllResources [i]);
if (extensionJarOrDllUrl != null) {
extensionJarsAndDlls.add(extensionJarOrDllUrl);
}
}
extensionJarsAndDlls.addAll(Arrays.asList(extensionJarAndDllUrls));
// Find extension Jars and DLLs
ArrayList extensionJars = new ArrayList();
for (int i = 0; i < extensionJarsAndDlls.size(); i++) {
URL extensionJarOrDllUrl = (URL)extensionJarsAndDlls.get(i);
try {
String extensionJarOrDllUrlFile = extensionJarOrDllUrl.getFile();
URLConnection connection = null;
long extensionJarOrDllFileDate;
String extensionJarOrDllFile;
if (extensionJarOrDllUrl.getProtocol().equals("jar")) {
// Don't instantiate connection to a file accessed by jar protocol otherwise it might download again its jar container
URL jarEntryUrl = new URL(extensionJarOrDllUrlFile.substring(0, extensionJarOrDllUrlFile.indexOf('!')));
URLConnection jarEntryUrlConnection = jarEntryUrl.openConnection();
// As connection.getLastModified() on an entry returns get modification date of the jar file itself
extensionJarOrDllFileDate = jarEntryUrlConnection.getLastModified();
extensionJarOrDllFile = extensionJarOrDllUrlFile.substring(extensionJarOrDllUrlFile.indexOf('!') + 2);
} else {
connection = extensionJarOrDllUrl.openConnection();
extensionJarOrDllFileDate = connection.getLastModified();
extensionJarOrDllFile = extensionJarOrDllUrlFile;
}
String extensionJarOrDllFileName;
int lastSlashIndex = extensionJarOrDllFile.lastIndexOf('/');
if (extensionJarOrDllFile.endsWith(".jar")) {
extensionJarOrDllFileName = extensionPrefix
+ extensionJarOrDllFile.substring(lastSlashIndex + 1);
} else {
extensionJarOrDllFileName = extensionPrefix
+ extensionJarOrDllFile.substring(lastSlashIndex + 1 + dllPrefix.length());
}
if (cacheFolder != null
&& ((cacheFolder.exists()
&& cacheFolder.isDirectory())
|| cacheFolder.mkdirs())) {
try {
File cachedFile = new File(cacheFolder, extensionJarOrDllFileName);
if (!cachedFile.exists()
|| cachedFile.lastModified() < extensionJarOrDllFileDate) {
// Copy jar to cache
if (connection == null) {
connection = extensionJarOrDllUrl.openConnection();
}
copyInputStreamToFile(connection.getInputStream(), cachedFile);
}
if (extensionJarOrDllFile.endsWith(".jar")) {
// Add tmp file to extension jars list
extensionJars.add(new JarFile(cachedFile.toString(), false));
} else if (extensionJarOrDllFile.endsWith(dllSuffix)) {
// Add tmp file to extension DLLs map
this.extensionDlls.put(extensionJarOrDllFileName.substring(extensionPrefix.length(),
extensionJarOrDllFileName.indexOf(dllSuffix)), cachedFile.toString());
}
continue;
} catch (IOException ex) {
// Try without cache
}
}
if (connection == null) {
connection = extensionJarOrDllUrl.openConnection();
}
InputStream input = connection.getInputStream();
if (extensionJarOrDllFile.endsWith(".jar")) {
// Copy jar to a tmp file
String extensionJar = copyInputStreamToTmpFile(input, ".jar");
// Add tmp file to extension jars list
extensionJars.add(new JarFile(extensionJar, false));
} else if (extensionJarOrDllFile.endsWith(dllSuffix)) {
// Copy DLL to a tmp file
String extensionDll = copyInputStreamToTmpFile(input, dllSuffix);
// Add tmp file to extension DLLs map
this.extensionDlls.put(extensionJarOrDllFileName.substring(extensionPrefix.length(),
extensionJarOrDllFileName.indexOf(dllSuffix)), extensionDll);
}
} catch (IOException ex) {
- throw new RuntimeException("Couldn't extract extension jars", ex);
+ throw new RuntimeException("Couldn't extract extension " + extensionJarOrDllUrl, ex);
}
}
// Create extensionJars array
if (extensionJars.size() > 0) {
this.extensionJars = (JarFile [])extensionJars.toArray(new JarFile [extensionJars.size()]);
}
}
/**
* Returns the file name of a temporary copy of <code>input</code> content.
*/
private String copyInputStreamToTmpFile(InputStream input,
String suffix) throws IOException {
File tmpFile = File.createTempFile("extension", suffix);
tmpFile.deleteOnExit();
copyInputStreamToFile(input, tmpFile);
return tmpFile.toString();
}
/**
* Copies the <code>input</code> content to the given file.
*/
public void copyInputStreamToFile(InputStream input, File file) throws FileNotFoundException, IOException {
OutputStream output = null;
try {
output = new BufferedOutputStream(new FileOutputStream(file));
byte [] buffer = new byte [8192];
int size;
while ((size = input.read(buffer)) != -1) {
output.write(buffer, 0, size);
}
} finally {
if (input != null) {
input.close();
}
if (output != null) {
output.close();
}
}
}
/**
* Finds and defines the given class among the extension JARs
* given in constructor, then among resources.
*/
protected Class findClass(String name) throws ClassNotFoundException {
// Build class file from its name
String classFile = name.replace('.', '/') + ".class";
InputStream classInputStream = null;
if (this.extensionJars != null) {
// Check if searched class is an extension class
for (int i = 0; i < this.extensionJars.length; i++) {
JarFile extensionJar = this.extensionJars [i];
JarEntry jarEntry = extensionJar.getJarEntry(classFile);
if (jarEntry != null) {
try {
classInputStream = extensionJar.getInputStream(jarEntry);
} catch (IOException ex) {
throw new ClassNotFoundException("Couldn't read class " + name, ex);
}
}
}
}
// If it's not an extension class, search if its an application
// class that can be read from resources
if (classInputStream == null) {
URL url = getResource(classFile);
if (url == null) {
throw new ClassNotFoundException("Class " + name);
}
try {
classInputStream = url.openStream();
} catch (IOException ex) {
throw new ClassNotFoundException("Couldn't read class " + name, ex);
}
}
try {
// Read class input content to a byte array
ByteArrayOutputStream out = new ByteArrayOutputStream();
BufferedInputStream in = new BufferedInputStream(classInputStream);
byte [] buffer = new byte [8192];
int size;
while ((size = in.read(buffer)) != -1) {
out.write(buffer, 0, size);
}
in.close();
// Define class
return defineClass(name, out.toByteArray(), 0, out.size(),
this.protectionDomain);
} catch (IOException ex) {
throw new ClassNotFoundException("Class " + name, ex);
}
}
/**
* Returns the library path of an extension DLL.
*/
protected String findLibrary(String libname) {
return (String)this.extensionDlls.get(libname);
}
/**
* Returns the URL of the given resource searching first if it exists among
* the extension JARs given in constructor.
*/
protected URL findResource(String name) {
if (this.extensionJars != null) {
// Try to find if resource belongs to one of the extracted jars
for (int i = 0; i < this.extensionJars.length; i++) {
JarFile extensionJar = this.extensionJars [i];
JarEntry jarEntry = extensionJar.getJarEntry(name);
if (jarEntry != null) {
try {
return new URL("jar:file:" + extensionJar.getName() + ":" + jarEntry.getName());
} catch (MalformedURLException ex) {
// Forget that we could have found a resource
}
}
}
}
return super.findResource(name);
}
/**
* Loads a class with this class loader if its package belongs to <code>applicationPackages</code>
* given in constructor.
*/
protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException {
// If no extension jars couldn't be found
if (this.extensionJars == null) {
// Let default class loader do its job
return super.loadClass(name, resolve);
}
// Check if the class has already been loaded
Class loadedClass = findLoadedClass(name);
if (loadedClass == null) {
try {
// Try to find if class belongs to one of the application packages
for (int i = 0; i < this.applicationPackages.length; i++) {
String applicationPackage = this.applicationPackages [i];
int applicationPackageLength = applicationPackage.length();
if ( (applicationPackageLength == 0
&& name.indexOf('.') == 0)
|| (applicationPackageLength > 0
&& name.startsWith(applicationPackage))) {
loadedClass = findClass(name);
break;
}
}
} catch (ClassNotFoundException ex) {
// Let a chance to class to be loaded by default implementation
}
if (loadedClass == null) {
loadedClass = super.loadClass(name, resolve);
}
}
if (resolve) {
resolveClass(loadedClass);
}
return loadedClass;
}
}
| true | true | public ExtensionsClassLoader(ClassLoader parent,
ProtectionDomain protectionDomain,
String [] extensionJarAndDllResources,
URL [] extensionJarAndDllUrls,
String [] applicationPackages,
File cacheFolder,
String cachedFilesPrefix) {
super(parent);
this.protectionDomain = protectionDomain;
this.applicationPackages = applicationPackages;
String extensionPrefix = cachedFilesPrefix == null ? "" : cachedFilesPrefix;
// Compute DLLs prefix and suffix
String dllSuffix;
String dllPrefix;
String osName = System.getProperty("os.name");
if (osName.startsWith("Windows")) {
dllSuffix = ".dll";
dllPrefix = "";
} else if (osName.startsWith("Mac OS X")) {
dllSuffix = ".jnilib";
dllPrefix = "lib";
} else {
dllSuffix = ".so";
dllPrefix = "lib";
}
// Create a list containing only URLs
ArrayList extensionJarsAndDlls = new ArrayList();
for (int i = 0; i < extensionJarAndDllResources.length; i++) {
URL extensionJarOrDllUrl = getResource(extensionJarAndDllResources [i]);
if (extensionJarOrDllUrl != null) {
extensionJarsAndDlls.add(extensionJarOrDllUrl);
}
}
extensionJarsAndDlls.addAll(Arrays.asList(extensionJarAndDllUrls));
// Find extension Jars and DLLs
ArrayList extensionJars = new ArrayList();
for (int i = 0; i < extensionJarsAndDlls.size(); i++) {
URL extensionJarOrDllUrl = (URL)extensionJarsAndDlls.get(i);
try {
String extensionJarOrDllUrlFile = extensionJarOrDllUrl.getFile();
URLConnection connection = null;
long extensionJarOrDllFileDate;
String extensionJarOrDllFile;
if (extensionJarOrDllUrl.getProtocol().equals("jar")) {
// Don't instantiate connection to a file accessed by jar protocol otherwise it might download again its jar container
URL jarEntryUrl = new URL(extensionJarOrDllUrlFile.substring(0, extensionJarOrDllUrlFile.indexOf('!')));
URLConnection jarEntryUrlConnection = jarEntryUrl.openConnection();
// As connection.getLastModified() on an entry returns get modification date of the jar file itself
extensionJarOrDllFileDate = jarEntryUrlConnection.getLastModified();
extensionJarOrDllFile = extensionJarOrDllUrlFile.substring(extensionJarOrDllUrlFile.indexOf('!') + 2);
} else {
connection = extensionJarOrDllUrl.openConnection();
extensionJarOrDllFileDate = connection.getLastModified();
extensionJarOrDllFile = extensionJarOrDllUrlFile;
}
String extensionJarOrDllFileName;
int lastSlashIndex = extensionJarOrDllFile.lastIndexOf('/');
if (extensionJarOrDllFile.endsWith(".jar")) {
extensionJarOrDllFileName = extensionPrefix
+ extensionJarOrDllFile.substring(lastSlashIndex + 1);
} else {
extensionJarOrDllFileName = extensionPrefix
+ extensionJarOrDllFile.substring(lastSlashIndex + 1 + dllPrefix.length());
}
if (cacheFolder != null
&& ((cacheFolder.exists()
&& cacheFolder.isDirectory())
|| cacheFolder.mkdirs())) {
try {
File cachedFile = new File(cacheFolder, extensionJarOrDllFileName);
if (!cachedFile.exists()
|| cachedFile.lastModified() < extensionJarOrDllFileDate) {
// Copy jar to cache
if (connection == null) {
connection = extensionJarOrDllUrl.openConnection();
}
copyInputStreamToFile(connection.getInputStream(), cachedFile);
}
if (extensionJarOrDllFile.endsWith(".jar")) {
// Add tmp file to extension jars list
extensionJars.add(new JarFile(cachedFile.toString(), false));
} else if (extensionJarOrDllFile.endsWith(dllSuffix)) {
// Add tmp file to extension DLLs map
this.extensionDlls.put(extensionJarOrDllFileName.substring(extensionPrefix.length(),
extensionJarOrDllFileName.indexOf(dllSuffix)), cachedFile.toString());
}
continue;
} catch (IOException ex) {
// Try without cache
}
}
if (connection == null) {
connection = extensionJarOrDllUrl.openConnection();
}
InputStream input = connection.getInputStream();
if (extensionJarOrDllFile.endsWith(".jar")) {
// Copy jar to a tmp file
String extensionJar = copyInputStreamToTmpFile(input, ".jar");
// Add tmp file to extension jars list
extensionJars.add(new JarFile(extensionJar, false));
} else if (extensionJarOrDllFile.endsWith(dllSuffix)) {
// Copy DLL to a tmp file
String extensionDll = copyInputStreamToTmpFile(input, dllSuffix);
// Add tmp file to extension DLLs map
this.extensionDlls.put(extensionJarOrDllFileName.substring(extensionPrefix.length(),
extensionJarOrDllFileName.indexOf(dllSuffix)), extensionDll);
}
} catch (IOException ex) {
throw new RuntimeException("Couldn't extract extension jars", ex);
}
}
// Create extensionJars array
if (extensionJars.size() > 0) {
this.extensionJars = (JarFile [])extensionJars.toArray(new JarFile [extensionJars.size()]);
}
}
| public ExtensionsClassLoader(ClassLoader parent,
ProtectionDomain protectionDomain,
String [] extensionJarAndDllResources,
URL [] extensionJarAndDllUrls,
String [] applicationPackages,
File cacheFolder,
String cachedFilesPrefix) {
super(parent);
this.protectionDomain = protectionDomain;
this.applicationPackages = applicationPackages;
String extensionPrefix = cachedFilesPrefix == null ? "" : cachedFilesPrefix;
// Compute DLLs prefix and suffix
String dllSuffix;
String dllPrefix;
String osName = System.getProperty("os.name");
if (osName.startsWith("Windows")) {
dllSuffix = ".dll";
dllPrefix = "";
} else if (osName.startsWith("Mac OS X")) {
dllSuffix = ".jnilib";
dllPrefix = "lib";
} else {
dllSuffix = ".so";
dllPrefix = "lib";
}
// Create a list containing only URLs
ArrayList extensionJarsAndDlls = new ArrayList();
for (int i = 0; i < extensionJarAndDllResources.length; i++) {
URL extensionJarOrDllUrl = getResource(extensionJarAndDllResources [i]);
if (extensionJarOrDllUrl != null) {
extensionJarsAndDlls.add(extensionJarOrDllUrl);
}
}
extensionJarsAndDlls.addAll(Arrays.asList(extensionJarAndDllUrls));
// Find extension Jars and DLLs
ArrayList extensionJars = new ArrayList();
for (int i = 0; i < extensionJarsAndDlls.size(); i++) {
URL extensionJarOrDllUrl = (URL)extensionJarsAndDlls.get(i);
try {
String extensionJarOrDllUrlFile = extensionJarOrDllUrl.getFile();
URLConnection connection = null;
long extensionJarOrDllFileDate;
String extensionJarOrDllFile;
if (extensionJarOrDllUrl.getProtocol().equals("jar")) {
// Don't instantiate connection to a file accessed by jar protocol otherwise it might download again its jar container
URL jarEntryUrl = new URL(extensionJarOrDllUrlFile.substring(0, extensionJarOrDllUrlFile.indexOf('!')));
URLConnection jarEntryUrlConnection = jarEntryUrl.openConnection();
// As connection.getLastModified() on an entry returns get modification date of the jar file itself
extensionJarOrDllFileDate = jarEntryUrlConnection.getLastModified();
extensionJarOrDllFile = extensionJarOrDllUrlFile.substring(extensionJarOrDllUrlFile.indexOf('!') + 2);
} else {
connection = extensionJarOrDllUrl.openConnection();
extensionJarOrDllFileDate = connection.getLastModified();
extensionJarOrDllFile = extensionJarOrDllUrlFile;
}
String extensionJarOrDllFileName;
int lastSlashIndex = extensionJarOrDllFile.lastIndexOf('/');
if (extensionJarOrDllFile.endsWith(".jar")) {
extensionJarOrDllFileName = extensionPrefix
+ extensionJarOrDllFile.substring(lastSlashIndex + 1);
} else {
extensionJarOrDllFileName = extensionPrefix
+ extensionJarOrDllFile.substring(lastSlashIndex + 1 + dllPrefix.length());
}
if (cacheFolder != null
&& ((cacheFolder.exists()
&& cacheFolder.isDirectory())
|| cacheFolder.mkdirs())) {
try {
File cachedFile = new File(cacheFolder, extensionJarOrDllFileName);
if (!cachedFile.exists()
|| cachedFile.lastModified() < extensionJarOrDllFileDate) {
// Copy jar to cache
if (connection == null) {
connection = extensionJarOrDllUrl.openConnection();
}
copyInputStreamToFile(connection.getInputStream(), cachedFile);
}
if (extensionJarOrDllFile.endsWith(".jar")) {
// Add tmp file to extension jars list
extensionJars.add(new JarFile(cachedFile.toString(), false));
} else if (extensionJarOrDllFile.endsWith(dllSuffix)) {
// Add tmp file to extension DLLs map
this.extensionDlls.put(extensionJarOrDllFileName.substring(extensionPrefix.length(),
extensionJarOrDllFileName.indexOf(dllSuffix)), cachedFile.toString());
}
continue;
} catch (IOException ex) {
// Try without cache
}
}
if (connection == null) {
connection = extensionJarOrDllUrl.openConnection();
}
InputStream input = connection.getInputStream();
if (extensionJarOrDllFile.endsWith(".jar")) {
// Copy jar to a tmp file
String extensionJar = copyInputStreamToTmpFile(input, ".jar");
// Add tmp file to extension jars list
extensionJars.add(new JarFile(extensionJar, false));
} else if (extensionJarOrDllFile.endsWith(dllSuffix)) {
// Copy DLL to a tmp file
String extensionDll = copyInputStreamToTmpFile(input, dllSuffix);
// Add tmp file to extension DLLs map
this.extensionDlls.put(extensionJarOrDllFileName.substring(extensionPrefix.length(),
extensionJarOrDllFileName.indexOf(dllSuffix)), extensionDll);
}
} catch (IOException ex) {
throw new RuntimeException("Couldn't extract extension " + extensionJarOrDllUrl, ex);
}
}
// Create extensionJars array
if (extensionJars.size() > 0) {
this.extensionJars = (JarFile [])extensionJars.toArray(new JarFile [extensionJars.size()]);
}
}
|
diff --git a/spring-social-config/src/main/java/org/springframework/social/config/xml/JdbcConnectionRepositoryElementParser.java b/spring-social-config/src/main/java/org/springframework/social/config/xml/JdbcConnectionRepositoryElementParser.java
index 665ff25..5c38702 100644
--- a/spring-social-config/src/main/java/org/springframework/social/config/xml/JdbcConnectionRepositoryElementParser.java
+++ b/spring-social-config/src/main/java/org/springframework/social/config/xml/JdbcConnectionRepositoryElementParser.java
@@ -1,48 +1,47 @@
/*
* Copyright 2011 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.springframework.social.config.xml;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.BeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.security.crypto.encrypt.Encryptors;
import org.springframework.social.provider.jdbc.JdbcConnectionRepository;
import org.w3c.dom.Element;
public class JdbcConnectionRepositoryElementParser implements BeanDefinitionParser {
public BeanDefinition parse(Element element, ParserContext parserContext) {
- BeanDefinitionBuilder beanBuilder = BeanDefinitionBuilder
-.genericBeanDefinition(JdbcConnectionRepository.class);
+ BeanDefinitionBuilder beanBuilder = BeanDefinitionBuilder.genericBeanDefinition(JdbcConnectionRepository.class);
- String jdbcTemplate = element.getAttribute("jdbc-template");
- beanBuilder.addConstructorArgReference(jdbcTemplate);
+ String dataSource = element.getAttribute("data-source");
+ beanBuilder.addConstructorArgReference(dataSource);
String stringEncryptor = element.getAttribute("string-encryptor");
if (stringEncryptor != null && !stringEncryptor.isEmpty()) {
beanBuilder.addConstructorArgReference(stringEncryptor);
} else {
beanBuilder.addConstructorArgValue(Encryptors.noOpText());
}
AbstractBeanDefinition beanDefinition = beanBuilder.getBeanDefinition();
- parserContext.getRegistry().registerBeanDefinition("accountConnectionRepository", beanDefinition);
+ parserContext.getRegistry().registerBeanDefinition("connectionRepository", beanDefinition);
return beanDefinition;
}
}
| false | true | public BeanDefinition parse(Element element, ParserContext parserContext) {
BeanDefinitionBuilder beanBuilder = BeanDefinitionBuilder
.genericBeanDefinition(JdbcConnectionRepository.class);
String jdbcTemplate = element.getAttribute("jdbc-template");
beanBuilder.addConstructorArgReference(jdbcTemplate);
String stringEncryptor = element.getAttribute("string-encryptor");
if (stringEncryptor != null && !stringEncryptor.isEmpty()) {
beanBuilder.addConstructorArgReference(stringEncryptor);
} else {
beanBuilder.addConstructorArgValue(Encryptors.noOpText());
}
AbstractBeanDefinition beanDefinition = beanBuilder.getBeanDefinition();
parserContext.getRegistry().registerBeanDefinition("accountConnectionRepository", beanDefinition);
return beanDefinition;
}
| public BeanDefinition parse(Element element, ParserContext parserContext) {
BeanDefinitionBuilder beanBuilder = BeanDefinitionBuilder.genericBeanDefinition(JdbcConnectionRepository.class);
String dataSource = element.getAttribute("data-source");
beanBuilder.addConstructorArgReference(dataSource);
String stringEncryptor = element.getAttribute("string-encryptor");
if (stringEncryptor != null && !stringEncryptor.isEmpty()) {
beanBuilder.addConstructorArgReference(stringEncryptor);
} else {
beanBuilder.addConstructorArgValue(Encryptors.noOpText());
}
AbstractBeanDefinition beanDefinition = beanBuilder.getBeanDefinition();
parserContext.getRegistry().registerBeanDefinition("connectionRepository", beanDefinition);
return beanDefinition;
}
|
diff --git a/CoordsServer.java b/CoordsServer.java
index cacf957..ba924e7 100644
--- a/CoordsServer.java
+++ b/CoordsServer.java
@@ -1,62 +1,67 @@
package com.ehalferty.mccoords;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Hashtable;
public class CoordsServer {
// Constants
private static final String CONFIG_FILENAME = "mccoordsserver.cfg";
// Defaults
private static final int DEFAULT_PORT = 1338;
private static final String DEFAULT_PASSWORD = "PA55W0RD";
private ServerSocket ss;
protected static Hashtable<String, Player> players = new Hashtable<String, Player>();
protected static Hashtable<Socket, DataOutputStream> outputStreams = new Hashtable<Socket, DataOutputStream>();
public CoordsServer(int port, String password) throws IOException {
try {
ss = new ServerSocket(port);
} catch (IOException e) {
System.out.println("Could not listen on port " + port);
e.printStackTrace();
}
System.out.println("Listening on " + ss);
while (true) {
Socket s = ss.accept();
System.out.println("Connection from " + s);
new ServerThread(this, s, password);
}
}
- public static void main(String[] args) throws Exception {
+ public static void main(String[] args) {
int port;
String password;
if (args.length == 2) {
port = Integer.parseInt(args[0]);
password = args[1];
} else {
port = DEFAULT_PORT;
password = DEFAULT_PASSWORD;
}
System.out.println("Running on port " + port + " with password " + password);
- new CoordsServer(port, password);
+ try {
+ new CoordsServer(port, password);
+ } catch (IOException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
}
public static void update(String name, int x, int y, int z, String addr) {
System.out.println("Adding coords for player " + name);
players.put(name, new Player(name, addr, x, y, z));
}
}
| false | true | public static void main(String[] args) throws Exception {
int port;
String password;
if (args.length == 2) {
port = Integer.parseInt(args[0]);
password = args[1];
} else {
port = DEFAULT_PORT;
password = DEFAULT_PASSWORD;
}
System.out.println("Running on port " + port + " with password " + password);
new CoordsServer(port, password);
}
| public static void main(String[] args) {
int port;
String password;
if (args.length == 2) {
port = Integer.parseInt(args[0]);
password = args[1];
} else {
port = DEFAULT_PORT;
password = DEFAULT_PASSWORD;
}
System.out.println("Running on port " + port + " with password " + password);
try {
new CoordsServer(port, password);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
|
diff --git a/enzyme-portal/mega-mapper/src/main/java/uk/ac/ebi/ep/mm/MegaJdbcMapper.java b/enzyme-portal/mega-mapper/src/main/java/uk/ac/ebi/ep/mm/MegaJdbcMapper.java
index ca5e997b2..114280895 100644
--- a/enzyme-portal/mega-mapper/src/main/java/uk/ac/ebi/ep/mm/MegaJdbcMapper.java
+++ b/enzyme-portal/mega-mapper/src/main/java/uk/ac/ebi/ep/mm/MegaJdbcMapper.java
@@ -1,419 +1,419 @@
package uk.ac.ebi.ep.mm;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.apache.log4j.Logger;
import uk.ac.ebi.biobabel.util.db.SQLLoader;
/**
* Plain JDBC implementation of {@link MegaMapper}.
* @author rafa
*
*/
public class MegaJdbcMapper implements MegaMapper {
private final Logger LOGGER = Logger.getLogger(MegaJdbcMapper.class);
private Connection con;
private SQLLoader sqlLoader;
public MegaJdbcMapper(Connection con) throws IOException{
this.con = con;
}
/**
* {@inheritDoc}
* <br>
* This implementation prepares the required statements.
*/
public void openMap() throws IOException {
sqlLoader = new SQLLoader(this.getClass(), con);
}
public void writeEntry(Entry entry) throws IOException {
try {
if (existsInMegaMap(entry)) return;
PreparedStatement wEntryStm = sqlLoader.getPreparedStatement(
"--insert.entry", new String[]{ "id" }, (Object) null);
int paramNum = 1;
// wEntryStm.setInt(paramNum++, entry.getId());
wEntryStm.setString(paramNum++, entry.getDbName());
wEntryStm.setString(paramNum++, entry.getEntryId());
if (entry.getEntryName() != null){
wEntryStm.setString(paramNum++, entry.getEntryName());
} else {
wEntryStm.setNull(paramNum++, Types.VARCHAR);
}
wEntryStm.execute();
final ResultSet generatedKeys = wEntryStm.getGeneratedKeys();
if (generatedKeys.next()){
int id = generatedKeys.getInt(1);
entry.setId(id);
- Statement checkMe = generatedKeys.getStatement();
- checkMe.close();
+// Statement checkMe = generatedKeys.getStatement();
+// checkMe.close();
} else {
LOGGER.warn("No generated keys!");
}
generatedKeys.close();
if (entry.getEntryAccessions() != null){
int index = 0;
PreparedStatement wAccStm =
- sqlLoader.getPreparedStatement("--insert.accession");;
+ sqlLoader.getPreparedStatement("--insert.accession");
for (String accession : entry.getEntryAccessions()) {
paramNum = 1;
wAccStm.setInt(paramNum++, entry.getId());
wAccStm.setString(paramNum++, accession);
wAccStm.setInt(paramNum++, index++);
wAccStm.execute();
}
}
} catch (SQLException e) {
throw new IOException(e);
}
}
public void writeEntries(Collection<Entry> entries) throws IOException {
if (entries != null){
for (Entry entry : entries) {
writeEntry(entry);
}
}
}
/**
* {@inheritDoc}
* <br>
* This implementation writes any (or both) of the two linked
* entries in case they don't already exist in the database.
*/
public void writeXref(XRef xref) throws IOException {
try {
// if (existsInMegaMap(xref)) return;
writeEntry(xref.getFromEntry());
writeEntry(xref.getToEntry());
PreparedStatement wXrefStm = sqlLoader.getPreparedStatement(
"--insert.xref", new String[]{ "id" }, (Object) null);
int paramNum = 1;
// wXrefStm.setInt(paramNum++, xref.getId());
wXrefStm.setInt(paramNum++, xref.getFromEntry().getId());
wXrefStm.setString(paramNum++, xref.getRelationship());
wXrefStm.setInt(paramNum++, xref.getToEntry().getId());
wXrefStm.execute();
final ResultSet generatedKeys = wXrefStm.getGeneratedKeys();
if (generatedKeys.next()){
int id = generatedKeys.getInt(1);
xref.setId(id);
} else {
LOGGER.warn("No generated keys!");
}
generatedKeys.close();
} catch (SQLException e){
throw new IOException(e);
}
}
public void writeXrefs(Collection<XRef> xrefs) throws IOException {
if (xrefs != null){
for (XRef xref : xrefs) {
writeXref(xref);
}
}
}
public void write(Collection<Entry> entries, Collection<XRef> xrefs)
throws IOException {
writeEntries(entries);
writeXrefs(xrefs);
}
/**
* Deletes one entry <i>and all the associated accessions and xrefs</i>.
* @param entry
*/
public void deleteEntry(Entry entry){
try {
PreparedStatement dXrefStm =
sqlLoader.getPreparedStatement("--delete.xrefs");
dXrefStm .setInt(1, entry.getId());
dXrefStm.setInt(2, entry.getId());
dXrefStm.execute();
PreparedStatement dAccStm =
sqlLoader.getPreparedStatement("--delete.accessions");
dAccStm .setInt(1, entry.getId());
dAccStm.execute();
PreparedStatement dEntryStm =
sqlLoader.getPreparedStatement("--delete.entry");
dEntryStm .setInt(1, entry.getId());
dEntryStm.execute();
} catch (SQLException e) {
LOGGER.error(entry.getEntryId()
+ " (" + entry.getDbName() + ")", e);
}
}
/**
* Checks if an entry already exists in the database. If so, the
* passed {@link Entry} object is updated with the internal id.
* @param entry
* @return <code>true</code> if the entry exists.
* @throws SQLException
*/
private boolean existsInMegaMap(Entry entry) throws SQLException{
PreparedStatement rEntryStm =
sqlLoader.getPreparedStatement("--entry.by.entryid");
int paramNum = 1;
rEntryStm.setString(paramNum++, entry.getEntryId());
rEntryStm.setString(paramNum++, entry.getDbName());
final ResultSet rs = rEntryStm.executeQuery();
final boolean exists = rs.next();
if (exists){
entry.setId(rs.getInt("id"));
}
rs.close();
return exists;
}
private boolean existsInMegaMap(XRef xref) throws SQLException{
PreparedStatement rXrefStm =
sqlLoader.getPreparedStatement("--xref.by.id");
rXrefStm.setInt(1, xref.getId());
final ResultSet rs = rXrefStm.executeQuery();
final boolean exists = rs.next();
if (exists){
LOGGER.warn("XRef already exists in the database: "
+ xref.toString() + " as " + xref.getId());
xref.setId(rs.getInt("id"));
}
rs.close();
return exists;
}
/**
* Converts an array of database objects into a comma-delimited list of
* single-quoted database names
* @param dbs
* @return
*/
private String dbArrayForQuery(MmDatabase... dbs) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < dbs.length; i++) {
if (sb.length() > 0) sb.append(',');
sb.append('\'').append(dbs[i].name()).append('\'');
}
return sb.toString();
}
private Entry getEntryById(int id) throws SQLException{
Entry entry = null;
PreparedStatement rEntryStm =
sqlLoader.getPreparedStatement("--entry.by.id");
rEntryStm.setInt(1, id);
ResultSet rs = rEntryStm.executeQuery();
if (rs.next()){
entry = new Entry();
entry.setId(id);
entry.setDbName(rs.getString("db_name"));
entry.setEntryId(rs.getString("entry_id"));
entry.setEntryName(rs.getString("entry_name"));
}
rs.close();
return entry;
}
/**
* Builds a list of XRef objects from a result set.
* @param rs
* @return
* @throws SQLException
*/
private List<XRef> buildXref(ResultSet rs) throws SQLException {
List<XRef> xrefs = null;
while (rs.next()){
if (xrefs == null) xrefs = new ArrayList<XRef>();
XRef xref = new XRef();
xref.setId(rs.getInt("id"));
xref.setFromEntry(getEntryById(rs.getInt("from_entry")));
xref.setToEntry(getEntryById(rs.getInt("to_entry")));
xref.setRelationship(rs.getString("relationship"));
xrefs.add(xref);
}
rs.close();
return xrefs;
}
/**
* {@inheritDoc}
* <br>
* Unlike the hibernate implementation, in case of getting more than
* one result this will will be logged as a warning, returning the
* first entry only.
*/
public Entry getEntryForAccession(MmDatabase db, String accession){
Entry entry = null;
try {
PreparedStatement entryForAccessionStm =
sqlLoader.getPreparedStatement("--entry.by.accession");
int paramNum = 1;
entryForAccessionStm .setString(paramNum++, accession);
entryForAccessionStm.setString(paramNum++, db.name());
ResultSet rs = entryForAccessionStm.executeQuery();
if (rs.next()){
entry = new Entry();
entry.setId(rs.getInt("id"));
entry.setDbName(rs.getString("db_name"));
entry.setEntryId(rs.getString("entry_id"));
entry.setEntryName(rs.getString("entry_name"));
// TODO: load accessions?
if (rs.next()){
LOGGER.error("More than one entry for same accession!"
+ accession + " (" + db.name() + ")");
}
}
} catch (SQLException e){
LOGGER.error(accession + " (" + db.name() + ")", e);
}
return entry;
}
public Collection<XRef> getXrefs(Entry entry) {
Collection<XRef> xrefs = null;
try {
if (entry.getId() == null){
// update with value from the database:
existsInMegaMap(entry);
}
if (entry.getId() != null){
PreparedStatement allXrefsByEntryStm =
sqlLoader.getPreparedStatement("--xrefs.all.by.entry");
allXrefsByEntryStm.setInt(1, entry.getId());
allXrefsByEntryStm.setInt(2, entry.getId());
ResultSet rs = allXrefsByEntryStm.executeQuery();
xrefs = buildXref(rs);
} else {
LOGGER.warn(entry.toString() + " not known in the mega-map");
}
} catch (SQLException e){
LOGGER.error(entry.getId(), e);
}
return xrefs;
}
public Collection<XRef> getXrefs(Entry entry, MmDatabase... dbs) {
Collection<XRef> xrefs = null;
try {
if (entry.getId() == null){
// update with value from the database:
existsInMegaMap(entry);
}
if (entry.getId() != null){
PreparedStatement ps = sqlLoader.getPreparedStatement(
"--xrefs.by.entry", dbArrayForQuery(dbs));
int paramNum = 1;
ps.setInt(paramNum++, entry.getId());
ps.setInt(paramNum++, entry.getId());
ResultSet rs = ps.executeQuery();
xrefs = buildXref(rs);
} else {
LOGGER.warn(entry.toString() + " not known in the mega-map");
}
} catch (SQLException e){
LOGGER.error(entry.getId(), e);
}
return xrefs;
}
public Collection<XRef> getXrefs(Collection<Entry> entries,
MmDatabase... dbs) {
// TODO check if a dedicated query is more performant!
Collection<XRef> allXrefs = null;
for (Entry entry : entries) {
Collection<XRef> xrefs = getXrefs(entry, dbs);
if (allXrefs == null) allXrefs = xrefs;
else if (xrefs != null) allXrefs.addAll(xrefs);
}
return allXrefs;
}
public Collection<XRef> getXrefs(MmDatabase db, String accession) {
Collection<XRef> xrefs = null;
try {
PreparedStatement allXrefsByAccStm =
sqlLoader.getPreparedStatement("--xrefs.all.by.accession");
allXrefsByAccStm .setString(1, accession);
allXrefsByAccStm.setString(2, db.name());
xrefs = buildXref(allXrefsByAccStm.executeQuery());
} catch (SQLException e){
LOGGER.error(accession + " (" + db.name() + ")", e);
}
return xrefs;
}
public Collection<XRef> getXrefs(MmDatabase db, String accession,
MmDatabase... xDbs) {
Collection<XRef> xrefs = null;
try {
PreparedStatement ps = sqlLoader.getPreparedStatement(
"--xrefs.by.accession", dbArrayForQuery(xDbs));
ps.setString(1, accession);
ps.setString(2, db.name());
xrefs = buildXref(ps.executeQuery());
} catch (SQLException e) {
LOGGER.error(accession + " (" + xDbs + ")", e);
}
return xrefs;
}
public void handleError() throws IOException {
closeStatements();
}
/**
* {@inheritDoc}
* <br>
* This implementation just closes the prepared statements. Note that the
* connection is not closed, that is the client's responsibility.
*/
public void closeMap() throws IOException {
closeStatements();
}
/**
* @throws IOException
*/
private void closeStatements() throws IOException {
try {
sqlLoader.close();
} catch (SQLException e) {
throw new IOException(e);
}
}
public void commit() throws IOException {
try {
con.commit();
} catch (SQLException e) {
throw new IOException(e);
}
}
public void rollback() throws IOException {
try {
con.rollback();
} catch (SQLException e) {
throw new IOException(e);
}
}
}
| false | true | public void writeEntry(Entry entry) throws IOException {
try {
if (existsInMegaMap(entry)) return;
PreparedStatement wEntryStm = sqlLoader.getPreparedStatement(
"--insert.entry", new String[]{ "id" }, (Object) null);
int paramNum = 1;
// wEntryStm.setInt(paramNum++, entry.getId());
wEntryStm.setString(paramNum++, entry.getDbName());
wEntryStm.setString(paramNum++, entry.getEntryId());
if (entry.getEntryName() != null){
wEntryStm.setString(paramNum++, entry.getEntryName());
} else {
wEntryStm.setNull(paramNum++, Types.VARCHAR);
}
wEntryStm.execute();
final ResultSet generatedKeys = wEntryStm.getGeneratedKeys();
if (generatedKeys.next()){
int id = generatedKeys.getInt(1);
entry.setId(id);
Statement checkMe = generatedKeys.getStatement();
checkMe.close();
} else {
LOGGER.warn("No generated keys!");
}
generatedKeys.close();
if (entry.getEntryAccessions() != null){
int index = 0;
PreparedStatement wAccStm =
sqlLoader.getPreparedStatement("--insert.accession");;
for (String accession : entry.getEntryAccessions()) {
paramNum = 1;
wAccStm.setInt(paramNum++, entry.getId());
wAccStm.setString(paramNum++, accession);
wAccStm.setInt(paramNum++, index++);
wAccStm.execute();
}
}
} catch (SQLException e) {
| public void writeEntry(Entry entry) throws IOException {
try {
if (existsInMegaMap(entry)) return;
PreparedStatement wEntryStm = sqlLoader.getPreparedStatement(
"--insert.entry", new String[]{ "id" }, (Object) null);
int paramNum = 1;
// wEntryStm.setInt(paramNum++, entry.getId());
wEntryStm.setString(paramNum++, entry.getDbName());
wEntryStm.setString(paramNum++, entry.getEntryId());
if (entry.getEntryName() != null){
wEntryStm.setString(paramNum++, entry.getEntryName());
} else {
wEntryStm.setNull(paramNum++, Types.VARCHAR);
}
wEntryStm.execute();
final ResultSet generatedKeys = wEntryStm.getGeneratedKeys();
if (generatedKeys.next()){
int id = generatedKeys.getInt(1);
entry.setId(id);
// Statement checkMe = generatedKeys.getStatement();
// checkMe.close();
} else {
LOGGER.warn("No generated keys!");
}
generatedKeys.close();
if (entry.getEntryAccessions() != null){
int index = 0;
PreparedStatement wAccStm =
sqlLoader.getPreparedStatement("--insert.accession");
for (String accession : entry.getEntryAccessions()) {
paramNum = 1;
wAccStm.setInt(paramNum++, entry.getId());
wAccStm.setString(paramNum++, accession);
wAccStm.setInt(paramNum++, index++);
wAccStm.execute();
}
}
} catch (SQLException e) {
|
diff --git a/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/semantics/CPPVisitor.java b/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/semantics/CPPVisitor.java
index c84e0c7a8..385702854 100644
--- a/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/semantics/CPPVisitor.java
+++ b/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/semantics/CPPVisitor.java
@@ -1,2335 +1,2338 @@
/*******************************************************************************
* Copyright (c) 2004, 2008 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Markus Schorn (Wind River Systems)
* Andrew Ferguson (Symbian)
* Sergey Prigogin (Google)
*******************************************************************************/
package org.eclipse.cdt.internal.core.dom.parser.cpp.semantics;
import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.SemanticUtil.getUltimateType;
import static org.eclipse.cdt.internal.core.dom.parser.cpp.semantics.SemanticUtil.getUltimateTypeUptoPointers;
import org.eclipse.cdt.core.dom.IName;
import org.eclipse.cdt.core.dom.ast.ASTNodeProperty;
import org.eclipse.cdt.core.dom.ast.DOMException;
import org.eclipse.cdt.core.dom.ast.IASTArrayDeclarator;
import org.eclipse.cdt.core.dom.ast.IASTArrayModifier;
import org.eclipse.cdt.core.dom.ast.IASTArraySubscriptExpression;
import org.eclipse.cdt.core.dom.ast.IASTBinaryExpression;
import org.eclipse.cdt.core.dom.ast.IASTCastExpression;
import org.eclipse.cdt.core.dom.ast.IASTCompositeTypeSpecifier;
import org.eclipse.cdt.core.dom.ast.IASTCompoundStatement;
import org.eclipse.cdt.core.dom.ast.IASTConditionalExpression;
import org.eclipse.cdt.core.dom.ast.IASTDeclSpecifier;
import org.eclipse.cdt.core.dom.ast.IASTDeclaration;
import org.eclipse.cdt.core.dom.ast.IASTDeclarationStatement;
import org.eclipse.cdt.core.dom.ast.IASTDeclarator;
import org.eclipse.cdt.core.dom.ast.IASTElaboratedTypeSpecifier;
import org.eclipse.cdt.core.dom.ast.IASTEnumerationSpecifier;
import org.eclipse.cdt.core.dom.ast.IASTExpression;
import org.eclipse.cdt.core.dom.ast.IASTExpressionList;
import org.eclipse.cdt.core.dom.ast.IASTExpressionStatement;
import org.eclipse.cdt.core.dom.ast.IASTFieldReference;
import org.eclipse.cdt.core.dom.ast.IASTForStatement;
import org.eclipse.cdt.core.dom.ast.IASTFunctionCallExpression;
import org.eclipse.cdt.core.dom.ast.IASTFunctionDeclarator;
import org.eclipse.cdt.core.dom.ast.IASTFunctionDefinition;
import org.eclipse.cdt.core.dom.ast.IASTGotoStatement;
import org.eclipse.cdt.core.dom.ast.IASTIdExpression;
import org.eclipse.cdt.core.dom.ast.IASTInitializer;
import org.eclipse.cdt.core.dom.ast.IASTInitializerExpression;
import org.eclipse.cdt.core.dom.ast.IASTLabelStatement;
import org.eclipse.cdt.core.dom.ast.IASTLiteralExpression;
import org.eclipse.cdt.core.dom.ast.IASTName;
import org.eclipse.cdt.core.dom.ast.IASTNamedTypeSpecifier;
import org.eclipse.cdt.core.dom.ast.IASTNode;
import org.eclipse.cdt.core.dom.ast.IASTParameterDeclaration;
import org.eclipse.cdt.core.dom.ast.IASTPointer;
import org.eclipse.cdt.core.dom.ast.IASTPointerOperator;
import org.eclipse.cdt.core.dom.ast.IASTProblem;
import org.eclipse.cdt.core.dom.ast.IASTProblemHolder;
import org.eclipse.cdt.core.dom.ast.IASTSimpleDeclSpecifier;
import org.eclipse.cdt.core.dom.ast.IASTSimpleDeclaration;
import org.eclipse.cdt.core.dom.ast.IASTStandardFunctionDeclarator;
import org.eclipse.cdt.core.dom.ast.IASTStatement;
import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit;
import org.eclipse.cdt.core.dom.ast.IASTTypeId;
import org.eclipse.cdt.core.dom.ast.IASTTypeIdExpression;
import org.eclipse.cdt.core.dom.ast.IASTUnaryExpression;
import org.eclipse.cdt.core.dom.ast.IArrayType;
import org.eclipse.cdt.core.dom.ast.IBasicType;
import org.eclipse.cdt.core.dom.ast.IBinding;
import org.eclipse.cdt.core.dom.ast.ICompositeType;
import org.eclipse.cdt.core.dom.ast.IEnumeration;
import org.eclipse.cdt.core.dom.ast.IEnumerator;
import org.eclipse.cdt.core.dom.ast.IFunction;
import org.eclipse.cdt.core.dom.ast.IFunctionType;
import org.eclipse.cdt.core.dom.ast.ILabel;
import org.eclipse.cdt.core.dom.ast.IParameter;
import org.eclipse.cdt.core.dom.ast.IPointerType;
import org.eclipse.cdt.core.dom.ast.IProblemBinding;
import org.eclipse.cdt.core.dom.ast.IQualifierType;
import org.eclipse.cdt.core.dom.ast.IScope;
import org.eclipse.cdt.core.dom.ast.IType;
import org.eclipse.cdt.core.dom.ast.ITypedef;
import org.eclipse.cdt.core.dom.ast.IVariable;
import org.eclipse.cdt.core.dom.ast.IASTEnumerationSpecifier.IASTEnumerator;
import org.eclipse.cdt.core.dom.ast.cpp.CPPASTVisitor;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTBinaryExpression;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTCompositeTypeSpecifier;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTConstructorChainInitializer;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTConversionName;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTDeclSpecifier;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTDeleteExpression;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTElaboratedTypeSpecifier;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTExplicitTemplateInstantiation;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTFieldReference;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTFunctionDeclarator;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTIfStatement;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTLinkageSpecification;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTLiteralExpression;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTNamedTypeSpecifier;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTNamespaceAlias;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTNamespaceDefinition;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTNewExpression;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTParameterDeclaration;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTPointerToMember;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTQualifiedName;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTReferenceOperator;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTSimpleDeclSpecifier;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTSimpleTypeTemplateParameter;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTSwitchStatement;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTTemplateDeclaration;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTTemplateId;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTTemplateParameter;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTTemplateSpecialization;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTTemplatedTypeTemplateParameter;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTTypeIdExpression;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTTypenameExpression;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTUsingDeclaration;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTUsingDirective;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTWhileStatement;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPBasicType;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPBlockScope;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPClassScope;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPClassTemplate;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPClassType;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPConstructor;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPFunction;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPFunctionScope;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPFunctionType;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPMethod;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPNamespace;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPNamespaceScope;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPPointerToMemberType;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPReferenceType;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPScope;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPSpecialization;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPTemplateNonTypeParameter;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPTemplateParameter;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPTemplateScope;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPUsingDeclaration;
import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTCompositeTypeSpecifier.ICPPASTBaseSpecifier;
import org.eclipse.cdt.core.dom.ast.gnu.IGNUASTCompoundStatementExpression;
import org.eclipse.cdt.core.dom.ast.gnu.cpp.IGPPASTPointer;
import org.eclipse.cdt.core.dom.ast.gnu.cpp.IGPPASTPointerToMember;
import org.eclipse.cdt.core.dom.ast.gnu.cpp.IGPPASTSimpleDeclSpecifier;
import org.eclipse.cdt.core.index.IIndexBinding;
import org.eclipse.cdt.core.parser.util.ArrayUtil;
import org.eclipse.cdt.core.parser.util.CharArrayUtils;
import org.eclipse.cdt.internal.core.dom.parser.ASTInternal;
import org.eclipse.cdt.internal.core.dom.parser.ITypeContainer;
import org.eclipse.cdt.internal.core.dom.parser.ProblemBinding;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTName;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPASTTemplateId;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPArrayType;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPBasicType;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPClassTemplate;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPClassType;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPConstructor;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPConstructorTemplate;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPEnumeration;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPEnumerator;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPField;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPFunction;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPFunctionTemplate;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPFunctionType;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPLabel;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPMethod;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPMethodTemplate;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPNamespace;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPNamespaceAlias;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPParameter;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPPointerToMemberType;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPPointerType;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPQualifierType;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPReferenceType;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPScope;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPTypedef;
import org.eclipse.cdt.internal.core.dom.parser.cpp.CPPVariable;
import org.eclipse.cdt.internal.core.dom.parser.cpp.GPPBasicType;
import org.eclipse.cdt.internal.core.dom.parser.cpp.GPPPointerToMemberType;
import org.eclipse.cdt.internal.core.dom.parser.cpp.GPPPointerType;
import org.eclipse.cdt.internal.core.dom.parser.cpp.ICPPInternalBinding;
import org.eclipse.cdt.internal.core.dom.parser.cpp.ICPPInternalFunction;
import org.eclipse.cdt.internal.core.dom.parser.cpp.ICPPUnknownBinding;
import org.eclipse.cdt.internal.core.index.IIndexScope;
/**
* @author aniefer
*/
public class CPPVisitor {
public static final String SIZE_T = "size_t"; //$NON-NLS-1$
public static final String PTRDIFF_T = "ptrdiff_t"; //$NON-NLS-1$
/**
* @param name
*/
public static IBinding createBinding(IASTName name) {
IASTNode parent = name.getParent();
IBinding binding = null;
if (parent instanceof IASTNamedTypeSpecifier ||
parent instanceof ICPPASTQualifiedName ||
parent instanceof ICPPASTBaseSpecifier ||
parent instanceof ICPPASTConstructorChainInitializer ||
name.getPropertyInParent() == ICPPASTNamespaceAlias.MAPPING_NAME ||
parent instanceof ICPPASTTemplateId) {
binding = CPPSemantics.resolveBinding(name);
if (binding instanceof IProblemBinding && parent instanceof ICPPASTQualifiedName &&
!(parent.getParent() instanceof ICPPASTNamespaceAlias)) {
final ICPPASTQualifiedName qname = (ICPPASTQualifiedName)parent;
final IASTName[] ns = qname.getNames();
if (ns[ns.length - 1] != name)
return binding;
parent = parent.getParent();
if (((IProblemBinding)binding).getID() == IProblemBinding.SEMANTIC_MEMBER_DECLARATION_NOT_FOUND) {
IASTNode node = getContainingBlockItem(name.getParent());
ASTNodeProperty prop= node.getPropertyInParent();
if (prop != IASTCompositeTypeSpecifier.MEMBER_DECLARATION &&
prop != ICPPASTNamespaceDefinition.OWNED_DECLARATION) {
return binding;
}
if (getContainingScope(qname) != getContainingScope(name))
return binding;
}
} else {
return binding;
}
}
if (parent instanceof IASTIdExpression) {
return resolveBinding(parent);
} else if (parent instanceof ICPPASTFieldReference) {
return resolveBinding(parent);
} else if (parent instanceof ICPPASTCompositeTypeSpecifier) {
return createBinding((ICPPASTCompositeTypeSpecifier) parent);
} else if (parent instanceof IASTDeclarator) {
return createBinding((IASTDeclarator) parent);
} else if (parent instanceof ICPPASTElaboratedTypeSpecifier) {
return createBinding((ICPPASTElaboratedTypeSpecifier) parent);
} else if (parent instanceof IASTDeclaration) {
return createBinding((IASTDeclaration) parent);
} else if (parent instanceof IASTEnumerationSpecifier) {
return createBinding((IASTEnumerationSpecifier) parent);
} else if (parent instanceof IASTEnumerator) {
return createBinding((IASTEnumerator) parent);
} else if (parent instanceof IASTGotoStatement) {
return createBinding((IASTGotoStatement) parent);
} else if (parent instanceof IASTLabelStatement) {
return createBinding((IASTLabelStatement) parent);
} else if (parent instanceof ICPPASTTemplateParameter) {
return CPPTemplates.createBinding((ICPPASTTemplateParameter) parent);
}
if (name.toCharArray().length > 0)
return binding;
return null;
}
private static IBinding createBinding(IASTGotoStatement gotoStatement) {
ICPPFunctionScope functionScope = (ICPPFunctionScope) getContainingScope(gotoStatement.getName());
IASTName name = gotoStatement.getName();
IBinding binding;
try {
binding = functionScope.getBinding(name, false);
if (binding == null || !(binding instanceof ILabel)) {
binding = new CPPLabel(name);
ASTInternal.addName(functionScope, name);
}
} catch (DOMException e) {
binding = e.getProblem();
}
return binding;
}
private static IBinding createBinding(IASTLabelStatement labelStatement) {
ICPPFunctionScope functionScope = (ICPPFunctionScope) getContainingScope(labelStatement.getName());
IASTName name = labelStatement.getName();
IBinding binding;
try {
binding = functionScope.getBinding(name, false);
if (binding == null || !(binding instanceof ILabel)) {
binding = new CPPLabel(name);
ASTInternal.addName(functionScope, name);
} else {
((CPPLabel)binding).setLabelStatement(name);
}
} catch (DOMException e) {
binding = e.getProblem();
}
return binding;
}
private static IBinding createBinding(IASTEnumerator enumerator) {
ICPPScope scope = (ICPPScope) getContainingScope(enumerator);
IBinding enumtor;
try {
enumtor = scope.getBinding(enumerator.getName(), false);
if (enumtor == null || !(enumtor instanceof IEnumerator)) {
enumtor = new CPPEnumerator(enumerator.getName());
ASTInternal.addName(scope, enumerator.getName());
}
} catch (DOMException e) {
enumtor = e.getProblem();
}
return enumtor;
}
private static IBinding createBinding(IASTEnumerationSpecifier specifier) {
ICPPScope scope = (ICPPScope) getContainingScope(specifier);
IBinding enumeration;
try {
enumeration = scope.getBinding(specifier.getName(), false);
if (enumeration == null || !(enumeration instanceof IEnumeration)) {
enumeration = new CPPEnumeration(specifier.getName());
ASTInternal.addName(scope, specifier.getName());
}
} catch (DOMException e) {
enumeration = e.getProblem();
}
return enumeration;
}
private static IBinding createBinding(final ICPPASTElaboratedTypeSpecifier elabType) {
final IASTNode parent = elabType.getParent();
IBinding binding = null;
boolean mustBeSimple = true;
boolean isFriend = false;
boolean qualified = false;
IASTName name = elabType.getName();
if (name instanceof ICPPASTQualifiedName) {
qualified = true;
IASTName[] ns = ((ICPPASTQualifiedName)name).getNames();
name = ns[ns.length - 1];
}
if (parent instanceof IASTSimpleDeclaration) {
IASTDeclarator[] dtors = ((IASTSimpleDeclaration)parent).getDeclarators();
ICPPASTDeclSpecifier declSpec = (ICPPASTDeclSpecifier) ((IASTSimpleDeclaration)parent).getDeclSpecifier();
isFriend = declSpec.isFriend() && dtors.length == 0;
if (dtors.length > 0 || isFriend) {
binding = CPPSemantics.resolveBinding(name);
mustBeSimple = !isFriend;
} else {
mustBeSimple = false;
}
} else if (parent instanceof IASTParameterDeclaration ||
parent instanceof IASTDeclaration ||
parent instanceof IASTTypeId) {
binding = CPPSemantics.resolveBinding(elabType.getName());
}
if (binding != null &&
(!(binding instanceof IProblemBinding) ||
((IProblemBinding)binding).getID() != IProblemBinding.SEMANTIC_NAME_NOT_FOUND)) {
return binding;
}
//7.1.5.3-2 ... If name lookup does not find a declaration for the name, the elaborated-type-specifier is ill-formed
//unless it is of the simple form class-key identifier
if (mustBeSimple && elabType.getName() instanceof ICPPASTQualifiedName)
return binding;
boolean template = false;
ICPPScope scope = (ICPPScope) getContainingScope(name);
if (scope instanceof ICPPTemplateScope) {
ICPPScope parentScope = null;
try {
template = true;
parentScope = (ICPPScope) getParentScope(scope, elabType.getTranslationUnit());
} catch (DOMException e1) {
}
scope = parentScope;
}
if (mustBeSimple) {
//3.3.1-5 ... the identifier is declared in the smallest non-class non-function-prototype scope that contains
//the declaration
while (scope instanceof ICPPClassScope || scope instanceof ICPPFunctionScope) {
try {
scope = (ICPPScope) getParentScope(scope, elabType.getTranslationUnit());
} catch (DOMException e1) {
}
}
}
if (scope instanceof ICPPClassScope && isFriend && !qualified) {
try {
while (scope instanceof ICPPClassScope)
scope = (ICPPScope) getParentScope(scope, elabType.getTranslationUnit());
} catch (DOMException e1) {
}
}
try {
if (scope != null) {
binding = scope.getBinding(elabType.getName(), false);
}
if (!(binding instanceof ICPPInternalBinding) || !(binding instanceof ICPPClassType)) {
if (elabType.getKind() != IASTElaboratedTypeSpecifier.k_enum) {
if (template)
binding = new CPPClassTemplate(name);
else
binding = new CPPClassType(name, binding);
ASTInternal.addName(scope, elabType.getName());
}
} else {
((ICPPInternalBinding)binding).addDeclaration(elabType);
}
} catch (DOMException e) {
binding = e.getProblem();
}
return binding;
}
private static IBinding createBinding(ICPPASTCompositeTypeSpecifier compType) {
IASTName name = compType.getName();
if (name instanceof ICPPASTQualifiedName) {
IASTName[] ns = ((ICPPASTQualifiedName)name).getNames();
name = ns[ns.length - 1];
}
ICPPScope scope = (ICPPScope) getContainingScope(name);
boolean template = false;
if (scope instanceof ICPPTemplateScope) {
template = true;
ICPPScope parentScope = null;
try {
parentScope = (ICPPScope) getParentScope(scope, compType.getTranslationUnit());
} catch (DOMException e1) {
}
scope = parentScope;
}
IBinding binding = null;
if (name instanceof ICPPASTTemplateId) {
return CPPTemplates.createClassSpecialization(compType);
}
try {
if (name.toCharArray().length > 0 && scope != null) //can't lookup anonymous things
binding = scope.getBinding(name, false);
if (!(binding instanceof ICPPInternalBinding) || !(binding instanceof ICPPClassType)) {
if (template) {
binding = new CPPClassTemplate(name);
} else {
binding = new CPPClassType(name, binding);
}
if (scope != null) {
ASTInternal.addName(scope, compType.getName());
}
} else {
ICPPInternalBinding internal = (ICPPInternalBinding) binding;
if (internal.getDefinition() == null) {
internal.addDefinition(compType);
} else {
binding = new ProblemBinding(name,
IProblemBinding.SEMANTIC_INVALID_REDEFINITION, name.toCharArray());
}
}
} catch (DOMException e) {
binding = e.getProblem();
}
return binding;
}
private static IBinding createBinding(IASTDeclaration declaration) {
if (declaration instanceof ICPPASTNamespaceDefinition) {
ICPPASTNamespaceDefinition namespaceDef = (ICPPASTNamespaceDefinition) declaration;
ICPPScope scope = (ICPPScope) getContainingScope(namespaceDef);
IBinding binding;
try {
binding = scope.getBinding(namespaceDef.getName(), false);
if (!(binding instanceof ICPPInternalBinding) || binding instanceof IProblemBinding
|| !(binding instanceof ICPPNamespace)) {
binding = new CPPNamespace(namespaceDef);
ASTInternal.addName(scope, namespaceDef.getName());
}
} catch (DOMException e) {
binding = e.getProblem();
}
return binding;
} else if (declaration instanceof ICPPASTUsingDirective) {
return CPPSemantics.resolveBinding(((ICPPASTUsingDirective) declaration).getQualifiedName());
} else if (declaration instanceof ICPPASTNamespaceAlias) {
ICPPASTNamespaceAlias alias = (ICPPASTNamespaceAlias) declaration;
ICPPScope scope = (ICPPScope) getContainingScope(declaration);
IBinding binding;
try {
binding = scope.getBinding(alias.getAlias(), false);
if (!(binding instanceof ICPPInternalBinding)) {
IBinding namespace = alias.getMappingName().resolveBinding();
if (namespace instanceof IProblemBinding) {
IProblemBinding problem = (IProblemBinding) namespace;
namespace = new CPPNamespace.CPPNamespaceProblem(problem.getASTNode(),
problem.getID(), alias.getMappingName().toCharArray());
}
if (namespace instanceof ICPPNamespace) {
binding = new CPPNamespaceAlias(alias.getAlias(), (ICPPNamespace) namespace);
ASTInternal.addName(scope, alias.getAlias());
} else {
binding = new ProblemBinding(alias.getAlias(),
IProblemBinding.SEMANTIC_NAME_NOT_FOUND, alias.getAlias().toCharArray());
}
}
} catch(DOMException e) {
binding = e.getProblem();
}
return binding;
}
return null;
}
private static IBinding createBinding(IASTDeclarator declarator) {
IASTNode parent = declarator.getParent();
while (parent instanceof IASTDeclarator) {
parent = parent.getParent();
}
while (declarator.getNestedDeclarator() != null)
declarator = declarator.getNestedDeclarator();
IASTFunctionDeclarator funcDeclarator= null;
IASTNode tmpNode= declarator;
do {
if (tmpNode instanceof IASTFunctionDeclarator) {
funcDeclarator= (IASTFunctionDeclarator) tmpNode;
break;
}
if (((IASTDeclarator) tmpNode).getPointerOperators().length > 0 ||
tmpNode.getPropertyInParent() != IASTDeclarator.NESTED_DECLARATOR) {
break;
}
tmpNode= tmpNode.getParent();
}
while (tmpNode instanceof IASTDeclarator);
IASTName name = declarator.getName();
if (name instanceof ICPPASTQualifiedName) {
IASTName[] ns = ((ICPPASTQualifiedName)name).getNames();
name = ns[ns.length - 1];
}
ASTNodeProperty prop = parent.getPropertyInParent();
if (parent instanceof IASTTypeId) {
return CPPSemantics.resolveBinding(name);
} else if (prop == ICPPASTTemplateSpecialization.OWNED_DECLARATION ||
prop == ICPPASTExplicitTemplateInstantiation.OWNED_DECLARATION) {
return CPPTemplates.createFunctionSpecialization(name);
} else if (prop == ICPPASTTemplateDeclaration.PARAMETER) {
return CPPTemplates.createBinding((ICPPASTTemplateParameter) parent);
}
boolean template = false;
ICPPScope scope = (ICPPScope) getContainingScope((IASTNode) name);
if (scope instanceof ICPPTemplateScope) {
ICPPScope parentScope = null;
try {
template = true;
parentScope = (ICPPScope) getParentScope(scope, name.getTranslationUnit());
} catch (DOMException e1) {
}
scope = parentScope;
}
if (parent instanceof IASTSimpleDeclaration && scope instanceof ICPPClassScope) {
ICPPASTDeclSpecifier declSpec = (ICPPASTDeclSpecifier) ((IASTSimpleDeclaration)parent).getDeclSpecifier();
if (declSpec.isFriend()) {
try {
scope = (ICPPScope) getParentScope(scope, name.getTranslationUnit());
} catch (DOMException e1) {
}
}
}
IBinding binding;
try {
binding = (scope != null) ? scope.getBinding(name, false) : null;
} catch (DOMException e) {
binding = null;
}
IASTSimpleDeclaration simpleDecl = (parent instanceof IASTSimpleDeclaration) ?
(IASTSimpleDeclaration)parent : null;
if (parent instanceof ICPPASTParameterDeclaration) {
ICPPASTParameterDeclaration param = (ICPPASTParameterDeclaration) parent;
parent = param.getParent();
if (parent instanceof IASTStandardFunctionDeclarator) {
IASTStandardFunctionDeclarator fDtor = (IASTStandardFunctionDeclarator) param.getParent();
if (hasNestedPointerOperator(fDtor))
return null;
IBinding temp = fDtor.getName().resolveBinding();
if (temp instanceof ICPPInternalFunction) {
binding = ((ICPPInternalFunction) temp).resolveParameter(param);
} else if (temp instanceof IProblemBinding) {
//problems with the function, still create binding for the parameter
binding = new CPPParameter(name);
} else if (temp instanceof IIndexBinding) {
binding= new CPPParameter(name);
}
} else if (parent instanceof ICPPASTTemplateDeclaration) {
return CPPTemplates.createBinding(param);
}
} else if (simpleDecl != null &&
simpleDecl.getDeclSpecifier().getStorageClass() == IASTDeclSpecifier.sc_typedef) {
if (binding instanceof ICPPInternalBinding && binding instanceof ITypedef) {
try {
IType t1 = ((ITypedef)binding).getType();
IType t2 = createType(declarator);
if (t1 != null && t2 != null && t1.isSameType(t2)) {
ICPPInternalBinding internal = (ICPPInternalBinding) binding;
internal.addDeclaration(name);
return binding;
}
} catch (DOMException e1) {
return e1.getProblem();
}
return new ProblemBinding(name, IProblemBinding.SEMANTIC_INVALID_REDECLARATION, name.toCharArray());
}
binding = new CPPTypedef(name);
} else if (funcDeclarator != null) {
if (binding instanceof ICPPInternalBinding && binding instanceof IFunction) {
IFunction function = (IFunction) binding;
if (CPPSemantics.isSameFunction(function, funcDeclarator)) {
ICPPInternalBinding internal = (ICPPInternalBinding) function;
if (parent instanceof IASTSimpleDeclaration) {
internal.addDeclaration(name);
} else if (internal.getDefinition() == null) {
internal.addDefinition(name);
} else {
IASTNode def = internal.getDefinition();
if (def instanceof IASTDeclarator)
def = ((IASTDeclarator)def).getName();
if (def != name) {
return new ProblemBinding(name,
IProblemBinding.SEMANTIC_INVALID_REDEFINITION, name.toCharArray());
}
}
return function;
}
}
if (binding instanceof IIndexBinding) {
ICPPASTTemplateDeclaration templateDecl = CPPTemplates.getTemplateDeclaration(name);
if (templateDecl != null) {
ICPPASTTemplateParameter[] params = templateDecl.getTemplateParameters();
for (ICPPASTTemplateParameter param : params) {
IASTName paramName = CPPTemplates.getTemplateParameterName(param);
paramName.setBinding(null);
//unsetting the index bindings so that they
//can be re-resolved with normal bindings
}
}
}
if (scope instanceof ICPPClassScope) {
if (isConstructor(scope, funcDeclarator)) {
binding = template ? (ICPPConstructor) new CPPConstructorTemplate(name)
: new CPPConstructor((ICPPASTFunctionDeclarator) funcDeclarator);
} else {
binding = template ? (ICPPMethod) new CPPMethodTemplate(name)
: new CPPMethod((ICPPASTFunctionDeclarator) funcDeclarator);
}
} else {
binding = template ? (ICPPFunction) new CPPFunctionTemplate(name)
: new CPPFunction((ICPPASTFunctionDeclarator) funcDeclarator);
}
} else if (parent instanceof IASTSimpleDeclaration) {
IType t1 = null, t2 = null;
if (binding != null && binding instanceof IVariable && !(binding instanceof IIndexBinding)) {
t1 = createType(declarator);
try {
t2 = ((IVariable)binding).getType();
} catch (DOMException e1) {
}
}
if (t1 != null && t2 != null) {
if (t1.isSameType(t2)) {
if (binding instanceof ICPPInternalBinding)
((ICPPInternalBinding)binding).addDeclaration(name);
} else {
binding = new ProblemBinding(name, IProblemBinding.SEMANTIC_INVALID_REDECLARATION, declarator.getName().toCharArray());
}
} else if (simpleDecl != null && simpleDecl.getParent() instanceof ICPPASTCompositeTypeSpecifier) {
binding = new CPPField(name);
} else {
binding = new CPPVariable(name);
}
}
if (scope != null && binding != null) {
try {
ASTInternal.addName(scope, name);
} catch (DOMException e1) {
}
}
return binding;
}
private static boolean hasNestedPointerOperator(IASTDeclarator decl) {
decl= decl.getNestedDeclarator();
while (decl != null) {
if (decl.getPointerOperators().length > 0) {
return true;
}
decl= decl.getNestedDeclarator();
}
return false;
}
public static boolean isConstructor(IScope containingScope, IASTDeclarator declarator) {
if (containingScope == null || !(containingScope instanceof ICPPClassScope))
return false;
ICPPASTCompositeTypeSpecifier clsTypeSpec;
try {
IASTNode node = ASTInternal.getPhysicalNodeOfScope(containingScope);
if (node instanceof ICPPASTCompositeTypeSpecifier)
clsTypeSpec = (ICPPASTCompositeTypeSpecifier)node;
else
return false;
} catch (DOMException e) {
return false;
}
IASTName clsName = clsTypeSpec.getName();
if (clsName instanceof ICPPASTQualifiedName) {
IASTName[] names = ((ICPPASTQualifiedName)clsName).getNames();
clsName = names[names.length - 1];
}
return isConstructor(clsName, declarator);
}
public static boolean isConstructor(IASTName parentName, IASTDeclarator declarator) {
if (declarator == null || !(declarator instanceof IASTFunctionDeclarator))
return false;
IASTName name = declarator.getName();
if (name instanceof ICPPASTQualifiedName) {
IASTName[] names = ((ICPPASTQualifiedName)name).getNames();
name = names[names.length - 1];
}
if (!CharArrayUtils.equals(name.toCharArray(), parentName.toCharArray()))
return false;
IASTDeclSpecifier declSpec = null;
IASTNode parent = declarator.getParent();
if (parent instanceof IASTSimpleDeclaration) {
declSpec = ((IASTSimpleDeclaration)parent).getDeclSpecifier();
} else if (parent instanceof IASTFunctionDefinition) {
declSpec = ((IASTFunctionDefinition)parent).getDeclSpecifier();
}
if (declSpec != null && declSpec instanceof IASTSimpleDeclSpecifier) {
return (((IASTSimpleDeclSpecifier)declSpec).getType() == IASTSimpleDeclSpecifier.t_unspecified);
}
return false;
}
public static IScope getContainingScope(final IASTNode inputNode) {
if (inputNode == null || inputNode instanceof IASTTranslationUnit)
return null;
IASTNode node= inputNode;
while (node != null) {
if (node instanceof IASTName && !(node instanceof ICPPASTQualifiedName)) {
return getContainingScope((IASTName) node);
}
if (node instanceof IASTDeclaration) {
IASTNode parent = node.getParent();
if (parent instanceof IASTTranslationUnit) {
return ((IASTTranslationUnit)parent).getScope();
} else if (parent instanceof IASTDeclarationStatement) {
return getContainingScope((IASTStatement) parent);
} else if (parent instanceof IASTForStatement) {
return ((IASTForStatement)parent).getScope();
} else if (parent instanceof IASTCompositeTypeSpecifier) {
return ((IASTCompositeTypeSpecifier)parent).getScope();
} else if (parent instanceof ICPPASTNamespaceDefinition) {
return ((ICPPASTNamespaceDefinition)parent).getScope();
} else if (parent instanceof ICPPASTSwitchStatement) {
return ((ICPPASTSwitchStatement)parent).getScope();
} else if (parent instanceof ICPPASTIfStatement) {
return ((ICPPASTIfStatement)parent).getScope();
} else if (parent instanceof ICPPASTWhileStatement) {
return ((ICPPASTWhileStatement)parent).getScope();
} else if (parent instanceof ICPPASTTemplateDeclaration) {
return ((ICPPASTTemplateDeclaration)parent).getScope();
}
} else if (node instanceof IASTStatement) {
return getContainingScope((IASTStatement) node);
} else if (node instanceof IASTTypeId) {
if (node.getPropertyInParent() == ICPPASTTemplateId.TEMPLATE_ID_ARGUMENT) {
ICPPASTTemplateDeclaration decl = CPPTemplates.getTemplateDeclaration((IASTName) node.getParent());
if (decl == null) {
node = node.getParent();
while (node instanceof IASTName)
node = node.getParent();
continue;
}
}
} else if (node instanceof IASTParameterDeclaration) {
IASTNode parent = node.getParent();
if (parent instanceof ICPPASTFunctionDeclarator) {
ICPPASTFunctionDeclarator dtor = (ICPPASTFunctionDeclarator) parent;
if (dtor.getNestedDeclarator() == null || dtor.getNestedDeclarator().getPointerOperators().length == 0) {
while (parent.getParent() instanceof IASTDeclarator)
parent = parent.getParent();
ASTNodeProperty prop = parent.getPropertyInParent();
if (prop == IASTSimpleDeclaration.DECLARATOR)
return dtor.getFunctionScope();
else if (prop == IASTFunctionDefinition.DECLARATOR)
return ((IASTCompoundStatement)((IASTFunctionDefinition)parent.getParent()).getBody()).getScope();
}
} else if (parent instanceof ICPPASTTemplateDeclaration) {
return CPPTemplates.getContainingScope(node);
}
} else if (node instanceof IASTInitializerExpression) {
IASTNode parent = node.getParent();
while (!(parent instanceof IASTDeclarator))
parent = parent.getParent();
IASTDeclarator dtor = (IASTDeclarator) parent;
IASTName name = dtor.getName();
if (name instanceof ICPPASTQualifiedName) {
IASTName[] ns = ((ICPPASTQualifiedName)name).getNames();
return getContainingScope(ns[ns.length - 1]);
}
} else if (node instanceof IASTExpression) {
IASTNode parent = node.getParent();
if (parent instanceof IASTForStatement) {
return ((IASTForStatement)parent).getScope();
} else if (parent instanceof ICPPASTIfStatement) {
return ((ICPPASTIfStatement)parent).getScope();
} else if (parent instanceof ICPPASTSwitchStatement) {
return ((ICPPASTSwitchStatement)parent).getScope();
} else if (parent instanceof ICPPASTWhileStatement) {
return ((ICPPASTWhileStatement)parent).getScope();
} else if (parent instanceof IASTCompoundStatement) {
return ((IASTCompoundStatement)parent).getScope();
} else if (parent instanceof ICPPASTConstructorChainInitializer) {
IASTNode temp = getContainingBlockItem(parent.getParent());
if (temp instanceof IASTFunctionDefinition) {
IASTCompoundStatement body = (IASTCompoundStatement) ((IASTFunctionDefinition)temp).getBody();
return body.getScope();
}
} else if (parent instanceof IASTArrayModifier || parent instanceof IASTInitializer) {
IASTNode d = parent.getParent();
while (!(d instanceof IASTDeclarator))
d = d.getParent();
IASTDeclarator dtor = (IASTDeclarator) d;
while (dtor.getNestedDeclarator() != null)
dtor = dtor.getNestedDeclarator();
IASTName name = dtor.getName();
if (name instanceof ICPPASTQualifiedName) {
IASTName[] ns = ((ICPPASTQualifiedName)name).getNames();
return getContainingScope(ns[ns.length - 1]);
}
}
} else if (node instanceof ICPPASTTemplateParameter) {
return CPPTemplates.getContainingScope(node);
} else if (node instanceof ICPPASTBaseSpecifier) {
ICPPASTCompositeTypeSpecifier compSpec = (ICPPASTCompositeTypeSpecifier) node.getParent();
IASTName n = compSpec.getName();
if (n instanceof ICPPASTQualifiedName) {
IASTName[] ns = ((ICPPASTQualifiedName)n).getNames();
n = ns[ns.length - 1];
}
return CPPVisitor.getContainingScope(n);
}
node = node.getParent();
}
return new CPPScope.CPPScopeProblem(inputNode, IProblemBinding.SEMANTIC_BAD_SCOPE,
inputNode.getRawSignature().toCharArray());
}
public static IScope getContainingScope(IASTName name) {
IScope scope= getContainingScopeOrNull(name);
if (scope == null) {
return new CPPScope.CPPScopeProblem(name, IProblemBinding.SEMANTIC_BAD_SCOPE,
name == null ? CharArrayUtils.EMPTY : name.toCharArray());
}
return scope;
}
private static IScope getContainingScopeOrNull(IASTName name) {
if (name == null) {
return null;
}
IASTNode parent = name.getParent();
try {
if (parent instanceof ICPPASTTemplateId) {
name = (IASTName) parent;
parent = name.getParent();
}
ICPPASTTemplateDeclaration tmplDecl = CPPTemplates.getTemplateDeclaration(name);
if (tmplDecl != null)
return tmplDecl.getScope();
if (parent instanceof ICPPASTQualifiedName) {
final ICPPASTQualifiedName qname= (ICPPASTQualifiedName) parent;
final IASTName[] names = qname.getNames();
int i = 0;
for (; i < names.length; i++) {
if (names[i] == name) break;
}
if (i == 0) {
if (qname.isFullyQualified()) {
return parent.getTranslationUnit().getScope();
}
for (int j=1; j < names.length; j++) {
tmplDecl = CPPTemplates.getTemplateDeclaration(names[j]);
if (tmplDecl != null) {
return getContainingScope(tmplDecl);
}
}
}
if (i > 0) {
IBinding binding = names[i-1].resolveBinding();
while (binding instanceof ITypedef) {
IType t = ((ITypedef)binding).getType();
if (t instanceof IBinding)
binding = (IBinding) t;
else break;
}
boolean done= true;
IScope scope= null;
if (binding instanceof ICPPClassType) {
scope= ((ICPPClassType)binding).getCompositeScope();
} else if (binding instanceof ICPPNamespace) {
scope= ((ICPPNamespace)binding).getNamespaceScope();
} else if (binding instanceof ICPPUnknownBinding) {
scope= ((ICPPUnknownBinding)binding).getUnknownScope();
} else if (binding instanceof IProblemBinding) {
if (binding instanceof ICPPScope)
scope= (IScope) binding;
} else {
done= false;
}
if (done) {
if (scope == null) {
return new CPPScope.CPPScopeProblem(names[i - 1],
IProblemBinding.SEMANTIC_BAD_SCOPE, names[i-1].toCharArray());
}
return scope;
}
}
} else if (parent instanceof ICPPASTFieldReference) {
final ICPPASTFieldReference fieldReference = (ICPPASTFieldReference)parent;
IASTExpression owner = fieldReference.getFieldOwner();
IType type = getExpressionType(owner);
if (fieldReference.isPointerDereference()) {
type= getUltimateTypeUptoPointers(type);
if (type instanceof ICPPClassType) {
ICPPFunction op = CPPSemantics.findOperator(fieldReference, (ICPPClassType) type);
if (op != null) {
type = op.getType().getReturnType();
}
}
}
type = getUltimateType(type, false);
if (type instanceof ICPPClassType) {
return ((ICPPClassType) type).getCompositeScope();
}
} else if (parent instanceof IASTGotoStatement || parent instanceof IASTLabelStatement) {
while (!(parent instanceof IASTFunctionDefinition)) {
parent = parent.getParent();
}
IASTFunctionDefinition fdef = (IASTFunctionDefinition) parent;
return ((ICPPASTFunctionDeclarator)fdef.getDeclarator()).getFunctionScope();
}
} catch(DOMException e) {
IProblemBinding problem = e.getProblem();
if (problem instanceof ICPPScope)
return problem;
return new CPPScope.CPPScopeProblem(problem.getASTNode(), problem.getID(), problem.getNameCharArray());
}
return getContainingScope(parent);
}
public static IScope getContainingScope(IASTStatement statement) {
IASTNode parent = statement.getParent();
IScope scope = null;
if (parent instanceof IASTCompoundStatement) {
IASTCompoundStatement compound = (IASTCompoundStatement) parent;
scope = compound.getScope();
} else if (parent instanceof IASTForStatement) {
scope = ((IASTForStatement)parent).getScope();
} else if (parent instanceof ICPPASTSwitchStatement) {
scope = ((ICPPASTSwitchStatement)parent).getScope();
} else if (parent instanceof ICPPASTIfStatement) {
scope = ((ICPPASTIfStatement)parent).getScope();
} else if (parent instanceof ICPPASTWhileStatement) {
scope = ((ICPPASTWhileStatement)parent).getScope();
} else if (parent instanceof IASTStatement) {
scope = getContainingScope((IASTStatement)parent);
} else if (parent instanceof IASTFunctionDefinition) {
IASTFunctionDeclarator fnDeclarator = ((IASTFunctionDefinition) parent).getDeclarator();
IASTName name = fnDeclarator.getName();
if (name instanceof ICPPASTQualifiedName) {
IASTName[] ns = ((ICPPASTQualifiedName)name).getNames();
name = ns[ns.length -1];
}
return getContainingScope(name);
}
if (scope == null)
return getContainingScope(parent);
return scope;
}
public static IASTNode getContainingBlockItem(IASTNode node) {
if (node == null) return null;
if (node.getPropertyInParent() == CPPSemantics.STRING_LOOKUP_PROPERTY) return null;
IASTNode parent = node.getParent();
if (parent == null)
return null;
while (parent != null) {
if (parent instanceof IASTDeclaration) {
IASTNode p = parent.getParent();
if (p instanceof IASTDeclarationStatement)
return p;
return parent;
} else if (parent instanceof IASTExpression) {
IASTNode p = parent.getParent();
if (p instanceof IASTForStatement)
return parent;
if (p instanceof IASTStatement)
return p;
} else if (parent instanceof IASTStatement || parent instanceof IASTTranslationUnit) {
return parent;
} else if (parent instanceof IASTFunctionDeclarator && node.getPropertyInParent() == IASTStandardFunctionDeclarator.FUNCTION_PARAMETER) {
return node;
} else if (parent instanceof IASTEnumerationSpecifier.IASTEnumerator) {
return parent;
}
node = parent;
parent = node.getParent();
}
return null;
}
static private IBinding resolveBinding(IASTNode node) {
IASTName name = null;
while (node != null) {
if (node instanceof IASTIdExpression) {
name = ((IASTIdExpression) node).getName();
break;
} else if (node instanceof ICPPASTFieldReference) {
name = ((ICPPASTFieldReference)node).getFieldName();
break;
} else if (node instanceof IASTFunctionCallExpression) {
node = ((IASTFunctionCallExpression)node).getFunctionNameExpression();
} else if (node instanceof IASTUnaryExpression) {
node = ((IASTUnaryExpression)node).getOperand();
} else if (node instanceof IASTBinaryExpression) {
node = ((IASTBinaryExpression)node).getOperand2();
} else {
node = null;
}
}
if (name != null) {
if (name instanceof ICPPASTQualifiedName) {
IASTName ns[] = ((ICPPASTQualifiedName)name).getNames();
name = ns[ns.length - 1];
}
if (name instanceof CPPASTName) {
((CPPASTName) name).incResolutionDepth();
}
else if (name instanceof CPPASTTemplateId) {
((CPPASTTemplateId) name).incResolutionDepth();
}
IBinding binding = name.getBinding();
if (binding == null) {
binding = CPPSemantics.resolveBinding(name);
name.setBinding(binding);
if (name instanceof ICPPASTTemplateId && binding instanceof ICPPSpecialization) {
((ICPPASTTemplateId)name).getTemplateName().setBinding(((ICPPSpecialization)binding).getSpecializedBinding());
}
}
return binding;
}
return null;
}
public static class CollectProblemsAction extends CPPASTVisitor {
{
shouldVisitDeclarations = true;
shouldVisitExpressions = true;
shouldVisitStatements = true;
shouldVisitTypeIds = true;
}
private static final int DEFAULT_CHILDREN_LIST_SIZE = 8;
private IASTProblem[] problems = null;
int numFound = 0;
public CollectProblemsAction() {
problems = new IASTProblem[DEFAULT_CHILDREN_LIST_SIZE];
}
private void addProblem(IASTProblem problem) {
if (problems.length == numFound) { // if the found array is full, then double the array
IASTProblem[] old = problems;
problems = new IASTProblem[old.length * 2];
for (int j = 0; j < old.length; ++j)
problems[j] = old[j];
}
problems[numFound++] = problem;
}
private IASTProblem[] removeNullFromProblems() {
if (problems[problems.length-1] != null) { // if the last element in the list is not null then return the list
return problems;
} else if (problems[0] == null) { // if the first element in the list is null, then return empty list
return new IASTProblem[0];
}
IASTProblem[] results = new IASTProblem[numFound];
for (int i=0; i<results.length; i++)
results[i] = problems[i];
return results;
}
public IASTProblem[] getProblems() {
return removeNullFromProblems();
}
/* (non-Javadoc)
* @see org.eclipse.cdt.internal.core.dom.parser.c.CVisitor.CBaseVisitorAction#processDeclaration(org.eclipse.cdt.core.dom.ast.IASTDeclaration)
*/
@Override
public int visit(IASTDeclaration declaration) {
if (declaration instanceof IASTProblemHolder)
addProblem(((IASTProblemHolder)declaration).getProblem());
return PROCESS_CONTINUE;
}
/* (non-Javadoc)
* @see org.eclipse.cdt.internal.core.dom.parser.c.CVisitor.CBaseVisitorAction#processExpression(org.eclipse.cdt.core.dom.ast.IASTExpression)
*/
@Override
public int visit(IASTExpression expression) {
if (expression instanceof IASTProblemHolder)
addProblem(((IASTProblemHolder)expression).getProblem());
return PROCESS_CONTINUE;
}
/* (non-Javadoc)
* @see org.eclipse.cdt.internal.core.dom.parser.c.CVisitor.CBaseVisitorAction#processStatement(org.eclipse.cdt.core.dom.ast.IASTStatement)
*/
@Override
public int visit(IASTStatement statement) {
if (statement instanceof IASTProblemHolder)
addProblem(((IASTProblemHolder)statement).getProblem());
return PROCESS_CONTINUE;
}
/* (non-Javadoc)
* @see org.eclipse.cdt.internal.core.dom.parser.c.CVisitor.CBaseVisitorAction#processTypeId(org.eclipse.cdt.core.dom.ast.IASTTypeId)
*/
@Override
public int visit(IASTTypeId typeId) {
if (typeId instanceof IASTProblemHolder)
addProblem(((IASTProblemHolder)typeId).getProblem());
return PROCESS_CONTINUE;
}
}
public static class CollectDeclarationsAction extends CPPASTVisitor {
private static final int DEFAULT_LIST_SIZE = 8;
private IASTName[] decls;
private IBinding[] bindings;
private int idx = 0;
private int kind;
private static final int KIND_LABEL = 1;
private static final int KIND_OBJ_FN = 2;
private static final int KIND_TYPE = 3;
private static final int KIND_NAMESPACE = 4;
private static final int KIND_COMPOSITE = 5;
private static final int KIND_TEMPLATE_PARAMETER = 6;
public CollectDeclarationsAction(IBinding binding) {
shouldVisitNames = true;
this.decls = new IASTName[DEFAULT_LIST_SIZE];
this.bindings = new IBinding[] {binding};
if (binding instanceof ICPPUsingDeclaration) {
this.bindings= ((ICPPUsingDeclaration) binding).getDelegates();
kind= KIND_COMPOSITE;
} else if (binding instanceof ILabel) {
kind = KIND_LABEL;
} else if (binding instanceof ICPPTemplateParameter) {
kind = KIND_TEMPLATE_PARAMETER;
} else if (binding instanceof ICompositeType ||
binding instanceof ITypedef ||
binding instanceof IEnumeration) {
kind = KIND_TYPE;
} else if (binding instanceof ICPPNamespace) {
kind = KIND_NAMESPACE;
} else {
kind = KIND_OBJ_FN;
}
}
@SuppressWarnings("fallthrough")
@Override
public int visit(IASTName name) {
if (name instanceof ICPPASTQualifiedName) return PROCESS_CONTINUE;
ASTNodeProperty prop = name.getPropertyInParent();
if (prop == ICPPASTQualifiedName.SEGMENT_NAME)
prop = name.getParent().getPropertyInParent();
switch(kind) {
case KIND_TEMPLATE_PARAMETER:
if (prop == ICPPASTSimpleTypeTemplateParameter.PARAMETER_NAME ||
prop == ICPPASTTemplatedTypeTemplateParameter.PARAMETER_NAME) {
break;
} else if (prop == IASTDeclarator.DECLARATOR_NAME) {
IASTNode d = name.getParent();
while (d.getParent() instanceof IASTDeclarator)
d = d.getParent();
if (d.getPropertyInParent() == IASTParameterDeclaration.DECLARATOR) {
break;
}
}
return PROCESS_CONTINUE;
case KIND_LABEL:
if (prop == IASTLabelStatement.NAME)
break;
return PROCESS_CONTINUE;
case KIND_TYPE:
case KIND_COMPOSITE:
if (prop == IASTCompositeTypeSpecifier.TYPE_NAME ||
prop == IASTEnumerationSpecifier.ENUMERATION_NAME ||
prop == ICPPASTUsingDeclaration.NAME) {
break;
} else if (prop == IASTElaboratedTypeSpecifier.TYPE_NAME) {
IASTNode p = name.getParent().getParent();
if (p instanceof IASTSimpleDeclaration &&
((IASTSimpleDeclaration)p).getDeclarators().length == 0)
{
break;
}
} else if (prop == IASTDeclarator.DECLARATOR_NAME) {
IASTNode p = name.getParent();
while (p instanceof IASTDeclarator) {
p= p.getParent();
}
if (p instanceof IASTSimpleDeclaration) {
IASTDeclSpecifier declSpec = ((IASTSimpleDeclaration)p).getDeclSpecifier();
if (declSpec.getStorageClass() == IASTDeclSpecifier.sc_typedef)
break;
}
}
if (kind == KIND_TYPE)
return PROCESS_CONTINUE;
// fall through
case KIND_OBJ_FN:
if (prop == IASTDeclarator.DECLARATOR_NAME ||
prop == IASTEnumerationSpecifier.IASTEnumerator.ENUMERATOR_NAME ||
prop == ICPPASTUsingDeclaration.NAME) {
break;
}
return PROCESS_CONTINUE;
case KIND_NAMESPACE:
if (prop == ICPPASTNamespaceDefinition.NAMESPACE_NAME ||
prop == ICPPASTNamespaceAlias.ALIAS_NAME) {
break;
}
return PROCESS_CONTINUE;
}
if (bindings != null) {
if (isDeclarationsBinding(name.resolveBinding())) {
if (decls.length == idx) {
IASTName[] temp = new IASTName[decls.length * 2];
System.arraycopy(decls, 0, temp, 0, decls.length);
decls = temp;
}
decls[idx++] = name;
}
}
return PROCESS_CONTINUE;
}
private boolean isDeclarationsBinding(IBinding nameBinding) {
nameBinding= unwindBinding(nameBinding);
if (nameBinding != null) {
for (IBinding binding : bindings) {
if (nameBinding.equals(unwindBinding(binding))) {
return true;
}
// a using declaration is a declaration for the references of its delegates
if (nameBinding instanceof ICPPUsingDeclaration) {
if (ArrayUtil.contains(((ICPPUsingDeclaration) nameBinding).getDelegates(), binding)) {
return true;
}
}
}
}
return false;
}
public IASTName[] getDeclarations() {
if (idx < decls.length) {
IASTName[] temp = new IASTName[idx];
System.arraycopy(decls, 0, temp, 0, idx);
decls = temp;
}
return decls;
}
}
protected static IBinding unwindBinding(IBinding binding) {
while (true) {
if (binding instanceof ICPPSpecialization) {
binding= ((ICPPSpecialization) binding).getSpecializedBinding();
} else {
break;
}
}
return binding;
}
public static class CollectReferencesAction extends CPPASTVisitor {
private static final int DEFAULT_LIST_SIZE = 8;
private IASTName[] refs;
private IBinding[] bindings;
private int idx = 0;
private int kind;
private static final int KIND_LABEL = 1;
private static final int KIND_OBJ_FN = 2;
private static final int KIND_TYPE = 3;
private static final int KIND_NAMESPACE = 4;
private static final int KIND_COMPOSITE = 5;
public CollectReferencesAction(IBinding binding) {
shouldVisitNames = true;
this.refs = new IASTName[DEFAULT_LIST_SIZE];
binding = unwindBinding(binding);
this.bindings = new IBinding[] {binding};
if (binding instanceof ICPPUsingDeclaration) {
this.bindings= ((ICPPUsingDeclaration) binding).getDelegates();
kind= KIND_COMPOSITE;
} else if (binding instanceof ILabel) {
kind = KIND_LABEL;
} else if (binding instanceof ICompositeType ||
binding instanceof ITypedef ||
binding instanceof IEnumeration) {
kind = KIND_TYPE;
} else if (binding instanceof ICPPNamespace) {
kind = KIND_NAMESPACE;
} else if (binding instanceof ICPPTemplateParameter) {
kind = KIND_COMPOSITE;
} else {
kind = KIND_OBJ_FN;
}
}
@SuppressWarnings("fallthrough")
@Override
public int visit(IASTName name) {
if (name instanceof ICPPASTQualifiedName || name instanceof ICPPASTTemplateId)
return PROCESS_CONTINUE;
ASTNodeProperty prop = name.getPropertyInParent();
ASTNodeProperty p2 = null;
if (prop == ICPPASTQualifiedName.SEGMENT_NAME) {
p2 = prop;
prop = name.getParent().getPropertyInParent();
}
switch(kind) {
case KIND_LABEL:
if (prop == IASTGotoStatement.NAME)
break;
return PROCESS_CONTINUE;
case KIND_TYPE:
case KIND_COMPOSITE:
if (prop == IASTNamedTypeSpecifier.NAME ||
prop == ICPPASTPointerToMember.NAME ||
prop == ICPPASTTypenameExpression.TYPENAME ||
prop == ICPPASTUsingDeclaration.NAME ||
prop == ICPPASTCompositeTypeSpecifier.ICPPASTBaseSpecifier.NAME ||
prop == ICPPASTTemplateId.TEMPLATE_NAME ||
p2 == ICPPASTQualifiedName.SEGMENT_NAME) {
break;
} else if (prop == IASTElaboratedTypeSpecifier.TYPE_NAME) {
IASTNode p = name.getParent().getParent();
if (!(p instanceof IASTSimpleDeclaration) ||
((IASTSimpleDeclaration)p).getDeclarators().length > 0)
{
break;
}
}
if (kind == KIND_TYPE)
return PROCESS_CONTINUE;
// fall through
case KIND_OBJ_FN:
if (prop == IASTIdExpression.ID_NAME ||
prop == IASTFieldReference.FIELD_NAME ||
prop == ICPPASTUsingDirective.QUALIFIED_NAME ||
prop == ICPPASTUsingDeclaration.NAME ||
prop == IASTFunctionCallExpression.FUNCTION_NAME ||
prop == ICPPASTUsingDeclaration.NAME ||
prop == IASTNamedTypeSpecifier.NAME ||
prop == ICPPASTConstructorChainInitializer.MEMBER_ID ||
prop == ICPPASTTemplateId.TEMPLATE_ID_ARGUMENT) {
break;
}
return PROCESS_CONTINUE;
case KIND_NAMESPACE:
if (prop == ICPPASTUsingDirective.QUALIFIED_NAME ||
prop == ICPPASTNamespaceAlias.MAPPING_NAME ||
prop == ICPPASTUsingDeclaration.NAME ||
p2 == ICPPASTQualifiedName.SEGMENT_NAME) {
break;
}
return PROCESS_CONTINUE;
}
if (bindings != null) {
if (isReferenceBinding(name.resolveBinding())) {
if (refs.length == idx) {
IASTName[] temp = new IASTName[refs.length * 2];
System.arraycopy(refs, 0, temp, 0, refs.length);
refs = temp;
}
refs[idx++] = name;
}
}
return PROCESS_CONTINUE;
}
private boolean isReferenceBinding(IBinding nameBinding) {
nameBinding= unwindBinding(nameBinding);
if (nameBinding != null) {
for (IBinding binding : bindings) {
if (nameBinding.equals(binding)) {
return true;
}
}
if (nameBinding instanceof ICPPUsingDeclaration) {
IBinding[] delegates= ((ICPPUsingDeclaration) nameBinding).getDelegates();
for (IBinding delegate : delegates) {
if (isReferenceBinding(delegate)) {
return true;
}
}
return false;
} else {
return false;
}
}
return false;
}
public IASTName[] getReferences() {
if (idx < refs.length) {
IASTName[] temp = new IASTName[idx];
System.arraycopy(refs, 0, temp, 0, idx);
refs = temp;
}
return refs;
}
}
/**
* Generate a function type for an implicit function.
* NOTE: This does not currectly handle parameters with typedef types.
* @param returnType
* @param parameters
*/
public static IFunctionType createImplicitFunctionType(IType returnType, IParameter[] parameters) {
IType[] pTypes = new IType[parameters.length];
IType pt = null;
for (int i = 0; i < parameters.length; i++) {
try {
pt = parameters[i].getType();
// remove qualifiers
if (pt instanceof IQualifierType) {
pt= ((IQualifierType) pt).getType();
}
if (pt instanceof IArrayType) {
pt = new CPPPointerType(((IArrayType) pt).getType());
} else if (pt instanceof IFunctionType) {
pt = new CPPPointerType(pt);
}
} catch (DOMException e) {
pt = e.getProblem();
}
pTypes[i] = pt;
}
return new CPPFunctionType(returnType, pTypes);
}
private static IType createType(IType returnType, ICPPASTFunctionDeclarator fnDtor) {
IASTParameterDeclaration[] params = fnDtor.getParameters();
IType[] pTypes = new IType[params.length];
IType pt = null;
for (int i = 0; i < params.length; i++) {
IASTDeclSpecifier pDeclSpec = params[i].getDeclSpecifier();
IASTDeclarator pDtor = params[i].getDeclarator();
pt = createType(pDeclSpec);
pt = createType(pt, pDtor);
//8.3.5-3
//Any cv-qualifier modifying a parameter type is deleted.
//so only create the base type from the declspec and not the qualifiers
try {
if (pt instanceof IQualifierType) {
pt= ((IQualifierType) pt).getType();
}
if (pt instanceof CPPPointerType) {
pt= ((CPPPointerType) pt).stripQualifiers();
}
//any parameter of type array of T is adjusted to be pointer to T
if (pt instanceof IArrayType) {
IArrayType at = (IArrayType) pt;
pt = new CPPPointerType(at.getType());
}
} catch (DOMException e) {
pt = e.getProblem();
}
//any parameter to type function returning T is adjusted to be pointer to function
if (pt instanceof IFunctionType) {
pt = new CPPPointerType(pt);
}
pTypes[i] = pt;
}
IASTName name = fnDtor.getName();
if (name instanceof ICPPASTQualifiedName) {
IASTName[] ns = ((ICPPASTQualifiedName) name).getNames();
name = ns[ns.length - 1];
}
if (name instanceof ICPPASTConversionName) {
returnType = createType(((ICPPASTConversionName) name).getTypeId());
} else {
returnType = getPointerTypes(returnType, fnDtor);
}
IScope scope = fnDtor.getFunctionScope();
IType thisType = getThisType(scope);
if (thisType instanceof IPointerType) {
try {
IType classType = ((IPointerType) thisType).getType();
thisType = new CPPPointerType(classType, fnDtor.isConst(), fnDtor.isVolatile());
} catch (DOMException e) {
}
} else {
thisType = null;
}
IType type = new CPPFunctionType(returnType, pTypes, (IPointerType) thisType);
IASTDeclarator nested = fnDtor.getNestedDeclarator();
if (nested != null) {
return createType(type, nested);
}
return type;
}
/**
* @param declarator
* @return
*/
private static IType createType(IType baseType, IASTDeclarator declarator) {
if (declarator instanceof ICPPASTFunctionDeclarator)
return createType(baseType, (ICPPASTFunctionDeclarator)declarator);
IType type = baseType;
type = getPointerTypes(type, declarator);
if (declarator instanceof IASTArrayDeclarator)
type = getArrayTypes(type, (IASTArrayDeclarator) declarator);
IASTDeclarator nested = declarator.getNestedDeclarator();
if (nested != null) {
return createType(type, nested);
}
return type;
}
private static IType getPointerTypes(IType type, IASTDeclarator declarator) {
IASTPointerOperator[] ptrOps = declarator.getPointerOperators();
for (IASTPointerOperator ptrOp : ptrOps) {
if (ptrOp instanceof IGPPASTPointerToMember)
type = new GPPPointerToMemberType(type, (IGPPASTPointerToMember) ptrOp);
else if (ptrOp instanceof ICPPASTPointerToMember)
type = new CPPPointerToMemberType(type, (ICPPASTPointerToMember) ptrOp);
else if (ptrOp instanceof IGPPASTPointer)
type = new GPPPointerType(type, (IGPPASTPointer) ptrOp);
else if (ptrOp instanceof IASTPointer)
type = new CPPPointerType(type, (IASTPointer) ptrOp);
else if (ptrOp instanceof ICPPASTReferenceOperator)
type = new CPPReferenceType(type);
}
return type;
}
private static IType getArrayTypes(IType type, IASTArrayDeclarator declarator) {
IASTArrayModifier[] mods = declarator.getArrayModifiers();
for (IASTArrayModifier mod : mods) {
type = new CPPArrayType(type, mod.getConstantExpression());
}
return type;
}
public static IType createType(IASTNode node) {
if (node == null)
return null;
if (node instanceof IASTExpression)
return getExpressionType((IASTExpression) node);
if (node instanceof IASTTypeId)
return createType(((IASTTypeId) node).getAbstractDeclarator());
if (node instanceof IASTParameterDeclaration)
return createType(((IASTParameterDeclaration)node).getDeclarator());
return null;
}
public static IType createType(IASTDeclarator declarator) {
IASTDeclSpecifier declSpec = null;
IASTNode node = declarator.getParent();
while (node instanceof IASTDeclarator) {
declarator = (IASTDeclarator) node;
node = node.getParent();
}
if (node instanceof IASTParameterDeclaration)
declSpec = ((IASTParameterDeclaration) node).getDeclSpecifier();
else if (node instanceof IASTSimpleDeclaration)
declSpec = ((IASTSimpleDeclaration)node).getDeclSpecifier();
else if (node instanceof IASTFunctionDefinition)
declSpec = ((IASTFunctionDefinition)node).getDeclSpecifier();
else if (node instanceof IASTTypeId)
declSpec = ((IASTTypeId)node).getDeclSpecifier();
IType type = createType(declSpec);
type = createType(type, declarator);
return type;
}
public static IType createType(IASTDeclSpecifier declSpec) {
IType type = getBaseType(declSpec);
if (type != null && (declSpec.isConst() || declSpec.isVolatile())) {
type = new CPPQualifierType(type, declSpec.isConst(), declSpec.isVolatile());
}
return type;
}
private static IType getBaseType(IASTDeclSpecifier declSpec) {
IType type = null;
IASTName name = null;
if (declSpec instanceof ICPPASTCompositeTypeSpecifier) {
name = ((ICPPASTCompositeTypeSpecifier) declSpec).getName();
} else if (declSpec instanceof ICPPASTNamedTypeSpecifier) {
name = ((ICPPASTNamedTypeSpecifier)declSpec).getName();
} else if (declSpec instanceof ICPPASTElaboratedTypeSpecifier) {
name = ((ICPPASTElaboratedTypeSpecifier)declSpec).getName();
} else if (declSpec instanceof IASTEnumerationSpecifier) {
name = ((IASTEnumerationSpecifier)declSpec).getName();
} else if (declSpec instanceof ICPPASTSimpleDeclSpecifier) {
ICPPASTSimpleDeclSpecifier spec = (ICPPASTSimpleDeclSpecifier) declSpec;
int bits = (spec.isLong() ? ICPPBasicType.IS_LONG : 0) |
(spec.isShort() ? ICPPBasicType.IS_SHORT : 0) |
(spec.isSigned() ? ICPPBasicType.IS_SIGNED: 0) |
(spec.isUnsigned() ? ICPPBasicType.IS_UNSIGNED : 0);
if (spec instanceof IGPPASTSimpleDeclSpecifier) {
IGPPASTSimpleDeclSpecifier gspec = (IGPPASTSimpleDeclSpecifier) spec;
if (gspec.getTypeofExpression() != null) {
type = getExpressionType(gspec.getTypeofExpression());
} else {
bits |= (gspec.isLongLong() ? ICPPBasicType.IS_LONG_LONG : 0);
type = new GPPBasicType(spec.getType(), bits, getExpressionType(gspec.getTypeofExpression()));
}
} else {
type = new CPPBasicType(spec.getType(), bits);
}
}
if (name != null) {
IBinding binding = name.resolveBinding();
if (binding instanceof ICPPConstructor) {
try {
ICPPClassScope scope = (ICPPClassScope) binding.getScope();
type = scope.getClassType();
type = new CPPPointerType(type);
} catch (DOMException e) {
type = e.getProblem();
}
} else if (binding instanceof IType) {
type = (IType) binding;
} else if (binding instanceof ICPPTemplateNonTypeParameter) {
//TODO workaround... is there anything better?
try {
type = ((ICPPTemplateNonTypeParameter)binding).getType();
} catch (DOMException e) {
type = e.getProblem();
}
} else if (binding instanceof IVariable) {
//this is to help with the ambiguity between typeid & idexpression in template arguments
try {
type = ((IVariable)binding).getType();
} catch (DOMException e) {
type = e.getProblem();
}
}
}
return type;
}
public static IType getThisType(IScope scope) {
try {
IASTNode node = null;
while (scope != null) {
if (scope instanceof ICPPBlockScope || scope instanceof ICPPFunctionScope) {
node = ASTInternal.getPhysicalNodeOfScope(scope);
if (node instanceof IASTFunctionDeclarator)
break;
if (node.getParent() instanceof IASTFunctionDefinition)
break;
}
scope = scope.getParent();
}
if (node != null) {
if (node.getParent() instanceof IASTFunctionDefinition) {
IASTFunctionDefinition def = (IASTFunctionDefinition) node.getParent();
node = def.getDeclarator();
}
if (node instanceof IASTFunctionDeclarator) {
ICPPASTFunctionDeclarator dtor = (ICPPASTFunctionDeclarator) node;
IASTName fName = dtor.getName();
if (fName instanceof ICPPASTQualifiedName) {
IASTName[] ns = ((ICPPASTQualifiedName)fName).getNames();
fName = ns[ns.length - 1];
}
IScope s = getContainingScope(fName);
if (s instanceof ICPPTemplateScope)
s = getParentScope(s, fName.getTranslationUnit());
if (s instanceof ICPPClassScope) {
ICPPClassScope cScope = (ICPPClassScope) s;
IType type = cScope.getClassType();
if (type instanceof ICPPClassTemplate) {
type = (IType) CPPTemplates.instantiateWithinClassTemplate((ICPPClassTemplate) type);
}
if (dtor.isConst() || dtor.isVolatile())
type = new CPPQualifierType(type, dtor.isConst(), dtor.isVolatile());
type = new CPPPointerType(type);
return type;
}
}
}
} catch (DOMException e) {
return e.getProblem();
}
return null;
}
public static IType getExpressionType(IASTExpression expression) {
if (expression == null)
return null;
if (expression instanceof IASTIdExpression) {
IBinding binding = resolveBinding(expression);
try {
if (binding instanceof IVariable) {
return ((IVariable) binding).getType();
} else if (binding instanceof IEnumerator) {
return ((IEnumerator) binding).getType();
} else if (binding instanceof IProblemBinding) {
return (IType) binding;
} else if (binding instanceof IFunction) {
return ((IFunction) binding).getType();
} else if (binding instanceof ICPPTemplateNonTypeParameter) {
return ((ICPPTemplateNonTypeParameter) binding).getType();
} else if (binding instanceof ICPPClassType) {
return ((ICPPClassType) binding);
}
} catch (DOMException e) {
return e.getProblem();
}
} else if (expression instanceof IASTCastExpression) {
IASTTypeId id = ((IASTCastExpression)expression).getTypeId();
IType type = createType(id.getDeclSpecifier());
return createType(type, id.getAbstractDeclarator());
} else if (expression instanceof ICPPASTLiteralExpression) {
ICPPASTLiteralExpression lit= (ICPPASTLiteralExpression) expression;
switch(lit.getKind()) {
case ICPPASTLiteralExpression.lk_this : {
IScope scope = getContainingScope(expression);
return getThisType(scope);
}
case ICPPASTLiteralExpression.lk_true :
case ICPPASTLiteralExpression.lk_false:
return new CPPBasicType(ICPPBasicType.t_bool, 0, expression);
case IASTLiteralExpression.lk_char_constant:
return new CPPBasicType(IBasicType.t_char, 0, expression);
case IASTLiteralExpression.lk_float_constant:
return classifyTypeOfFloatLiteral(lit);
case IASTLiteralExpression.lk_integer_constant:
return classifyTypeOfIntLiteral(lit);
case IASTLiteralExpression.lk_string_literal:
IType type = new CPPBasicType(IBasicType.t_char, 0, expression);
type = new CPPQualifierType(type, true, false);
return new CPPPointerType(type);
}
} else if (expression instanceof IASTFunctionCallExpression) {
IBinding binding = resolveBinding(expression);
if (binding instanceof ICPPConstructor) {
try {
IScope scope= binding.getScope();
if (scope instanceof ICPPTemplateScope && ! (scope instanceof ICPPClassScope)) {
scope= scope.getParent();
}
if (scope instanceof ICPPClassScope) {
return ((ICPPClassScope) scope).getClassType();
}
} catch (DOMException e) {
return e.getProblem();
}
return new ProblemBinding(expression, IProblemBinding.SEMANTIC_BAD_SCOPE,
binding.getName().toCharArray());
} else if (binding instanceof IFunction) {
IFunctionType fType;
try {
fType = ((IFunction)binding).getType();
if (fType != null)
return fType.getReturnType();
} catch (DOMException e) {
return e.getProblem();
}
} else if (binding instanceof IVariable) {
try {
IType t = ((IVariable)binding).getType();
while (t instanceof ITypedef) {
t = ((ITypedef)t).getType();
}
if (t instanceof IPointerType && ((IPointerType)t).getType() instanceof IFunctionType) {
IFunctionType ftype = (IFunctionType) ((IPointerType)t).getType();
if (ftype != null)
return ftype.getReturnType();
}
t= getUltimateTypeUptoPointers(t);
if (t instanceof ICPPClassType) {
ICPPFunction op = CPPSemantics.findOperator(expression, (ICPPClassType) t);
if (op != null) {
return op.getType().getReturnType();
}
}
} catch(DOMException e) {
return e.getProblem();
}
} else if (binding instanceof ITypedef) {
try {
IType type = ((ITypedef)binding).getType();
while (type instanceof ITypedef)
type = ((ITypedef)type).getType();
if (type instanceof IFunctionType) {
return ((IFunctionType)type).getReturnType();
}
return type;
} catch (DOMException e) {
return e.getProblem();
}
} else if (binding instanceof IProblemBinding) {
return (IType) binding;
}
} else if (expression instanceof IASTBinaryExpression) {
final IASTBinaryExpression binary = (IASTBinaryExpression) expression;
final int op = binary.getOperator();
switch(op) {
case IASTBinaryExpression.op_lessEqual:
case IASTBinaryExpression.op_lessThan:
case IASTBinaryExpression.op_greaterEqual:
case IASTBinaryExpression.op_greaterThan:
case IASTBinaryExpression.op_logicalAnd:
case IASTBinaryExpression.op_logicalOr:
case IASTBinaryExpression.op_equals:
case IASTBinaryExpression.op_notequals:
CPPBasicType basicType= new CPPBasicType(ICPPBasicType.t_bool, 0);
basicType.setValue(expression);
return basicType;
case IASTBinaryExpression.op_plus:
IType t2 = getExpressionType(binary.getOperand2());
if (SemanticUtil.getUltimateTypeViaTypedefs(t2) instanceof IPointerType) {
return t2;
}
break;
case IASTBinaryExpression.op_minus:
t2= getExpressionType(binary.getOperand2());
if (SemanticUtil.getUltimateTypeViaTypedefs(t2) instanceof IPointerType) {
IType t1 = getExpressionType(binary.getOperand1());
if (SemanticUtil.getUltimateTypeViaTypedefs(t1) instanceof IPointerType) {
IScope scope = getContainingScope(expression);
try {
IBinding[] bs = scope.find(PTRDIFF_T);
if (bs.length > 0) {
for (IBinding b : bs) {
if (b instanceof IType && CPPSemantics.declaredBefore(b, binary, false)) {
return (IType) b;
}
}
}
} catch (DOMException e) {
}
basicType= new CPPBasicType(IBasicType.t_int, ICPPBasicType.IS_LONG | ICPPBasicType.IS_UNSIGNED);
basicType.setValue(expression);
return basicType;
}
return t1;
}
break;
case ICPPASTBinaryExpression.op_pmarrow:
case ICPPASTBinaryExpression.op_pmdot:
IType type = getExpressionType(((IASTBinaryExpression) expression).getOperand2());
if (type instanceof ICPPPointerToMemberType) {
try {
return ((ICPPPointerToMemberType)type).getType();
} catch (DOMException e) {
return e.getProblem();
}
}
return new ProblemBinding(binary, IProblemBinding.SEMANTIC_INVALID_TYPE, new char[0]);
}
return getExpressionType(((IASTBinaryExpression) expression).getOperand1());
} else if (expression instanceof IASTUnaryExpression) {
int op = ((IASTUnaryExpression)expression).getOperator();
if (op == IASTUnaryExpression.op_sizeof) {
IScope scope = getContainingScope(expression);
try {
IBinding[] bs = scope.find(SIZE_T);
if (bs.length > 0 && bs[0] instanceof IType) {
return (IType) bs[0];
}
} catch (DOMException e) {
}
return new CPPBasicType(IBasicType.t_int, ICPPBasicType.IS_LONG | ICPPBasicType.IS_UNSIGNED);
}
IType type = getExpressionType(((IASTUnaryExpression)expression).getOperand());
while (type instanceof ITypedef) {
try {
type = ((ITypeContainer)type).getType();
} catch (DOMException e) {
break;
}
}
if (op == IASTUnaryExpression.op_star && type instanceof ICPPClassType) {
try {
ICPPFunction operator= CPPSemantics.findOperator(expression, (ICPPClassType) type);
if (operator != null) {
return operator.getType().getReturnType();
}
} catch(DOMException de) {
return de.getProblem();
}
}
if (op == IASTUnaryExpression.op_star && (type instanceof IPointerType || type instanceof IArrayType)) {
try {
return ((ITypeContainer) type).getType();
} catch (DOMException e) {
return e.getProblem();
}
} else if (op == IASTUnaryExpression.op_amper) {
if (type instanceof ICPPReferenceType) {
try {
type = ((ICPPReferenceType) type).getType();
} catch (DOMException e) {
}
}
if (type instanceof ICPPFunctionType) {
ICPPFunctionType functionType = (ICPPFunctionType) type;
IPointerType thisType = functionType.getThisType();
if (thisType != null) {
- ICPPClassType classType;
+ IType nestedType;
try {
- classType = (ICPPClassType) thisType.getType();
+ nestedType = thisType.getType();
+ while (nestedType instanceof ITypeContainer) {
+ nestedType = ((ITypeContainer) nestedType).getType();
+ }
} catch (DOMException e) {
return e.getProblem();
}
- return new CPPPointerToMemberType(type, classType,
+ return new CPPPointerToMemberType(type, (ICPPClassType) nestedType,
thisType.isConst(), thisType.isVolatile());
}
}
return new CPPPointerType(type);
} else if (type instanceof CPPBasicType) {
((CPPBasicType) type).setValue(expression);
}
return type;
} else if (expression instanceof ICPPASTFieldReference) {
IASTName name = ((ICPPASTFieldReference)expression).getFieldName();
IBinding binding = name.resolveBinding();
try {
if (binding instanceof IVariable)
return ((IVariable)binding).getType();
else if (binding instanceof IFunction)
return ((IFunction)binding).getType();
else if (binding instanceof IEnumerator)
return ((IEnumerator)binding).getType();
} catch (DOMException e) {
return e.getProblem();
}
} else if (expression instanceof IASTExpressionList) {
IASTExpression[] exps = ((IASTExpressionList)expression).getExpressions();
return getExpressionType(exps[exps.length - 1]);
} else if (expression instanceof ICPPASTTypeIdExpression) {
ICPPASTTypeIdExpression typeidExp = (ICPPASTTypeIdExpression) expression;
if (typeidExp.getOperator() == IASTTypeIdExpression.op_sizeof) {
IScope scope = getContainingScope(typeidExp);
try {
IBinding[] bs = scope.find(SIZE_T);
if (bs.length > 0 && bs[0] instanceof IType) {
return (IType) bs[0];
}
} catch (DOMException e) {
}
return new CPPBasicType(IBasicType.t_int, ICPPBasicType.IS_LONG | ICPPBasicType.IS_UNSIGNED);
}
return createType(typeidExp.getTypeId());
} else if (expression instanceof IASTArraySubscriptExpression) {
IType t = getExpressionType(((IASTArraySubscriptExpression) expression).getArrayExpression());
try {
if (t instanceof ICPPReferenceType)
t = ((ICPPReferenceType)t).getType();
while (t instanceof ITypedef) {
t = ((ITypedef)t).getType();
}
if (t instanceof ICPPClassType) {
ICPPFunction op = CPPSemantics.findOperator(expression, (ICPPClassType) t);
if (op != null) {
return op.getType().getReturnType();
}
}
if (t instanceof IPointerType)
return ((IPointerType)t).getType();
else if (t instanceof IArrayType)
return ((IArrayType)t).getType();
} catch(DOMException e) {
}
} else if (expression instanceof IGNUASTCompoundStatementExpression) {
IASTCompoundStatement compound = ((IGNUASTCompoundStatementExpression)expression).getCompoundStatement();
IASTStatement[] statements = compound.getStatements();
if (statements.length > 0) {
IASTStatement st = statements[statements.length - 1];
if (st instanceof IASTExpressionStatement)
return getExpressionType(((IASTExpressionStatement)st).getExpression());
}
} else if (expression instanceof IASTConditionalExpression) {
final IASTConditionalExpression conditional = (IASTConditionalExpression) expression;
IASTExpression positiveExpression = conditional.getPositiveResultExpression();
if (positiveExpression == null) {
positiveExpression= conditional.getLogicalConditionExpression();
}
IType t2 = getExpressionType(positiveExpression);
IType t3 = getExpressionType(conditional.getNegativeResultExpression());
if (t3 instanceof IPointerType || t2 == null)
return t3;
return t2;
} else if (expression instanceof ICPPASTDeleteExpression) {
return CPPSemantics.VOID_TYPE;
} else if (expression instanceof ICPPASTTypenameExpression) {
IBinding binding = ((ICPPASTTypenameExpression)expression).getName().resolveBinding();
if (binding instanceof IType)
return (IType) binding;
} else if (expression instanceof ICPPASTNewExpression) {
ICPPASTNewExpression newExp = (ICPPASTNewExpression) expression;
return createType(newExp.getTypeId());
}
return null;
}
private static IType classifyTypeOfFloatLiteral(final IASTLiteralExpression expr) {
final String lit= expr.toString();
final int len= lit.length();
int kind= IBasicType.t_double;
int flags= 0;
if (len > 0) {
switch(lit.charAt(len-1)) {
case 'f': case 'F':
kind= IBasicType.t_float;
break;
case 'l': case 'L':
flags |= ICPPBasicType.IS_LONG;
break;
}
}
return new CPPBasicType(kind, flags, expr);
}
private static IType classifyTypeOfIntLiteral(IASTLiteralExpression expression) {
int makelong= 0;
boolean unsigned= false;
final String lit= expression.toString();
for (int i=lit.length()-1; i >=0; i--) {
final char c= lit.charAt(i);
if (!(c > 'f' && c <= 'z') && !(c > 'F' && c <= 'Z')) {
break;
}
switch (lit.charAt(i)) {
case 'u':
case 'U':
unsigned = true;
break;
case 'l':
case 'L':
makelong++;
break;
}
}
int flags= 0;
if (unsigned) {
flags |= ICPPBasicType.IS_UNSIGNED;
}
if (makelong > 1) {
flags |= ICPPBasicType.IS_LONG_LONG;
GPPBasicType result = new GPPBasicType(IBasicType.t_int, flags, null);
result.setValue(expression);
return result;
}
if (makelong == 1) {
flags |= ICPPBasicType.IS_LONG;
}
return new CPPBasicType(IBasicType.t_int, flags, expression);
}
public static IASTDeclarator getMostNestedDeclarator(IASTDeclarator dtor) {
if (dtor == null) return null;
IASTDeclarator nested = null;
while ((nested = dtor.getNestedDeclarator()) != null) {
dtor = nested;
}
return dtor;
}
public static IASTProblem[] getProblems(IASTTranslationUnit tu) {
CollectProblemsAction action = new CollectProblemsAction();
tu.accept(action);
return action.getProblems();
}
public static IASTName[] getReferences(IASTTranslationUnit tu, IBinding binding) {
CollectReferencesAction action = new CollectReferencesAction(binding);
tu.accept(action);
return action.getReferences();
}
public static IASTName[] getDeclarations(IASTTranslationUnit tu, IBinding binding) {
CollectDeclarationsAction action = new CollectDeclarationsAction(binding);
tu.accept(action);
IASTName[] found = action.getDeclarations();
if (found.length == 0 && binding instanceof ICPPSpecialization && binding instanceof ICPPInternalBinding) {
IASTNode node = ((ICPPInternalBinding)binding).getDefinition();
if (node == null) {
IASTNode[] nds = ((ICPPInternalBinding)binding).getDeclarations();
if (nds != null && nds.length > 0)
node = nds[0];
}
if (node != null) {
IASTName name = null;
if (node instanceof IASTDeclarator)
name = ((IASTDeclarator)node).getName();
else if (node instanceof IASTName)
name = (IASTName) node;
if (name != null)
found = new IASTName[] { name };
}
}
return found;
}
/**
* Return the qualified name by concatenating component names with the
* Scope resolution operator ::
* @param qn the component names
* @return the qualified name
*/
public static String renderQualifiedName(String[] qn) {
StringBuffer result = new StringBuffer();
for (int i = 0; i < qn.length; i++) {
result.append(qn[i] + (i + 1 < qn.length ? "::" : "")); //$NON-NLS-1$//$NON-NLS-2$
}
return result.toString();
}
public static String[] getQualifiedName(IBinding binding) {
IName[] ns = null;
try {
ICPPScope scope = (ICPPScope) binding.getScope();
while (scope != null) {
if (scope instanceof ICPPTemplateScope)
scope = (ICPPScope) scope.getParent();
if (scope == null)
break;
IName n = scope.getScopeName();
if (n == null)
break;
if (scope instanceof ICPPBlockScope || scope instanceof ICPPFunctionScope)
break;
if (scope instanceof ICPPNamespaceScope && scope.getScopeName().toCharArray().length == 0)
break;
ns = (IName[]) ArrayUtil.append(IName.class, ns, n);
scope = (ICPPScope) scope.getParent();
}
} catch (DOMException e) {
}
ns = (IName[]) ArrayUtil.trim(IName.class, ns);
String[] result = new String[ns.length + 1];
for (int i = ns.length - 1; i >= 0; i--) {
result[ns.length - i - 1] = ns[i].toString();
}
result[ns.length] = binding.getName();
return result;
}
public static char[][] getQualifiedNameCharArray(IBinding binding) {
IName[] ns = null;
try {
ICPPScope scope = (ICPPScope) binding.getScope();
while (scope != null) {
if (scope instanceof ICPPTemplateScope)
scope = (ICPPScope) scope.getParent();
if (scope == null)
break;
IName n = scope.getScopeName();
if (n == null)
break;
if (scope instanceof ICPPBlockScope || scope instanceof ICPPFunctionScope)
break;
if (scope instanceof ICPPNamespaceScope && scope.getScopeName().toCharArray().length == 0)
break;
ns = (IName[]) ArrayUtil.append(IName.class, ns, n);
scope = (ICPPScope) scope.getParent();
}
} catch (DOMException e) {
}
ns = (IName[]) ArrayUtil.trim(IName.class, ns);
char[][] result = new char[ns.length + 1][];
for (int i = ns.length - 1; i >= 0; i--) {
result[ns.length - i - 1] = ns[i].toCharArray();
}
result[ns.length] = binding.getNameCharArray();
return result;
}
private static IScope getParentScope(IScope scope, IASTTranslationUnit unit) throws DOMException {
IScope parentScope= scope.getParent();
// the index cannot return the translation unit as parent scope
if (parentScope == null && scope instanceof IIndexScope && unit != null) {
parentScope= unit.getScope();
}
return parentScope;
}
public static boolean isExternC(IASTNode node) {
while (node != null) {
node= node.getParent();
if (node instanceof ICPPASTLinkageSpecification) {
if ("\"C\"".equals(((ICPPASTLinkageSpecification) node).getLiteral())) { //$NON-NLS-1$
return true;
}
}
}
return false;
}
/**
* [3.10] Lvalues and Rvalues
* @param exp
* @return whether the specified expression is an rvalue
*/
static boolean isRValue(IASTExpression exp) {
if (exp instanceof IASTUnaryExpression) {
IASTUnaryExpression ue= (IASTUnaryExpression) exp;
if (ue.getOperator() == IASTUnaryExpression.op_amper) {
return true;
}
}
if (exp instanceof IASTLiteralExpression)
return true;
if (exp instanceof IASTFunctionCallExpression) {
try {
IASTFunctionCallExpression fc= (IASTFunctionCallExpression) exp;
IASTExpression fne= fc.getFunctionNameExpression();
if (fne instanceof IASTIdExpression) {
IASTIdExpression ide= (IASTIdExpression) fne;
IBinding b= ide.getName().resolveBinding();
if (b instanceof IFunction) {
IFunctionType tp= ((IFunction)b).getType();
return !(tp.getReturnType() instanceof ICPPReferenceType);
}
}
} catch(DOMException de) {
// fall-through
}
}
return false;
}
}
| false | true | public static IType getExpressionType(IASTExpression expression) {
if (expression == null)
return null;
if (expression instanceof IASTIdExpression) {
IBinding binding = resolveBinding(expression);
try {
if (binding instanceof IVariable) {
return ((IVariable) binding).getType();
} else if (binding instanceof IEnumerator) {
return ((IEnumerator) binding).getType();
} else if (binding instanceof IProblemBinding) {
return (IType) binding;
} else if (binding instanceof IFunction) {
return ((IFunction) binding).getType();
} else if (binding instanceof ICPPTemplateNonTypeParameter) {
return ((ICPPTemplateNonTypeParameter) binding).getType();
} else if (binding instanceof ICPPClassType) {
return ((ICPPClassType) binding);
}
} catch (DOMException e) {
return e.getProblem();
}
} else if (expression instanceof IASTCastExpression) {
IASTTypeId id = ((IASTCastExpression)expression).getTypeId();
IType type = createType(id.getDeclSpecifier());
return createType(type, id.getAbstractDeclarator());
} else if (expression instanceof ICPPASTLiteralExpression) {
ICPPASTLiteralExpression lit= (ICPPASTLiteralExpression) expression;
switch(lit.getKind()) {
case ICPPASTLiteralExpression.lk_this : {
IScope scope = getContainingScope(expression);
return getThisType(scope);
}
case ICPPASTLiteralExpression.lk_true :
case ICPPASTLiteralExpression.lk_false:
return new CPPBasicType(ICPPBasicType.t_bool, 0, expression);
case IASTLiteralExpression.lk_char_constant:
return new CPPBasicType(IBasicType.t_char, 0, expression);
case IASTLiteralExpression.lk_float_constant:
return classifyTypeOfFloatLiteral(lit);
case IASTLiteralExpression.lk_integer_constant:
return classifyTypeOfIntLiteral(lit);
case IASTLiteralExpression.lk_string_literal:
IType type = new CPPBasicType(IBasicType.t_char, 0, expression);
type = new CPPQualifierType(type, true, false);
return new CPPPointerType(type);
}
} else if (expression instanceof IASTFunctionCallExpression) {
IBinding binding = resolveBinding(expression);
if (binding instanceof ICPPConstructor) {
try {
IScope scope= binding.getScope();
if (scope instanceof ICPPTemplateScope && ! (scope instanceof ICPPClassScope)) {
scope= scope.getParent();
}
if (scope instanceof ICPPClassScope) {
return ((ICPPClassScope) scope).getClassType();
}
} catch (DOMException e) {
return e.getProblem();
}
return new ProblemBinding(expression, IProblemBinding.SEMANTIC_BAD_SCOPE,
binding.getName().toCharArray());
} else if (binding instanceof IFunction) {
IFunctionType fType;
try {
fType = ((IFunction)binding).getType();
if (fType != null)
return fType.getReturnType();
} catch (DOMException e) {
return e.getProblem();
}
} else if (binding instanceof IVariable) {
try {
IType t = ((IVariable)binding).getType();
while (t instanceof ITypedef) {
t = ((ITypedef)t).getType();
}
if (t instanceof IPointerType && ((IPointerType)t).getType() instanceof IFunctionType) {
IFunctionType ftype = (IFunctionType) ((IPointerType)t).getType();
if (ftype != null)
return ftype.getReturnType();
}
t= getUltimateTypeUptoPointers(t);
if (t instanceof ICPPClassType) {
ICPPFunction op = CPPSemantics.findOperator(expression, (ICPPClassType) t);
if (op != null) {
return op.getType().getReturnType();
}
}
} catch(DOMException e) {
return e.getProblem();
}
} else if (binding instanceof ITypedef) {
try {
IType type = ((ITypedef)binding).getType();
while (type instanceof ITypedef)
type = ((ITypedef)type).getType();
if (type instanceof IFunctionType) {
return ((IFunctionType)type).getReturnType();
}
return type;
} catch (DOMException e) {
return e.getProblem();
}
} else if (binding instanceof IProblemBinding) {
return (IType) binding;
}
} else if (expression instanceof IASTBinaryExpression) {
final IASTBinaryExpression binary = (IASTBinaryExpression) expression;
final int op = binary.getOperator();
switch(op) {
case IASTBinaryExpression.op_lessEqual:
case IASTBinaryExpression.op_lessThan:
case IASTBinaryExpression.op_greaterEqual:
case IASTBinaryExpression.op_greaterThan:
case IASTBinaryExpression.op_logicalAnd:
case IASTBinaryExpression.op_logicalOr:
case IASTBinaryExpression.op_equals:
case IASTBinaryExpression.op_notequals:
CPPBasicType basicType= new CPPBasicType(ICPPBasicType.t_bool, 0);
basicType.setValue(expression);
return basicType;
case IASTBinaryExpression.op_plus:
IType t2 = getExpressionType(binary.getOperand2());
if (SemanticUtil.getUltimateTypeViaTypedefs(t2) instanceof IPointerType) {
return t2;
}
break;
case IASTBinaryExpression.op_minus:
t2= getExpressionType(binary.getOperand2());
if (SemanticUtil.getUltimateTypeViaTypedefs(t2) instanceof IPointerType) {
IType t1 = getExpressionType(binary.getOperand1());
if (SemanticUtil.getUltimateTypeViaTypedefs(t1) instanceof IPointerType) {
IScope scope = getContainingScope(expression);
try {
IBinding[] bs = scope.find(PTRDIFF_T);
if (bs.length > 0) {
for (IBinding b : bs) {
if (b instanceof IType && CPPSemantics.declaredBefore(b, binary, false)) {
return (IType) b;
}
}
}
} catch (DOMException e) {
}
basicType= new CPPBasicType(IBasicType.t_int, ICPPBasicType.IS_LONG | ICPPBasicType.IS_UNSIGNED);
basicType.setValue(expression);
return basicType;
}
return t1;
}
break;
case ICPPASTBinaryExpression.op_pmarrow:
case ICPPASTBinaryExpression.op_pmdot:
IType type = getExpressionType(((IASTBinaryExpression) expression).getOperand2());
if (type instanceof ICPPPointerToMemberType) {
try {
return ((ICPPPointerToMemberType)type).getType();
} catch (DOMException e) {
return e.getProblem();
}
}
return new ProblemBinding(binary, IProblemBinding.SEMANTIC_INVALID_TYPE, new char[0]);
}
return getExpressionType(((IASTBinaryExpression) expression).getOperand1());
} else if (expression instanceof IASTUnaryExpression) {
int op = ((IASTUnaryExpression)expression).getOperator();
if (op == IASTUnaryExpression.op_sizeof) {
IScope scope = getContainingScope(expression);
try {
IBinding[] bs = scope.find(SIZE_T);
if (bs.length > 0 && bs[0] instanceof IType) {
return (IType) bs[0];
}
} catch (DOMException e) {
}
return new CPPBasicType(IBasicType.t_int, ICPPBasicType.IS_LONG | ICPPBasicType.IS_UNSIGNED);
}
IType type = getExpressionType(((IASTUnaryExpression)expression).getOperand());
while (type instanceof ITypedef) {
try {
type = ((ITypeContainer)type).getType();
} catch (DOMException e) {
break;
}
}
if (op == IASTUnaryExpression.op_star && type instanceof ICPPClassType) {
try {
ICPPFunction operator= CPPSemantics.findOperator(expression, (ICPPClassType) type);
if (operator != null) {
return operator.getType().getReturnType();
}
} catch(DOMException de) {
return de.getProblem();
}
}
if (op == IASTUnaryExpression.op_star && (type instanceof IPointerType || type instanceof IArrayType)) {
try {
return ((ITypeContainer) type).getType();
} catch (DOMException e) {
return e.getProblem();
}
} else if (op == IASTUnaryExpression.op_amper) {
if (type instanceof ICPPReferenceType) {
try {
type = ((ICPPReferenceType) type).getType();
} catch (DOMException e) {
}
}
if (type instanceof ICPPFunctionType) {
ICPPFunctionType functionType = (ICPPFunctionType) type;
IPointerType thisType = functionType.getThisType();
if (thisType != null) {
ICPPClassType classType;
try {
classType = (ICPPClassType) thisType.getType();
} catch (DOMException e) {
return e.getProblem();
}
return new CPPPointerToMemberType(type, classType,
thisType.isConst(), thisType.isVolatile());
}
}
return new CPPPointerType(type);
} else if (type instanceof CPPBasicType) {
((CPPBasicType) type).setValue(expression);
}
return type;
} else if (expression instanceof ICPPASTFieldReference) {
IASTName name = ((ICPPASTFieldReference)expression).getFieldName();
IBinding binding = name.resolveBinding();
try {
if (binding instanceof IVariable)
return ((IVariable)binding).getType();
else if (binding instanceof IFunction)
return ((IFunction)binding).getType();
else if (binding instanceof IEnumerator)
return ((IEnumerator)binding).getType();
} catch (DOMException e) {
return e.getProblem();
}
} else if (expression instanceof IASTExpressionList) {
IASTExpression[] exps = ((IASTExpressionList)expression).getExpressions();
return getExpressionType(exps[exps.length - 1]);
} else if (expression instanceof ICPPASTTypeIdExpression) {
ICPPASTTypeIdExpression typeidExp = (ICPPASTTypeIdExpression) expression;
if (typeidExp.getOperator() == IASTTypeIdExpression.op_sizeof) {
IScope scope = getContainingScope(typeidExp);
try {
IBinding[] bs = scope.find(SIZE_T);
if (bs.length > 0 && bs[0] instanceof IType) {
return (IType) bs[0];
}
} catch (DOMException e) {
}
return new CPPBasicType(IBasicType.t_int, ICPPBasicType.IS_LONG | ICPPBasicType.IS_UNSIGNED);
}
return createType(typeidExp.getTypeId());
} else if (expression instanceof IASTArraySubscriptExpression) {
IType t = getExpressionType(((IASTArraySubscriptExpression) expression).getArrayExpression());
try {
if (t instanceof ICPPReferenceType)
t = ((ICPPReferenceType)t).getType();
while (t instanceof ITypedef) {
t = ((ITypedef)t).getType();
}
if (t instanceof ICPPClassType) {
ICPPFunction op = CPPSemantics.findOperator(expression, (ICPPClassType) t);
if (op != null) {
return op.getType().getReturnType();
}
}
if (t instanceof IPointerType)
return ((IPointerType)t).getType();
else if (t instanceof IArrayType)
return ((IArrayType)t).getType();
} catch(DOMException e) {
}
} else if (expression instanceof IGNUASTCompoundStatementExpression) {
IASTCompoundStatement compound = ((IGNUASTCompoundStatementExpression)expression).getCompoundStatement();
IASTStatement[] statements = compound.getStatements();
if (statements.length > 0) {
IASTStatement st = statements[statements.length - 1];
if (st instanceof IASTExpressionStatement)
return getExpressionType(((IASTExpressionStatement)st).getExpression());
}
} else if (expression instanceof IASTConditionalExpression) {
final IASTConditionalExpression conditional = (IASTConditionalExpression) expression;
IASTExpression positiveExpression = conditional.getPositiveResultExpression();
if (positiveExpression == null) {
positiveExpression= conditional.getLogicalConditionExpression();
}
IType t2 = getExpressionType(positiveExpression);
IType t3 = getExpressionType(conditional.getNegativeResultExpression());
if (t3 instanceof IPointerType || t2 == null)
return t3;
return t2;
} else if (expression instanceof ICPPASTDeleteExpression) {
return CPPSemantics.VOID_TYPE;
} else if (expression instanceof ICPPASTTypenameExpression) {
IBinding binding = ((ICPPASTTypenameExpression)expression).getName().resolveBinding();
if (binding instanceof IType)
return (IType) binding;
} else if (expression instanceof ICPPASTNewExpression) {
ICPPASTNewExpression newExp = (ICPPASTNewExpression) expression;
return createType(newExp.getTypeId());
}
return null;
}
| public static IType getExpressionType(IASTExpression expression) {
if (expression == null)
return null;
if (expression instanceof IASTIdExpression) {
IBinding binding = resolveBinding(expression);
try {
if (binding instanceof IVariable) {
return ((IVariable) binding).getType();
} else if (binding instanceof IEnumerator) {
return ((IEnumerator) binding).getType();
} else if (binding instanceof IProblemBinding) {
return (IType) binding;
} else if (binding instanceof IFunction) {
return ((IFunction) binding).getType();
} else if (binding instanceof ICPPTemplateNonTypeParameter) {
return ((ICPPTemplateNonTypeParameter) binding).getType();
} else if (binding instanceof ICPPClassType) {
return ((ICPPClassType) binding);
}
} catch (DOMException e) {
return e.getProblem();
}
} else if (expression instanceof IASTCastExpression) {
IASTTypeId id = ((IASTCastExpression)expression).getTypeId();
IType type = createType(id.getDeclSpecifier());
return createType(type, id.getAbstractDeclarator());
} else if (expression instanceof ICPPASTLiteralExpression) {
ICPPASTLiteralExpression lit= (ICPPASTLiteralExpression) expression;
switch(lit.getKind()) {
case ICPPASTLiteralExpression.lk_this : {
IScope scope = getContainingScope(expression);
return getThisType(scope);
}
case ICPPASTLiteralExpression.lk_true :
case ICPPASTLiteralExpression.lk_false:
return new CPPBasicType(ICPPBasicType.t_bool, 0, expression);
case IASTLiteralExpression.lk_char_constant:
return new CPPBasicType(IBasicType.t_char, 0, expression);
case IASTLiteralExpression.lk_float_constant:
return classifyTypeOfFloatLiteral(lit);
case IASTLiteralExpression.lk_integer_constant:
return classifyTypeOfIntLiteral(lit);
case IASTLiteralExpression.lk_string_literal:
IType type = new CPPBasicType(IBasicType.t_char, 0, expression);
type = new CPPQualifierType(type, true, false);
return new CPPPointerType(type);
}
} else if (expression instanceof IASTFunctionCallExpression) {
IBinding binding = resolveBinding(expression);
if (binding instanceof ICPPConstructor) {
try {
IScope scope= binding.getScope();
if (scope instanceof ICPPTemplateScope && ! (scope instanceof ICPPClassScope)) {
scope= scope.getParent();
}
if (scope instanceof ICPPClassScope) {
return ((ICPPClassScope) scope).getClassType();
}
} catch (DOMException e) {
return e.getProblem();
}
return new ProblemBinding(expression, IProblemBinding.SEMANTIC_BAD_SCOPE,
binding.getName().toCharArray());
} else if (binding instanceof IFunction) {
IFunctionType fType;
try {
fType = ((IFunction)binding).getType();
if (fType != null)
return fType.getReturnType();
} catch (DOMException e) {
return e.getProblem();
}
} else if (binding instanceof IVariable) {
try {
IType t = ((IVariable)binding).getType();
while (t instanceof ITypedef) {
t = ((ITypedef)t).getType();
}
if (t instanceof IPointerType && ((IPointerType)t).getType() instanceof IFunctionType) {
IFunctionType ftype = (IFunctionType) ((IPointerType)t).getType();
if (ftype != null)
return ftype.getReturnType();
}
t= getUltimateTypeUptoPointers(t);
if (t instanceof ICPPClassType) {
ICPPFunction op = CPPSemantics.findOperator(expression, (ICPPClassType) t);
if (op != null) {
return op.getType().getReturnType();
}
}
} catch(DOMException e) {
return e.getProblem();
}
} else if (binding instanceof ITypedef) {
try {
IType type = ((ITypedef)binding).getType();
while (type instanceof ITypedef)
type = ((ITypedef)type).getType();
if (type instanceof IFunctionType) {
return ((IFunctionType)type).getReturnType();
}
return type;
} catch (DOMException e) {
return e.getProblem();
}
} else if (binding instanceof IProblemBinding) {
return (IType) binding;
}
} else if (expression instanceof IASTBinaryExpression) {
final IASTBinaryExpression binary = (IASTBinaryExpression) expression;
final int op = binary.getOperator();
switch(op) {
case IASTBinaryExpression.op_lessEqual:
case IASTBinaryExpression.op_lessThan:
case IASTBinaryExpression.op_greaterEqual:
case IASTBinaryExpression.op_greaterThan:
case IASTBinaryExpression.op_logicalAnd:
case IASTBinaryExpression.op_logicalOr:
case IASTBinaryExpression.op_equals:
case IASTBinaryExpression.op_notequals:
CPPBasicType basicType= new CPPBasicType(ICPPBasicType.t_bool, 0);
basicType.setValue(expression);
return basicType;
case IASTBinaryExpression.op_plus:
IType t2 = getExpressionType(binary.getOperand2());
if (SemanticUtil.getUltimateTypeViaTypedefs(t2) instanceof IPointerType) {
return t2;
}
break;
case IASTBinaryExpression.op_minus:
t2= getExpressionType(binary.getOperand2());
if (SemanticUtil.getUltimateTypeViaTypedefs(t2) instanceof IPointerType) {
IType t1 = getExpressionType(binary.getOperand1());
if (SemanticUtil.getUltimateTypeViaTypedefs(t1) instanceof IPointerType) {
IScope scope = getContainingScope(expression);
try {
IBinding[] bs = scope.find(PTRDIFF_T);
if (bs.length > 0) {
for (IBinding b : bs) {
if (b instanceof IType && CPPSemantics.declaredBefore(b, binary, false)) {
return (IType) b;
}
}
}
} catch (DOMException e) {
}
basicType= new CPPBasicType(IBasicType.t_int, ICPPBasicType.IS_LONG | ICPPBasicType.IS_UNSIGNED);
basicType.setValue(expression);
return basicType;
}
return t1;
}
break;
case ICPPASTBinaryExpression.op_pmarrow:
case ICPPASTBinaryExpression.op_pmdot:
IType type = getExpressionType(((IASTBinaryExpression) expression).getOperand2());
if (type instanceof ICPPPointerToMemberType) {
try {
return ((ICPPPointerToMemberType)type).getType();
} catch (DOMException e) {
return e.getProblem();
}
}
return new ProblemBinding(binary, IProblemBinding.SEMANTIC_INVALID_TYPE, new char[0]);
}
return getExpressionType(((IASTBinaryExpression) expression).getOperand1());
} else if (expression instanceof IASTUnaryExpression) {
int op = ((IASTUnaryExpression)expression).getOperator();
if (op == IASTUnaryExpression.op_sizeof) {
IScope scope = getContainingScope(expression);
try {
IBinding[] bs = scope.find(SIZE_T);
if (bs.length > 0 && bs[0] instanceof IType) {
return (IType) bs[0];
}
} catch (DOMException e) {
}
return new CPPBasicType(IBasicType.t_int, ICPPBasicType.IS_LONG | ICPPBasicType.IS_UNSIGNED);
}
IType type = getExpressionType(((IASTUnaryExpression)expression).getOperand());
while (type instanceof ITypedef) {
try {
type = ((ITypeContainer)type).getType();
} catch (DOMException e) {
break;
}
}
if (op == IASTUnaryExpression.op_star && type instanceof ICPPClassType) {
try {
ICPPFunction operator= CPPSemantics.findOperator(expression, (ICPPClassType) type);
if (operator != null) {
return operator.getType().getReturnType();
}
} catch(DOMException de) {
return de.getProblem();
}
}
if (op == IASTUnaryExpression.op_star && (type instanceof IPointerType || type instanceof IArrayType)) {
try {
return ((ITypeContainer) type).getType();
} catch (DOMException e) {
return e.getProblem();
}
} else if (op == IASTUnaryExpression.op_amper) {
if (type instanceof ICPPReferenceType) {
try {
type = ((ICPPReferenceType) type).getType();
} catch (DOMException e) {
}
}
if (type instanceof ICPPFunctionType) {
ICPPFunctionType functionType = (ICPPFunctionType) type;
IPointerType thisType = functionType.getThisType();
if (thisType != null) {
IType nestedType;
try {
nestedType = thisType.getType();
while (nestedType instanceof ITypeContainer) {
nestedType = ((ITypeContainer) nestedType).getType();
}
} catch (DOMException e) {
return e.getProblem();
}
return new CPPPointerToMemberType(type, (ICPPClassType) nestedType,
thisType.isConst(), thisType.isVolatile());
}
}
return new CPPPointerType(type);
} else if (type instanceof CPPBasicType) {
((CPPBasicType) type).setValue(expression);
}
return type;
} else if (expression instanceof ICPPASTFieldReference) {
IASTName name = ((ICPPASTFieldReference)expression).getFieldName();
IBinding binding = name.resolveBinding();
try {
if (binding instanceof IVariable)
return ((IVariable)binding).getType();
else if (binding instanceof IFunction)
return ((IFunction)binding).getType();
else if (binding instanceof IEnumerator)
return ((IEnumerator)binding).getType();
} catch (DOMException e) {
return e.getProblem();
}
} else if (expression instanceof IASTExpressionList) {
IASTExpression[] exps = ((IASTExpressionList)expression).getExpressions();
return getExpressionType(exps[exps.length - 1]);
} else if (expression instanceof ICPPASTTypeIdExpression) {
ICPPASTTypeIdExpression typeidExp = (ICPPASTTypeIdExpression) expression;
if (typeidExp.getOperator() == IASTTypeIdExpression.op_sizeof) {
IScope scope = getContainingScope(typeidExp);
try {
IBinding[] bs = scope.find(SIZE_T);
if (bs.length > 0 && bs[0] instanceof IType) {
return (IType) bs[0];
}
} catch (DOMException e) {
}
return new CPPBasicType(IBasicType.t_int, ICPPBasicType.IS_LONG | ICPPBasicType.IS_UNSIGNED);
}
return createType(typeidExp.getTypeId());
} else if (expression instanceof IASTArraySubscriptExpression) {
IType t = getExpressionType(((IASTArraySubscriptExpression) expression).getArrayExpression());
try {
if (t instanceof ICPPReferenceType)
t = ((ICPPReferenceType)t).getType();
while (t instanceof ITypedef) {
t = ((ITypedef)t).getType();
}
if (t instanceof ICPPClassType) {
ICPPFunction op = CPPSemantics.findOperator(expression, (ICPPClassType) t);
if (op != null) {
return op.getType().getReturnType();
}
}
if (t instanceof IPointerType)
return ((IPointerType)t).getType();
else if (t instanceof IArrayType)
return ((IArrayType)t).getType();
} catch(DOMException e) {
}
} else if (expression instanceof IGNUASTCompoundStatementExpression) {
IASTCompoundStatement compound = ((IGNUASTCompoundStatementExpression)expression).getCompoundStatement();
IASTStatement[] statements = compound.getStatements();
if (statements.length > 0) {
IASTStatement st = statements[statements.length - 1];
if (st instanceof IASTExpressionStatement)
return getExpressionType(((IASTExpressionStatement)st).getExpression());
}
} else if (expression instanceof IASTConditionalExpression) {
final IASTConditionalExpression conditional = (IASTConditionalExpression) expression;
IASTExpression positiveExpression = conditional.getPositiveResultExpression();
if (positiveExpression == null) {
positiveExpression= conditional.getLogicalConditionExpression();
}
IType t2 = getExpressionType(positiveExpression);
IType t3 = getExpressionType(conditional.getNegativeResultExpression());
if (t3 instanceof IPointerType || t2 == null)
return t3;
return t2;
} else if (expression instanceof ICPPASTDeleteExpression) {
return CPPSemantics.VOID_TYPE;
} else if (expression instanceof ICPPASTTypenameExpression) {
IBinding binding = ((ICPPASTTypenameExpression)expression).getName().resolveBinding();
if (binding instanceof IType)
return (IType) binding;
} else if (expression instanceof ICPPASTNewExpression) {
ICPPASTNewExpression newExp = (ICPPASTNewExpression) expression;
return createType(newExp.getTypeId());
}
return null;
}
|
diff --git a/src/main/java/name/kazennikov/morph/aot/TestRun.java b/src/main/java/name/kazennikov/morph/aot/TestRun.java
index 7b9aa01..9062961 100644
--- a/src/main/java/name/kazennikov/morph/aot/TestRun.java
+++ b/src/main/java/name/kazennikov/morph/aot/TestRun.java
@@ -1,236 +1,236 @@
package name.kazennikov.morph.aot;
import gnu.trove.list.array.TIntArrayList;
import gnu.trove.map.hash.TObjectIntHashMap;
import gnu.trove.procedure.TObjectIntProcedure;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import javax.xml.bind.JAXBException;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multiset;
import name.kazennikov.dafsa.CharFSA;
import name.kazennikov.dafsa.CharTrie;
import name.kazennikov.dafsa.FSAException;
import name.kazennikov.dafsa.GenericTrie;
import name.kazennikov.dafsa.IntFSA;
import name.kazennikov.dafsa.IntNFSA;
import name.kazennikov.dafsa.IntNFSAv2;
import name.kazennikov.dafsa.Nodes;
public class TestRun {
public static List<Character> expand(String s) {
List<Character> chars = new ArrayList<Character>();
for(int i = 0; i != s.length(); i++) {
chars.add(s.charAt(i));
}
return chars;
}
public static class FSTNode extends GenericTrie.SimpleNode<Character, Set<Integer>, Integer> {
public FSTNode(Set<Integer> fin) {
super(fin);
}
@Override
public GenericTrie.SimpleNode makeNode() {
return new FSTNode(new HashSet<Integer>());
}
}
public static void main(String[] args) throws JAXBException, IOException, FSAException {
MorphConfig mc = MorphConfig.newInstance(new File("russian.xml"));
final MorphLanguage ml = new MorphLanguage(mc);
long st = System.currentTimeMillis();
MorphDict md = ml.readDict();
final TObjectIntHashMap<BitSet> featSets = new TObjectIntHashMap<BitSet>();
final TObjectIntHashMap<String> lemmaSet = new TObjectIntHashMap<String>();
IntFSA fst = new IntFSA.Simple(new Nodes.IntTroveNode());
CharFSA fsaGold = new CharFSA.Simple(new Nodes.CharTroveNode());
CharFSA fsa = new CharFSA.Simple(new Nodes.CharSimpleNode());
CharTrie charTrie = new CharTrie();
TIntArrayList fstInput = new TIntArrayList();
long st1 = System.currentTimeMillis();
int count = 0;
for(MorphDict.Lemma lemma : md.lemmas) {
int lemmaId = lemmaSet.get(lemma.lemma);
if(lemmaId == 0) {
lemmaId = lemmaSet.size() + 1;
lemmaSet.put(lemma.lemma, lemmaId);
}
- for(MorphDict.WordForm wf : lemma.expand()) {
+ for(MorphDict.WordForm wf : lemma.expand(true)) {
BitSet feats = ml.getWordFormFeats(wf.feats, wf.commonAnCode);
int featId = featSets.get(feats);
if(featId == 0) {
featId = featSets.size() + 1;
featSets.put(feats, featId);
}
count++;
//System.out.println(wf.wordForm);
//MorphCompiler.expand(fstInput, wf.wordForm, wf.lemma);
//fst.add(fstInput, featId);
//fsaGold.addMinWord(wf.getWordForm(), featId);
fsa.addMinWord(wf.getWordForm(), featId);
//charTrie.add(wf.getWordForm(), featId);
//charTrie.add(fstInput, featId);
// if(fsa.size() != fsaGold.size()) {
// count = count;
// }
}
}
System.out.printf("%d ms%n", System.currentTimeMillis() - st1);
PrintWriter pw = new PrintWriter("mama.dot");
fst.write(new IntFSA.FSTDotFormatter(pw));
pw.close();
st = System.currentTimeMillis() - st;
System.out.printf("Elapsed: %d ms%n", st);
System.out.printf("FSA size: %d%n", fst.size());
System.out.printf("FSA size: %d%n", fsa.size());
System.out.printf("charTrie size: %d%n", charTrie.size());
System.out.printf("Dict size: %d%n", md.lemmas.size());
System.out.printf("featSets: %d%n", featSets.size());
System.out.printf("Wordforms: %d%n", count);
final AtomicInteger stateFinals = new AtomicInteger(0);
charTrie.write(new IntFSA.Events() {
int state = 0;
@Override
public void transitions(int n) throws FSAException {
// TODO Auto-generated method stub
}
@Override
public void transition(int input, int dest) throws FSAException {
// TODO Auto-generated method stub
}
@Override
public void states(int states) throws FSAException {
// TODO Auto-generated method stub
}
@Override
public void stateFinal(int fin) throws FSAException {
// TODO Auto-generated method stub
}
@Override
public void state(int state) throws FSAException {
this.state = state;
}
@Override
public void startTransitions() {
// TODO Auto-generated method stub
}
@Override
public void startStates() {
// TODO Auto-generated method stub
}
@Override
public void startState() {
// TODO Auto-generated method stub
}
@Override
public void startFinals() {
// TODO Auto-generated method stub
}
@Override
public void finals(int n) throws FSAException {
if(n > 0) {
stateFinals.incrementAndGet();
}
}
@Override
public void endTransitions() {
// TODO Auto-generated method stub
}
@Override
public void endStates() {
// TODO Auto-generated method stub
}
@Override
public void endState() {
// TODO Auto-generated method stub
}
@Override
public void endFinals() {
// TODO Auto-generated method stub
}
});
System.out.printf("State with finals (charTrie): %d%n", stateFinals.get());
IntNFSAv2.IntNFSABuilder intFSTBuilder = new IntNFSAv2.IntNFSABuilder();
fst.write(intFSTBuilder);
IntNFSAv2 nfsa = intFSTBuilder.build();
final BitSet[] fss = new BitSet[featSets.size() + 1];
featSets.forEachEntry(new TObjectIntProcedure<BitSet>() {
@Override
public boolean execute(BitSet a, int b) {
fss[b] = a;
return true;
}
});
}
}
| true | true | public static void main(String[] args) throws JAXBException, IOException, FSAException {
MorphConfig mc = MorphConfig.newInstance(new File("russian.xml"));
final MorphLanguage ml = new MorphLanguage(mc);
long st = System.currentTimeMillis();
MorphDict md = ml.readDict();
final TObjectIntHashMap<BitSet> featSets = new TObjectIntHashMap<BitSet>();
final TObjectIntHashMap<String> lemmaSet = new TObjectIntHashMap<String>();
IntFSA fst = new IntFSA.Simple(new Nodes.IntTroveNode());
CharFSA fsaGold = new CharFSA.Simple(new Nodes.CharTroveNode());
CharFSA fsa = new CharFSA.Simple(new Nodes.CharSimpleNode());
CharTrie charTrie = new CharTrie();
TIntArrayList fstInput = new TIntArrayList();
long st1 = System.currentTimeMillis();
int count = 0;
for(MorphDict.Lemma lemma : md.lemmas) {
int lemmaId = lemmaSet.get(lemma.lemma);
if(lemmaId == 0) {
lemmaId = lemmaSet.size() + 1;
lemmaSet.put(lemma.lemma, lemmaId);
}
for(MorphDict.WordForm wf : lemma.expand()) {
BitSet feats = ml.getWordFormFeats(wf.feats, wf.commonAnCode);
int featId = featSets.get(feats);
if(featId == 0) {
featId = featSets.size() + 1;
featSets.put(feats, featId);
}
count++;
//System.out.println(wf.wordForm);
//MorphCompiler.expand(fstInput, wf.wordForm, wf.lemma);
//fst.add(fstInput, featId);
//fsaGold.addMinWord(wf.getWordForm(), featId);
fsa.addMinWord(wf.getWordForm(), featId);
//charTrie.add(wf.getWordForm(), featId);
//charTrie.add(fstInput, featId);
// if(fsa.size() != fsaGold.size()) {
// count = count;
// }
}
}
System.out.printf("%d ms%n", System.currentTimeMillis() - st1);
PrintWriter pw = new PrintWriter("mama.dot");
fst.write(new IntFSA.FSTDotFormatter(pw));
pw.close();
st = System.currentTimeMillis() - st;
System.out.printf("Elapsed: %d ms%n", st);
System.out.printf("FSA size: %d%n", fst.size());
System.out.printf("FSA size: %d%n", fsa.size());
System.out.printf("charTrie size: %d%n", charTrie.size());
System.out.printf("Dict size: %d%n", md.lemmas.size());
System.out.printf("featSets: %d%n", featSets.size());
System.out.printf("Wordforms: %d%n", count);
final AtomicInteger stateFinals = new AtomicInteger(0);
charTrie.write(new IntFSA.Events() {
int state = 0;
@Override
public void transitions(int n) throws FSAException {
// TODO Auto-generated method stub
}
@Override
public void transition(int input, int dest) throws FSAException {
// TODO Auto-generated method stub
}
@Override
public void states(int states) throws FSAException {
// TODO Auto-generated method stub
}
@Override
public void stateFinal(int fin) throws FSAException {
// TODO Auto-generated method stub
}
@Override
public void state(int state) throws FSAException {
this.state = state;
}
@Override
public void startTransitions() {
// TODO Auto-generated method stub
}
@Override
public void startStates() {
// TODO Auto-generated method stub
}
@Override
public void startState() {
// TODO Auto-generated method stub
}
@Override
public void startFinals() {
// TODO Auto-generated method stub
}
@Override
public void finals(int n) throws FSAException {
if(n > 0) {
stateFinals.incrementAndGet();
}
}
@Override
public void endTransitions() {
// TODO Auto-generated method stub
}
@Override
public void endStates() {
// TODO Auto-generated method stub
}
@Override
public void endState() {
// TODO Auto-generated method stub
}
@Override
public void endFinals() {
// TODO Auto-generated method stub
}
});
System.out.printf("State with finals (charTrie): %d%n", stateFinals.get());
IntNFSAv2.IntNFSABuilder intFSTBuilder = new IntNFSAv2.IntNFSABuilder();
fst.write(intFSTBuilder);
IntNFSAv2 nfsa = intFSTBuilder.build();
final BitSet[] fss = new BitSet[featSets.size() + 1];
featSets.forEachEntry(new TObjectIntProcedure<BitSet>() {
@Override
public boolean execute(BitSet a, int b) {
fss[b] = a;
return true;
}
});
}
| public static void main(String[] args) throws JAXBException, IOException, FSAException {
MorphConfig mc = MorphConfig.newInstance(new File("russian.xml"));
final MorphLanguage ml = new MorphLanguage(mc);
long st = System.currentTimeMillis();
MorphDict md = ml.readDict();
final TObjectIntHashMap<BitSet> featSets = new TObjectIntHashMap<BitSet>();
final TObjectIntHashMap<String> lemmaSet = new TObjectIntHashMap<String>();
IntFSA fst = new IntFSA.Simple(new Nodes.IntTroveNode());
CharFSA fsaGold = new CharFSA.Simple(new Nodes.CharTroveNode());
CharFSA fsa = new CharFSA.Simple(new Nodes.CharSimpleNode());
CharTrie charTrie = new CharTrie();
TIntArrayList fstInput = new TIntArrayList();
long st1 = System.currentTimeMillis();
int count = 0;
for(MorphDict.Lemma lemma : md.lemmas) {
int lemmaId = lemmaSet.get(lemma.lemma);
if(lemmaId == 0) {
lemmaId = lemmaSet.size() + 1;
lemmaSet.put(lemma.lemma, lemmaId);
}
for(MorphDict.WordForm wf : lemma.expand(true)) {
BitSet feats = ml.getWordFormFeats(wf.feats, wf.commonAnCode);
int featId = featSets.get(feats);
if(featId == 0) {
featId = featSets.size() + 1;
featSets.put(feats, featId);
}
count++;
//System.out.println(wf.wordForm);
//MorphCompiler.expand(fstInput, wf.wordForm, wf.lemma);
//fst.add(fstInput, featId);
//fsaGold.addMinWord(wf.getWordForm(), featId);
fsa.addMinWord(wf.getWordForm(), featId);
//charTrie.add(wf.getWordForm(), featId);
//charTrie.add(fstInput, featId);
// if(fsa.size() != fsaGold.size()) {
// count = count;
// }
}
}
System.out.printf("%d ms%n", System.currentTimeMillis() - st1);
PrintWriter pw = new PrintWriter("mama.dot");
fst.write(new IntFSA.FSTDotFormatter(pw));
pw.close();
st = System.currentTimeMillis() - st;
System.out.printf("Elapsed: %d ms%n", st);
System.out.printf("FSA size: %d%n", fst.size());
System.out.printf("FSA size: %d%n", fsa.size());
System.out.printf("charTrie size: %d%n", charTrie.size());
System.out.printf("Dict size: %d%n", md.lemmas.size());
System.out.printf("featSets: %d%n", featSets.size());
System.out.printf("Wordforms: %d%n", count);
final AtomicInteger stateFinals = new AtomicInteger(0);
charTrie.write(new IntFSA.Events() {
int state = 0;
@Override
public void transitions(int n) throws FSAException {
// TODO Auto-generated method stub
}
@Override
public void transition(int input, int dest) throws FSAException {
// TODO Auto-generated method stub
}
@Override
public void states(int states) throws FSAException {
// TODO Auto-generated method stub
}
@Override
public void stateFinal(int fin) throws FSAException {
// TODO Auto-generated method stub
}
@Override
public void state(int state) throws FSAException {
this.state = state;
}
@Override
public void startTransitions() {
// TODO Auto-generated method stub
}
@Override
public void startStates() {
// TODO Auto-generated method stub
}
@Override
public void startState() {
// TODO Auto-generated method stub
}
@Override
public void startFinals() {
// TODO Auto-generated method stub
}
@Override
public void finals(int n) throws FSAException {
if(n > 0) {
stateFinals.incrementAndGet();
}
}
@Override
public void endTransitions() {
// TODO Auto-generated method stub
}
@Override
public void endStates() {
// TODO Auto-generated method stub
}
@Override
public void endState() {
// TODO Auto-generated method stub
}
@Override
public void endFinals() {
// TODO Auto-generated method stub
}
});
System.out.printf("State with finals (charTrie): %d%n", stateFinals.get());
IntNFSAv2.IntNFSABuilder intFSTBuilder = new IntNFSAv2.IntNFSABuilder();
fst.write(intFSTBuilder);
IntNFSAv2 nfsa = intFSTBuilder.build();
final BitSet[] fss = new BitSet[featSets.size() + 1];
featSets.forEachEntry(new TObjectIntProcedure<BitSet>() {
@Override
public boolean execute(BitSet a, int b) {
fss[b] = a;
return true;
}
});
}
|
diff --git a/src/main/java/org/cchmc/bmi/snpomics/annotation/annotator/TranscriptEffectAnnotator.java b/src/main/java/org/cchmc/bmi/snpomics/annotation/annotator/TranscriptEffectAnnotator.java
index 58dd255..fbd1e99 100644
--- a/src/main/java/org/cchmc/bmi/snpomics/annotation/annotator/TranscriptEffectAnnotator.java
+++ b/src/main/java/org/cchmc/bmi/snpomics/annotation/annotator/TranscriptEffectAnnotator.java
@@ -1,224 +1,224 @@
package org.cchmc.bmi.snpomics.annotation.annotator;
import java.util.ArrayList;
import java.util.List;
import org.cchmc.bmi.snpomics.GenomicSpan;
import org.cchmc.bmi.snpomics.SimpleVariant;
import org.cchmc.bmi.snpomics.annotation.factory.AnnotationFactory;
import org.cchmc.bmi.snpomics.annotation.interactive.HgvsDnaName;
import org.cchmc.bmi.snpomics.annotation.interactive.TranscriptEffectAnnotation;
import org.cchmc.bmi.snpomics.annotation.loader.TranscriptLoader;
import org.cchmc.bmi.snpomics.annotation.reference.TranscriptAnnotation;
import org.cchmc.bmi.snpomics.translation.AminoAcid;
import org.cchmc.bmi.snpomics.translation.GeneticCode;
import org.cchmc.bmi.snpomics.util.BaseUtils;
public class TranscriptEffectAnnotator implements Annotator<TranscriptEffectAnnotation> {
@Override
public List<TranscriptEffectAnnotation> annotate(SimpleVariant variant,
AnnotationFactory factory) {
TranscriptLoader loader = (TranscriptLoader) factory.getLoader(TranscriptAnnotation.class);
loader.enableLookaheadCache();
GeneticCode code = GeneticCode.getTable(factory.getGenome().getTransTableId(variant.getPosition().getChromosome()));
List<TranscriptEffectAnnotation> result = new ArrayList<TranscriptEffectAnnotation>();
for (TranscriptAnnotation tx : loader.loadByOverlappingPosition(variant.getPosition())) {
TranscriptEffectAnnotation effect = new TranscriptEffectAnnotation(tx);
long startCoord = variant.getPosition().getStart();
long endCoord = variant.getPosition().getEnd();
if (variant.isInvariant()) {
effect.setCdnaStartCoord(getHgvsCoord(tx, startCoord));
if (endCoord != startCoord)
effect.setCdnaEndCoord(getHgvsCoord(tx, endCoord));
} else {
String ref = variant.getRef();
String alt = variant.getAlt();
//Normalize alleles to remove common parts
while (ref.length() > 0 && alt.length() > 0 && ref.charAt(0) == alt.charAt(0)) {
ref = ref.substring(1);
alt = alt.substring(1);
startCoord += 1;
}
//Switch strands if appropriate
int dir = 1;
if (!tx.isOnForwardStrand()) {
ref = BaseUtils.reverseComplement(ref);
alt = BaseUtils.reverseComplement(alt);
long temp = startCoord;
startCoord = endCoord;
endCoord = temp;
dir = -1;
}
effect.setCdnaRefAllele(ref);
effect.setCdnaAltAllele(alt);
//Insertions are given the flanking coordinates
if (ref.isEmpty()) {
effect.setCdnaStartCoord(getHgvsCoord(tx, startCoord-dir));
effect.setCdnaEndCoord(getHgvsCoord(tx, endCoord+dir));
} else {
effect.setCdnaStartCoord(getHgvsCoord(tx, startCoord));
if (endCoord != startCoord)
effect.setCdnaEndCoord(getHgvsCoord(tx, endCoord));
}
HgvsDnaName dna = effect.getHgvsCdnaObject();
- if (dna.isCoding() && dna.affectsSplicing())
+ if (tx.isProteinCoding() && dna.affectsSplicing())
effect.setProtUnknownEffect();
else if (dna.isCoding() && (tx.getCdsLength() % 3 == 0)) {
loader.loadSequence(tx);
int cdnaStart = dna.getNearestCodingNtToStart();
int cdnaEnd = dna.getNearestCodingNtToEnd();
//Revert the insertion coordinates
//Conditionals account for insertions between an intron and exon
// (which we assume become exonic)
if (ref.isEmpty()) {
if (dna.getStartCoord().equals(Integer.toString(cdnaStart))) cdnaStart++;
if (dna.getEndCoord().equals(Integer.toString(cdnaEnd))) cdnaEnd--;
}
String cdsSeq = tx.getCodingSequence();
int codonStart = (cdnaStart-1) / 3 + 1;
int codonEnd = (cdnaEnd-1) / 3 + 1;
//Determine how many codons 5' of the variation to pull
//This is usually 1, but we need more for insertions to determine
//duplications
int prefixCodons = 1;
if (alt.length() > ref.length())
prefixCodons = ((alt.length() - ref.length()) / 3) + 1;
if (codonStart > prefixCodons)
codonStart -= prefixCodons;
else
codonStart = 1; //Might not be necessary, but grab as much as possible
if ((codonEnd+1)*3 <= cdsSeq.length()) codonEnd++;
effect.setProtStartPos(codonStart);
String refDNA = cdsSeq.substring((codonStart-1)*3, codonEnd*3);
String altDNA = refDNA.substring(0, cdnaStart-(codonStart-1)*3-1) +
alt +
refDNA.substring(cdnaEnd-(codonStart-1)*3);
List<AminoAcid> refAA = code.translate(refDNA);
effect.setProtRefAllele(refAA);
String utr3Sequence = tx.getSplicedSequence().substring(tx.get5UtrLength()+tx.getCdsLength());
//This is a specific special case:
// If we have a deletion that starts in the CDS and includes part of the UTR,
// We want to be sure that the appropriate nts are deleted from the UTR
// and grab enough nts from the modified UTR to fill in the stop codon.
// Example: deleting tAACaac is a synonymous mutation, since the TAA-stop is preserved
if (codonEnd*3 == cdsSeq.length() &&
ref.length() > alt.length() &&
refDNA.length() - altDNA.length() < ref.length() - alt.length()) {
int expectedLength = ref.length() - alt.length();
int observedLength = refDNA.length() - altDNA.length();
if (expectedLength > utr3Sequence.length())
effect.setProtUnknownEffect();
else
altDNA += utr3Sequence.substring(expectedLength-observedLength, expectedLength);
effect.setProtFrameshift(Math.abs(alt.length()-ref.length()) % 3 != 0);
} else if (Math.abs(alt.length()-ref.length()) % 3 != 0) {
effect.setProtFrameshift(true);
altDNA += cdsSeq.substring(codonEnd*3);
}
effect.setProtExtension(code.translate(cdsSeq.substring(codonEnd*3)+
utr3Sequence));
effect.setProtAltAllele(code.translate(altDNA));
}
}
result.add(effect);
}
return result;
}
/**
* Generates the HGVS-style coordinate of a position in genomic coordinates relative
* to the cDNA represented by tx
* @param tx
* @param genomicCoord
* @return
*/
private String getHgvsCoord(TranscriptAnnotation tx, long genomicCoord) {
GenomicSpan span = new GenomicSpan(tx.getPosition().getChromosome(), genomicCoord);
//There are three basic cases here:
// 1) The position is inside an exon (either coding or UTR)
// 2) The position is inside an intron (again, could be in a UTR)
// 3) The position is outside the transcript (ie, one end of a deletion)
if (tx.contains(span)) {
if (tx.exonContains(span)) {
//In an exon: Coding nts are a positive number, 5' UTR are negative, 3' UTR are positive but prefixed with '*'
int pos = 1;
for (GenomicSpan x : tx.getExons()) {
if (x.getEnd() < genomicCoord)
pos += x.length();
else if (x.getStart() < genomicCoord)
pos += genomicCoord - x.getStart();
else
break; //We've passed it, no need to keep looking
}
if (!tx.isOnForwardStrand())
pos = tx.length() - pos + 1;
pos -= tx.get5UtrLength();
//There is no position 0 - it transitions from -1 to 1
if (pos < 1) pos -= 1;
if (pos > tx.getCdsLength()) {
pos -= tx.getCdsLength();
return "*"+pos;
}
return ""+pos;
} else {
//In an intron: Coord is nearest exonic nt followed by distance and direction (+12, -43)
long closest = 0;
long closestdist = 1000000000;
for (GenomicSpan x : tx.getExons()) {
//The complex second clause in the ifs is to properly break ties.
//In the case that a position is in the dead center of the intron (equidistant from
//both exons), it should be reported relative to the preceding exon (ie, 2+3, not 3-3)
//This, of course, depends on strand
if (genomicCoord < x.getStart()) {
if ((x.getStart() - genomicCoord < Math.abs(closestdist)) ||
(!tx.isOnForwardStrand() && x.getStart() - genomicCoord == Math.abs(closestdist))) {
closest = x.getStart();
closestdist = genomicCoord - closest;
}
} else {
if ((genomicCoord - x.getEnd() < Math.abs(closestdist)) ||
(tx.isOnForwardStrand() && genomicCoord - x.getEnd() == Math.abs(closestdist))) {
closest = x.getEnd();
closestdist = genomicCoord - closest;
}
}
}
if (!tx.isOnForwardStrand())
closestdist *= -1;
StringBuilder sb = new StringBuilder();
sb.append(getHgvsCoord(tx, closest));
if (closestdist > 0)
sb.append("+");
sb.append(closestdist);
return sb.toString();
}
} else {
//Outside the transcript
//4 cases: left/right of a transcript on the +/- strand
// Left/+ and right/- are upstream
// Right/+ and left/- are downstream
long distance = 0;
String nearestNT;
if (genomicCoord < tx.getPosition().getStart()) {
nearestNT = getHgvsCoord(tx, tx.getPosition().getStart());
distance = genomicCoord - tx.getPosition().getStart();
} else {
nearestNT = getHgvsCoord(tx, tx.getPosition().getEnd());
distance = genomicCoord - tx.getPosition().getEnd();
}
if (!tx.isOnForwardStrand())
distance *= -1;
if (distance < 0)
return nearestNT + "-u" + Long.toString(Math.abs(distance));
else
return nearestNT + "+d" + Long.toString(distance);
}
}
@Override
public Class<TranscriptEffectAnnotation> getAnnotationClass() {
return TranscriptEffectAnnotation.class;
}
}
| true | true | public List<TranscriptEffectAnnotation> annotate(SimpleVariant variant,
AnnotationFactory factory) {
TranscriptLoader loader = (TranscriptLoader) factory.getLoader(TranscriptAnnotation.class);
loader.enableLookaheadCache();
GeneticCode code = GeneticCode.getTable(factory.getGenome().getTransTableId(variant.getPosition().getChromosome()));
List<TranscriptEffectAnnotation> result = new ArrayList<TranscriptEffectAnnotation>();
for (TranscriptAnnotation tx : loader.loadByOverlappingPosition(variant.getPosition())) {
TranscriptEffectAnnotation effect = new TranscriptEffectAnnotation(tx);
long startCoord = variant.getPosition().getStart();
long endCoord = variant.getPosition().getEnd();
if (variant.isInvariant()) {
effect.setCdnaStartCoord(getHgvsCoord(tx, startCoord));
if (endCoord != startCoord)
effect.setCdnaEndCoord(getHgvsCoord(tx, endCoord));
} else {
String ref = variant.getRef();
String alt = variant.getAlt();
//Normalize alleles to remove common parts
while (ref.length() > 0 && alt.length() > 0 && ref.charAt(0) == alt.charAt(0)) {
ref = ref.substring(1);
alt = alt.substring(1);
startCoord += 1;
}
//Switch strands if appropriate
int dir = 1;
if (!tx.isOnForwardStrand()) {
ref = BaseUtils.reverseComplement(ref);
alt = BaseUtils.reverseComplement(alt);
long temp = startCoord;
startCoord = endCoord;
endCoord = temp;
dir = -1;
}
effect.setCdnaRefAllele(ref);
effect.setCdnaAltAllele(alt);
//Insertions are given the flanking coordinates
if (ref.isEmpty()) {
effect.setCdnaStartCoord(getHgvsCoord(tx, startCoord-dir));
effect.setCdnaEndCoord(getHgvsCoord(tx, endCoord+dir));
} else {
effect.setCdnaStartCoord(getHgvsCoord(tx, startCoord));
if (endCoord != startCoord)
effect.setCdnaEndCoord(getHgvsCoord(tx, endCoord));
}
HgvsDnaName dna = effect.getHgvsCdnaObject();
if (dna.isCoding() && dna.affectsSplicing())
effect.setProtUnknownEffect();
else if (dna.isCoding() && (tx.getCdsLength() % 3 == 0)) {
loader.loadSequence(tx);
int cdnaStart = dna.getNearestCodingNtToStart();
int cdnaEnd = dna.getNearestCodingNtToEnd();
//Revert the insertion coordinates
//Conditionals account for insertions between an intron and exon
// (which we assume become exonic)
if (ref.isEmpty()) {
if (dna.getStartCoord().equals(Integer.toString(cdnaStart))) cdnaStart++;
if (dna.getEndCoord().equals(Integer.toString(cdnaEnd))) cdnaEnd--;
}
String cdsSeq = tx.getCodingSequence();
int codonStart = (cdnaStart-1) / 3 + 1;
int codonEnd = (cdnaEnd-1) / 3 + 1;
//Determine how many codons 5' of the variation to pull
//This is usually 1, but we need more for insertions to determine
//duplications
int prefixCodons = 1;
if (alt.length() > ref.length())
prefixCodons = ((alt.length() - ref.length()) / 3) + 1;
if (codonStart > prefixCodons)
codonStart -= prefixCodons;
else
codonStart = 1; //Might not be necessary, but grab as much as possible
if ((codonEnd+1)*3 <= cdsSeq.length()) codonEnd++;
effect.setProtStartPos(codonStart);
String refDNA = cdsSeq.substring((codonStart-1)*3, codonEnd*3);
String altDNA = refDNA.substring(0, cdnaStart-(codonStart-1)*3-1) +
alt +
refDNA.substring(cdnaEnd-(codonStart-1)*3);
List<AminoAcid> refAA = code.translate(refDNA);
effect.setProtRefAllele(refAA);
String utr3Sequence = tx.getSplicedSequence().substring(tx.get5UtrLength()+tx.getCdsLength());
//This is a specific special case:
// If we have a deletion that starts in the CDS and includes part of the UTR,
// We want to be sure that the appropriate nts are deleted from the UTR
// and grab enough nts from the modified UTR to fill in the stop codon.
// Example: deleting tAACaac is a synonymous mutation, since the TAA-stop is preserved
if (codonEnd*3 == cdsSeq.length() &&
ref.length() > alt.length() &&
refDNA.length() - altDNA.length() < ref.length() - alt.length()) {
int expectedLength = ref.length() - alt.length();
int observedLength = refDNA.length() - altDNA.length();
if (expectedLength > utr3Sequence.length())
effect.setProtUnknownEffect();
else
altDNA += utr3Sequence.substring(expectedLength-observedLength, expectedLength);
effect.setProtFrameshift(Math.abs(alt.length()-ref.length()) % 3 != 0);
} else if (Math.abs(alt.length()-ref.length()) % 3 != 0) {
effect.setProtFrameshift(true);
altDNA += cdsSeq.substring(codonEnd*3);
}
effect.setProtExtension(code.translate(cdsSeq.substring(codonEnd*3)+
utr3Sequence));
effect.setProtAltAllele(code.translate(altDNA));
}
}
result.add(effect);
}
return result;
}
| public List<TranscriptEffectAnnotation> annotate(SimpleVariant variant,
AnnotationFactory factory) {
TranscriptLoader loader = (TranscriptLoader) factory.getLoader(TranscriptAnnotation.class);
loader.enableLookaheadCache();
GeneticCode code = GeneticCode.getTable(factory.getGenome().getTransTableId(variant.getPosition().getChromosome()));
List<TranscriptEffectAnnotation> result = new ArrayList<TranscriptEffectAnnotation>();
for (TranscriptAnnotation tx : loader.loadByOverlappingPosition(variant.getPosition())) {
TranscriptEffectAnnotation effect = new TranscriptEffectAnnotation(tx);
long startCoord = variant.getPosition().getStart();
long endCoord = variant.getPosition().getEnd();
if (variant.isInvariant()) {
effect.setCdnaStartCoord(getHgvsCoord(tx, startCoord));
if (endCoord != startCoord)
effect.setCdnaEndCoord(getHgvsCoord(tx, endCoord));
} else {
String ref = variant.getRef();
String alt = variant.getAlt();
//Normalize alleles to remove common parts
while (ref.length() > 0 && alt.length() > 0 && ref.charAt(0) == alt.charAt(0)) {
ref = ref.substring(1);
alt = alt.substring(1);
startCoord += 1;
}
//Switch strands if appropriate
int dir = 1;
if (!tx.isOnForwardStrand()) {
ref = BaseUtils.reverseComplement(ref);
alt = BaseUtils.reverseComplement(alt);
long temp = startCoord;
startCoord = endCoord;
endCoord = temp;
dir = -1;
}
effect.setCdnaRefAllele(ref);
effect.setCdnaAltAllele(alt);
//Insertions are given the flanking coordinates
if (ref.isEmpty()) {
effect.setCdnaStartCoord(getHgvsCoord(tx, startCoord-dir));
effect.setCdnaEndCoord(getHgvsCoord(tx, endCoord+dir));
} else {
effect.setCdnaStartCoord(getHgvsCoord(tx, startCoord));
if (endCoord != startCoord)
effect.setCdnaEndCoord(getHgvsCoord(tx, endCoord));
}
HgvsDnaName dna = effect.getHgvsCdnaObject();
if (tx.isProteinCoding() && dna.affectsSplicing())
effect.setProtUnknownEffect();
else if (dna.isCoding() && (tx.getCdsLength() % 3 == 0)) {
loader.loadSequence(tx);
int cdnaStart = dna.getNearestCodingNtToStart();
int cdnaEnd = dna.getNearestCodingNtToEnd();
//Revert the insertion coordinates
//Conditionals account for insertions between an intron and exon
// (which we assume become exonic)
if (ref.isEmpty()) {
if (dna.getStartCoord().equals(Integer.toString(cdnaStart))) cdnaStart++;
if (dna.getEndCoord().equals(Integer.toString(cdnaEnd))) cdnaEnd--;
}
String cdsSeq = tx.getCodingSequence();
int codonStart = (cdnaStart-1) / 3 + 1;
int codonEnd = (cdnaEnd-1) / 3 + 1;
//Determine how many codons 5' of the variation to pull
//This is usually 1, but we need more for insertions to determine
//duplications
int prefixCodons = 1;
if (alt.length() > ref.length())
prefixCodons = ((alt.length() - ref.length()) / 3) + 1;
if (codonStart > prefixCodons)
codonStart -= prefixCodons;
else
codonStart = 1; //Might not be necessary, but grab as much as possible
if ((codonEnd+1)*3 <= cdsSeq.length()) codonEnd++;
effect.setProtStartPos(codonStart);
String refDNA = cdsSeq.substring((codonStart-1)*3, codonEnd*3);
String altDNA = refDNA.substring(0, cdnaStart-(codonStart-1)*3-1) +
alt +
refDNA.substring(cdnaEnd-(codonStart-1)*3);
List<AminoAcid> refAA = code.translate(refDNA);
effect.setProtRefAllele(refAA);
String utr3Sequence = tx.getSplicedSequence().substring(tx.get5UtrLength()+tx.getCdsLength());
//This is a specific special case:
// If we have a deletion that starts in the CDS and includes part of the UTR,
// We want to be sure that the appropriate nts are deleted from the UTR
// and grab enough nts from the modified UTR to fill in the stop codon.
// Example: deleting tAACaac is a synonymous mutation, since the TAA-stop is preserved
if (codonEnd*3 == cdsSeq.length() &&
ref.length() > alt.length() &&
refDNA.length() - altDNA.length() < ref.length() - alt.length()) {
int expectedLength = ref.length() - alt.length();
int observedLength = refDNA.length() - altDNA.length();
if (expectedLength > utr3Sequence.length())
effect.setProtUnknownEffect();
else
altDNA += utr3Sequence.substring(expectedLength-observedLength, expectedLength);
effect.setProtFrameshift(Math.abs(alt.length()-ref.length()) % 3 != 0);
} else if (Math.abs(alt.length()-ref.length()) % 3 != 0) {
effect.setProtFrameshift(true);
altDNA += cdsSeq.substring(codonEnd*3);
}
effect.setProtExtension(code.translate(cdsSeq.substring(codonEnd*3)+
utr3Sequence));
effect.setProtAltAllele(code.translate(altDNA));
}
}
result.add(effect);
}
return result;
}
|
diff --git a/src/com/sk/api/impl/LinkedinApiSearcher.java b/src/com/sk/api/impl/LinkedinApiSearcher.java
index f45c610..bc4aeb7 100644
--- a/src/com/sk/api/impl/LinkedinApiSearcher.java
+++ b/src/com/sk/api/impl/LinkedinApiSearcher.java
@@ -1,79 +1,81 @@
package com.sk.api.impl;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.parser.Parser;
import org.scribe.builder.api.LinkedInApi;
import org.scribe.model.OAuthRequest;
import org.scribe.model.Response;
import org.scribe.model.Verb;
import com.sk.api.AbstractApiSearcher;
import com.sk.api.ApiUtility;
import com.sk.util.PersonalData;
import com.sk.util.parse.scrape.BasicGrabber;
import com.sk.util.parse.scrape.Grabber;
public class LinkedinApiSearcher extends AbstractApiSearcher {
public LinkedinApiSearcher() {
super(new ApiUtility(LinkedInApi.class));
util.init("gtgrab");
}
private static final String BASE = "http://api.linkedin.com/v1/people-search:(people:(api-standard-profile-request))?count=25";
private static final String REQUEST_FIELDS = ":(first-name,last-name,headline,location:(name,country:(code)),industry,summary,specialties,positions)";
@Override
public OAuthRequest getNameRequest(String first, String last) {
try {
return new OAuthRequest(Verb.GET, BASE + "&first-name=" + URLEncoder.encode(first, "UTF-8")
+ "&last-name=" + URLEncoder.encode(last, "UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException();
}
}
private static final Grabber[] grabbers = { new BasicGrabber("first-name", "first-name"),
new BasicGrabber("last-name", "last-name"), new BasicGrabber("location name", "location"),
new BasicGrabber("location country code", "country"), new BasicGrabber("industry", "industry"),
new BasicGrabber("headline", "job-title") };
@Override
public boolean parseResponse(Response resp) {
if (resp == null)
return false;
String body = resp.getBody();
if (body == null || body.length() == 0)
return false;
Document xdoc = Jsoup.parse(body, "", Parser.xmlParser());
List<PersonalData> data = new ArrayList<PersonalData>();
for (Element person : xdoc.select("person")) {
String url = person.select("api-standard-profile-request url").text();
+ if (url.length() < 10)
+ continue;
OAuthRequest req = new OAuthRequest(Verb.GET, url + REQUEST_FIELDS);
for (Element httpHeader : person.select("api-standard-profile-request http-header")) {
req.addHeader(httpHeader.select("name").text(), httpHeader.select("value").text());
}
Response presp = util.send(req);
String pbody = presp.getBody();
if (pbody == null || pbody.length() == 0)
continue;
PersonalData dat = new PersonalData("linkedin");
Document pdoc = Jsoup.parse(pbody, "", Parser.xmlParser());
for (Grabber g : grabbers) {
g.grab(pdoc, dat);
}
dat.put("name", dat.get("first-name").get() + " " + dat.get("last-name").get());
data.add(dat);
}
this.data.set(data.toArray(new PersonalData[data.size()]));
return true;
}
}
| true | true | public boolean parseResponse(Response resp) {
if (resp == null)
return false;
String body = resp.getBody();
if (body == null || body.length() == 0)
return false;
Document xdoc = Jsoup.parse(body, "", Parser.xmlParser());
List<PersonalData> data = new ArrayList<PersonalData>();
for (Element person : xdoc.select("person")) {
String url = person.select("api-standard-profile-request url").text();
OAuthRequest req = new OAuthRequest(Verb.GET, url + REQUEST_FIELDS);
for (Element httpHeader : person.select("api-standard-profile-request http-header")) {
req.addHeader(httpHeader.select("name").text(), httpHeader.select("value").text());
}
Response presp = util.send(req);
String pbody = presp.getBody();
if (pbody == null || pbody.length() == 0)
continue;
PersonalData dat = new PersonalData("linkedin");
Document pdoc = Jsoup.parse(pbody, "", Parser.xmlParser());
for (Grabber g : grabbers) {
g.grab(pdoc, dat);
}
dat.put("name", dat.get("first-name").get() + " " + dat.get("last-name").get());
data.add(dat);
}
this.data.set(data.toArray(new PersonalData[data.size()]));
return true;
}
| public boolean parseResponse(Response resp) {
if (resp == null)
return false;
String body = resp.getBody();
if (body == null || body.length() == 0)
return false;
Document xdoc = Jsoup.parse(body, "", Parser.xmlParser());
List<PersonalData> data = new ArrayList<PersonalData>();
for (Element person : xdoc.select("person")) {
String url = person.select("api-standard-profile-request url").text();
if (url.length() < 10)
continue;
OAuthRequest req = new OAuthRequest(Verb.GET, url + REQUEST_FIELDS);
for (Element httpHeader : person.select("api-standard-profile-request http-header")) {
req.addHeader(httpHeader.select("name").text(), httpHeader.select("value").text());
}
Response presp = util.send(req);
String pbody = presp.getBody();
if (pbody == null || pbody.length() == 0)
continue;
PersonalData dat = new PersonalData("linkedin");
Document pdoc = Jsoup.parse(pbody, "", Parser.xmlParser());
for (Grabber g : grabbers) {
g.grab(pdoc, dat);
}
dat.put("name", dat.get("first-name").get() + " " + dat.get("last-name").get());
data.add(dat);
}
this.data.set(data.toArray(new PersonalData[data.size()]));
return true;
}
|
diff --git a/src/haven/CharWnd.java b/src/haven/CharWnd.java
index a8ea701..8d979b1 100644
--- a/src/haven/CharWnd.java
+++ b/src/haven/CharWnd.java
@@ -1,610 +1,610 @@
package haven;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.util.*;
public class CharWnd extends Window {
Widget cattr, skill, belief;
Label cost, skcost;
Label explbl;
int exp;
int btime = 0;
SkillList psk, nsk;
SkillInfo ski;
FoodMeter foodm;
Map<String, Attr> attrs = new TreeMap<String, Attr>();
public static final Tex missing = Resource.loadtex("gfx/invobjs/missing");
public static final Tex foodmimg = Resource.loadtex("gfx/hud/charsh/foodm");
public static final Color debuff = new Color(255, 128, 128);
public static final Color buff = new Color(128, 255, 128);
public static final Text.Foundry sktitfnd = new Text.Foundry("Serif", 16);
public static final Text.Foundry skbodfnd = new Text.Foundry("SansSerif", 9);
public static final Tex btimeoff = Resource.loadtex("gfx/hud/charsh/shieldgray");
public static final Tex btimeon = Resource.loadtex("gfx/hud/charsh/shield");
static {
Widget.addtype("chr", new WidgetFactory() {
public Widget create(Coord c, Widget parent, Object[] args) {
return(new CharWnd(c, parent));
}
});
}
class Attr implements Observer {
String nm;
Glob.CAttr attr;
Attr(String nm) {
this.nm = nm;
attr = ui.sess.glob.cattr.get(nm);
attrs.put(nm, this);
attr.addObserver(this);
}
public void update() {}
public void update(Observable attrslen, Object uudata) {
Glob.CAttr attr = (Glob.CAttr)attrslen;
update();
}
private void destroy() {
attr.deleteObserver(this);
}
}
class Belief extends Attr {
boolean inv;
Img flarper;
int lx;
final Tex slider = Resource.loadtex("gfx/hud/charsh/bslider");
final Tex flarp = Resource.loadtex("gfx/hud/sflarp");
final IButton lb, rb;
final BufferedImage lbu = Resource.loadimg("gfx/hud/charsh/leftup");
final BufferedImage lbd = Resource.loadimg("gfx/hud/charsh/leftdown");
final BufferedImage lbg = Resource.loadimg("gfx/hud/charsh/leftgrey");
final BufferedImage rbu = Resource.loadimg("gfx/hud/charsh/rightup");
final BufferedImage rbd = Resource.loadimg("gfx/hud/charsh/rightdown");
final BufferedImage rbg = Resource.loadimg("gfx/hud/charsh/rightgrey");
Belief(String nm, String left, String right, boolean inv, int x, int y) {
super(nm);
this.inv = inv;
lx = x;
Label lbl = new Label(new Coord(x, y), belief, String.format("%s / %s", Utils.titlecase(left), Utils.titlecase(right)));
lbl.c = new Coord(72 + x - (lbl.sz.x / 2), y);
y += 15;
new Img(new Coord(x, y), Resource.loadtex("gfx/hud/charsh/" + left), belief);
lb = new IButton(new Coord(x + 16, y), belief, lbu, lbd) {
public void click() {
buy(-1);
}
};
new Img(new Coord(x + 32, y + 4), slider, belief);
rb = new IButton(new Coord(x + 112, y), belief, rbu, rbd) {
public void click() {
buy(1);
}
};
new Img(new Coord(x + 128, y), Resource.loadtex("gfx/hud/charsh/" + right), belief);
flarper = new Img(new Coord(0, y + 2), flarp, belief);
update();
}
public void buy(int ch) {
if(inv)
ch = -ch;
CharWnd.this.wdgmsg("believe", nm, ch);
}
public void update() {
int val = attr.comp;
if(inv)
val = -val;
flarper.c = new Coord((7 * (val + 5)) + 31 + lx, flarper.c.y);
if(btime > 0) {
lb.up = lbg;
lb.down = lbg;
rb.up = rbg;
rb.down = rbg;
} else {
lb.up = lbu;
lb.down = lbd;
rb.up = rbu;
rb.down = rbd;
}
lb.render();
rb.render();
}
}
class NAttr extends Attr {
Label lbl;
NAttr(String nm, int x, int y) {
super(nm);
this.lbl = new Label(new Coord(x, y), cattr, "0");
update();
}
public void update() {
lbl.settext(Integer.toString(attr.comp));
if(attr.comp < attr.base)
lbl.setcolor(debuff);
else if(attr.comp > attr.base)
lbl.setcolor(buff);
else
lbl.setcolor(Color.WHITE);
}
}
private void updexp() {
int cost = 0;
for(Attr attr : attrs.values()) {
if(attr instanceof SAttr)
cost += ((SAttr)attr).cost;
}
this.cost.settext(Integer.toString(cost));
this.explbl.settext(Integer.toString(exp));
if(cost > exp)
this.cost.setcolor(new Color(255, 128, 128));
else
this.cost.setcolor(new Color(255, 255, 255));
}
class SAttr extends NAttr {
IButton minus, plus;
int tvalb, tvalc;
int cost;
SAttr(String nm, int x, int y) {
super(nm, x, y);
tvalb = attr.base;
tvalc = attr.comp;
minus = new IButton(new Coord(x + 30, y), cattr, Resource.loadimg("gfx/hud/charsh/minusup"), Resource.loadimg("gfx/hud/charsh/minusdown")) {
public void click() {
dec();
upd();
}
public boolean mousewheel(Coord c, int a) {
if(a < 0)
inc();
else
dec();
upd();
return(true);
}
};
plus = new IButton(new Coord(x + 45, y), cattr, Resource.loadimg("gfx/hud/charsh/plusup"), Resource.loadimg("gfx/hud/charsh/plusdown")) {
public void click() {
inc();
upd();
}
public boolean mousewheel(Coord c, int a) {
if(a < 0)
inc();
else
dec();
upd();
return(true);
}
};
}
void upd() {
lbl.settext(Integer.toString(tvalc));
if(tvalb > attr.base)
lbl.setcolor(new Color(128, 128, 255));
else
lbl.setcolor(new Color(255, 255, 255));
updexp();
}
boolean inc() {
tvalb++; tvalc++;
cost += tvalb * 100;
return(true);
}
boolean dec() {
if(tvalb > attr.base) {
cost -= tvalb * 100;
tvalb--; tvalc--;
return(true);
}
return(false);
}
public void update() {
super.update();
tvalb = attr.base;
tvalc = attr.comp;
cost = 0;
upd();
}
}
private class BTimer extends Widget {
public BTimer(Coord c, Widget parent) {
super(c, btimeoff.sz(), parent);
}
public void draw(GOut g) {
if(btime > 0) {
g.image(btimeoff, Coord.z);
if(btime < 3600)
tooltip = "Less than one hour left";
else
tooltip = String.format("%d hours left", ((btime - 1) / 3600) + 1);
} else {
g.image(btimeon, Coord.z);
tooltip = null;
}
}
}
private class FoodMeter extends Widget {
int cap;
List<El> els = new LinkedList<El>();
private class El {
String id;
int amount;
Color col;
public El(String id, int amount, Color col) {
this.id = id;
this.amount = amount;
this.col = col;
}
}
public FoodMeter(Coord c, Widget parent) {
super(c, foodmimg.sz(), parent);
}
public void draw(GOut g) {
g.chcolor(Color.BLACK);
g.frect(new Coord(4, 4), sz.add(-8, -8));
g.chcolor();
synchronized(els) {
int x = 4;
for(El el : els) {
int w = (174 * el.amount) / cap;
g.chcolor(el.col);
g.frect(new Coord(x, 4), new Coord(w, 24));
x += w;
}
g.chcolor();
}
g.image(foodmimg, Coord.z);
super.draw(g);
}
public void clear() {
synchronized(els) {
els.clear();
}
}
public void addel(String id, int amount, Color col) {
synchronized(els) {
els.add(new El(id, amount, col));
}
}
}
private class SkillInfo extends Widget {
Resource cur = null;
Tex img;
Text tit;
Text body;
Scrollbar sb;
public SkillInfo(Coord c, Coord sz, Widget parent) {
super(c, sz, parent);
sb = new Scrollbar(new Coord(sz.x, 0), sz.y, this, 0, 0);
}
public void draw(GOut g) {
g.chcolor(Color.BLACK);
g.frect(Coord.z, sz);
g.chcolor();
if((cur != null) && !cur.loading) {
img = cur.layer(Resource.imgc).tex();
tit = sktitfnd.render(cur.layer(Resource.tooltip).t);
body = skbodfnd.renderwrap(cur.layer(Resource.pagina).text, sz.x - 20);
sb.max = (img.sz().y + tit.sz().y + body.sz().y + 50) - sz.y;
sb.val = 0;
cur = null;
}
if(img != null) {
int y = 10;
g.image(img, new Coord(10, y - sb.val));
y += img.sz().y + 10;
g.image(tit.tex(), new Coord(10, y - sb.val));
y += tit.sz().y + 20;
g.image(body.tex(), new Coord(10, y - sb.val));
}
super.draw(g);
}
public void setsk(Resource sk) {
cur = sk;
img = null;
sb.min = sb.max = 0;
}
public boolean mousewheel(Coord c, int amount) {
sb.ch(amount * 20);
return(true);
}
}
private class SkillList extends Widget {
int h;
Scrollbar sb;
int sel;
List<Resource> skills = new ArrayList<Resource>();
Map<Resource, Integer> costs = new HashMap<Resource, Integer>();
Comparator<Resource> rescomp = new Comparator<Resource>() {
public int compare(Resource a, Resource b) {
String an, bn;
if(a.loading)
an = a.name;
else
an = a.layer(Resource.tooltip).t;
if(b.loading)
bn = b.name;
else
bn = b.layer(Resource.tooltip).t;
return(an.compareTo(bn));
}
};
public SkillList(Coord c, Coord sz, Widget parent) {
super(c, sz, parent);
h = sz.y / 20;
sel = -1;
sb = new Scrollbar(new Coord(sz.x, 0), sz.y, this, 0, 4) {
public void changed() {
}
};
}
public void draw(GOut g) {
Collections.sort(skills, rescomp);
g.chcolor(Color.BLACK);
g.frect(Coord.z, sz);
g.chcolor();
for(int i = 0; i < h; i++) {
if(i + sb.val >= skills.size())
continue;
Resource sk = skills.get(i + sb.val);
if(i + sb.val == sel) {
g.chcolor(255, 255, 0, 128);
g.frect(new Coord(0, i * 20), new Coord(sz.x, 20));
g.chcolor();
}
if(getcost(sk) > exp)
g.chcolor(255, 128, 128, 255);
if(sk.loading) {
g.image(missing, new Coord(0, i * 20), new Coord(20, 20));
g.atext("...", new Coord(25, i * 20 + 10), 0, 0.5);
continue;
}
g.image(sk.layer(Resource.imgc).tex(), new Coord(0, i * 20), new Coord(20, 20));
g.atext(sk.layer(Resource.tooltip).t, new Coord(25, i * 20 + 10), 0, 0.5);
g.chcolor();
}
super.draw(g);
}
public void pop(Collection<Resource> nsk) {
List<Resource> skills = new ArrayList<Resource>();
for(Resource res : nsk)
skills.add(res);
sb.val = 0;
sb.max = skills.size() - h;
sel = -1;
this.skills = skills;
}
public boolean mousewheel(Coord c, int amount) {
sb.ch(amount);
return(true);
}
public int getcost(Resource sk) {
synchronized(costs) {
if(costs.get(sk) == null)
return(0);
else
return(costs.get(sk));
}
}
public boolean mousedown(Coord c, int button) {
if(super.mousedown(c, button))
return(true);
if(button == 1) {
sel = (c.y / 20) + sb.val;
if(sel >= skills.size())
sel = -1;
changed((sel < 0)?null:skills.get(sel));
return(true);
}
return(false);
}
public void changed(Resource sk) {
}
public void unsel() {
sel = -1;
}
}
private void buysattrs() {
ArrayList<Object> args = new ArrayList<Object>();
for(Attr attr : attrs.values()) {
if(attr instanceof SAttr) {
SAttr sa = (SAttr)attr;
args.add(sa.nm);
args.add(sa.tvalb);
}
}
wdgmsg("sattr", args.toArray());
}
private void buyskill() {
if(nsk.sel >= 0)
wdgmsg("buy", nsk.skills.get(nsk.sel).basename());
}
public CharWnd(Coord c, Widget parent) {
super(c, new Coord(400, 310), parent, "Character Sheet");
cattr = new Widget(Coord.z, new Coord(400, 275), this);
new Label(new Coord(10, 10), cattr, "Base Attributes:");
new Img(new Coord(10, 40), Resource.loadtex("gfx/hud/charsh/str"), cattr);
new Img(new Coord(10, 55), Resource.loadtex("gfx/hud/charsh/agil"), cattr);
new Img(new Coord(10, 70), Resource.loadtex("gfx/hud/charsh/intel"), cattr);
new Img(new Coord(10, 85), Resource.loadtex("gfx/hud/charsh/cons"), cattr);
new Img(new Coord(10, 100), Resource.loadtex("gfx/hud/charsh/perc"), cattr);
new Img(new Coord(10, 115), Resource.loadtex("gfx/hud/charsh/csm"), cattr);
new Label(new Coord(30, 40), cattr, "Strength:");
new Label(new Coord(30, 55), cattr, "Agility:");
new Label(new Coord(30, 70), cattr, "Intelligence:");
new Label(new Coord(30, 85), cattr, "Constitution:");
new Label(new Coord(30, 100), cattr, "Perception:");
new Label(new Coord(30, 115), cattr, "Charisma:");
new NAttr("str", 100, 40);
new NAttr("agil", 100, 55);
new NAttr("intel", 100, 70);
new NAttr("cons", 100, 85);
new NAttr("perc", 100, 100);
new NAttr("csm", 100, 115);
foodm = new FoodMeter(new Coord(10, 150), cattr);
new Label(new Coord(210, 85), cattr, "Cost:");
cost = new Label(new Coord(300, 85), cattr, "0");
new Label(new Coord(210, 100), cattr, "Learning Points:");
explbl = new Label(new Coord(300, 100), cattr, "0");
new Button(new Coord(210, 115), 75, cattr, "Buy") {
public void click() {
buysattrs();
}
};
new Label(new Coord(210, 10), cattr, "Skill Values:");
new Label(new Coord(210, 40), cattr, "Unarmed Combat:");
new SAttr("unarmed", 300, 40);
new Label(new Coord(210, 55), cattr, "Melee Combat:");
new SAttr("melee", 300, 55);
new Label(new Coord(210, 70), cattr, "Marksmanship:");
new SAttr("ranged", 300, 70);
skill = new Widget(Coord.z, new Coord(400, 275), this);
ski = new SkillInfo(new Coord(10, 10), new Coord(180, 260), skill);
new Label(new Coord(210, 10), skill, "Available Skills:");
nsk = new SkillList(new Coord(210, 25), new Coord(180, 100), skill) {
public void changed(Resource sk) {
psk.unsel();
skcost.settext("Cost: " + nsk.getcost(sk));
ski.setsk(sk);
}
};
new Button(new Coord(210, 130), 75, skill, "Learn") {
public void click() {
buyskill();
}
};
skcost = new Label(new Coord(300, 130), skill, "Cost: N/A");
new Label(new Coord(210, 155), skill, "Current Skills:");
psk = new SkillList(new Coord(210, 170), new Coord(180, 100), skill) {
public void changed(Resource sk) {
nsk.unsel();
skcost.settext("Cost: N/A");
ski.setsk(sk);
}
};
skill.visible = false;
belief = new Widget(Coord.z, new Coord(400, 275), this);
new BTimer(new Coord(10, 10), belief);
new Belief("life", "death", "life", false, 18, 50);
new Belief("night", "night", "day", true, 18, 85);
new Belief("civil", "barbarism", "civilization", false, 18, 120);
new Belief("nature", "nature", "industry", true, 18, 155);
new Belief("martial", "martial", "peaceful", true, 18, 190);
new Belief("change", "tradition", "change", false, 18, 225);
belief.visible = false;
new IButton(new Coord(10, 280), this, Resource.loadimg("gfx/hud/charsh/attribup"), Resource.loadimg("gfx/hud/charsh/attribdown")) {
public void click() {
cattr.visible = true;
skill.visible = false;
belief.visible = false;
}
}.tooltip = "Attributes";
new IButton(new Coord(80, 280), this, Resource.loadimg("gfx/hud/charsh/skillsup"), Resource.loadimg("gfx/hud/charsh/skillsdown")) {
public void click() {
cattr.visible = false;
skill.visible = true;
belief.visible = false;
}
- }.tooltip = "Skillz0rs";
+ }.tooltip = "Skills";
new IButton(new Coord(150, 280), this, Resource.loadimg("gfx/hud/charsh/ideasup"), Resource.loadimg("gfx/hud/charsh/ideasdown")) {
public void click() {
cattr.visible = false;
skill.visible = false;
belief.visible = true;
}
}.tooltip = "Personal Beliefs";
}
public void uimsg(String msg, Object... args) {
if(msg == "exp") {
exp = (Integer)args[0];
updexp();
} else if(msg == "reset") {
updexp();
} else if(msg == "nsk") {
Collection<Resource> skl = new LinkedList<Resource>();
for(int i = 0; i < args.length; i += 2) {
Resource res = Resource.load("gfx/hud/skills/" + (String)args[i]);
int cost = (Integer)args[i + 1];
skl.add(res);
synchronized(nsk.costs) {
nsk.costs.put(res, cost);
}
}
nsk.pop(skl);
} else if(msg == "psk") {
Collection<Resource> skl = new LinkedList<Resource>();
for(int i = 0; i < args.length; i++) {
Resource res = Resource.load("gfx/hud/skills/" + (String)args[i]);
skl.add(res);
}
psk.pop(skl);
} else if(msg == "food") {
foodm.cap = (Integer)args[0];
foodm.clear();
for(int i = 1; i < args.length; i += 3)
foodm.addel((String)args[i], (Integer)args[i + 1], (Color)args[i + 2]);
} else if(msg == "btime") {
btime = (Integer)args[0];
}
}
public void destroy() {
for(Attr attr : attrs.values())
attr.destroy();
super.destroy();
}
}
| true | true | public CharWnd(Coord c, Widget parent) {
super(c, new Coord(400, 310), parent, "Character Sheet");
cattr = new Widget(Coord.z, new Coord(400, 275), this);
new Label(new Coord(10, 10), cattr, "Base Attributes:");
new Img(new Coord(10, 40), Resource.loadtex("gfx/hud/charsh/str"), cattr);
new Img(new Coord(10, 55), Resource.loadtex("gfx/hud/charsh/agil"), cattr);
new Img(new Coord(10, 70), Resource.loadtex("gfx/hud/charsh/intel"), cattr);
new Img(new Coord(10, 85), Resource.loadtex("gfx/hud/charsh/cons"), cattr);
new Img(new Coord(10, 100), Resource.loadtex("gfx/hud/charsh/perc"), cattr);
new Img(new Coord(10, 115), Resource.loadtex("gfx/hud/charsh/csm"), cattr);
new Label(new Coord(30, 40), cattr, "Strength:");
new Label(new Coord(30, 55), cattr, "Agility:");
new Label(new Coord(30, 70), cattr, "Intelligence:");
new Label(new Coord(30, 85), cattr, "Constitution:");
new Label(new Coord(30, 100), cattr, "Perception:");
new Label(new Coord(30, 115), cattr, "Charisma:");
new NAttr("str", 100, 40);
new NAttr("agil", 100, 55);
new NAttr("intel", 100, 70);
new NAttr("cons", 100, 85);
new NAttr("perc", 100, 100);
new NAttr("csm", 100, 115);
foodm = new FoodMeter(new Coord(10, 150), cattr);
new Label(new Coord(210, 85), cattr, "Cost:");
cost = new Label(new Coord(300, 85), cattr, "0");
new Label(new Coord(210, 100), cattr, "Learning Points:");
explbl = new Label(new Coord(300, 100), cattr, "0");
new Button(new Coord(210, 115), 75, cattr, "Buy") {
public void click() {
buysattrs();
}
};
new Label(new Coord(210, 10), cattr, "Skill Values:");
new Label(new Coord(210, 40), cattr, "Unarmed Combat:");
new SAttr("unarmed", 300, 40);
new Label(new Coord(210, 55), cattr, "Melee Combat:");
new SAttr("melee", 300, 55);
new Label(new Coord(210, 70), cattr, "Marksmanship:");
new SAttr("ranged", 300, 70);
skill = new Widget(Coord.z, new Coord(400, 275), this);
ski = new SkillInfo(new Coord(10, 10), new Coord(180, 260), skill);
new Label(new Coord(210, 10), skill, "Available Skills:");
nsk = new SkillList(new Coord(210, 25), new Coord(180, 100), skill) {
public void changed(Resource sk) {
psk.unsel();
skcost.settext("Cost: " + nsk.getcost(sk));
ski.setsk(sk);
}
};
new Button(new Coord(210, 130), 75, skill, "Learn") {
public void click() {
buyskill();
}
};
skcost = new Label(new Coord(300, 130), skill, "Cost: N/A");
new Label(new Coord(210, 155), skill, "Current Skills:");
psk = new SkillList(new Coord(210, 170), new Coord(180, 100), skill) {
public void changed(Resource sk) {
nsk.unsel();
skcost.settext("Cost: N/A");
ski.setsk(sk);
}
};
skill.visible = false;
belief = new Widget(Coord.z, new Coord(400, 275), this);
new BTimer(new Coord(10, 10), belief);
new Belief("life", "death", "life", false, 18, 50);
new Belief("night", "night", "day", true, 18, 85);
new Belief("civil", "barbarism", "civilization", false, 18, 120);
new Belief("nature", "nature", "industry", true, 18, 155);
new Belief("martial", "martial", "peaceful", true, 18, 190);
new Belief("change", "tradition", "change", false, 18, 225);
belief.visible = false;
new IButton(new Coord(10, 280), this, Resource.loadimg("gfx/hud/charsh/attribup"), Resource.loadimg("gfx/hud/charsh/attribdown")) {
public void click() {
cattr.visible = true;
skill.visible = false;
belief.visible = false;
}
}.tooltip = "Attributes";
new IButton(new Coord(80, 280), this, Resource.loadimg("gfx/hud/charsh/skillsup"), Resource.loadimg("gfx/hud/charsh/skillsdown")) {
public void click() {
cattr.visible = false;
skill.visible = true;
belief.visible = false;
}
}.tooltip = "Skillz0rs";
new IButton(new Coord(150, 280), this, Resource.loadimg("gfx/hud/charsh/ideasup"), Resource.loadimg("gfx/hud/charsh/ideasdown")) {
public void click() {
cattr.visible = false;
skill.visible = false;
belief.visible = true;
}
}.tooltip = "Personal Beliefs";
}
| public CharWnd(Coord c, Widget parent) {
super(c, new Coord(400, 310), parent, "Character Sheet");
cattr = new Widget(Coord.z, new Coord(400, 275), this);
new Label(new Coord(10, 10), cattr, "Base Attributes:");
new Img(new Coord(10, 40), Resource.loadtex("gfx/hud/charsh/str"), cattr);
new Img(new Coord(10, 55), Resource.loadtex("gfx/hud/charsh/agil"), cattr);
new Img(new Coord(10, 70), Resource.loadtex("gfx/hud/charsh/intel"), cattr);
new Img(new Coord(10, 85), Resource.loadtex("gfx/hud/charsh/cons"), cattr);
new Img(new Coord(10, 100), Resource.loadtex("gfx/hud/charsh/perc"), cattr);
new Img(new Coord(10, 115), Resource.loadtex("gfx/hud/charsh/csm"), cattr);
new Label(new Coord(30, 40), cattr, "Strength:");
new Label(new Coord(30, 55), cattr, "Agility:");
new Label(new Coord(30, 70), cattr, "Intelligence:");
new Label(new Coord(30, 85), cattr, "Constitution:");
new Label(new Coord(30, 100), cattr, "Perception:");
new Label(new Coord(30, 115), cattr, "Charisma:");
new NAttr("str", 100, 40);
new NAttr("agil", 100, 55);
new NAttr("intel", 100, 70);
new NAttr("cons", 100, 85);
new NAttr("perc", 100, 100);
new NAttr("csm", 100, 115);
foodm = new FoodMeter(new Coord(10, 150), cattr);
new Label(new Coord(210, 85), cattr, "Cost:");
cost = new Label(new Coord(300, 85), cattr, "0");
new Label(new Coord(210, 100), cattr, "Learning Points:");
explbl = new Label(new Coord(300, 100), cattr, "0");
new Button(new Coord(210, 115), 75, cattr, "Buy") {
public void click() {
buysattrs();
}
};
new Label(new Coord(210, 10), cattr, "Skill Values:");
new Label(new Coord(210, 40), cattr, "Unarmed Combat:");
new SAttr("unarmed", 300, 40);
new Label(new Coord(210, 55), cattr, "Melee Combat:");
new SAttr("melee", 300, 55);
new Label(new Coord(210, 70), cattr, "Marksmanship:");
new SAttr("ranged", 300, 70);
skill = new Widget(Coord.z, new Coord(400, 275), this);
ski = new SkillInfo(new Coord(10, 10), new Coord(180, 260), skill);
new Label(new Coord(210, 10), skill, "Available Skills:");
nsk = new SkillList(new Coord(210, 25), new Coord(180, 100), skill) {
public void changed(Resource sk) {
psk.unsel();
skcost.settext("Cost: " + nsk.getcost(sk));
ski.setsk(sk);
}
};
new Button(new Coord(210, 130), 75, skill, "Learn") {
public void click() {
buyskill();
}
};
skcost = new Label(new Coord(300, 130), skill, "Cost: N/A");
new Label(new Coord(210, 155), skill, "Current Skills:");
psk = new SkillList(new Coord(210, 170), new Coord(180, 100), skill) {
public void changed(Resource sk) {
nsk.unsel();
skcost.settext("Cost: N/A");
ski.setsk(sk);
}
};
skill.visible = false;
belief = new Widget(Coord.z, new Coord(400, 275), this);
new BTimer(new Coord(10, 10), belief);
new Belief("life", "death", "life", false, 18, 50);
new Belief("night", "night", "day", true, 18, 85);
new Belief("civil", "barbarism", "civilization", false, 18, 120);
new Belief("nature", "nature", "industry", true, 18, 155);
new Belief("martial", "martial", "peaceful", true, 18, 190);
new Belief("change", "tradition", "change", false, 18, 225);
belief.visible = false;
new IButton(new Coord(10, 280), this, Resource.loadimg("gfx/hud/charsh/attribup"), Resource.loadimg("gfx/hud/charsh/attribdown")) {
public void click() {
cattr.visible = true;
skill.visible = false;
belief.visible = false;
}
}.tooltip = "Attributes";
new IButton(new Coord(80, 280), this, Resource.loadimg("gfx/hud/charsh/skillsup"), Resource.loadimg("gfx/hud/charsh/skillsdown")) {
public void click() {
cattr.visible = false;
skill.visible = true;
belief.visible = false;
}
}.tooltip = "Skills";
new IButton(new Coord(150, 280), this, Resource.loadimg("gfx/hud/charsh/ideasup"), Resource.loadimg("gfx/hud/charsh/ideasdown")) {
public void click() {
cattr.visible = false;
skill.visible = false;
belief.visible = true;
}
}.tooltip = "Personal Beliefs";
}
|
diff --git a/minecraft/net/minecraft/src/mod_automation.java b/minecraft/net/minecraft/src/mod_automation.java
index 7ad4d852..26708ecb 100644
--- a/minecraft/net/minecraft/src/mod_automation.java
+++ b/minecraft/net/minecraft/src/mod_automation.java
@@ -1,54 +1,54 @@
package net.minecraft.src;
import net.minecraft.client.Minecraft;
import net.minecraft.src.basiccomponents.BasicComponents;
import net.minecraft.src.eui.*;
import net.minecraft.src.eui.robotics.ModelModelShoeBot;
import net.minecraft.src.eui.robotics.RenderShoeBot;
import net.minecraft.src.forge.*;
import net.minecraft.src.universalelectricity.*;
import java.util.ArrayList;
import java.util.Map;
import java.io.*;
public class mod_automation extends NetworkMod {
static Configuration config = new Configuration((new File(Minecraft.getMinecraftDir(), "config/EUIndustry/SteamPower.cfg")));
public static int spawnItemId = configurationProperties();
public static Item spawnItem = (new net.minecraft.src.eui.robotics.ItemSpawn(spawnItemId)).setItemName("Bot");
private static int BlockID = 3454;
public static Block machine = new net.minecraft.src.eui.robotics.BlockComp(BlockID).setBlockName("machine");
@Override
public String getVersion() {
// TODO change version on each update ;/
return "0.0.1";
}
public static int configurationProperties()
{
config.load();
spawnItemId = Integer.parseInt(config.getOrCreateIntProperty("BotItem", Configuration.CATEGORY_ITEM, 31356).value);
config.save();
return spawnItemId;
}
@Override
public void load() {
MinecraftForgeClient.preloadTexture("/eui/Blocks.png");
MinecraftForgeClient.preloadTexture("/eui/Items.png");
//register
UniversalElectricity.registerAddon(this, "0.4.5");
ModLoader.registerBlock(machine, net.minecraft.src.eui.robotics.ItemMachine.class);
//names................................................
ModLoader.addName((new ItemStack(spawnItem, 1, 0)), "Bot");
- ModLoader.addName((new ItemStack(machine, 1, 0)), "Controler");
+ ModLoader.addName((new ItemStack(machine, 1, 0)), "Controller");
//TileEntities..................................
- ModLoader.registerTileEntity(net.minecraft.src.eui.robotics.TileEntityComp.class, "controler");
+ ModLoader.registerTileEntity(net.minecraft.src.eui.robotics.TileEntityComp.class, "controller");
//Entities...................
ModLoader.registerEntityID(net.minecraft.src.eui.robotics.EntityShoeBot.class, "Bot", 101);//collector
}
@Override
public void addRenderer(Map map)
{
map.put(net.minecraft.src.eui.robotics.EntityShoeBot.class, new RenderShoeBot());
}
}
| false | true | public void load() {
MinecraftForgeClient.preloadTexture("/eui/Blocks.png");
MinecraftForgeClient.preloadTexture("/eui/Items.png");
//register
UniversalElectricity.registerAddon(this, "0.4.5");
ModLoader.registerBlock(machine, net.minecraft.src.eui.robotics.ItemMachine.class);
//names................................................
ModLoader.addName((new ItemStack(spawnItem, 1, 0)), "Bot");
ModLoader.addName((new ItemStack(machine, 1, 0)), "Controler");
//TileEntities..................................
ModLoader.registerTileEntity(net.minecraft.src.eui.robotics.TileEntityComp.class, "controler");
//Entities...................
ModLoader.registerEntityID(net.minecraft.src.eui.robotics.EntityShoeBot.class, "Bot", 101);//collector
}
| public void load() {
MinecraftForgeClient.preloadTexture("/eui/Blocks.png");
MinecraftForgeClient.preloadTexture("/eui/Items.png");
//register
UniversalElectricity.registerAddon(this, "0.4.5");
ModLoader.registerBlock(machine, net.minecraft.src.eui.robotics.ItemMachine.class);
//names................................................
ModLoader.addName((new ItemStack(spawnItem, 1, 0)), "Bot");
ModLoader.addName((new ItemStack(machine, 1, 0)), "Controller");
//TileEntities..................................
ModLoader.registerTileEntity(net.minecraft.src.eui.robotics.TileEntityComp.class, "controller");
//Entities...................
ModLoader.registerEntityID(net.minecraft.src.eui.robotics.EntityShoeBot.class, "Bot", 101);//collector
}
|
diff --git a/tests/org.jboss.tools.ws.ui.bot.test/src/org/jboss/tools/ws/ui/bot/test/utils/ProjectHelper.java b/tests/org.jboss.tools.ws.ui.bot.test/src/org/jboss/tools/ws/ui/bot/test/utils/ProjectHelper.java
index b12b5353..b51c1c30 100644
--- a/tests/org.jboss.tools.ws.ui.bot.test/src/org/jboss/tools/ws/ui/bot/test/utils/ProjectHelper.java
+++ b/tests/org.jboss.tools.ws.ui.bot.test/src/org/jboss/tools/ws/ui/bot/test/utils/ProjectHelper.java
@@ -1,167 +1,172 @@
/*******************************************************************************
* Copyright (c) 2010-2011 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:
* Red Hat, Inc. - initial API and implementation
******************************************************************************/
package org.jboss.tools.ws.ui.bot.test.utils;
import org.eclipse.swtbot.eclipse.finder.widgets.SWTBotEditor;
import org.eclipse.swtbot.swt.finder.SWTBot;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotCombo;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotShell;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotTable;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotTree;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotTreeItem;
import org.jboss.tools.ui.bot.ext.SWTBotExt;
import org.jboss.tools.ui.bot.ext.SWTOpenExt;
import org.jboss.tools.ui.bot.ext.SWTUtilExt;
import org.jboss.tools.ui.bot.ext.condition.ShellIsActiveCondition;
import org.jboss.tools.ui.bot.ext.condition.TaskDuration;
import org.jboss.tools.ui.bot.ext.gen.ActionItem.NewObject.JavaEEEnterpriseApplicationProject;
import org.jboss.tools.ui.bot.ext.gen.ActionItem.NewObject.WebServicesWSDL;
import org.jboss.tools.ui.bot.ext.types.IDELabel;
import org.jboss.tools.ui.bot.ext.view.ProjectExplorer;
import org.jboss.tools.ws.ui.bot.test.uiutils.actions.NewFileWizardAction;
import org.jboss.tools.ws.ui.bot.test.uiutils.actions.TreeItemAction;
import org.jboss.tools.ws.ui.bot.test.uiutils.wizards.DynamicWebProjectWizard;
import org.jboss.tools.ws.ui.bot.test.uiutils.wizards.Wizard;
public class ProjectHelper {
private final SWTBotExt bot = new SWTBotExt();
private final ProjectExplorer projectExplorer = new ProjectExplorer();
private final SWTOpenExt open = new SWTOpenExt(bot);
private final SWTUtilExt util = new SWTUtilExt(bot);
/**
* Method creates basic java class for entered project with
* entered package and class name
* @param projectName
* @param pkg
* @param cName
* @return
*/
public SWTBotEditor createClass(String projectName, String pkg, String cName) {
new NewFileWizardAction().run().selectTemplate("Java", "Class").next();
Wizard w = new Wizard();
w.bot().textWithLabel("Package:").setText(pkg);
w.bot().textWithLabel("Name:").setText(cName);
w.bot().textWithLabel("Source folder:")
.setText(projectName + "/src");
w.finish();
bot.sleep(4500);
return bot.editorByTitle(cName + ".java");
}
/**
* Method creates wsdl file for entered project with
* entered package name
* @param projectName
* @param s
* @return
*/
public SWTBotEditor createWsdl(String projectName, String s) {
SWTBot wiz1 = open.newObject(WebServicesWSDL.LABEL);
wiz1.textWithLabel(WebServicesWSDL.TEXT_FILE_NAME).setText(s + ".wsdl");
wiz1.textWithLabel(
WebServicesWSDL.TEXT_ENTER_OR_SELECT_THE_PARENT_FOLDER)
.setText(projectName + "/src");
wiz1.button(IDELabel.Button.NEXT).click();
open.finish(wiz1);
return bot.editorByTitle(s + ".wsdl");
}
/**
* Method creates new Dynamic Web Project with entered name
* @param name
*/
public void createProject(String name) {
new NewFileWizardAction().run()
.selectTemplate("Web", "Dynamic Web Project").next();
new DynamicWebProjectWizard().setProjectName(name).finish();
util.waitForNonIgnoredJobs();
projectExplorer.selectProject(name);
}
/**
* Method creates new Dynamic Web Project with entered name for
* ear project
* @param name
*/
public void createProjectForEAR(String name, String earProject) {
new NewFileWizardAction().run()
.selectTemplate("Web", "Dynamic Web Project").next();
new DynamicWebProjectWizard().setProjectName(name).
addProjectToEar(earProject).finish();
util.waitForNonIgnoredJobs();
projectExplorer.selectProject(name);
}
/**
* Method creates new EAR Project with entered name
* @param name
*/
public void createEARProject(String name) {
SWTBot wiz = open.newObject(JavaEEEnterpriseApplicationProject.LABEL);
wiz.textWithLabel(JavaEEEnterpriseApplicationProject.TEXT_PROJECT_NAME)
.setText(name);
// set EAR version
SWTBotCombo combo = wiz.comboBox(1);
combo.setSelection(combo.itemCount() - 1);
wiz.button(IDELabel.Button.NEXT).click();
wiz.checkBox("Generate application.xml deployment descriptor").click();
open.finish(wiz);
bot.sleep(5000);
projectExplorer.selectProject(name);
}
/**
* Method generates Deployment Descriptor for entered project
* @param project
*/
public void createDD(String project) {
SWTBotTree tree = projectExplorer.bot().tree();
SWTBotTreeItem ti = tree.expandNode(project);
bot.sleep(1500);
ti = ti.getNode("Deployment Descriptor: " + project);
new TreeItemAction(ti, "Generate Deployment Descriptor Stub").run();
bot.sleep(1500);
util.waitForNonIgnoredJobs();
bot.sleep(1500);
}
/**
* Add first defined runtime into project as targeted runtime
* @param project
*/
- public void addDefaultRuntimeIntoProject(String project) {
+ public void addConfiguredRuntimeIntoProject(String project,
+ String configuredRuntime) {
projectExplorer.selectProject(project);
bot.menu(IDELabel.Menu.FILE).menu(
IDELabel.Menu.PROPERTIES).click();
bot.waitForShell(IDELabel.Shell.PROPERTIES_FOR + " " + project);
SWTBotShell propertiesShell = bot.shell(
IDELabel.Shell.PROPERTIES_FOR + " " + project);
propertiesShell.activate();
SWTBotTreeItem item = bot.tree().getTreeItem("Targeted Runtimes");
item.select();
SWTBotTable runtimes = bot.table();
for (int i = 0; i < runtimes.rowCount(); i++) {
runtimes.getTableItem(i).uncheck();
}
- bot.table().getTableItem(0).check();
+ for (int i = 0; i < runtimes.rowCount(); i++) {
+ if (runtimes.getTableItem(i).getText().equals(configuredRuntime)) {
+ runtimes.getTableItem(i).check();
+ }
+ }
bot.button(IDELabel.Button.OK).click();
bot.waitWhile(new ShellIsActiveCondition(propertiesShell),
TaskDuration.LONG.getTimeout());
}
}
| false | true | public void addDefaultRuntimeIntoProject(String project) {
projectExplorer.selectProject(project);
bot.menu(IDELabel.Menu.FILE).menu(
IDELabel.Menu.PROPERTIES).click();
bot.waitForShell(IDELabel.Shell.PROPERTIES_FOR + " " + project);
SWTBotShell propertiesShell = bot.shell(
IDELabel.Shell.PROPERTIES_FOR + " " + project);
propertiesShell.activate();
SWTBotTreeItem item = bot.tree().getTreeItem("Targeted Runtimes");
item.select();
SWTBotTable runtimes = bot.table();
for (int i = 0; i < runtimes.rowCount(); i++) {
runtimes.getTableItem(i).uncheck();
}
bot.table().getTableItem(0).check();
bot.button(IDELabel.Button.OK).click();
bot.waitWhile(new ShellIsActiveCondition(propertiesShell),
TaskDuration.LONG.getTimeout());
}
| public void addConfiguredRuntimeIntoProject(String project,
String configuredRuntime) {
projectExplorer.selectProject(project);
bot.menu(IDELabel.Menu.FILE).menu(
IDELabel.Menu.PROPERTIES).click();
bot.waitForShell(IDELabel.Shell.PROPERTIES_FOR + " " + project);
SWTBotShell propertiesShell = bot.shell(
IDELabel.Shell.PROPERTIES_FOR + " " + project);
propertiesShell.activate();
SWTBotTreeItem item = bot.tree().getTreeItem("Targeted Runtimes");
item.select();
SWTBotTable runtimes = bot.table();
for (int i = 0; i < runtimes.rowCount(); i++) {
runtimes.getTableItem(i).uncheck();
}
for (int i = 0; i < runtimes.rowCount(); i++) {
if (runtimes.getTableItem(i).getText().equals(configuredRuntime)) {
runtimes.getTableItem(i).check();
}
}
bot.button(IDELabel.Button.OK).click();
bot.waitWhile(new ShellIsActiveCondition(propertiesShell),
TaskDuration.LONG.getTimeout());
}
|
diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/Window.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/Window.java
index 2b556422f..b13eb5794 100644
--- a/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/Window.java
+++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/Window.java
@@ -1,253 +1,255 @@
/*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.scenes.scene2d.ui;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.BitmapFont.HAlignment;
import com.badlogic.gdx.graphics.g2d.BitmapFont.TextBounds;
import com.badlogic.gdx.graphics.g2d.NinePatch;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Matrix4;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.tablelayout.Table;
import com.badlogic.gdx.scenes.scene2d.ui.tablelayout.TableLayout;
import com.badlogic.gdx.scenes.scene2d.ui.utils.ScissorStack;
/** A container acting as a dialog or window.
*
* <h2>Functionality</h2> A Window is a {@link Table} that can be moved around by touching and dragging its titlebar.It can house
* multiple {@link Actor} instances in a table-layout. The difference to a pure Container is that the Window will automatically
* set the padding of the layout to respect the width and height of the border patches of its background NinePatch. See
* {@link Table} for more information on how Actor instances are laid out when using this class.</p>
*
* A Window can also be set to be modal via a call to {@link #setModal(boolean)}, in which case all touch input will go to that
* window no matter where the user touched the screen.
*
* <h2>Layout</h2> The (preferred) width and height are determined by the values given in the constructor of this class. Please
* consult the {@link Table} documentation on how the width and height will be manipulated if the Window is contained in another
* Container, a not so common use case. Additionally you can set the (preferred) width and height via a call to
* {@link TableLayout#size(int, int)}.
*
* <h2>Style</h2> A Window is a {@link Table} displaying a background {@link NinePatch} and its child Actors, clipped to the
* Window's area, taking into account the padding as described in the functionality section. Additionally the window will render a
* title string in its top border patches. The style is defined via an instance of {@link WindowStyle}, which can be either done
* programmatically or via a {@link Skin}.</p>
*
* A Pane's style definition in a skin XML file should look like this:
*
* <pre>
* {@code
* <window name="name"
* titleFont="fontName"
* titleFontColor="fontColor"
* background="backgroundPatch"/>
* }
* </pre>
*
* <ul>
* <li>The <code>name</code> attribute defines the name of the style which you can later use with .</li>
* <li>The <code>titleFont</code> attribute references a {@link BitmapFont} by name, to be used to render the title string.</li>
* *
* <li>The <code>titleFontColor</code> attribute references a {@link Color} by name, to be used to render the title string.</li>
* <li>The <code>background</code> attribute references a {@link NinePatch} by name, to be used as the Window's background.</li> *
* </ul>
*
* @author mzechner */
public class Window extends Table {
protected WindowStyle style;
protected String title;
protected final Stage stage;
protected final Rectangle widgetBounds = new Rectangle();
protected final Rectangle titleBounds = new Rectangle();
protected final TextBounds textBounds = new TextBounds();
protected final Rectangle scissors = new Rectangle();
protected boolean move = false;
protected boolean isMovable = true;
protected final Vector2 initial = new Vector2();
protected boolean isModal = false;
public Window (Stage stage, Skin skin) {
this(null, "", stage, skin.getStyle(WindowStyle.class), 150, 150);
}
public Window (String title, Stage stage, Skin skin) {
this(null, title, stage, skin.getStyle(WindowStyle.class), 150, 150);
}
public Window (String title, Stage stage, WindowStyle style) {
this(null, title, stage, style, 150, 150);
}
/** Creates a new Window. The width and height are determined by the given parameters.
* @param name the name
* @param stage the {@link Stage}, used for clipping
* @param title the title
* @param prefWidth the (preferred) width
* @param prefHeight the (preferred) height
* @param style the {@link WindowStyle} */
public Window (String name, String title, Stage stage, WindowStyle style, int prefWidth, int prefHeight) {
super(null, null, null, name);
this.stage = stage;
this.title = title;
width = prefWidth;
height = prefHeight;
setStyle(style);
transform = true;
}
/** Sets the style of this widget.
* @param style */
public void setStyle (WindowStyle style) {
this.style = style;
setBackground(style.background);
invalidateHierarchy();
}
private void calculateBoundsAndScissors (Matrix4 transform) {
final NinePatch background = style.background;
final BitmapFont titleFont = style.titleFont;
widgetBounds.x = background.getLeftWidth();
widgetBounds.y = background.getBottomHeight();
widgetBounds.width = width - background.getLeftWidth() - background.getRightWidth();
widgetBounds.height = height - background.getTopHeight() - background.getBottomHeight();
ScissorStack.calculateScissors(stage.getCamera(), transform, widgetBounds, scissors);
titleBounds.x = 0;
titleBounds.y = height - background.getTopHeight();
titleBounds.width = width;
titleBounds.height = background.getTopHeight();
textBounds.set(titleFont.getBounds(title));
textBounds.height -= titleFont.getDescent();
}
public void draw (SpriteBatch batch, float parentAlpha) {
final NinePatch backgroundPatch = style.background;
final BitmapFont titleFont = style.titleFont;
final Color titleFontColor = style.titleFontColor;
validate();
applyTransform(batch);
calculateBoundsAndScissors(batch.getTransformMatrix());
batch.setColor(color.r, color.g, color.b, color.a * parentAlpha);
backgroundPatch.draw(batch, 0, 0, width, height);
float textY = height - (int)(backgroundPatch.getTopHeight() / 2) + (int)(textBounds.height / 2);
+ titleFont.setColor(color.r * titleFontColor.r, color.g * titleFontColor.g, color.b * titleFontColor.b, color.a
+ * parentAlpha * titleFontColor.a);
titleFont.setColor(titleFontColor.r, titleFontColor.g, titleFontColor.b, titleFontColor.a * parentAlpha);
titleFont.drawMultiLine(batch, title, (int)(width / 2), textY, 0, HAlignment.CENTER);
batch.flush();
if (ScissorStack.pushScissors(scissors)) {
super.drawChildren(batch, parentAlpha);
ScissorStack.popScissors();
}
resetTransform(batch);
}
@Override
public boolean touchDown (float x, float y, int pointer) {
if (pointer != 0) return false;
if (parent.getActors().size() > 1) parent.swapActor(this, parent.getActors().get(parent.getActors().size() - 1));
if (titleBounds.contains(x, y)) {
if (isMovable) move = true;
initial.set(x, y);
} else
super.touchDown(x, y, pointer);
return true;
}
@Override
public void touchUp (float x, float y, int pointer) {
move = false;
if (parent.focusedActor[0] != this) super.touchUp(x, y, pointer);
}
@Override
public void touchDragged (float x, float y, int pointer) {
if (move) {
this.x += (x - initial.x);
this.y += (y - initial.y);
return;
}
if (parent.focusedActor[0] != this) super.touchDragged(x, y, pointer);
}
@Override
public Actor hit (float x, float y) {
return isModal || (x > 0 && x < width && y > 0 && y < height) ? this : null;
}
/** Sets the title of the Window
* @param title the title */
public void setTitle (String title) {
this.title = title;
}
/** @return the title of the window */
public String getTitle () {
return title;
}
/** Sets whether this Window is movable by touch or not. In case it is the user will be able to grab and move the window by its
* title bar
* @param isMovable whether the window is movable or not */
public void setMovable (boolean isMovable) {
this.isMovable = isMovable;
}
/** @return whether the window is movable */
public boolean isMovable () {
return isMovable;
}
/** Sets whether this Window is modal or not. In case it is it will receive all touch events, no matter where the user touched
* the screen.
* @param isModal whether the window is modal or not */
public void setModal (boolean isModal) {
this.isModal = isModal;
}
/** @return whether the window is modal */
public boolean isModal () {
return isModal;
}
/** Defines the style of a window, see {@link Window}
* @author mzechner */
static public class WindowStyle {
public NinePatch background;
public BitmapFont titleFont;
public Color titleFontColor = new Color(1, 1, 1, 1);
public WindowStyle () {
}
public WindowStyle (BitmapFont titleFont, Color titleFontColor, NinePatch backgroundPatch) {
this.background = backgroundPatch;
this.titleFont = titleFont;
this.titleFontColor.set(titleFontColor);
}
}
}
| true | true | public void draw (SpriteBatch batch, float parentAlpha) {
final NinePatch backgroundPatch = style.background;
final BitmapFont titleFont = style.titleFont;
final Color titleFontColor = style.titleFontColor;
validate();
applyTransform(batch);
calculateBoundsAndScissors(batch.getTransformMatrix());
batch.setColor(color.r, color.g, color.b, color.a * parentAlpha);
backgroundPatch.draw(batch, 0, 0, width, height);
float textY = height - (int)(backgroundPatch.getTopHeight() / 2) + (int)(textBounds.height / 2);
titleFont.setColor(titleFontColor.r, titleFontColor.g, titleFontColor.b, titleFontColor.a * parentAlpha);
titleFont.drawMultiLine(batch, title, (int)(width / 2), textY, 0, HAlignment.CENTER);
batch.flush();
if (ScissorStack.pushScissors(scissors)) {
super.drawChildren(batch, parentAlpha);
ScissorStack.popScissors();
}
resetTransform(batch);
}
| public void draw (SpriteBatch batch, float parentAlpha) {
final NinePatch backgroundPatch = style.background;
final BitmapFont titleFont = style.titleFont;
final Color titleFontColor = style.titleFontColor;
validate();
applyTransform(batch);
calculateBoundsAndScissors(batch.getTransformMatrix());
batch.setColor(color.r, color.g, color.b, color.a * parentAlpha);
backgroundPatch.draw(batch, 0, 0, width, height);
float textY = height - (int)(backgroundPatch.getTopHeight() / 2) + (int)(textBounds.height / 2);
titleFont.setColor(color.r * titleFontColor.r, color.g * titleFontColor.g, color.b * titleFontColor.b, color.a
* parentAlpha * titleFontColor.a);
titleFont.setColor(titleFontColor.r, titleFontColor.g, titleFontColor.b, titleFontColor.a * parentAlpha);
titleFont.drawMultiLine(batch, title, (int)(width / 2), textY, 0, HAlignment.CENTER);
batch.flush();
if (ScissorStack.pushScissors(scissors)) {
super.drawChildren(batch, parentAlpha);
ScissorStack.popScissors();
}
resetTransform(batch);
}
|
diff --git a/src/com/android/mms/ui/SlideView.java b/src/com/android/mms/ui/SlideView.java
index 4d3710b..5b36b3c 100644
--- a/src/com/android/mms/ui/SlideView.java
+++ b/src/com/android/mms/ui/SlideView.java
@@ -1,543 +1,544 @@
/*
* Copyright (C) 2008 Esmertec AG.
* 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.mms.ui;
import com.android.mms.R;
import com.android.mms.layout.LayoutManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.net.Uri;
import android.text.method.HideReturnsTransformationMethod;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsoluteLayout;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.MediaController;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.VideoView;
import java.io.IOException;
import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;
/**
* A basic view to show the contents of a slide.
*/
public class SlideView extends AbsoluteLayout implements
AdaptableSlideViewInterface {
private static final String TAG = "SlideView";
private static final boolean DEBUG = false;
private static final boolean LOCAL_LOGV = false;
// FIXME: Need getHeight from mAudioInfoView instead of constant AUDIO_INFO_HEIGHT.
private static final int AUDIO_INFO_HEIGHT = 82;
private View mAudioInfoView;
private ImageView mImageView;
private VideoView mVideoView;
private ScrollView mScrollText;
private TextView mTextView;
private OnSizeChangedListener mSizeChangedListener;
private MediaPlayer mAudioPlayer;
private boolean mIsPrepared;
private boolean mStartWhenPrepared;
private int mSeekWhenPrepared;
private boolean mStopWhenPrepared;
private ScrollView mScrollViewPort;
private LinearLayout mViewPort;
// Indicates whether the view is in MMS conformance mode.
private boolean mConformanceMode;
private MediaController mMediaController;
MediaPlayer.OnPreparedListener mPreparedListener = new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
mIsPrepared = true;
if (mSeekWhenPrepared > 0) {
mAudioPlayer.seekTo(mSeekWhenPrepared);
mSeekWhenPrepared = 0;
}
if (mStartWhenPrepared) {
mAudioPlayer.start();
mStartWhenPrepared = false;
displayAudioInfo();
}
if (mStopWhenPrepared) {
mAudioPlayer.stop();
mAudioPlayer.release();
mAudioPlayer = null;
mStopWhenPrepared = false;
hideAudioInfo();
}
}
};
public SlideView(Context context) {
super(context);
}
public SlideView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setImage(String name, Bitmap bitmap) {
if (mImageView == null) {
mImageView = new ImageView(mContext);
mImageView.setPadding(0, 5, 0, 5);
addView(mImageView, new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 0, 0));
if (DEBUG) {
mImageView.setBackgroundColor(0xFFFF0000);
}
}
try {
if (null == bitmap) {
bitmap = BitmapFactory.decodeResource(getResources(),
R.drawable.ic_missing_thumbnail_picture);
}
mImageView.setVisibility(View.VISIBLE);
mImageView.setImageBitmap(bitmap);
} catch (java.lang.OutOfMemoryError e) {
Log.e(TAG, "setImage: out of memory: ", e);
}
}
public void setImageRegion(int left, int top, int width, int height) {
// Ignore any requirement of layout change once we are in MMS conformance mode.
if (mImageView != null && !mConformanceMode) {
mImageView.setLayoutParams(new LayoutParams(width, height, left, top));
}
}
public void setImageRegionFit(String fit) {
// TODO Auto-generated method stub
}
public void setVideo(String name, Uri video) {
if (mVideoView == null) {
mVideoView = new VideoView(mContext);
addView(mVideoView, new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 0, 0));
if (DEBUG) {
mVideoView.setBackgroundColor(0xFFFF0000);
}
}
if (LOCAL_LOGV) {
Log.v(TAG, "Changing video source to " + video);
}
mVideoView.setVisibility(View.VISIBLE);
mVideoView.setVideoURI(video);
}
public void setMediaController(MediaController mediaController) {
mMediaController = mediaController;
}
private void initAudioInfoView(String name) {
if (null == mAudioInfoView) {
LayoutInflater factory = LayoutInflater.from(getContext());
mAudioInfoView = factory.inflate(R.layout.playing_audio_info, null);
int height = mAudioInfoView.getHeight();
if (mConformanceMode) {
mViewPort.addView(mAudioInfoView, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
AUDIO_INFO_HEIGHT));
} else {
addView(mAudioInfoView, new LayoutParams(
LayoutParams.MATCH_PARENT, AUDIO_INFO_HEIGHT,
0, getHeight() - AUDIO_INFO_HEIGHT));
if (DEBUG) {
mAudioInfoView.setBackgroundColor(0xFFFF0000);
}
}
}
TextView audioName = (TextView) mAudioInfoView.findViewById(R.id.name);
audioName.setText(name);
mAudioInfoView.setVisibility(View.GONE);
}
private void displayAudioInfo() {
if (null != mAudioInfoView) {
mAudioInfoView.setVisibility(View.VISIBLE);
}
}
private void hideAudioInfo() {
if (null != mAudioInfoView) {
mAudioInfoView.setVisibility(View.GONE);
}
}
public void setAudio(Uri audio, String name, Map<String, ?> extras) {
if (audio == null) {
throw new IllegalArgumentException("Audio URI may not be null.");
}
if (LOCAL_LOGV) {
Log.v(TAG, "Changing audio source to " + audio);
}
if (mAudioPlayer != null) {
mAudioPlayer.reset();
mAudioPlayer.release();
mAudioPlayer = null;
}
// Reset state variables
mIsPrepared = false;
mStartWhenPrepared = false;
mSeekWhenPrepared = 0;
mStopWhenPrepared = false;
try {
mAudioPlayer = new MediaPlayer();
mAudioPlayer.setOnPreparedListener(mPreparedListener);
mAudioPlayer.setDataSource(mContext, audio);
mAudioPlayer.prepareAsync();
} catch (IOException e) {
Log.e(TAG, "Unexpected IOException.", e);
mAudioPlayer.release();
mAudioPlayer = null;
}
initAudioInfoView(name);
}
public void setText(String name, String text) {
if (!mConformanceMode) {
if (null == mScrollText) {
mScrollText = new ScrollView(mContext);
mScrollText.setScrollBarStyle(SCROLLBARS_OUTSIDE_INSET);
addView(mScrollText, new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 0, 0));
if (DEBUG) {
mScrollText.setBackgroundColor(0xFF00FF00);
}
}
if (null == mTextView) {
mTextView = new TextView(mContext);
mTextView.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
mScrollText.addView(mTextView);
}
mScrollText.requestFocus();
}
mTextView.setVisibility(View.VISIBLE);
mTextView.setText(text);
}
public void setTextRegion(int left, int top, int width, int height) {
// Ignore any requirement of layout change once we are in MMS conformance mode.
if (mScrollText != null && !mConformanceMode) {
mScrollText.setLayoutParams(new LayoutParams(width, height, left, top));
}
}
public void setVideoRegion(int left, int top, int width, int height) {
if (mVideoView != null && !mConformanceMode) {
mVideoView.setLayoutParams(new LayoutParams(width, height, left, top));
}
}
public void setImageVisibility(boolean visible) {
if (mImageView != null) {
if (mConformanceMode) {
mImageView.setVisibility(visible ? View.VISIBLE : View.GONE);
} else {
mImageView.setVisibility(visible ? View.VISIBLE : View.INVISIBLE);
}
}
}
public void setTextVisibility(boolean visible) {
if (mConformanceMode) {
if (mTextView != null) {
mTextView.setVisibility(visible ? View.VISIBLE : View.GONE);
}
} else if (mScrollText != null) {
mScrollText.setVisibility(visible ? View.VISIBLE : View.INVISIBLE);
}
}
public void setVideoVisibility(boolean visible) {
if (mVideoView != null) {
if (mConformanceMode) {
mVideoView.setVisibility(visible ? View.VISIBLE : View.GONE);
} else {
mVideoView.setVisibility(visible ? View.VISIBLE : View.INVISIBLE);
}
}
}
public void startAudio() {
if ((mAudioPlayer != null) && mIsPrepared) {
mAudioPlayer.start();
mStartWhenPrepared = false;
displayAudioInfo();
} else {
mStartWhenPrepared = true;
}
}
public void stopAudio() {
if ((mAudioPlayer != null) && mIsPrepared) {
mAudioPlayer.stop();
mAudioPlayer.release();
mAudioPlayer = null;
hideAudioInfo();
} else {
mStopWhenPrepared = true;
}
}
public void pauseAudio() {
if ((mAudioPlayer != null) && mIsPrepared) {
if (mAudioPlayer.isPlaying()) {
mAudioPlayer.pause();
}
}
mStartWhenPrepared = false;
}
public void seekAudio(int seekTo) {
if ((mAudioPlayer != null) && mIsPrepared) {
mAudioPlayer.seekTo(seekTo);
} else {
mSeekWhenPrepared = seekTo;
}
}
public void startVideo() {
if (mVideoView != null) {
if (LOCAL_LOGV) {
Log.v(TAG, "Starting video playback.");
}
mVideoView.start();
}
}
public void stopVideo() {
if ((mVideoView != null)) {
if (LOCAL_LOGV) {
Log.v(TAG, "Stopping video playback.");
}
mVideoView.stopPlayback();
}
}
public void pauseVideo() {
if (mVideoView != null) {
if (LOCAL_LOGV) {
Log.v(TAG, "Pausing video playback.");
}
mVideoView.pause();
}
}
public void seekVideo(int seekTo) {
if (mVideoView != null) {
if (seekTo > 0) {
if (LOCAL_LOGV) {
Log.v(TAG, "Seeking video playback to " + seekTo);
}
mVideoView.seekTo(seekTo);
}
}
}
public void reset() {
if (null != mScrollText) {
mScrollText.setVisibility(View.GONE);
}
if (null != mImageView) {
mImageView.setVisibility(View.GONE);
}
if (null != mAudioPlayer) {
stopAudio();
}
if (null != mVideoView) {
stopVideo();
mVideoView.setVisibility(View.GONE);
}
if (null != mTextView) {
mTextView.setVisibility(View.GONE);
}
if (mScrollViewPort != null) {
mScrollViewPort.scrollTo(0, 0);
mScrollViewPort.setLayoutParams(
new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 0, 0));
}
}
public void setVisibility(boolean visible) {
// TODO Auto-generated method stub
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
if (mSizeChangedListener != null) {
if (LOCAL_LOGV) {
Log.v(TAG, "new size=" + w + "x" + h);
}
mSizeChangedListener.onSizeChanged(w, h - AUDIO_INFO_HEIGHT);
}
}
public void setOnSizeChangedListener(OnSizeChangedListener l) {
mSizeChangedListener = l;
}
private class Position {
public Position(int left, int top) {
mTop = top;
mLeft = left;
}
public int mTop;
public int mLeft;
}
/**
* Makes the SlideView working on MMSConformance Mode. The view will be
* re-layout to the linear view.
* <p>
* This is Chinese requirement about mms conformance.
* The most popular Mms service in China is newspaper which is MMS conformance,
* normally it mixes the image and text and has a number of slides. The
* AbsoluteLayout doesn't have good user experience for this kind of message,
* for example,
*
* 1. AbsoluteLayout exactly follows the smil's layout which is not optimized,
* and actually, no other MMS applications follow the smil's layout, they adjust
* the layout according their screen size. MMS conformance doc also allows the
* implementation to adjust the layout.
*
* 2. The TextView is fixed in the small area of screen, and other part of screen
* is empty once there is no image in the current slide.
*
* 3. The TextView is scrollable in a small area of screen and the font size is
* small which make the user experience bad.
*
* The better UI for the MMS conformance message could be putting the image/video
* and text in a linear layout view and making them scrollable together.
*
* Another reason for only applying the LinearLayout to the MMS conformance message
* is that the AbsoluteLayout has ability to play image and video in a same screen.
* which shouldn't be broken.
*/
public void enableMMSConformanceMode(int textLeft, int textTop,
int imageLeft, int imageTop) {
mConformanceMode = true;
if (mScrollViewPort == null) {
mScrollViewPort = new ScrollView(mContext) {
private int mBottomY;
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
if (getChildCount() > 0) {
int childHeight = getChildAt(0).getHeight();
int height = getHeight();
mBottomY = height < childHeight ? childHeight - height : 0;
}
}
@Override
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
// Shows MediaController when the view is scrolled to the top/bottom of itself.
if (t == 0 || t >= mBottomY){
- if (mMediaController != null) {
+ if (mMediaController != null
+ && !((SlideshowActivity) mContext).isFinishing()) {
mMediaController.show();
}
}
}
};
mScrollViewPort.setScrollBarStyle(SCROLLBARS_OUTSIDE_INSET);
mViewPort = new LinearLayout(mContext);
mViewPort.setOrientation(LinearLayout.VERTICAL);
mViewPort.setGravity(Gravity.CENTER);
mViewPort.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (mMediaController != null) {
mMediaController.show();
}
}
});
mScrollViewPort.addView(mViewPort, new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
addView(mScrollViewPort);
}
// Layout views to fit the LinearLayout from left to right, then top to
// bottom.
TreeMap<Position, View> viewsByPosition = new TreeMap<Position, View>(new Comparator<Position>() {
public int compare(Position p1, Position p2) {
int l1 = p1.mLeft;
int t1 = p1.mTop;
int l2 = p2.mLeft;
int t2 = p2.mTop;
int res = t1 - t2;
if (res == 0) {
res = l1 - l2;
}
if (res == 0) {
// A view will be lost if return 0.
return -1;
}
return res;
}
});
if (textLeft >=0 && textTop >=0) {
mTextView = new TextView(mContext);
mTextView.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
mTextView.setTextSize(18);
mTextView.setPadding(5, 5, 5, 5);
viewsByPosition.put(new Position(textLeft, textTop), mTextView);
}
if (imageLeft >=0 && imageTop >=0) {
mImageView = new ImageView(mContext);
mImageView.setPadding(0, 5, 0, 5);
viewsByPosition.put(new Position(imageLeft, imageTop), mImageView);
// According MMS Conformance Document, the image and video should use the same
// region. So, put the VideoView below the ImageView.
mVideoView = new VideoView(mContext);
viewsByPosition.put(new Position(imageLeft + 1, imageTop), mVideoView);
}
for (View view : viewsByPosition.values()) {
if (view instanceof VideoView) {
mViewPort.addView(view, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
LayoutManager.getInstance().getLayoutParameters().getHeight()));
} else {
mViewPort.addView(view, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
}
view.setVisibility(View.GONE);
}
}
}
| true | true | public void enableMMSConformanceMode(int textLeft, int textTop,
int imageLeft, int imageTop) {
mConformanceMode = true;
if (mScrollViewPort == null) {
mScrollViewPort = new ScrollView(mContext) {
private int mBottomY;
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
if (getChildCount() > 0) {
int childHeight = getChildAt(0).getHeight();
int height = getHeight();
mBottomY = height < childHeight ? childHeight - height : 0;
}
}
@Override
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
// Shows MediaController when the view is scrolled to the top/bottom of itself.
if (t == 0 || t >= mBottomY){
if (mMediaController != null) {
mMediaController.show();
}
}
}
};
mScrollViewPort.setScrollBarStyle(SCROLLBARS_OUTSIDE_INSET);
mViewPort = new LinearLayout(mContext);
mViewPort.setOrientation(LinearLayout.VERTICAL);
mViewPort.setGravity(Gravity.CENTER);
mViewPort.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (mMediaController != null) {
mMediaController.show();
}
}
});
mScrollViewPort.addView(mViewPort, new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
addView(mScrollViewPort);
}
// Layout views to fit the LinearLayout from left to right, then top to
// bottom.
TreeMap<Position, View> viewsByPosition = new TreeMap<Position, View>(new Comparator<Position>() {
public int compare(Position p1, Position p2) {
int l1 = p1.mLeft;
int t1 = p1.mTop;
int l2 = p2.mLeft;
int t2 = p2.mTop;
int res = t1 - t2;
if (res == 0) {
res = l1 - l2;
}
if (res == 0) {
// A view will be lost if return 0.
return -1;
}
return res;
}
});
if (textLeft >=0 && textTop >=0) {
mTextView = new TextView(mContext);
mTextView.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
mTextView.setTextSize(18);
mTextView.setPadding(5, 5, 5, 5);
viewsByPosition.put(new Position(textLeft, textTop), mTextView);
}
if (imageLeft >=0 && imageTop >=0) {
mImageView = new ImageView(mContext);
mImageView.setPadding(0, 5, 0, 5);
viewsByPosition.put(new Position(imageLeft, imageTop), mImageView);
// According MMS Conformance Document, the image and video should use the same
// region. So, put the VideoView below the ImageView.
mVideoView = new VideoView(mContext);
viewsByPosition.put(new Position(imageLeft + 1, imageTop), mVideoView);
}
for (View view : viewsByPosition.values()) {
if (view instanceof VideoView) {
mViewPort.addView(view, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
LayoutManager.getInstance().getLayoutParameters().getHeight()));
} else {
mViewPort.addView(view, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
}
view.setVisibility(View.GONE);
}
}
| public void enableMMSConformanceMode(int textLeft, int textTop,
int imageLeft, int imageTop) {
mConformanceMode = true;
if (mScrollViewPort == null) {
mScrollViewPort = new ScrollView(mContext) {
private int mBottomY;
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
if (getChildCount() > 0) {
int childHeight = getChildAt(0).getHeight();
int height = getHeight();
mBottomY = height < childHeight ? childHeight - height : 0;
}
}
@Override
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
// Shows MediaController when the view is scrolled to the top/bottom of itself.
if (t == 0 || t >= mBottomY){
if (mMediaController != null
&& !((SlideshowActivity) mContext).isFinishing()) {
mMediaController.show();
}
}
}
};
mScrollViewPort.setScrollBarStyle(SCROLLBARS_OUTSIDE_INSET);
mViewPort = new LinearLayout(mContext);
mViewPort.setOrientation(LinearLayout.VERTICAL);
mViewPort.setGravity(Gravity.CENTER);
mViewPort.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (mMediaController != null) {
mMediaController.show();
}
}
});
mScrollViewPort.addView(mViewPort, new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
addView(mScrollViewPort);
}
// Layout views to fit the LinearLayout from left to right, then top to
// bottom.
TreeMap<Position, View> viewsByPosition = new TreeMap<Position, View>(new Comparator<Position>() {
public int compare(Position p1, Position p2) {
int l1 = p1.mLeft;
int t1 = p1.mTop;
int l2 = p2.mLeft;
int t2 = p2.mTop;
int res = t1 - t2;
if (res == 0) {
res = l1 - l2;
}
if (res == 0) {
// A view will be lost if return 0.
return -1;
}
return res;
}
});
if (textLeft >=0 && textTop >=0) {
mTextView = new TextView(mContext);
mTextView.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
mTextView.setTextSize(18);
mTextView.setPadding(5, 5, 5, 5);
viewsByPosition.put(new Position(textLeft, textTop), mTextView);
}
if (imageLeft >=0 && imageTop >=0) {
mImageView = new ImageView(mContext);
mImageView.setPadding(0, 5, 0, 5);
viewsByPosition.put(new Position(imageLeft, imageTop), mImageView);
// According MMS Conformance Document, the image and video should use the same
// region. So, put the VideoView below the ImageView.
mVideoView = new VideoView(mContext);
viewsByPosition.put(new Position(imageLeft + 1, imageTop), mVideoView);
}
for (View view : viewsByPosition.values()) {
if (view instanceof VideoView) {
mViewPort.addView(view, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
LayoutManager.getInstance().getLayoutParameters().getHeight()));
} else {
mViewPort.addView(view, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
}
view.setVisibility(View.GONE);
}
}
|
diff --git a/flex-pmd-ruleset/src/main/java/com/adobe/ac/pmd/rules/maintanability/UselessOverridenFunctionRule.java b/flex-pmd-ruleset/src/main/java/com/adobe/ac/pmd/rules/maintanability/UselessOverridenFunctionRule.java
index 8e033d47..9c5674f6 100644
--- a/flex-pmd-ruleset/src/main/java/com/adobe/ac/pmd/rules/maintanability/UselessOverridenFunctionRule.java
+++ b/flex-pmd-ruleset/src/main/java/com/adobe/ac/pmd/rules/maintanability/UselessOverridenFunctionRule.java
@@ -1,82 +1,83 @@
/**
* Copyright (c) 2009, Adobe Systems, Incorporated
* 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 Adobe Systems, Incorporated. 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 com.adobe.ac.pmd.rules.maintanability;
import java.util.List;
import com.adobe.ac.pmd.nodes.IFunction;
import com.adobe.ac.pmd.parser.IParserNode;
import com.adobe.ac.pmd.parser.KeyWords;
import com.adobe.ac.pmd.rules.core.AbstractAstFlexRule;
import com.adobe.ac.pmd.rules.core.ViolationPriority;
public class UselessOverridenFunctionRule extends AbstractAstFlexRule
{
@Override
protected final void findViolations( final IFunction function )
{
final int statementNbAtFirstLevelInBody = function.getStatementNbInBody();
if ( function.getBody() != null
&& function.isOverriden() && statementNbAtFirstLevelInBody == 1 )
{
final List< IParserNode > statements = function.findPrimaryStatementsInBody( KeyWords.SUPER.toString() );
if ( statements != null
- && statements.size() == 1
+ && statements.size() == 1 && function.getBody().getChild( 0 ).getChild( 1 ) != null
+ && function.getBody().getChild( 0 ).getChild( 1 ).getChild( 1 ) != null
&& !areArgumentsModified( function.getBody().getChild( 0 ).getChild( 1 ).getChild( 1 ) ) )
{
addViolation( function );
}
}
}
@Override
protected final ViolationPriority getDefaultPriority()
{
return ViolationPriority.LOW;
}
private boolean areArgumentsModified( final IParserNode args )
{
if ( args.getChildren() != null )
{
for ( final IParserNode arg : args.getChildren() )
{
if ( arg.getChildren() != null )
{
return true;
}
}
}
return false;
}
}
| true | true | protected final void findViolations( final IFunction function )
{
final int statementNbAtFirstLevelInBody = function.getStatementNbInBody();
if ( function.getBody() != null
&& function.isOverriden() && statementNbAtFirstLevelInBody == 1 )
{
final List< IParserNode > statements = function.findPrimaryStatementsInBody( KeyWords.SUPER.toString() );
if ( statements != null
&& statements.size() == 1
&& !areArgumentsModified( function.getBody().getChild( 0 ).getChild( 1 ).getChild( 1 ) ) )
{
addViolation( function );
}
}
}
| protected final void findViolations( final IFunction function )
{
final int statementNbAtFirstLevelInBody = function.getStatementNbInBody();
if ( function.getBody() != null
&& function.isOverriden() && statementNbAtFirstLevelInBody == 1 )
{
final List< IParserNode > statements = function.findPrimaryStatementsInBody( KeyWords.SUPER.toString() );
if ( statements != null
&& statements.size() == 1 && function.getBody().getChild( 0 ).getChild( 1 ) != null
&& function.getBody().getChild( 0 ).getChild( 1 ).getChild( 1 ) != null
&& !areArgumentsModified( function.getBody().getChild( 0 ).getChild( 1 ).getChild( 1 ) ) )
{
addViolation( function );
}
}
}
|
diff --git a/src/main/java/org/ObjectLayout/StructuredArray.java b/src/main/java/org/ObjectLayout/StructuredArray.java
index da9b52b..ed1f8bc 100644
--- a/src/main/java/org/ObjectLayout/StructuredArray.java
+++ b/src/main/java/org/ObjectLayout/StructuredArray.java
@@ -1,925 +1,925 @@
/*
* Copyright 2013 Gil Tene
* Copyright 2012, 2013 Martin Thompson
*
* 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.ObjectLayout;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Iterator;
import java.util.NoSuchElementException;
import static java.lang.reflect.Modifier.isFinal;
import static java.lang.reflect.Modifier.isStatic;
/**
* An array of (potentially) mutable but non-replaceable objects.
* <p>
* A structured array contains array element objects of a fixed (at creation time, per array instance) class,
* and can support elements of any class that provides public constructors. The elements in a StructuredArray
* are all allocated and constructed at array creation time, and individual elements cannot be removed or
* replaced after array creation. Array elements can be accessed using an index-based accessor methods in
* the form of {@link StructuredArray#get}() using either {@link int} or
* {@link long} indices. Individual element contents can then be accessed and manipulated using any and all
* operations supported by the member element's class.
* <p>
* While simple creation of default-constructed elements and fixed constructor parameters are available through
* the newInstance factory methods, supporting arbitrary member types requires a wider range of construction
* options. The ConstructorAndArgsLocator API provides for array creation with arbitrary, user-supplied
* constructors and arguments, either of which can take the element index into account.
* <p>
* StructuredArray is designed with semantics specifically restricted to be consistent with layouts of an
* array of structures in C-like languages. While fully functional on all JVM implementation (of Java SE 5
* and above), the semantics are such that a JVM may transparently optimise the implementation to provide a
* compact contiguous layout that facilitates consistent stride based memory access and dead-reckoning
* (as opposed to de-referenced) access to elements
*
* @param <T> type of the element occupying each array slot.
*/
public final class StructuredArray<T> implements Iterable<T> {
private static final int MAX_EXTRA_PARTITION_SIZE_POW2_EXPONENT = 30;
private static final int MAX_EXTRA_PARTITION_SIZE = 1 << MAX_EXTRA_PARTITION_SIZE_POW2_EXPONENT;
private static final int MASK = MAX_EXTRA_PARTITION_SIZE - 1;
private final Field[] fields;
private final boolean hasFinalFields;
private final Class<T> elementClass;
private final long[] lengths;
private final long length; // A cached lengths[0]
private final int dimensionCount;
// Separated internal storage arrays by type for performance reasons, to avoid casting and checkcast at runtime.
// Wrong dimension count gets (of the wrong type for the dimension depth) will result in NPEs rather
// than class cast exceptions.
private final StructuredArray<T>[][] longAddressableSubArrays; // Used to store subArrays at indexes above Integer.MAX_VALUE
private final StructuredArray<T>[] intAddressableSubArrays;
private final T[][] longAddressableElements; // Used to store elements at indexes above Integer.MAX_VALUE
private final T[] intAddressableElements;
// Single-dimensional newInstance forms:
/**
* Create an array of <code>length</code> elements, each containing an element object of
* type <code>elementClass</code>. Using the <code>elementClass</code>'s default constructor.
*
* @param length of the array to create.
* @param elementClass of each element in the array
* @throws NoSuchMethodException if the element class does not have a public default constructor
*/
public static <T> StructuredArray<T> newInstance(final Class<T> elementClass,
final long length) throws NoSuchMethodException {
final ConstructorAndArgsLocator<T> constructorAndArgsLocator = new FixedConstructorAndArgsLocator<T>(elementClass);
final long[] lengths = {length};
return new StructuredArray<T>(lengths.length, constructorAndArgsLocator, lengths, null);
}
/**
* Create an array of <code>length</code> elements, each containing an element object of
* type <code>elementClass</code>. Use constructor and arguments supplied (on a potentially
* per element index basis) by the specified <code>constructorAndArgsLocator</code> to construct and initialize
* each element.
*
* @param length of the array to create.
* @param constructorAndArgsLocator produces element constructors [potentially] on a per element basis.
* @throws NoSuchMethodException if the element class does not not support a supplied constructor
*/
public static <T> StructuredArray<T> newInstance(final ConstructorAndArgsLocator<T> constructorAndArgsLocator,
final long length) throws NoSuchMethodException {
final long[] lengths = {length};
return new StructuredArray<T>(lengths.length, constructorAndArgsLocator, lengths, null);
}
/**
* Create an array of <code>length</code> elements, each containing an element object of
* type <code>elementClass</code>. Use a fixed (same for all elements) constructor identified by the argument
* classes specified in <code>initArgs</code> to construct and initialize each element, passing the remaining
* arguments to that constructor.
*
* @param length of the array to create.
* @param elementClass of each element in the array
* @param initArgTypes for selecting the constructor to call for initialising each structure object.
* @param initArgs to be passed to a constructor for initialising each structure object.
* @throws IllegalArgumentException if initArgTypes and constructor arguments do not match in length
* @throws NoSuchMethodException if initArgTypes does not match a public constructor signature in elementClass
*/
public static <T> StructuredArray<T> newInstance(final Class<T> elementClass,
final long length,
final Class[] initArgTypes,
final Object... initArgs) throws NoSuchMethodException {
final ConstructorAndArgsLocator<T> constructorAndArgsLocator =
new FixedConstructorAndArgsLocator<T>(elementClass, initArgTypes, initArgs);
final long[] lengths = {length};
return new StructuredArray<T>(lengths.length, constructorAndArgsLocator, lengths, null);
}
// Multi-dimensional newInstance forms:
/**
* Create a multi dimensional array of elements. Each dimension of the array will be of a length designated
* in the <code>lengths</code> parameters passed. Each element of the array will consist of
* an object of type <code>elementClass</code>. Elements will be constructed Using the
* <code>elementClass</code>'s default constructor.
*
* @param elementClass of each element in the array
* @param lengths of the array dimensions to create.
* @throws NoSuchMethodException if the element class does not not support a supplied constructor
*/
public static <T> StructuredArray<T> newInstance(final Class<T> elementClass,
final Long... lengths) throws NoSuchMethodException {
final ConstructorAndArgsLocator constructorAndArgsLocator = new FixedConstructorAndArgsLocator<T>(elementClass);
return new StructuredArray<T>(lengths.length, constructorAndArgsLocator, LongArrayToPrimitiveLongArray(lengths), null);
}
/**
* Create a multi dimensional array of elements. Each dimension of the array will be of a length designated
* in the <code>lengths[]</code> passed. Each element of the array will consist of
* an object of type <code>elementClass</code>. Elements will be constructed Using the
* <code>elementClass</code>'s default constructor.
*
* @param elementClass of each element in the array
* @param lengths of the array dimensions to create.
* @throws NoSuchMethodException if the element class does not not support a supplied constructor
*/
public static <T> StructuredArray<T> newInstance(final Class<T> elementClass,
final long[] lengths) throws NoSuchMethodException {
final ConstructorAndArgsLocator<T> constructorAndArgsLocator = new FixedConstructorAndArgsLocator<T>(elementClass);
return new StructuredArray<T>(lengths.length, constructorAndArgsLocator, lengths, null);
}
/**
* Create a multi dimensional array of elements. Each dimension of the array will be of a length designated
* in the <code>lengths[]</code> passed. Each element of the array will consist of
* an object of type <code>elementClass</code>. Elements will be constructed using a fixed (same for all elements)
* constructor identified by the argument classes specified in <code>initArgTypes</code> to construct and
* initialize each element, passing the <code>initArgs</code> arguments to that constructor.
*
* @param elementClass of each element in the array
* @param lengths of the array dimensions to create.
* @param initArgTypes for selecting the constructor to call for initialising each structure object.
* @param initArgs to be passed to a constructor for initialising each structure object.
* @throws IllegalArgumentException if initArgTypes and constructor arguments do not match in length
* @throws NoSuchMethodException if initArgTypes does not match a public constructor signature in elementClass
*/
public static <T> StructuredArray<T> newInstance(final Class<T> elementClass,
final long[] lengths,
final Class[] initArgTypes,
final Object... initArgs) throws NoSuchMethodException {
final ConstructorAndArgsLocator<T> constructorAndArgsLocator =
new FixedConstructorAndArgsLocator<T>(elementClass, initArgTypes, initArgs);
return new StructuredArray<T>(lengths.length, constructorAndArgsLocator, lengths, null);
}
/**
* Create a multi dimensional array of elements. Each dimension of the array will be of a length designated
* in the <code>lengths</code> arguments passed. Each element of the array will consist of
* an object of type <code>elementClass</code>. Elements will be constructed using the constructor and arguments
* supplied (on a potentially per element index basis) by the specified <code>constructorAndArgsLocator</code>.
* to construct and initialize each element.
*
* @param constructorAndArgsLocator produces element constructors [potentially] on a per element basis.
* @param lengths of the array dimensions to create.
* @throws NoSuchMethodException if the element class does not not support a supplied constructor
*/
public static <T> StructuredArray<T> newInstance(final ConstructorAndArgsLocator<T> constructorAndArgsLocator,
final Long... lengths) throws NoSuchMethodException {
return new StructuredArray<T>(lengths.length, constructorAndArgsLocator, LongArrayToPrimitiveLongArray(lengths), null);
}
/**
* Create a multi dimensional array of elements. Each dimension of the array will be of a length designated
* in the <code>lengths[]</code> passed. Each element of the array will consist of
* an object of type <code>elementClass</code>. Elements will be constructed using the constructor and arguments
* supplied (on a potentially per element index basis) by the specified <code>constructorAndArgsLocator</code>.
* to construct and initialize each element.
*
* @param constructorAndArgsLocator produces element constructors [potentially] on a per element basis.
* @param lengths of the array dimensions to create.
* @throws NoSuchMethodException if the element class does not not support a supplied constructor
*/
public static <T> StructuredArray<T> newInstance(final ConstructorAndArgsLocator<T> constructorAndArgsLocator,
final long[] lengths) throws NoSuchMethodException {
return new StructuredArray<T>(lengths.length, constructorAndArgsLocator, lengths, null);
}
/**
* Copy an array of elements to a newly created array. Copying of individual elements is done by using
* the <code>elementClass</code> copy constructor to construct the individual member elements of the new
* array based on the corresponding elements of the <code>source</code> array.
*
* @param source The array to duplicate.
* @throws NoSuchMethodException if the element class does not have a public copy constructor.
*/
public static <T> StructuredArray<T> copyInstance(final StructuredArray<T> source) throws NoSuchMethodException {
return copyInstance(source, new long[source.getDimensionCount()], source.getLengths());
}
/**
* Copy a range from an array of elements to a newly created array. Copying of individual elements is done
* by using the <code>elementClass</code> copy constructor to construct the individual member elements of
* the new array based on the corresponding elements of the <code>source</code> array.
*
* @param source The array to copy from.
* @param sourceOffsets offset indexes for each dimension, indicating where the source region to be copied begins.
* @param counts the number of elements in each dimension to copy.
* @throws NoSuchMethodException if the element class does not have a public copy constructor.
*/
public static <T> StructuredArray<T> copyInstance(final StructuredArray<T> source,
final long[] sourceOffsets,
final Long... counts) throws NoSuchMethodException {
return copyInstance(source, sourceOffsets, LongArrayToPrimitiveLongArray(counts));
}
/**
* Copy a range from an array of elements to a newly created array. Copying of individual elements is done
* by using the <code>elementClass</code> copy constructor to construct the individual member elements of
* the new array based on the corresponding elements of the <code>source</code> array.
*
* @param source The array to copy from.
* @param sourceOffsets offset indexes for each dimension, indicating where the source region to be copied begins.
* @param counts the number of elements in each dimension to copy.
* @throws NoSuchMethodException if the element class does not have a public copy constructor.
*/
public static <T> StructuredArray<T> copyInstance(final StructuredArray<T> source,
final long[] sourceOffsets,
final long[] counts) throws NoSuchMethodException {
if (source.getDimensionCount() != sourceOffsets.length) {
throw new IllegalArgumentException("source.getNumDimensions() must match sourceOffsets.length");
}
if (counts.length != source.getDimensionCount()) {
throw new IllegalArgumentException("source.getNumDimensions() must match counts.length");
}
for (int i = 0; i < counts.length; i++) {
if (source.getLengths()[i] < sourceOffsets[i] + counts[i]) {
throw new ArrayIndexOutOfBoundsException(
"Dimension " + i + ": source " + source + " length of " + source.getLengths()[i] +
" is smaller than sourceOffset (" + sourceOffsets[i] + ") + count (" + counts[i] + ")" );
}
}
final ConstructorAndArgsLocator<T> constructorAndArgsLocator =
new CopyConstructorAndArgsLocator<T>(source.getElementClass(), source, sourceOffsets, false);
return new StructuredArray<T>(source.getDimensionCount(), constructorAndArgsLocator, counts, null);
}
@SuppressWarnings("unchecked")
private StructuredArray(final int dimensionCount,
final ConstructorAndArgsLocator constructorAndArgsLocator,
final long[] lengths,
final long[] containingIndices) throws NoSuchMethodException {
if (dimensionCount < 1) {
throw new IllegalArgumentException("dimensionCount must be at least 1");
}
this.dimensionCount = dimensionCount;
this.lengths = lengths;
this.length = lengths[0];
if (length < 0) {
throw new IllegalArgumentException("length cannot be negative");
}
if (lengths.length != dimensionCount) {
throw new IllegalArgumentException("number of lengths provided (" + lengths.length +
") does not match numDimensions (" + dimensionCount + ")");
}
this.elementClass = constructorAndArgsLocator.getElementClass();
final Field[] fields = removeStaticFields(elementClass.getDeclaredFields());
for (final Field field : fields) {
field.setAccessible(true);
}
this.fields = fields;
this.hasFinalFields = containsFinalQualifiedFields(fields);
if (dimensionCount > 1) {
// We have sub arrays, not elements:
intAddressableElements = null;
longAddressableElements = null;
// int-addressable sub arrays:
final int intLength = (int) Math.min(length, Integer.MAX_VALUE);
intAddressableSubArrays = new StructuredArray[intLength];
// Subsequent partitions hold long-addressable-only sub arrays:
final long extraLength = length - intLength;
final int numFullPartitions = (int)(extraLength >>> MAX_EXTRA_PARTITION_SIZE_POW2_EXPONENT);
final int lastPartitionSize = (int)extraLength & MASK;
longAddressableSubArrays = new StructuredArray[numFullPartitions + 1][];
// full long-addressable-only partitions:
for (int i = 0; i < numFullPartitions; i++) {
longAddressableSubArrays[i] = new StructuredArray[MAX_EXTRA_PARTITION_SIZE];
}
// Last partition with leftover long-addressable-only size:
longAddressableSubArrays[numFullPartitions] = new StructuredArray[lastPartitionSize];
// This is an array of arrays. Pass the constructorAndArgsLocator through to
// a subArrayConstructorAndArgsLocator that will be used to populate the sub-array:
final long[] subArrayLengths = new long[lengths.length - 1];
System.arraycopy(lengths, 1, subArrayLengths, 0, subArrayLengths.length);
final Class[] subArrayArgTypes = {Integer.TYPE, ConstructorAndArgsLocator.class,
long[].class, long[].class};
final Object[] subArrayArgs = {dimensionCount - 1, constructorAndArgsLocator,
subArrayLengths, null /* containingIndices arg goes here */};
final Class targetClass = StructuredArray.class;
final Constructor<StructuredArray<T>> constructor = targetClass.getDeclaredConstructor(subArrayArgTypes);
final ConstructorAndArgsLocator<StructuredArray<T>> subArrayConstructorAndArgsLocator =
new ArrayConstructorAndArgsLocator<StructuredArray<T>>(constructor, subArrayArgs, 3);
populateElements(subArrayConstructorAndArgsLocator, intAddressableSubArrays,
longAddressableSubArrays, containingIndices);
} else {
// We have elements, no sub arrays:
intAddressableSubArrays = null;
longAddressableSubArrays = null;
// int-addressable elements:
final int intLength = (int) Math.min(length, Integer.MAX_VALUE);
intAddressableElements = (T[])new Object[intLength];
// Subsequent partitions hold long-addressable-only elements:
final long extraLength = length - intLength;
final int numFullPartitions = (int)(extraLength >>> MAX_EXTRA_PARTITION_SIZE_POW2_EXPONENT);
final int lastPartitionSize = (int)extraLength & MASK;
longAddressableElements = (T[][])new Object[numFullPartitions + 1][];
// full long-addressable-only partitions:
for (int i = 0; i < numFullPartitions; i++) {
- longAddressableElements[i] = (T[])new StructuredArray[MAX_EXTRA_PARTITION_SIZE];
+ longAddressableElements[i] = (T[])new Object[MAX_EXTRA_PARTITION_SIZE];
}
// Last partition with leftover long-addressable-only size:
longAddressableElements[numFullPartitions] = (T[])new Object[lastPartitionSize];
// This is a single dimension array. Populate it:
populateElements(constructorAndArgsLocator, intAddressableElements,
longAddressableElements, containingIndices);
}
}
/**
* Get the number of dimensions of the array.
*
* @return the number of dimensions of the array.
*/
public int getDimensionCount() {
return dimensionCount;
}
/**
* Get the lengths (number of elements per dimension) of the array.
*
* @return the number of elements in each dimension in the array.
*/
public long[] getLengths() {
return lengths;
}
/**
* Get the total number of elements (in all dimensions combined) in this multi-dimensional array.
*
* @return the total number of elements (in all dimensions combined) in the array.
*/
public long getTotalElementCount() {
long totalElementCount = 1;
for (long length : lengths) {
totalElementCount *= length;
}
return totalElementCount;
}
/**
* Get the length (number of elements) of the array.
*
* @return the number of elements in the array.
*/
public long getLength() {
return length;
}
// Variations on get():
/**
* Get a reference to an element in the array, using a <code>long[]</code> index array.
*
* @param indices The indices (at each dimension) of the element to retrieve.
* @return a reference to the indexed element.
* @throws IllegalArgumentException if number of indices does not match number of dimensions in the array
*/
public T get(final long[] indices) throws IllegalArgumentException {
return get(indices, 0);
}
/**
* Get a reference to an element in the array, using <code>long</code> indices supplied in an array.
* indexOffset indicates the starting point in the array at which the first index should be found.
* This form is useful when passing index arrays through multiple levels to avoid construction of
* temporary varargs containers or construction of new shorter index arrays.
*
* @param indices The indices (at each dimension) of the element to retrieve.
* @param indexOffset The beginning offset in the indices array related to this arrays contents.
* @return a reference to the indexed element.
* @throws IllegalArgumentException if number of relevant indices does not match number of dimensions in the array
*/
public T get(final long[] indices, final int indexOffset) throws IllegalArgumentException {
if ((indices.length - indexOffset) != dimensionCount) {
throw new IllegalArgumentException("number of relevant elements in indices must match array dimension count");
}
if (dimensionCount > 1) {
StructuredArray<T> containedArray = getSubArray(indices[indexOffset]);
return containedArray.get(indices, indexOffset + 1);
} else {
return get(indices[indexOffset]);
}
}
/**
* Get a reference to an element in the array, using a varargs long indices.
*
* @param indices The indices (at each dimension) of the element to retrieve.
* @return a reference to the indexed element.
* @throws IllegalArgumentException if number of indices does not match number of dimensions in the array
*/
public T get(final Long... indices) throws IllegalArgumentException {
return get(LongArrayToPrimitiveLongArray(indices));
}
/**
* Get a reference to an element in the array, using a varargs int indices.
*
* @param indices The indices (at each dimension) of the element to retrieve.
* @return a reference to the indexed element.
* @throws IllegalArgumentException if number of indices does not match number of dimensions in the array
*/
public T get(final Integer... indices) throws IllegalArgumentException {
return get(IntegerArrayToPrimitiveLongArray(indices));
}
// fast long index element get variants:
/**
* Get a reference to an element in the array, using a <code>long</code> index.
*
* @param index of the element to retrieve.
* @return a reference to the indexed element.
* @throws IllegalArgumentException if array has more than one dimensions
*/
public T get(final long index) throws IllegalArgumentException {
if (index < Integer.MAX_VALUE) {
return get((int) index);
}
if (dimensionCount != 1) {
throw new IllegalArgumentException("number of index parameters to get() must match array dimension count");
}
// Calculate index into long-addressable-only partitions:
final long longIndex = (index - Integer.MAX_VALUE);
final int partitionIndex = (int)(longIndex >>> MAX_EXTRA_PARTITION_SIZE_POW2_EXPONENT);
final int partitionOffset = (int)longIndex & MASK;
return longAddressableElements[partitionIndex][partitionOffset];
}
/**
* Get a reference to an element in the array, using 2 <code>long</code> indexes.
* @param index0 the first index (in the first array dimension) of the element to retrieve
* @param index1 the second index (in the second array dimension) of the element to retrieve
* @return the element at [index0, index1]
* @throws NullPointerException if number of indexes does not match number of dimensions in the array
*/
public T get(final long index0, final long index1) throws IllegalArgumentException {
if (dimensionCount != 2) {
throw new IllegalArgumentException("number of index parameters to get() must match array dimension count");
}
return getSubArray(index0).get(index1);
}
/**
* Get a reference to an element in the array, using 3 <code>long</code> indexes.
* @param index0 the first index (in the first array dimension) of the element to retrieve
* @param index1 the second index (in the second array dimension) of the element to retrieve
* @param index2 the third index (in the third array dimension) of the element to retrieve
* @return the element at [index0, index1, index2]
* @throws NullPointerException if number of indexes does not match number of dimensions in the array
*/
public T get(final long index0, final long index1, final long index2) throws IllegalArgumentException {
if (dimensionCount != 3) {
throw new IllegalArgumentException("number of index parameters to get() must match array dimension count");
}
return getSubArray(index0).getSubArray(index1).get(index2);
}
/**
* Get a reference to an element in the array, using 4 <code>long</code> indexes.
* @param index0 the first index (in the first array dimension) of the element to retrieve
* @param index1 the second index (in the second array dimension) of the element to retrieve
* @param index2 the third index (in the third array dimension) of the element to retrieve
* @param index3 the fourth index (in the fourth array dimension) of the element to retrieve
* @return the element at [index0, index1, index2, index3]
* @throws NullPointerException if number of indexes does not match number of dimensions in the array
*/
public T get(final long index0, final long index1, final long index2, final long index3) throws IllegalArgumentException {
if (dimensionCount != 4) {
throw new IllegalArgumentException("number of index parameters to get() must match array dimension count");
}
return getSubArray(index0).getSubArray(index1).getSubArray(index2).get(index3);
}
// fast int index element get variants:
/**
* Get a reference to an element in the array, using an <code>int</code> index.
*
* @param index of the element to retrieve.
* @return a reference to the indexed element.
* @throws NullPointerException if array has more than one dimensions
*/
public T get(final int index) throws IllegalArgumentException {
if (dimensionCount != 1) {
throw new IllegalArgumentException("number of index parameters to get() must match array dimension count");
}
return intAddressableElements[index];
}
/**
* Get a reference to an element in the array, using 2 <code>int</code> indexes.
* @param index0 the first index (in the first array dimension) of the element to retrieve
* @param index1 the second index (in the second array dimension) of the element to retrieve
* @return the element at [index0, index1]
* @throws NullPointerException if number of indexes does not match number of dimensions in the array
*/
public T get(final int index0, final int index1) throws IllegalArgumentException {
if (dimensionCount != 2) {
throw new IllegalArgumentException("number of index parameters to get() must match array dimension count");
}
return getSubArray(index0).get(index1);
}
/**
* Get a reference to an element in the array, using 3 <code>int</code> indexes.
* @param index0 the first index (in the first array dimension) of the element to retrieve
* @param index1 the second index (in the second array dimension) of the element to retrieve
* @param index2 the third index (in the third array dimension) of the element to retrieve
* @return the element at [index0, index1, index2]
* @throws NullPointerException if number of indexes does not match number of dimensions in the array
*/
public T get(final int index0, final int index1, final int index2) throws IllegalArgumentException {
if (dimensionCount != 3) {
throw new IllegalArgumentException("number of index parameters to get() must match array dimension count");
}
return getSubArray(index0).getSubArray(index1).get(index2);
}
/**
* Get a reference to an element in the array, using 4 <code>int</code> indexes.
* @param index0 the first index (in the first array dimension) of the element to retrieve
* @param index1 the second index (in the second array dimension) of the element to retrieve
* @param index2 the third index (in the third array dimension) of the element to retrieve
* @param index3 the fourth index (in the fourth array dimension) of the element to retrieve
* @return the element at [index0, index1, index2, index3]
* @throws NullPointerException if number of indexes does not match number of dimensions in the array
*/
public T get(final int index0, final int index1, final int index2, final int index3) throws IllegalArgumentException {
if (dimensionCount != 4) {
throw new IllegalArgumentException("number of index parameters to get() must match array dimension count");
}
return getSubArray(index0).getSubArray(index1).getSubArray(index2).get(index3);
}
// Type specific public gets of first dimension:
/**
* Get a reference to a StructuredArray element in this array, using a <code>long</code> index.
* @param index (in this array's first dimension) of the StructuredArray to retrieve
* @return a reference to the StructuredArray located at [index] in the first dimension of this array
* @throws IllegalArgumentException if array has less than two dimensions
*/
@SuppressWarnings("unchecked")
public StructuredArray<T> getSubArray(final long index) throws IllegalArgumentException {
if (index < Integer.MAX_VALUE) {
return getSubArray((int) index);
}
if (dimensionCount < 2) {
throw new IllegalArgumentException("cannot call getSubArrayL() on single dimensional array");
}
// Calculate index into long-addressable-only partitions:
final long longIndex = (index - Integer.MAX_VALUE);
final int partitionIndex = (int)(longIndex >>> MAX_EXTRA_PARTITION_SIZE_POW2_EXPONENT);
final int partitionOffset = (int)longIndex & MASK;
return longAddressableSubArrays[partitionIndex][partitionOffset];
}
/**
* Get a reference to a StructuredArray element in this array, using a <code>int</code> index.
* @param index (in this array's first dimension) of the StructuredArray to retrieve
* @return a reference to the StructuredArray located at [index] in the first dimension of this array
* @throws IllegalArgumentException if array has less than two dimensions
*/
@SuppressWarnings("unchecked")
public StructuredArray<T> getSubArray(final int index) throws IllegalArgumentException {
if (dimensionCount < 2) {
throw new IllegalArgumentException("cannot call getSubArray() on single dimensional array");
}
return intAddressableSubArrays[index];
}
private <E> void populateElements(final ConstructorAndArgsLocator<E> constructorAndArgsLocator,
final E[] intAddressable,
final E[][] longAddressable,
final long[] containingIndices) throws NoSuchMethodException {
try {
final long[] indexes;
if (containingIndices != null) {
indexes = new long[containingIndices.length + 1];
System.arraycopy(containingIndices, 0, indexes, 0, containingIndices.length);
} else {
indexes = new long[1];
}
final int thisIndex = indexes.length - 1;
long index = 0;
for (int i = 0; i < intAddressable.length; i++, index++) {
indexes[thisIndex] = index;
final ConstructorAndArgs<E> constructorAndArgs = constructorAndArgsLocator.getForIndices(indexes);
final Constructor<E> constructor = constructorAndArgs.getConstructor();
intAddressable[i] = constructor.newInstance(constructorAndArgs.getConstructorArgs());
constructorAndArgsLocator.recycle(constructorAndArgs);
}
for (final E[] partition : longAddressable) {
indexes[thisIndex] = index;
for (int i = 0, size = partition.length; i < size; i++, index++) {
final ConstructorAndArgs<E> constructorAndArgs = constructorAndArgsLocator.getForIndices(indexes);
final Constructor<E> constructor = constructorAndArgs.getConstructor();
partition[i] = constructor.newInstance(constructorAndArgs.getConstructorArgs());
constructorAndArgsLocator.recycle(constructorAndArgs);
}
}
} catch (final NoSuchMethodException ex) {
throw ex;
} catch (final Exception ex) {
throw new RuntimeException(ex);
}
}
/**
* Get the {@link Class} of elements stored in the array.
*
* @return the {@link Class} of elements stored in the array.
*/
public Class<T> getElementClass() {
return elementClass;
}
/**
* {@inheritDoc}
*/
public StructureIterator iterator() {
return new StructureIterator();
}
/**
* Specialised {@link java.util.Iterator} with the ability to be {@link #reset()} enabling reuse.
*/
public class StructureIterator implements Iterator<T> {
private final long[] cursors = new long[dimensionCount];
private long elementCountToCursor = 0;
private final long totalElementCount = getTotalElementCount();
/**
* {@inheritDoc}
*/
public boolean hasNext() {
return elementCountToCursor < totalElementCount;
}
/**
* {@inheritDoc}
*/
public T next() {
if (elementCountToCursor >= totalElementCount) {
throw new NoSuchElementException();
}
T t = get(cursors);
// Increment cursors from inner-most dimension out:
for (int cursorDimension = cursors.length - 1; cursorDimension >= 0; cursorDimension--) {
if ((++cursors[cursorDimension]) < lengths[cursorDimension])
break;
// This dimension wrapped. Reset to zero and continue to one dimension higher
cursors[cursorDimension] = 0;
}
elementCountToCursor++;
return t;
}
/**
* Remove operation is not supported on {@link StructuredArray}s.
*
* @throws UnsupportedOperationException if called.
*/
public void remove() {
throw new UnsupportedOperationException();
}
/**
* Reset to the beginning of the collection enabling reuse of the iterator.
*/
public void reset() {
for (int i = 0; i < cursors.length; i++) {
cursors[i] = 0;
}
elementCountToCursor = 0;
}
public long[] getCursors() {
return Arrays.copyOf(cursors, cursors.length);
}
}
private static Field[] removeStaticFields(final Field[] declaredFields) {
int staticFieldCount = 0;
for (final Field field : declaredFields) {
if (isStatic(field.getModifiers())) {
staticFieldCount++;
}
}
final Field[] instanceFields = new Field[declaredFields.length - staticFieldCount];
int i = 0;
for (final Field field : declaredFields) {
if (!isStatic(field.getModifiers())) {
instanceFields[i++] = field;
}
}
return instanceFields;
}
private boolean containsFinalQualifiedFields(final Field[] fields) {
for (final Field field : fields) {
if (isFinal(field.getModifiers())) {
return true;
}
}
return false;
}
private static void shallowCopy(final Object src, final Object dst, final Field[] fields) {
try {
for (final Field field : fields) {
field.set(dst, field.get(src));
}
} catch (final IllegalAccessException shouldNotHappen) {
throw new RuntimeException(shouldNotHappen);
}
}
private static void reverseShallowCopy(final Object src, final Object dst, final Field[] fields) {
try {
for (int i = fields.length - 1; i >= 0; i--) {
final Field field = fields[i];
field.set(dst, field.get(src));
}
} catch (final IllegalAccessException shouldNotHappen) {
throw new RuntimeException(shouldNotHappen);
}
}
private static long[] LongArrayToPrimitiveLongArray(final Long[] lengths) {
long [] longLengths = new long[lengths.length];
for (int i = 0; i < lengths.length; i++) {
longLengths[i] = lengths[i];
}
return longLengths;
}
private static long[] IntegerArrayToPrimitiveLongArray(final Integer[] lengths) {
long [] longLengths = new long[lengths.length];
for (int i = 0; i < lengths.length; i++) {
longLengths[i] = lengths[i];
}
return longLengths;
}
/**
* Shallow copy a region of element object contents from one array to the other.
* <p>
* shallowCopy will copy all fields from each of the source elements to the corresponding fields in each
* of the corresponding destination elements. If the same array is both the src and dst then the copy will
* happen as if a temporary intermediate array was used.
*
* @param src array to copy.
* @param srcOffset offset index in src where the region begins.
* @param dst array into which the copy should occur.
* @param dstOffset offset index in the dst where the region begins.
* @param count of structure elements to copy.
* @throws IllegalStateException if final fields are discovered.
* @throws ArrayStoreException if the element classes in src and dst are not identical.
*/
public static void shallowCopy(final StructuredArray src, final long srcOffset,
final StructuredArray dst, final long dstOffset,
final long count) {
shallowCopy(src, srcOffset, dst, dstOffset, count, false);
}
/**
* Shallow copy a region of element object contents from one array to the other.
* <p>
* shallowCopy will copy all fields from each of the source elements to the corresponding fields in each
* of the corresponding destination elements. If the same array is both the src and dst then the copy will
* happen as if a temporary intermediate array was used.
*
* If <code>allowFinalFieldOverwrite</code> is specified as <code>true</code>, even final fields will be copied.
*
* @param src array to copy.
* @param srcOffset offset index in src where the region begins.
* @param dst array into which the copy should occur.
* @param dstOffset offset index in the dst where the region begins.
* @param count of structure elements to copy.
* @param allowFinalFieldOverwrite allow final fields to be overwritten during a copy operation.
* @throws IllegalArgumentException if source or destination arrays have more than one dimension, or
* if final fields are discovered and all allowFinalFieldOverwrite is not true.
* @throws ArrayStoreException if the element classes in src and dst are not identical.
*/
public static void shallowCopy(final StructuredArray src, final long srcOffset,
final StructuredArray dst, final long dstOffset,
final long count,
final boolean allowFinalFieldOverwrite) {
if (src.elementClass != dst.elementClass) {
throw new ArrayStoreException(String.format("Only objects of the same class can be copied: %s != %s",
src.getClass(), dst.getClass()));
}
if ((src.dimensionCount > 1) || (dst.dimensionCount > 1)) {
throw new IllegalArgumentException("shallowCopy only supported for single dimension arrays");
}
final Field[] fields = src.fields;
if (!allowFinalFieldOverwrite && dst.hasFinalFields) {
throw new IllegalArgumentException("Cannot shallow copy onto final fields");
}
if (((srcOffset + count) < Integer.MAX_VALUE) && ((dstOffset + count) < Integer.MAX_VALUE)) {
// use the (faster) int based get
if (dst == src && (dstOffset >= srcOffset && (dstOffset + count) >= srcOffset)) {
for (int srcIdx = (int)(srcOffset + count), dstIdx = (int)(dstOffset + count), limit = (int)(srcOffset - 1);
srcIdx > limit; srcIdx--, dstIdx--) {
reverseShallowCopy(src.get(srcIdx), dst.get(dstIdx), fields);
}
} else {
for (int srcIdx = (int)srcOffset, dstIdx = (int)dstOffset, limit = (int)(srcOffset + count);
srcIdx < limit; srcIdx++, dstIdx++) {
shallowCopy(src.get(srcIdx), dst.get(dstIdx), fields);
}
}
} else {
// use the (slower) long based getL
if (dst == src && (dstOffset >= srcOffset && (dstOffset + count) >= srcOffset)) {
for (long srcIdx = srcOffset + count, dstIdx = dstOffset + count, limit = srcOffset - 1;
srcIdx > limit; srcIdx--, dstIdx--) {
reverseShallowCopy(src.get(srcIdx), dst.get(dstIdx), fields);
}
} else {
for (long srcIdx = srcOffset, dstIdx = dstOffset, limit = srcOffset + count;
srcIdx < limit; srcIdx++, dstIdx++) {
shallowCopy(src.get(srcIdx), dst.get(dstIdx), fields);
}
}
}
}
}
| true | true | private StructuredArray(final int dimensionCount,
final ConstructorAndArgsLocator constructorAndArgsLocator,
final long[] lengths,
final long[] containingIndices) throws NoSuchMethodException {
if (dimensionCount < 1) {
throw new IllegalArgumentException("dimensionCount must be at least 1");
}
this.dimensionCount = dimensionCount;
this.lengths = lengths;
this.length = lengths[0];
if (length < 0) {
throw new IllegalArgumentException("length cannot be negative");
}
if (lengths.length != dimensionCount) {
throw new IllegalArgumentException("number of lengths provided (" + lengths.length +
") does not match numDimensions (" + dimensionCount + ")");
}
this.elementClass = constructorAndArgsLocator.getElementClass();
final Field[] fields = removeStaticFields(elementClass.getDeclaredFields());
for (final Field field : fields) {
field.setAccessible(true);
}
this.fields = fields;
this.hasFinalFields = containsFinalQualifiedFields(fields);
if (dimensionCount > 1) {
// We have sub arrays, not elements:
intAddressableElements = null;
longAddressableElements = null;
// int-addressable sub arrays:
final int intLength = (int) Math.min(length, Integer.MAX_VALUE);
intAddressableSubArrays = new StructuredArray[intLength];
// Subsequent partitions hold long-addressable-only sub arrays:
final long extraLength = length - intLength;
final int numFullPartitions = (int)(extraLength >>> MAX_EXTRA_PARTITION_SIZE_POW2_EXPONENT);
final int lastPartitionSize = (int)extraLength & MASK;
longAddressableSubArrays = new StructuredArray[numFullPartitions + 1][];
// full long-addressable-only partitions:
for (int i = 0; i < numFullPartitions; i++) {
longAddressableSubArrays[i] = new StructuredArray[MAX_EXTRA_PARTITION_SIZE];
}
// Last partition with leftover long-addressable-only size:
longAddressableSubArrays[numFullPartitions] = new StructuredArray[lastPartitionSize];
// This is an array of arrays. Pass the constructorAndArgsLocator through to
// a subArrayConstructorAndArgsLocator that will be used to populate the sub-array:
final long[] subArrayLengths = new long[lengths.length - 1];
System.arraycopy(lengths, 1, subArrayLengths, 0, subArrayLengths.length);
final Class[] subArrayArgTypes = {Integer.TYPE, ConstructorAndArgsLocator.class,
long[].class, long[].class};
final Object[] subArrayArgs = {dimensionCount - 1, constructorAndArgsLocator,
subArrayLengths, null /* containingIndices arg goes here */};
final Class targetClass = StructuredArray.class;
final Constructor<StructuredArray<T>> constructor = targetClass.getDeclaredConstructor(subArrayArgTypes);
final ConstructorAndArgsLocator<StructuredArray<T>> subArrayConstructorAndArgsLocator =
new ArrayConstructorAndArgsLocator<StructuredArray<T>>(constructor, subArrayArgs, 3);
populateElements(subArrayConstructorAndArgsLocator, intAddressableSubArrays,
longAddressableSubArrays, containingIndices);
} else {
// We have elements, no sub arrays:
intAddressableSubArrays = null;
longAddressableSubArrays = null;
// int-addressable elements:
final int intLength = (int) Math.min(length, Integer.MAX_VALUE);
intAddressableElements = (T[])new Object[intLength];
// Subsequent partitions hold long-addressable-only elements:
final long extraLength = length - intLength;
final int numFullPartitions = (int)(extraLength >>> MAX_EXTRA_PARTITION_SIZE_POW2_EXPONENT);
final int lastPartitionSize = (int)extraLength & MASK;
longAddressableElements = (T[][])new Object[numFullPartitions + 1][];
// full long-addressable-only partitions:
for (int i = 0; i < numFullPartitions; i++) {
longAddressableElements[i] = (T[])new StructuredArray[MAX_EXTRA_PARTITION_SIZE];
}
// Last partition with leftover long-addressable-only size:
longAddressableElements[numFullPartitions] = (T[])new Object[lastPartitionSize];
// This is a single dimension array. Populate it:
populateElements(constructorAndArgsLocator, intAddressableElements,
longAddressableElements, containingIndices);
}
}
| private StructuredArray(final int dimensionCount,
final ConstructorAndArgsLocator constructorAndArgsLocator,
final long[] lengths,
final long[] containingIndices) throws NoSuchMethodException {
if (dimensionCount < 1) {
throw new IllegalArgumentException("dimensionCount must be at least 1");
}
this.dimensionCount = dimensionCount;
this.lengths = lengths;
this.length = lengths[0];
if (length < 0) {
throw new IllegalArgumentException("length cannot be negative");
}
if (lengths.length != dimensionCount) {
throw new IllegalArgumentException("number of lengths provided (" + lengths.length +
") does not match numDimensions (" + dimensionCount + ")");
}
this.elementClass = constructorAndArgsLocator.getElementClass();
final Field[] fields = removeStaticFields(elementClass.getDeclaredFields());
for (final Field field : fields) {
field.setAccessible(true);
}
this.fields = fields;
this.hasFinalFields = containsFinalQualifiedFields(fields);
if (dimensionCount > 1) {
// We have sub arrays, not elements:
intAddressableElements = null;
longAddressableElements = null;
// int-addressable sub arrays:
final int intLength = (int) Math.min(length, Integer.MAX_VALUE);
intAddressableSubArrays = new StructuredArray[intLength];
// Subsequent partitions hold long-addressable-only sub arrays:
final long extraLength = length - intLength;
final int numFullPartitions = (int)(extraLength >>> MAX_EXTRA_PARTITION_SIZE_POW2_EXPONENT);
final int lastPartitionSize = (int)extraLength & MASK;
longAddressableSubArrays = new StructuredArray[numFullPartitions + 1][];
// full long-addressable-only partitions:
for (int i = 0; i < numFullPartitions; i++) {
longAddressableSubArrays[i] = new StructuredArray[MAX_EXTRA_PARTITION_SIZE];
}
// Last partition with leftover long-addressable-only size:
longAddressableSubArrays[numFullPartitions] = new StructuredArray[lastPartitionSize];
// This is an array of arrays. Pass the constructorAndArgsLocator through to
// a subArrayConstructorAndArgsLocator that will be used to populate the sub-array:
final long[] subArrayLengths = new long[lengths.length - 1];
System.arraycopy(lengths, 1, subArrayLengths, 0, subArrayLengths.length);
final Class[] subArrayArgTypes = {Integer.TYPE, ConstructorAndArgsLocator.class,
long[].class, long[].class};
final Object[] subArrayArgs = {dimensionCount - 1, constructorAndArgsLocator,
subArrayLengths, null /* containingIndices arg goes here */};
final Class targetClass = StructuredArray.class;
final Constructor<StructuredArray<T>> constructor = targetClass.getDeclaredConstructor(subArrayArgTypes);
final ConstructorAndArgsLocator<StructuredArray<T>> subArrayConstructorAndArgsLocator =
new ArrayConstructorAndArgsLocator<StructuredArray<T>>(constructor, subArrayArgs, 3);
populateElements(subArrayConstructorAndArgsLocator, intAddressableSubArrays,
longAddressableSubArrays, containingIndices);
} else {
// We have elements, no sub arrays:
intAddressableSubArrays = null;
longAddressableSubArrays = null;
// int-addressable elements:
final int intLength = (int) Math.min(length, Integer.MAX_VALUE);
intAddressableElements = (T[])new Object[intLength];
// Subsequent partitions hold long-addressable-only elements:
final long extraLength = length - intLength;
final int numFullPartitions = (int)(extraLength >>> MAX_EXTRA_PARTITION_SIZE_POW2_EXPONENT);
final int lastPartitionSize = (int)extraLength & MASK;
longAddressableElements = (T[][])new Object[numFullPartitions + 1][];
// full long-addressable-only partitions:
for (int i = 0; i < numFullPartitions; i++) {
longAddressableElements[i] = (T[])new Object[MAX_EXTRA_PARTITION_SIZE];
}
// Last partition with leftover long-addressable-only size:
longAddressableElements[numFullPartitions] = (T[])new Object[lastPartitionSize];
// This is a single dimension array. Populate it:
populateElements(constructorAndArgsLocator, intAddressableElements,
longAddressableElements, containingIndices);
}
}
|
diff --git a/src/Sed.java b/src/Sed.java
index 01bc053..99f4a82 100644
--- a/src/Sed.java
+++ b/src/Sed.java
@@ -1,149 +1,150 @@
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Stack;
import core.event.Join;
import core.event.Kick;
import core.event.Message;
import core.event.Quit;
import core.plugin.PluginTemp;
import core.utils.IRC;
public class Sed implements PluginTemp
{
private static final int CACHE_SIZE = 10; // per user
private Map<String, Stack<Message>> cache = new HashMap<String, Stack<Message>>();
public String name()
{
return "Sed";
}
@Override
public void onMessage(Message in_message) throws Exception
{
IRC irc = IRC.getInstance();
String message = in_message.getMessage();
String channel = in_message.getChannel();
String user = in_message.getUser();
// help string
if (message.matches("^\\.help") || message.matches("^\\."))
irc.sendPrivmsg(
channel,
"SED: "
+ "[<username>: ]s/<search>/<replacement>/ - e.g XeTK: s/.*/hello/ is used to replace the previous statement with hello :");
// set up sed finding regex
Matcher m = Pattern
.compile(
"(?:([\\s\\w]*):\\s)?s/([\\s\\w\\d\\$\\*\\.]*)/([\\s\\w\\d]*)(?:/)?",
Pattern.CASE_INSENSITIVE | Pattern.DOTALL).matcher(
message);
// it's sed time, baby
if (m.find())
{
String targetUser = new String();
String replacement = new String();
String search = new String();
if (m.group(1) != null)
targetUser = m.group(1);
search = m.group(2);
replacement = m.group(3);
Stack<Message> userCache = new Stack<Message>();
- if (targetUser.equals(new String()))
+ boolean hasTarget = !targetUser.equals(new String());
+ if (!hasTarget)
{
// no target, use last message from sourceUser's cache
// (or do nothing)
userCache = getUserCache(user);
}
else
{
// target specified, run through the cache (most recent first)
// and either match and replace or do nothing
userCache = getUserCache(targetUser);
}
while (!userCache.empty())
{
Message mmessage = userCache.pop();
m = Pattern.compile(search,
Pattern.CASE_INSENSITIVE | Pattern.DOTALL).matcher(
mmessage.getMessage());
if (m.find())
{
String reply = new String();
- if (!targetUser.equalsIgnoreCase(targetUser))
+ if (hasTarget)
reply = user + " thought ";
reply += "%s meant : %s";
irc.sendPrivmsg(channel, String.format(
reply,
mmessage.getUser(),
mmessage.getMessage().replaceAll(search,
replacement)));
break;
}
}
}
else // no dice, add message to history queue
{
addToCache(in_message);
}
}
private void addToCache(Message msg) {
String username = msg.getUser();
if (!cache.containsKey(username))
cache.put(username, new Stack<Message>());
cache.get(username).push(msg);
if (cache.get(username).size() > CACHE_SIZE)
cache.get(username).remove(0);
}
private Stack<Message> getUserCache(String username) {
Stack<Message> userCache = new Stack<Message>();
if (cache.containsKey(username))
userCache.addAll(cache.get(username));
return userCache;
}
public void emptyCache() {
cache = new HashMap<String, Stack<Message>>();
}
@Override
public void onCreate() throws Exception
{
}
@Override
public void onTime() throws Exception
{
}
@Override
public void onJoin(Join in_join) throws Exception
{
}
@Override
public void onQuit(Quit in_quit) throws Exception
{
}
@Override
public void onKick(Kick in_kick) throws Exception
{
}
}
| false | true | public void onMessage(Message in_message) throws Exception
{
IRC irc = IRC.getInstance();
String message = in_message.getMessage();
String channel = in_message.getChannel();
String user = in_message.getUser();
// help string
if (message.matches("^\\.help") || message.matches("^\\."))
irc.sendPrivmsg(
channel,
"SED: "
+ "[<username>: ]s/<search>/<replacement>/ - e.g XeTK: s/.*/hello/ is used to replace the previous statement with hello :");
// set up sed finding regex
Matcher m = Pattern
.compile(
"(?:([\\s\\w]*):\\s)?s/([\\s\\w\\d\\$\\*\\.]*)/([\\s\\w\\d]*)(?:/)?",
Pattern.CASE_INSENSITIVE | Pattern.DOTALL).matcher(
message);
// it's sed time, baby
if (m.find())
{
String targetUser = new String();
String replacement = new String();
String search = new String();
if (m.group(1) != null)
targetUser = m.group(1);
search = m.group(2);
replacement = m.group(3);
Stack<Message> userCache = new Stack<Message>();
if (targetUser.equals(new String()))
{
// no target, use last message from sourceUser's cache
// (or do nothing)
userCache = getUserCache(user);
}
else
{
// target specified, run through the cache (most recent first)
// and either match and replace or do nothing
userCache = getUserCache(targetUser);
}
while (!userCache.empty())
{
Message mmessage = userCache.pop();
m = Pattern.compile(search,
Pattern.CASE_INSENSITIVE | Pattern.DOTALL).matcher(
mmessage.getMessage());
if (m.find())
{
String reply = new String();
if (!targetUser.equalsIgnoreCase(targetUser))
reply = user + " thought ";
reply += "%s meant : %s";
irc.sendPrivmsg(channel, String.format(
reply,
mmessage.getUser(),
mmessage.getMessage().replaceAll(search,
replacement)));
break;
}
}
}
else // no dice, add message to history queue
{
addToCache(in_message);
}
}
| public void onMessage(Message in_message) throws Exception
{
IRC irc = IRC.getInstance();
String message = in_message.getMessage();
String channel = in_message.getChannel();
String user = in_message.getUser();
// help string
if (message.matches("^\\.help") || message.matches("^\\."))
irc.sendPrivmsg(
channel,
"SED: "
+ "[<username>: ]s/<search>/<replacement>/ - e.g XeTK: s/.*/hello/ is used to replace the previous statement with hello :");
// set up sed finding regex
Matcher m = Pattern
.compile(
"(?:([\\s\\w]*):\\s)?s/([\\s\\w\\d\\$\\*\\.]*)/([\\s\\w\\d]*)(?:/)?",
Pattern.CASE_INSENSITIVE | Pattern.DOTALL).matcher(
message);
// it's sed time, baby
if (m.find())
{
String targetUser = new String();
String replacement = new String();
String search = new String();
if (m.group(1) != null)
targetUser = m.group(1);
search = m.group(2);
replacement = m.group(3);
Stack<Message> userCache = new Stack<Message>();
boolean hasTarget = !targetUser.equals(new String());
if (!hasTarget)
{
// no target, use last message from sourceUser's cache
// (or do nothing)
userCache = getUserCache(user);
}
else
{
// target specified, run through the cache (most recent first)
// and either match and replace or do nothing
userCache = getUserCache(targetUser);
}
while (!userCache.empty())
{
Message mmessage = userCache.pop();
m = Pattern.compile(search,
Pattern.CASE_INSENSITIVE | Pattern.DOTALL).matcher(
mmessage.getMessage());
if (m.find())
{
String reply = new String();
if (hasTarget)
reply = user + " thought ";
reply += "%s meant : %s";
irc.sendPrivmsg(channel, String.format(
reply,
mmessage.getUser(),
mmessage.getMessage().replaceAll(search,
replacement)));
break;
}
}
}
else // no dice, add message to history queue
{
addToCache(in_message);
}
}
|
diff --git a/beam-visat-rcp/src/main/java/org/esa/beam/visat/toolviews/stat/HistogramPanel.java b/beam-visat-rcp/src/main/java/org/esa/beam/visat/toolviews/stat/HistogramPanel.java
index b8748f4fa..c95540db5 100644
--- a/beam-visat-rcp/src/main/java/org/esa/beam/visat/toolviews/stat/HistogramPanel.java
+++ b/beam-visat-rcp/src/main/java/org/esa/beam/visat/toolviews/stat/HistogramPanel.java
@@ -1,483 +1,490 @@
/*
* Copyright (C) 2012 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 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 org.esa.beam.visat.toolviews.stat;
import com.bc.ceres.binding.PropertyContainer;
import com.bc.ceres.binding.ValueRange;
import com.bc.ceres.core.ProgressMonitor;
import com.bc.ceres.swing.binding.Binding;
import com.bc.ceres.swing.binding.BindingContext;
import com.bc.ceres.swing.progress.ProgressMonitorSwingWorker;
import org.esa.beam.framework.datamodel.Mask;
import org.esa.beam.framework.datamodel.RasterDataNode;
import org.esa.beam.framework.datamodel.Stx;
import org.esa.beam.framework.datamodel.StxFactory;
import org.esa.beam.framework.dataop.barithm.BandArithmetic;
import org.esa.beam.framework.ui.GridBagUtils;
import org.esa.beam.framework.ui.application.ToolView;
import org.esa.beam.util.math.MathUtils;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.StandardXYBarPainter;
import org.jfree.chart.renderer.xy.XYBarRenderer;
import org.jfree.data.xy.XIntervalSeries;
import org.jfree.data.xy.XIntervalSeriesCollection;
import org.jfree.ui.RectangleInsets;
import javax.media.jai.Histogram;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.Shape;
import java.awt.geom.Rectangle2D;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
/**
* A pane within the statistcs window which displays a histogram.
*/
class HistogramPanel extends ChartPagePanel {
private static final String NO_DATA_MESSAGE = "No histogram computed yet.\n" + ZOOM_TIP_MESSAGE;
private static final String CHART_TITLE = "Histogram";
public final static String PROPERTY_NAME_AUTO_MIN_MAX = "autoMinMax";
public final static String PROPERTY_NAME_MIN = "min";
public final static String PROPERTY_NAME_MAX = "max";
public static final String PROPERTY_NAME_NUM_BINS = "numBins";
public static final String PROPERTY_NAME_LOGARITHMIC_HISTOGRAM = "histogramLogScaled";
public static final String PROPERTY_NAME_LOG_SCALED = "xAxisLogScaled";
public final static String PROPERTY_NAME_USE_ROI_MASK = "useRoiMask";
public final static String PROPERTY_NAME_ROI_MASK = "roiMask";
private static final double HISTO_MIN_DEFAULT = 0.0;
private static final double HISTO_MAX_DEFAULT = 100.0;
private static final int NUM_BINS_DEFAULT = 512;
private AxisRangeControl xAxisRangeControl;
private XIntervalSeriesCollection dataset;
private JFreeChart chart;
private Stx stx;
private HistogramPlotConfig histogramPlotConfig;
private BindingContext bindingContext;
private boolean isInitialized;
private boolean histogramComputing;
HistogramPanel(final ToolView parentDialog, String helpID) {
super(parentDialog, helpID, CHART_TITLE, true);
}
@Override
protected void initComponents() {
xAxisRangeControl = new AxisRangeControl("X-Axis");
histogramPlotConfig = new HistogramPlotConfig();
bindingContext = new BindingContext(PropertyContainer.createObjectBacked(histogramPlotConfig));
createUI();
initActionEnablers();
updateComponents();
}
@Override
protected void updateComponents() {
if (!isInitialized || !isVisible()) {
return;
}
super.updateComponents();
chart.setTitle(getRaster() != null ? CHART_TITLE + " for " + getRaster().getName() : CHART_TITLE);
updateXAxis();
if (xAxisRangeControl.isAutoMinMax()) {
xAxisRangeControl.getBindingContext().getPropertySet().getDescriptor("min").setDefaultValue(
HISTO_MIN_DEFAULT);
xAxisRangeControl.getBindingContext().getPropertySet().getDescriptor("max").setDefaultValue(
HISTO_MAX_DEFAULT);
}
chart.getXYPlot().setDataset(null);
chart.fireChartChanged();
}
@Override
protected boolean mustHandleSelectionChange() {
return isRasterChanged();
}
private void createUI() {
dataset = new XIntervalSeriesCollection();
chart = ChartFactory.createHistogram(
CHART_TITLE,
"Values",
"Sample Frequency",
dataset,
PlotOrientation.VERTICAL,
false, // Legend?
true, // tooltips
false // url
);
final XYPlot xyPlot = chart.getXYPlot();
final XYBarRenderer renderer = (XYBarRenderer) xyPlot.getRenderer();
renderer.setDrawBarOutline(false);
renderer.setShadowVisible(false);
renderer.setShadowYOffset(-4.0);
renderer.setBaseToolTipGenerator(new XYPlotToolTipGenerator());
renderer.setBarPainter(new StandardXYBarPainter());
renderer.setSeriesPaint(0, new Color(0, 0, 200));
createUI(createChartPanel(chart), createComputationComponentsPanel(), createDisplayComponentsPanel(), bindingContext);
isInitialized = true;
updateUIState();
}
private void initActionEnablers(){
RefreshActionEnabler rangeControlActionEnabler = new RefreshActionEnabler(refreshButton,PROPERTY_NAME_MIN,PROPERTY_NAME_AUTO_MIN_MAX,
PROPERTY_NAME_MAX,PROPERTY_NAME_LOGARITHMIC_HISTOGRAM);
xAxisRangeControl.getBindingContext().addPropertyChangeListener(rangeControlActionEnabler);
RefreshActionEnabler componentsActionEnabler = new RefreshActionEnabler(refreshButton,PROPERTY_NAME_NUM_BINS,
PROPERTY_NAME_USE_ROI_MASK,PROPERTY_NAME_ROI_MASK);
bindingContext.addPropertyChangeListener(componentsActionEnabler);
}
private JPanel createComputationComponentsPanel() {
final JLabel numBinsLabel = new JLabel("#Bins:");
JTextField numBinsField = new JTextField(Integer.toString(NUM_BINS_DEFAULT));
numBinsField.setPreferredSize(new Dimension(50, numBinsField.getPreferredSize().height));
final JCheckBox histoLogCheck = new JCheckBox("Logarithmic Histogram");
bindingContext.getPropertySet().getDescriptor(PROPERTY_NAME_NUM_BINS).setDescription(
"Set the number of bins in the histogram");
bindingContext.getPropertySet().getDescriptor(PROPERTY_NAME_NUM_BINS).setValueRange(
new ValueRange(2.0, 2048.0));
bindingContext.getPropertySet().getDescriptor(PROPERTY_NAME_NUM_BINS).setDefaultValue(NUM_BINS_DEFAULT);
bindingContext.bind(PROPERTY_NAME_NUM_BINS, numBinsField);
bindingContext.getPropertySet().getDescriptor(PROPERTY_NAME_LOGARITHMIC_HISTOGRAM).setDescription(
"Compute a log-10 histogram for log-normal pixel distributions");
bindingContext.getPropertySet().getDescriptor(PROPERTY_NAME_LOGARITHMIC_HISTOGRAM).setDefaultValue(false);
bindingContext.bind(PROPERTY_NAME_LOGARITHMIC_HISTOGRAM, histoLogCheck);
PropertyChangeListener logChangeListener = new AxisControlChangeListener();
xAxisRangeControl.getBindingContext().addPropertyChangeListener(logChangeListener);
xAxisRangeControl.getBindingContext().getPropertySet().addProperty(
bindingContext.getPropertySet().getProperty(PROPERTY_NAME_LOGARITHMIC_HISTOGRAM));
xAxisRangeControl.getBindingContext().getPropertySet().addProperty(
bindingContext.getPropertySet().getProperty(PROPERTY_NAME_LOG_SCALED));
xAxisRangeControl.getBindingContext().getPropertySet().getDescriptor(PROPERTY_NAME_LOG_SCALED).setDescription(
"Toggle whether to use a logarithmic X-axis");
xAxisRangeControl.getBindingContext().bindEnabledState(PROPERTY_NAME_LOG_SCALED, false,
PROPERTY_NAME_LOGARITHMIC_HISTOGRAM, true);
JPanel dataSourceOptionsPanel = GridBagUtils.createPanel();
GridBagConstraints dataSourceOptionsConstraints = GridBagUtils.createConstraints(
"anchor=NORTHWEST,fill=HORIZONTAL,insets.top=2");
GridBagUtils.addToPanel(dataSourceOptionsPanel, new JLabel(" "), dataSourceOptionsConstraints,
"gridwidth=2,gridy=0,gridx=0,weightx=0");
GridBagUtils.addToPanel(dataSourceOptionsPanel, numBinsLabel, dataSourceOptionsConstraints,
"gridwidth=1,gridy=1,gridx=0,weightx=1");
GridBagUtils.addToPanel(dataSourceOptionsPanel, numBinsField, dataSourceOptionsConstraints,
"gridwidth=1,gridy=1,gridx=1");
GridBagUtils.addToPanel(dataSourceOptionsPanel, histoLogCheck, dataSourceOptionsConstraints,
"gridwidth=2,gridy=2,gridx=0");
xAxisRangeControl.getBindingContext().bind(PROPERTY_NAME_LOG_SCALED, new JCheckBox("Logarithmic X-axis"));
JPanel displayOptionsPanel = GridBagUtils.createPanel();
GridBagConstraints displayOptionsConstraints = GridBagUtils.createConstraints(
"anchor=SOUTH,fill=HORIZONTAL,weightx=1");
GridBagUtils.addToPanel(displayOptionsPanel, xAxisRangeControl.getPanel(), displayOptionsConstraints,
"gridy=2");
JPanel optionsPanel = GridBagUtils.createPanel();
GridBagConstraints gbc = GridBagUtils.createConstraints(
"anchor=NORTHWEST,fill=HORIZONTAL,insets.top=2,weightx=1");
GridBagUtils.addToPanel(optionsPanel, dataSourceOptionsPanel, gbc, "gridy=0");
GridBagUtils.addToPanel(optionsPanel, new JPanel(), gbc, "gridy=1,fill=VERTICAL,weighty=1");
GridBagUtils.addToPanel(optionsPanel, displayOptionsPanel, gbc, "gridy=2,fill=HORIZONTAL,weighty=0");
return optionsPanel;
}
private JPanel createDisplayComponentsPanel() {
JPanel displayComponentsPanel = GridBagUtils.createPanel();
GridBagConstraints displayComponentsConstraints = GridBagUtils.createConstraints(
"anchor=SOUTH,fill=HORIZONTAL,weightx=1");
GridBagUtils.addToPanel(displayComponentsPanel, xAxisRangeControl.getBindingContext().getBinding(
PROPERTY_NAME_LOG_SCALED).getComponents()[0], displayComponentsConstraints, "gridy=0");
return displayComponentsPanel;
}
private ChartPanel createChartPanel(JFreeChart chart) {
XYPlot plot = chart.getXYPlot();
plot.setForegroundAlpha(0.85f);
plot.setNoDataMessage(NO_DATA_MESSAGE);
plot.setAxisOffset(new RectangleInsets(5, 5, 5, 5));
ChartPanel chartPanel = new ChartPanel(chart);
MaskSelectionToolSupport maskSelectionToolSupport = new MaskSelectionToolSupport(this,
chartPanel,
"histogram_plot_area",
"Mask generated from selected histogram plot area",
Color.RED,
PlotAreaSelectionTool.AreaType.X_RANGE) {
@Override
protected String createMaskExpression(PlotAreaSelectionTool.AreaType areaType, Shape shape) {
Rectangle2D bounds = shape.getBounds2D();
return createMaskExpression(bounds.getMinX(), bounds.getMaxX());
}
protected String createMaskExpression(double x1, double x2) {
String bandName = BandArithmetic.createExternalName(getRaster().getName());
return String.format("%s >= %s && %s <= %s",
bandName,
stx != null ? stx.getHistogramScaling().scaleInverse(x1) : x1,
bandName,
stx != null ? stx.getHistogramScaling().scaleInverse(x2) : x2);
}
};
chartPanel.getPopupMenu().addSeparator();
chartPanel.getPopupMenu().add(maskSelectionToolSupport.createMaskSelectionModeMenuItem());
chartPanel.getPopupMenu().add(maskSelectionToolSupport.createDeleteMaskMenuItem());
chartPanel.getPopupMenu().addSeparator();
chartPanel.getPopupMenu().add(createCopyDataToClipboardMenuItem());
return chartPanel;
}
private void updateUIState() {
final Binding minBinding = xAxisRangeControl.getBindingContext().getBinding("min");
final double min = (Double) minBinding.getPropertyValue();
final Binding maxBinding = xAxisRangeControl.getBindingContext().getBinding("max");
final double max = (Double) maxBinding.getPropertyValue();
if (!histogramComputing && min > max) {
minBinding.setPropertyValue(max);
maxBinding.setPropertyValue(min);
}
updateXAxis();
}
private static class HistogramPlotConfig {
private boolean xAxisLogScaled;
private boolean histogramLogScaled;
private int numBins = NUM_BINS_DEFAULT;
private boolean useRoiMask;
private Mask roiMask;
}
@Override
public void updateChartData() {
final boolean autoMinMaxEnabled = getAutoMinMaxEnabled();
final Double min;
final Double max;
if (autoMinMaxEnabled) {
min = null;
max = null;
} else {
min = (Double) xAxisRangeControl.getBindingContext().getBinding("min").getPropertyValue();
max = (Double) xAxisRangeControl.getBindingContext().getBinding("max").getPropertyValue();
}
- ProgressMonitorSwingWorker<Stx, Object> swingWorker = new ProgressMonitorSwingWorker<Stx, Object>(this,
- "Computing Histogram") {
+ ProgressMonitorSwingWorker<Stx, Object> swingWorker = new ProgressMonitorSwingWorker<Stx, Object>(this, "Computing Histogram") {
@Override
protected Stx doInBackground(ProgressMonitor pm) throws Exception {
final Stx stx;
if (histogramPlotConfig.useRoiMask || histogramPlotConfig.numBins != Stx.DEFAULT_BIN_COUNT || histogramPlotConfig.histogramLogScaled || min != null || max != null) {
final StxFactory factory = new StxFactory();
if (histogramPlotConfig.useRoiMask) {
factory.withRoiMask(histogramPlotConfig.roiMask);
}
factory.withHistogramBinCount(histogramPlotConfig.numBins);
factory.withLogHistogram(histogramPlotConfig.histogramLogScaled);
if (min != null) {
- factory.withMinimum(Stx.LOG10_SCALING.scaleInverse(min));
+ if (histogramPlotConfig.histogramLogScaled) {
+ factory.withMinimum(Stx.LOG10_SCALING.scaleInverse(min));
+ } else {
+ factory.withMinimum(min);
+ }
}
if (max != null) {
- factory.withMaximum(Stx.LOG10_SCALING.scaleInverse(max));
+ if (histogramPlotConfig.histogramLogScaled) {
+ factory.withMaximum(Stx.LOG10_SCALING.scaleInverse(max));
+ } else {
+ factory.withMaximum(max);
+ }
}
stx = factory.create(getRaster(), pm);
} else {
stx = getRaster().getStx(true, pm);
}
return stx;
}
@Override
public void done() {
try {
Stx stx = get();
if (stx.getSampleCount() > 0) {
if (autoMinMaxEnabled) {
final double min = stx.getHistogramScaling().scale(stx.getMinimum());
final double max = stx.getHistogramScaling().scale(stx.getMaximum());
final double v = MathUtils.computeRoundFactor(min, max, 4);
histogramComputing = true;
xAxisRangeControl.getBindingContext().getBinding("min").setPropertyValue(
StatisticsUtils.round(min, v));
xAxisRangeControl.getBindingContext().getBinding("max").setPropertyValue(
StatisticsUtils.round(max, v));
histogramComputing = false;
}
} else {
JOptionPane.showMessageDialog(getParentComponent(),
"The ROI is empty or no pixels found between min/max.\n"
+ "A valid histogram could not be computed.",
CHART_TITLE,
JOptionPane.WARNING_MESSAGE);
}
setStx(stx);
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(getParentComponent(),
"Failed to compute histogram.\nAn internal error occurred:\n" + e.getMessage(),
CHART_TITLE,
JOptionPane.ERROR_MESSAGE);
}
}
};
swingWorker.execute();
}
private void setStx(Stx stx) {
updateXAxis();
this.stx = stx;
dataset = new XIntervalSeriesCollection();
if (this.stx != null) {
final int[] binCounts = this.stx.getHistogramBins();
final RasterDataNode raster = getRaster();
final XIntervalSeries series = new XIntervalSeries(raster.getName());
final Histogram histogram = stx.getHistogram();
for (int i = 0; i < binCounts.length; i++) {
final double xMin = histogram.getBinLowValue(0, i);
final double xMax = i < binCounts.length - 1 ? histogram.getBinLowValue(0,
i + 1) : histogram.getHighValue(
0);
series.add(xMin, xMin, xMax, binCounts[i]);
}
dataset.addSeries(series);
}
chart.getXYPlot().setDataset(dataset);
chart.fireChartChanged();
}
private String getAxisLabel() {
boolean logScaled = (Boolean) bindingContext.getBinding(PROPERTY_NAME_LOGARITHMIC_HISTOGRAM).getPropertyValue();
return StatisticChartStyling.getAxisLabel(getRaster(), "X", logScaled);
}
private Container getParentComponent() {
return getParentDialog().getContext().getPane().getControl();
}
private boolean getAutoMinMaxEnabled() {
return xAxisRangeControl.isAutoMinMax();
}
@Override
public String getDataAsText() {
if (stx == null) {
return null;
}
final int[] binVals = stx.getHistogramBins();
final int numBins = binVals.length;
final double min = stx.getMinimum();
final double max = stx.getMaximum();
final StringBuilder sb = new StringBuilder(16000);
sb.append("Product name:\t").append(getRaster().getProduct().getName()).append("\n");
sb.append("Dataset name:\t").append(getRaster().getName()).append("\n");
sb.append('\n');
sb.append("Histogram minimum:\t").append(min).append("\t").append(getRaster().getUnit()).append("\n");
sb.append("Histogram maximum:\t").append(max).append("\t").append(getRaster().getUnit()).append("\n");
sb.append("Histogram bin size:\t").append(
getRaster().isLog10Scaled() ? ("NA\t") : ((max - min) / numBins + "\t") +
getRaster().getUnit() + "\n");
sb.append("Histogram #bins:\t").append(numBins).append("\n");
sb.append('\n');
sb.append("Bin center value");
sb.append('\t');
sb.append("Bin counts");
sb.append('\n');
for (int i = 0; i < numBins; i++) {
sb.append(min + ((i + 0.5) * (max - min)) / numBins);
sb.append('\t');
sb.append(binVals[i]);
sb.append('\n');
}
return sb.toString();
}
private void updateXAxis() {
final boolean logScaled = (Boolean) xAxisRangeControl.getBindingContext().getBinding(
PROPERTY_NAME_LOG_SCALED).getPropertyValue();
final XYPlot plot = chart.getXYPlot();
plot.setDomainAxis(StatisticChartStyling.updateScalingOfAxis(logScaled, plot.getDomainAxis(), true));
plot.getDomainAxis().setLabel(getAxisLabel());
}
private class AxisControlChangeListener implements PropertyChangeListener {
boolean adjusting;
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (!adjusting) {
adjusting = true;
if (evt.getPropertyName().equals(PROPERTY_NAME_LOGARITHMIC_HISTOGRAM)) {
if (evt.getNewValue().equals(Boolean.TRUE)) {
xAxisRangeControl.getBindingContext().getBinding(PROPERTY_NAME_LOG_SCALED).setPropertyValue(Boolean.FALSE);
xAxisRangeControl.setMin(Stx.LOG10_SCALING.scale(xAxisRangeControl.getMin()));
xAxisRangeControl.setMax(Stx.LOG10_SCALING.scale(xAxisRangeControl.getMax()));
} else {
xAxisRangeControl.setMin(Stx.LOG10_SCALING.scaleInverse(xAxisRangeControl.getMin()));
xAxisRangeControl.setMax(Stx.LOG10_SCALING.scaleInverse(xAxisRangeControl.getMax()));
}
}
updateUIState();
adjusting = false;
}
}
}
}
| false | true | public void updateChartData() {
final boolean autoMinMaxEnabled = getAutoMinMaxEnabled();
final Double min;
final Double max;
if (autoMinMaxEnabled) {
min = null;
max = null;
} else {
min = (Double) xAxisRangeControl.getBindingContext().getBinding("min").getPropertyValue();
max = (Double) xAxisRangeControl.getBindingContext().getBinding("max").getPropertyValue();
}
ProgressMonitorSwingWorker<Stx, Object> swingWorker = new ProgressMonitorSwingWorker<Stx, Object>(this,
"Computing Histogram") {
@Override
protected Stx doInBackground(ProgressMonitor pm) throws Exception {
final Stx stx;
if (histogramPlotConfig.useRoiMask || histogramPlotConfig.numBins != Stx.DEFAULT_BIN_COUNT || histogramPlotConfig.histogramLogScaled || min != null || max != null) {
final StxFactory factory = new StxFactory();
if (histogramPlotConfig.useRoiMask) {
factory.withRoiMask(histogramPlotConfig.roiMask);
}
factory.withHistogramBinCount(histogramPlotConfig.numBins);
factory.withLogHistogram(histogramPlotConfig.histogramLogScaled);
if (min != null) {
factory.withMinimum(Stx.LOG10_SCALING.scaleInverse(min));
}
if (max != null) {
factory.withMaximum(Stx.LOG10_SCALING.scaleInverse(max));
}
stx = factory.create(getRaster(), pm);
} else {
stx = getRaster().getStx(true, pm);
}
return stx;
}
@Override
public void done() {
try {
Stx stx = get();
if (stx.getSampleCount() > 0) {
if (autoMinMaxEnabled) {
final double min = stx.getHistogramScaling().scale(stx.getMinimum());
final double max = stx.getHistogramScaling().scale(stx.getMaximum());
final double v = MathUtils.computeRoundFactor(min, max, 4);
histogramComputing = true;
xAxisRangeControl.getBindingContext().getBinding("min").setPropertyValue(
StatisticsUtils.round(min, v));
xAxisRangeControl.getBindingContext().getBinding("max").setPropertyValue(
StatisticsUtils.round(max, v));
histogramComputing = false;
}
} else {
JOptionPane.showMessageDialog(getParentComponent(),
"The ROI is empty or no pixels found between min/max.\n"
+ "A valid histogram could not be computed.",
CHART_TITLE,
JOptionPane.WARNING_MESSAGE);
}
setStx(stx);
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(getParentComponent(),
"Failed to compute histogram.\nAn internal error occurred:\n" + e.getMessage(),
CHART_TITLE,
JOptionPane.ERROR_MESSAGE);
}
}
};
swingWorker.execute();
}
| public void updateChartData() {
final boolean autoMinMaxEnabled = getAutoMinMaxEnabled();
final Double min;
final Double max;
if (autoMinMaxEnabled) {
min = null;
max = null;
} else {
min = (Double) xAxisRangeControl.getBindingContext().getBinding("min").getPropertyValue();
max = (Double) xAxisRangeControl.getBindingContext().getBinding("max").getPropertyValue();
}
ProgressMonitorSwingWorker<Stx, Object> swingWorker = new ProgressMonitorSwingWorker<Stx, Object>(this, "Computing Histogram") {
@Override
protected Stx doInBackground(ProgressMonitor pm) throws Exception {
final Stx stx;
if (histogramPlotConfig.useRoiMask || histogramPlotConfig.numBins != Stx.DEFAULT_BIN_COUNT || histogramPlotConfig.histogramLogScaled || min != null || max != null) {
final StxFactory factory = new StxFactory();
if (histogramPlotConfig.useRoiMask) {
factory.withRoiMask(histogramPlotConfig.roiMask);
}
factory.withHistogramBinCount(histogramPlotConfig.numBins);
factory.withLogHistogram(histogramPlotConfig.histogramLogScaled);
if (min != null) {
if (histogramPlotConfig.histogramLogScaled) {
factory.withMinimum(Stx.LOG10_SCALING.scaleInverse(min));
} else {
factory.withMinimum(min);
}
}
if (max != null) {
if (histogramPlotConfig.histogramLogScaled) {
factory.withMaximum(Stx.LOG10_SCALING.scaleInverse(max));
} else {
factory.withMaximum(max);
}
}
stx = factory.create(getRaster(), pm);
} else {
stx = getRaster().getStx(true, pm);
}
return stx;
}
@Override
public void done() {
try {
Stx stx = get();
if (stx.getSampleCount() > 0) {
if (autoMinMaxEnabled) {
final double min = stx.getHistogramScaling().scale(stx.getMinimum());
final double max = stx.getHistogramScaling().scale(stx.getMaximum());
final double v = MathUtils.computeRoundFactor(min, max, 4);
histogramComputing = true;
xAxisRangeControl.getBindingContext().getBinding("min").setPropertyValue(
StatisticsUtils.round(min, v));
xAxisRangeControl.getBindingContext().getBinding("max").setPropertyValue(
StatisticsUtils.round(max, v));
histogramComputing = false;
}
} else {
JOptionPane.showMessageDialog(getParentComponent(),
"The ROI is empty or no pixels found between min/max.\n"
+ "A valid histogram could not be computed.",
CHART_TITLE,
JOptionPane.WARNING_MESSAGE);
}
setStx(stx);
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(getParentComponent(),
"Failed to compute histogram.\nAn internal error occurred:\n" + e.getMessage(),
CHART_TITLE,
JOptionPane.ERROR_MESSAGE);
}
}
};
swingWorker.execute();
}
|
diff --git a/Spike1/src/modelo/VentanaRegiones.java b/Spike1/src/modelo/VentanaRegiones.java
index b3dc9a5..3bf88a9 100644
--- a/Spike1/src/modelo/VentanaRegiones.java
+++ b/Spike1/src/modelo/VentanaRegiones.java
@@ -1,172 +1,172 @@
package modelo;
import java.awt.Rectangle;
import java.util.Hashtable;
import java.util.List;
import java.util.Random;
import javax.swing.JProgressBar;
import utils.Graphic;
import ij.ImagePlus;
import ij.gui.Roi;
import ij.measure.ResultsTable;
import ij.plugin.filter.Analyzer;
import ij.process.ImageProcessor;
public class VentanaRegiones extends VentanaAbstracta {
private List<int[]> listaPixeles;
private Graphic imgPanel;
private Rectangle selection;
private Roi[] arrayRois;
private static int MIN = 8;
public VentanaRegiones(ImagePlus img, ImagePlus saliency,
ImagePlus convolucion, ImagePlus convolucionSaliency, int numHilo, Rectangle selection, Graphic imgPanel, JProgressBar progressBar, int[][] defectMatrix, List<int[]> pixeles) {
super(img, saliency, convolucion, convolucionSaliency, numHilo);
listaPixeles = pixeles;
this.imgPanel = imgPanel;
this.selection = selection;
this.progressBar = progressBar;
this.defectMatrix = defectMatrix;
}
@Override
public void run() {
ImageProcessor ip = getImage().getProcessor();
Hashtable <Integer, Integer> tablaPixelsPorRoi = new Hashtable<Integer, Integer>();
Hashtable <Integer, Integer> tablaPixelsConsideradosRoi = new Hashtable<Integer, Integer>();
Random rand = new Random();
for (int i = 0; i < arrayRois.length; i++ ){
ip.setRoi(arrayRois[i]);
Analyzer an = new Analyzer(getImage());
- an.measure();
- Analyzer.getResultsTable();
- int numPixelPorRoi = (int) (ResultsTable.AREA * 0.1);
+ an.measure();
+ ResultsTable rt = Analyzer.getResultsTable();
+ int numPixelPorRoi = (int) (rt.getValueAsDouble(ResultsTable.AREA, 0) * 0.1);
if (numPixelPorRoi < MIN){
numPixelPorRoi = MIN;
}
tablaPixelsPorRoi.put(i, numPixelPorRoi);
tablaPixelsConsideradosRoi.put(i, 0);
ip.resetRoi();
}
while(!listaPixeles.isEmpty()){
int randIndex = rand.nextInt(listaPixeles.size());
int[] coord = listaPixeles.get(randIndex);
int coordX = (coord[0] - selection.x) - getAnchuraVentana()/2;
int coordY = (coord[1] - selection.y) - getAlturaVentana()/2;
if(coordX >= 0 && coordY >= 0 && coordX <= (getImage().getProcessor().getWidth() - getAnchuraVentana())
&& coordY <= (getImage().getProcessor().getHeight() - getAlturaVentana())){
//comprobar a qu� regi�n pertenece el p�xel
int index = getIndexRoi(coordX, coordY);
if(index != -1){
if(tablaPixelsConsideradosRoi.get(index) < tablaPixelsPorRoi.get(index)){
pintarVentana(coordX, coordY);
ip.setRoi(coordX, coordY, getAnchuraVentana(), getAlturaVentana());
ejecutarCalculos(coordX, coordY, getImage());
double clase = clasificar();
imprimeRes(coordX, coordY, clase);
tablaPixelsConsideradosRoi.put(index, (tablaPixelsConsideradosRoi.get(index))+1);
}
}
}
listaPixeles.remove(randIndex);
setPorcentajeBarra();
}
/*
Iterator<int[]> it = listaPixeles.iterator();
while(it.hasNext()){
int[] coord = it.next();
int coordX = (coord[0] - selection.x) - getAnchuraVentana()/2;
int coordY = (coord[1] - selection.y) - getAlturaVentana()/2;
// synchronized(this){
// for(int i=0; i<arrayRois.length; i++){
// imgPanel.addRectangle(arrayRois[i].getBounds().x + selection.x, arrayRois[i].getBounds().y + selection.y, arrayRois[i].getBounds().width, arrayRois[i].getBounds().height);
// imgPanel.repaint();
// }
// }
if(coordX >= 0 && coordY >= 0 && coordX <= (getImage().getProcessor().getWidth() - getAnchuraVentana())
&& coordY <= (getImage().getProcessor().getHeight() - getAlturaVentana())){
//comprobar a qu� regi�n pertenece el p�xel
int index = getIndexRoi(coordX, coordY);
System.out.println("Coord0: " + coordX + " Coord1: " + coordY + " index: " + index);
if(index != -1){
pintarVentana(coordX, coordY);
ip.setRoi(coordX, coordY, getAnchuraVentana(), getAlturaVentana());
ejecutarCalculos(coordX, coordY, getImage());
double clase = clasificar();
imprimeRes(coordX, coordY, clase);
}
else{
System.out.println("No encontrado");
}
}
setPorcentajeBarra();
}
*/
}
private int getIndexRoi(int coordX, int coordY) {
Roi roi;
for(int i=0; i<arrayRois.length; i++){
roi = arrayRois[i];
if(roi.contains(coordX, coordY)){
return i;
}
}
return -1;
}
private synchronized void pintarVentana(int coordenadaX, int coordenadaY) {
int y = coordenadaY + selection.y;
// if(getNumHilo() == Runtime.getRuntime().availableProcessors() - 1){
// y -= getPropiedades().getTamVentana(); //para contrarrestar el solapamiento y que las ventanas no se salgan de la selecci�n
// }
imgPanel.drawWindow(coordenadaX + selection.x, y, getAnchuraVentana(), getAlturaVentana());
imgPanel.repaint();
}
private void imprimeRes(int coordX, int coordY, double prob) {
//para la coordenada Y, hay que determinar en qu� trozo de la imagen estamos analizando
int y = coordY + selection.y;
// if(getNumHilo() == Runtime.getRuntime().availableProcessors() - 1){
// y -= getPropiedades().getTamVentana(); //para contrarrestar el solapamiento y que las ventanas no se salgan de la selecci�n
// }
//CLASIFICACI�N CLASE NOMINAL
if(prob == 0){
imgPanel.addRectangle(coordX + selection.x, y, getAnchuraVentana(), getAlturaVentana());
imgPanel.repaint();
rellenarMatrizDefectos(coordX+ selection.x, y);
}
//REGRESI�N
// if(prob >= 0.5){
// imgPanel.addRectangle(coordX + selection.x, y, getAnchuraVentana(), getAlturaVentana());
// imgPanel.repaint();
// rellenarMatrizDefectos(coordX+ selection.x, y);
// }
}
public void setArrayRois(Roi[] array){
arrayRois = array;
}
public Roi[] getArrayRois(){
return arrayRois;
}
}
| true | true | public void run() {
ImageProcessor ip = getImage().getProcessor();
Hashtable <Integer, Integer> tablaPixelsPorRoi = new Hashtable<Integer, Integer>();
Hashtable <Integer, Integer> tablaPixelsConsideradosRoi = new Hashtable<Integer, Integer>();
Random rand = new Random();
for (int i = 0; i < arrayRois.length; i++ ){
ip.setRoi(arrayRois[i]);
Analyzer an = new Analyzer(getImage());
an.measure();
Analyzer.getResultsTable();
int numPixelPorRoi = (int) (ResultsTable.AREA * 0.1);
if (numPixelPorRoi < MIN){
numPixelPorRoi = MIN;
}
tablaPixelsPorRoi.put(i, numPixelPorRoi);
tablaPixelsConsideradosRoi.put(i, 0);
ip.resetRoi();
}
while(!listaPixeles.isEmpty()){
int randIndex = rand.nextInt(listaPixeles.size());
int[] coord = listaPixeles.get(randIndex);
int coordX = (coord[0] - selection.x) - getAnchuraVentana()/2;
int coordY = (coord[1] - selection.y) - getAlturaVentana()/2;
if(coordX >= 0 && coordY >= 0 && coordX <= (getImage().getProcessor().getWidth() - getAnchuraVentana())
&& coordY <= (getImage().getProcessor().getHeight() - getAlturaVentana())){
//comprobar a qu� regi�n pertenece el p�xel
int index = getIndexRoi(coordX, coordY);
if(index != -1){
if(tablaPixelsConsideradosRoi.get(index) < tablaPixelsPorRoi.get(index)){
pintarVentana(coordX, coordY);
ip.setRoi(coordX, coordY, getAnchuraVentana(), getAlturaVentana());
ejecutarCalculos(coordX, coordY, getImage());
double clase = clasificar();
imprimeRes(coordX, coordY, clase);
tablaPixelsConsideradosRoi.put(index, (tablaPixelsConsideradosRoi.get(index))+1);
}
}
}
listaPixeles.remove(randIndex);
setPorcentajeBarra();
}
/*
Iterator<int[]> it = listaPixeles.iterator();
while(it.hasNext()){
int[] coord = it.next();
int coordX = (coord[0] - selection.x) - getAnchuraVentana()/2;
int coordY = (coord[1] - selection.y) - getAlturaVentana()/2;
// synchronized(this){
// for(int i=0; i<arrayRois.length; i++){
// imgPanel.addRectangle(arrayRois[i].getBounds().x + selection.x, arrayRois[i].getBounds().y + selection.y, arrayRois[i].getBounds().width, arrayRois[i].getBounds().height);
// imgPanel.repaint();
// }
// }
if(coordX >= 0 && coordY >= 0 && coordX <= (getImage().getProcessor().getWidth() - getAnchuraVentana())
&& coordY <= (getImage().getProcessor().getHeight() - getAlturaVentana())){
//comprobar a qu� regi�n pertenece el p�xel
int index = getIndexRoi(coordX, coordY);
System.out.println("Coord0: " + coordX + " Coord1: " + coordY + " index: " + index);
if(index != -1){
pintarVentana(coordX, coordY);
ip.setRoi(coordX, coordY, getAnchuraVentana(), getAlturaVentana());
ejecutarCalculos(coordX, coordY, getImage());
double clase = clasificar();
imprimeRes(coordX, coordY, clase);
}
else{
System.out.println("No encontrado");
}
}
setPorcentajeBarra();
}
*/
}
| public void run() {
ImageProcessor ip = getImage().getProcessor();
Hashtable <Integer, Integer> tablaPixelsPorRoi = new Hashtable<Integer, Integer>();
Hashtable <Integer, Integer> tablaPixelsConsideradosRoi = new Hashtable<Integer, Integer>();
Random rand = new Random();
for (int i = 0; i < arrayRois.length; i++ ){
ip.setRoi(arrayRois[i]);
Analyzer an = new Analyzer(getImage());
an.measure();
ResultsTable rt = Analyzer.getResultsTable();
int numPixelPorRoi = (int) (rt.getValueAsDouble(ResultsTable.AREA, 0) * 0.1);
if (numPixelPorRoi < MIN){
numPixelPorRoi = MIN;
}
tablaPixelsPorRoi.put(i, numPixelPorRoi);
tablaPixelsConsideradosRoi.put(i, 0);
ip.resetRoi();
}
while(!listaPixeles.isEmpty()){
int randIndex = rand.nextInt(listaPixeles.size());
int[] coord = listaPixeles.get(randIndex);
int coordX = (coord[0] - selection.x) - getAnchuraVentana()/2;
int coordY = (coord[1] - selection.y) - getAlturaVentana()/2;
if(coordX >= 0 && coordY >= 0 && coordX <= (getImage().getProcessor().getWidth() - getAnchuraVentana())
&& coordY <= (getImage().getProcessor().getHeight() - getAlturaVentana())){
//comprobar a qu� regi�n pertenece el p�xel
int index = getIndexRoi(coordX, coordY);
if(index != -1){
if(tablaPixelsConsideradosRoi.get(index) < tablaPixelsPorRoi.get(index)){
pintarVentana(coordX, coordY);
ip.setRoi(coordX, coordY, getAnchuraVentana(), getAlturaVentana());
ejecutarCalculos(coordX, coordY, getImage());
double clase = clasificar();
imprimeRes(coordX, coordY, clase);
tablaPixelsConsideradosRoi.put(index, (tablaPixelsConsideradosRoi.get(index))+1);
}
}
}
listaPixeles.remove(randIndex);
setPorcentajeBarra();
}
/*
Iterator<int[]> it = listaPixeles.iterator();
while(it.hasNext()){
int[] coord = it.next();
int coordX = (coord[0] - selection.x) - getAnchuraVentana()/2;
int coordY = (coord[1] - selection.y) - getAlturaVentana()/2;
// synchronized(this){
// for(int i=0; i<arrayRois.length; i++){
// imgPanel.addRectangle(arrayRois[i].getBounds().x + selection.x, arrayRois[i].getBounds().y + selection.y, arrayRois[i].getBounds().width, arrayRois[i].getBounds().height);
// imgPanel.repaint();
// }
// }
if(coordX >= 0 && coordY >= 0 && coordX <= (getImage().getProcessor().getWidth() - getAnchuraVentana())
&& coordY <= (getImage().getProcessor().getHeight() - getAlturaVentana())){
//comprobar a qu� regi�n pertenece el p�xel
int index = getIndexRoi(coordX, coordY);
System.out.println("Coord0: " + coordX + " Coord1: " + coordY + " index: " + index);
if(index != -1){
pintarVentana(coordX, coordY);
ip.setRoi(coordX, coordY, getAnchuraVentana(), getAlturaVentana());
ejecutarCalculos(coordX, coordY, getImage());
double clase = clasificar();
imprimeRes(coordX, coordY, clase);
}
else{
System.out.println("No encontrado");
}
}
setPorcentajeBarra();
}
*/
}
|
diff --git a/src/cytoscape/view/CyMenus.java b/src/cytoscape/view/CyMenus.java
index 9e8acfe18..160e46f58 100644
--- a/src/cytoscape/view/CyMenus.java
+++ b/src/cytoscape/view/CyMenus.java
@@ -1,465 +1,465 @@
/** Copyright (c) 2002 Institute for Systems Biology and the Whitehead Institute
**
** 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; either version 2.1 of the License, or
** any later version.
**
** 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. The software and
** documentation provided hereunder is on an "as is" basis, and the
** Institute for Systems Biology and the Whitehead Institute
** have no obligations to provide maintenance, support,
** updates, enhancements or modifications. In no event shall the
** Institute for Systems Biology and the Whitehead Institute
** be liable to any party for direct, indirect, special,
** incidental or consequential damages, including lost profits, arising
** out of the use of this software and its documentation, even if the
** Institute for Systems Biology and the Whitehead Institute
** have been advised of the possibility of such damage. 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.
**/
//------------------------------------------------------------------------------
// $Revision$
// $Date$
// $Author$
//------------------------------------------------------------------------------
package cytoscape.view;
//------------------------------------------------------------------------------
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import cytoscape.CytoscapeObj;
import cytoscape.actions.*;
import cytoscape.dialogs.ShrinkExpandGraphUI;
import cytoscape.data.annotation.AnnotationGui;
import cytoscape.util.CytoscapeMenuBar;
import cytoscape.util.CytoscapeToolBar;
import cytoscape.util.CytoscapeAction;
//------------------------------------------------------------------------------
/**
* This class creates the menu and tool bars for a Cytoscape window object. It
* also provides access to individual menus and items.
*/
public class CyMenus {
CyWindow cyWindow;
boolean menusInitialized = false;
CytoscapeMenuBar menuBar;
JMenu fileMenu, loadSubMenu, saveSubMenu;
JMenu editMenu;
//JMenuItem undoMenuItem, redoMenuItem;
JMenuItem deleteSelectionMenuItem;
JMenu dataMenu;
JMenu selectMenu;
JMenu layoutMenu;
JMenu vizMenu;
JMenuItem vizMenuItem, disableVizMapperItem, enableVizMapperItem;
JButton vizButton;
JMenu opsMenu;
JMenuItem NO_OPERATIONS;
CytoscapeToolBar toolBar;
public CyMenus(CyWindow cyWindow) {
this.cyWindow = cyWindow;
//the following methods construct the basic bar objects, but
//don't fill them with menu items and associated action listeners
createMenuBar();
toolBar = new CytoscapeToolBar();
//default menu item used when the operations menu is empty
NO_OPERATIONS = new JMenuItem("No operations available");
NO_OPERATIONS.setEnabled(false);
}
/**
* Returns the main menu bar constructed by this object.
*/
public CytoscapeMenuBar getMenuBar() {return menuBar;}
/**
* Returns the menu with items related to file operations.
*/
public JMenu getFileMenu() {return fileMenu;}
/**
* Returns the submenu with items related to loading objects.
*/
public JMenu getLoadSubMenu() {return loadSubMenu;}
/**
* Returns the submenu with items related to saving objects.
*/
public JMenu getSaveSubMenu() {return saveSubMenu;}
/**
* returns the menu with items related to editing the graph.
*/
public JMenu getEditMenu() {return editMenu;}
/**
* Returns the menu with items related to data operations.
*/
public JMenu getDataMenu() {return dataMenu;}
/**
* Returns the menu with items related to selecting
* nodes and edges in the graph.
*/
public JMenu getSelectMenu() {return selectMenu;}
/**
* Returns the menu with items realted to layout actions.
*/
public JMenu getLayoutMenu() {return layoutMenu;}
/**
* Returns the menu with items related to visualiation.
*/
public JMenu getVizMenu() {return vizMenu;}
/**
* Returns the menu with items associated with plug-ins.
* Most plug-ins grab this menu and add their menu option.
* The plugins should then call refreshOperationsMenu to
* update the menu.
*/
public JMenu getOperationsMenu() {return opsMenu;}
/**
* Checks the operations menu for existing items. If there
* are none, adds a default item indicating that no plugin
* menu operations are available. If there is more than one
* menu item, then this method removes the default item if
* it exists.
*/
public void refreshOperationsMenu() {
if (opsMenu.getItemCount() == 0) {//no real items exist
opsMenu.add(NO_OPERATIONS); //so add the default item
} else if (opsMenu.getItemCount() > 1) {//one real item exists
//the default item will always be first if it's there
if (opsMenu.getItem(0) == NO_OPERATIONS) {
opsMenu.remove(0); //remove the default item
}
}
}
/**
* Returns the toolbar object constructed by this class.
*/
public CytoscapeToolBar getToolBar() {return toolBar;}
/**
* Takes a CytoscapeAction and will add it to the MenuBar or the
* Toolbar as is appropriate.
*/
public void addCytoscapeAction ( CytoscapeAction action ) {
if ( action.isInMenuBar() ) {
getMenuBar().addAction( action );
}
if ( action.isInToolBar() ) {
getToolBar().addAction( action );
}
}
/**
* @deprecated This method is no longer needed now that the undo
* manager has been removed. It will soon be removed, because
* there are better ways to manage the menu items. -AM 12-30-03<P>
*
* This helper method enables or disables the menu items
* associated with the undo manager. The undo menu option
* is enabled only if there is a previous state to undo to,
* and similarly for the redo menu option.
*
* It may make more sense to give the menu item objects to
* the undo maanger and let it handle the activation state.
*/
public void updateUndoRedoMenuItemStatus() {
}
/**
* Called when the window switches to edit mode, enabling
* the menu option for deleting selected objects.
*
* Again, the keeper of the edit modes should probably get
* a reference to the menu item and manage its state.
*/
public void enableDeleteSelectionMenuItem() {
if (deleteSelectionMenuItem != null) {
deleteSelectionMenuItem.setEnabled(true);
}
}
/**
* Called when the window switches to read-only mode, disabling
* the menu option for deleting selected objects.
*
* Again, the keeper of the edit modes should probably get
* a reference to the menu item and manage its state.
*/
public void disableDeleteSelectionMenuItem() {
if (deleteSelectionMenuItem != null) {
deleteSelectionMenuItem.setEnabled(false);
}
}
/**
* Enables the menu items related to the visual mapper if the argument
* is true, else disables them. This method should only be called from
* the window that holds this menu.
*/
public void setVisualMapperItemsEnabled(boolean newState) {
vizMenuItem.setEnabled(newState);
vizButton.setEnabled(newState);
this.disableVizMapperItem.setEnabled(newState);
this.enableVizMapperItem.setEnabled(!newState);
}
/**
* Creates the menu bar and the various menus and submenus, but
* defers filling those menus with items until later.
*/
private void createMenuBar() {
menuBar = new CytoscapeMenuBar();
fileMenu = menuBar.getMenu( "File" );
loadSubMenu = menuBar.getMenu( "File.Load" );
saveSubMenu = menuBar.getMenu( "File.Save" );
editMenu = menuBar.getMenu( "Edit" );
dataMenu = menuBar.getMenu( "Data" );
selectMenu = menuBar.getMenu( "Select" );
layoutMenu = menuBar.getMenu( "Layout" );
vizMenu = menuBar.getMenu( "Visualization" );
opsMenu = menuBar.getMenu( "Plugins" );
}
/**
* This method should be called by the creator of this object after
* the constructor has finished. It fills the previously created
* menu and tool bars with items and action listeners that respond
* when those items are activated. This needs to come after the
* constructor is done, because some of the listeners try to access
* this object in their constructors.
*
* Any calls to this method after the first will do nothing.
*/
public void initializeMenus() {
if (!menusInitialized) {
menusInitialized = true;
fillMenuBar();
fillToolBar();
}
}
/**
* Fills the previously created menu bar with a large number of
* items with attached action listener objects.
*/
private void fillMenuBar() {
NetworkView networkView = cyWindow; //restricted interface
CytoscapeObj cytoscapeObj = cyWindow.getCytoscapeObj();
//fill the Load submenu
JMenuItem mi = loadSubMenu.add(new LoadGraphFileAction(networkView));
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_G, ActionEvent.CTRL_MASK));
//mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_I, ActionEvent.CTRL_MASK));
//JMenuItem mi = loadSubMenu.add(new LoadInteractionFileAction(networkView));
//mi = loadSubMenu.add(new LoadGMLFileAction(networkView));
//mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_G, ActionEvent.CTRL_MASK));
mi = loadSubMenu.add(new LoadNodeAttributesAction(networkView));
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK|ActionEvent.SHIFT_MASK));
mi = loadSubMenu.add(new LoadEdgeAttributesAction(networkView));
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, ActionEvent.CTRL_MASK|ActionEvent.SHIFT_MASK));
mi = loadSubMenu.add(new LoadExpressionMatrixAction(networkView));
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, ActionEvent.CTRL_MASK));
mi = loadSubMenu.add(new LoadBioDataServerAction(networkView));
//fill the Save submenu
saveSubMenu.add(new SaveAsGMLAction(networkView));
saveSubMenu.add(new SaveAsInteractionsAction(networkView));
saveSubMenu.add(new SaveVisibleNodesAction(networkView));
saveSubMenu.add(new SaveSelectedNodesAction(networkView));
fileMenu.add(new PrintAction(networkView));
//mi = fileMenu.add(new CloseWindowAction(cyWindow)); removed 2004-03-08
//mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ActionEvent.CTRL_MASK));
if (cytoscapeObj.getParentApp() != null) {
mi = fileMenu.add(new ExitAction(cyWindow));
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, ActionEvent.CTRL_MASK));
}
//fill the Edit menu
//editing the graph not fully supported in Giny mode
//deleteSelectionMenuItem = editMenu.add(new DeleteSelectedAction(networkView));
//deleteSelectionMenuItem.setEnabled(false);
editMenu.add( new SquiggleAction( networkView ) );
//fill the Data menu
mi = dataMenu.add(new DisplayBrowserAction(networkView));
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, ActionEvent.CTRL_MASK));
menuBar.addAction( new GraphObjectSelectionAction( networkView ) );
mi = dataMenu.add(new EdgeManipulationAction(networkView));
//fill the Select menu
JMenu selectNodesSubMenu = new JMenu("Nodes");
selectMenu.add(selectNodesSubMenu);
JMenu selectEdgesSubMenu = new JMenu("Edges");
selectMenu.add(selectEdgesSubMenu);
JMenu displayNWSubMenu = new JMenu("To New Window");
selectMenu.add(displayNWSubMenu);
// mi = selectEdgesSubMenu.add(new EdgeTypeDialogAction());
mi = selectNodesSubMenu.add(new InvertSelectedNodesAction(networkView));
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.CTRL_MASK));
mi = selectNodesSubMenu.add(new HideSelectedNodesAction(networkView));
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H, ActionEvent.CTRL_MASK));
// added by larissa 10/09/03
mi = selectNodesSubMenu.add(new UnHideSelectedNodesAction(networkView));
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_U, ActionEvent.CTRL_MASK));
mi = selectNodesSubMenu.add(new SelectAllNodesAction(networkView));
mi = selectNodesSubMenu.add(new DeSelectAllNodesAction(networkView));
mi = selectNodesSubMenu.add(new SelectFirstNeighborsAction(networkView));
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F, ActionEvent.CTRL_MASK));
selectNodesSubMenu.add(new AlphabeticalSelectionAction(networkView));
selectNodesSubMenu.add(new ListFromFileSelectionAction(networkView));
//mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_D, ActionEvent.CTRL_MASK));
mi = selectEdgesSubMenu.add(new InvertSelectedEdgesAction(networkView));
mi = selectEdgesSubMenu.add(new HideSelectedEdgesAction(networkView));
mi = selectEdgesSubMenu.add(new UnHideSelectedEdgesAction(networkView));
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_U, ActionEvent.CTRL_MASK));
mi = selectEdgesSubMenu.add(new SelectAllEdgesAction(networkView));
mi = selectEdgesSubMenu.add(new DeSelectAllEdgesAction(networkView));
mi = selectNodesSubMenu.add(new SelectFirstNeighborsAction(networkView));
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F, ActionEvent.CTRL_MASK));
// RHC Added Menu Items
//selectNodesSubMenu.add(new GraphObjectSelectionAction(networkView));
menuBar.addAction( new GraphObjectSelectionAction( networkView ) );
//editMenu.add( new SquiggleAction( networkView ) );
vizMenu.add( new BirdsEyeViewAction( networkView ) );
menuBar.addAction( new AnimatedLayoutAction( networkView ) );
vizMenu.add ( new BackgroundColorAction (networkView) );
selectNodesSubMenu.add(new AlphabeticalSelectionAction(networkView));
selectNodesSubMenu.add(new ListFromFileSelectionAction(networkView));
mi = displayNWSubMenu.add(new NewWindowSelectedNodesOnlyAction(cyWindow));
- mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK));
+ mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ActionEvent.SHIFT_MASK|ActionEvent.CTRL_MASK));
mi = displayNWSubMenu.add(new NewWindowSelectedNodesEdgesAction(cyWindow));
mi = displayNWSubMenu.add(new CloneGraphInNewWindowAction(cyWindow));
- mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_K, ActionEvent.CTRL_MASK));
+ mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ActionEvent.CTRL_MASK));
mi = selectMenu.add(new SelectAllAction(networkView));
mi = selectMenu.add(new DeselectAllAction(networkView));
//fill the Layout menu
//need to add Giny layout operations
//layoutMenu.addSeparator();
//mi = layoutMenu.add(new LayoutAction(networkView));
//mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, ActionEvent.CTRL_MASK));
layoutMenu.add(new SpringEmbeddedLayoutAction(networkView));
layoutMenu.addSeparator();
JMenu alignSubMenu = new JMenu("Align Selected Nodes");
layoutMenu.add(alignSubMenu);
alignSubMenu.add(new AlignHorizontalAction(networkView));
alignSubMenu.add(new AlignVerticalAction(networkView));
layoutMenu.add(new RotateSelectedNodesAction(networkView));
//layoutMenu.add(new ReduceEquivalentNodesAction(networkView));
ShrinkExpandGraphUI shrinkExpand =
new ShrinkExpandGraphUI(cyWindow, layoutMenu);
//fill the Visualization menu
vizMenu.add( new BirdsEyeViewAction( networkView ) );
JMenu showExpressionData = new JMenu ("Show Expression Data" );
vizMenu.add ( new BackgroundColorAction (networkView) );
this.vizMenuItem = vizMenu.add(new SetVisualPropertiesAction(cyWindow));
this.disableVizMapperItem = vizMenu.add(new ToggleVisualMapperAction(cyWindow, false));
this.enableVizMapperItem = vizMenu.add(new ToggleVisualMapperAction(cyWindow, true));
this.enableVizMapperItem.setEnabled(false);
menuBar.addAction( new AnimatedLayoutAction( networkView ) );
}
/**
* Fills the toolbar for easy access to commonly used actions.
*/
private void fillToolBar() {
NetworkView networkView = cyWindow; //restricted interface
JButton b;
b = toolBar.add( new LoadGraphFileAction( networkView, null ) );
b.setIcon( new ImageIcon(getClass().getResource("images/new/load36.gif") ) );
b.setToolTipText("Load Graph");
b.setBorderPainted(false);
b.setRolloverEnabled(true);
b = toolBar.add( new SaveAsGMLAction( networkView, null ) );
b.setIcon( new ImageIcon(getClass().getResource("images/new/save36.gif") ) );
b.setToolTipText("Save Graph as GML");
b.setBorderPainted(false);
b.setRolloverEnabled(true);
toolBar.addSeparator();
b = toolBar.add(new ZoomAction(networkView, 0.9));
b.setIcon(new ImageIcon(getClass().getResource("images/new/zoom_out36.gif")));
b.setToolTipText("Zoom Out");
b.setBorderPainted(false);
b.setRolloverEnabled(true);
b = toolBar.add(new ZoomAction(networkView, 1.1));
b.setIcon(new ImageIcon(getClass().getResource("images/new/zoom_in36.gif")));
b.setToolTipText("Zoom In");
b.setBorderPainted(false);
b = toolBar.add(new ZoomSelectedAction(networkView));
b.setIcon(new ImageIcon(getClass().getResource("images/new/crop36.gif")));
b.setToolTipText("Zoom Selected Region");
b.setBorderPainted(false);
b = toolBar.add(new FitContentAction(networkView));
b.setIcon(new ImageIcon(getClass().getResource("images/new/fit36.gif")));
b.setToolTipText("Zoom out to display all of current graph");
b.setBorderPainted(false);
// toolBar.addSeparator();
b = toolBar.add(new ShowAllAction(networkView));
b.setIcon(new ImageIcon(getClass().getResource("images/new/add36.gif")));
b.setToolTipText("Show all nodes and edges (unhiding as necessary)");
b.setBorderPainted(false);
b = toolBar.add(new HideSelectedAction(networkView));
b.setIcon(new ImageIcon(getClass().getResource("images/new/delete36.gif")));
b.setToolTipText("Hide Selected Region");
b.setBorderPainted(false);
toolBar.addSeparator();
b = toolBar.add(new AnnotationGui(cyWindow));
b.setIcon(new ImageIcon(getClass().getResource("images/AnnotationGui.gif")));
b.setToolTipText("add annotation to nodes");
b.setBorderPainted(false);
toolBar.addSeparator();
this.vizButton = toolBar.add(new SetVisualPropertiesAction(cyWindow, false));
vizButton.setIcon(new ImageIcon(getClass().getResource("images/new/color_wheel36.gif")));
vizButton.setToolTipText("Set Visual Properties");
vizButton.setBorderPainted(false);
}//createToolBar
}
| false | true | private void fillMenuBar() {
NetworkView networkView = cyWindow; //restricted interface
CytoscapeObj cytoscapeObj = cyWindow.getCytoscapeObj();
//fill the Load submenu
JMenuItem mi = loadSubMenu.add(new LoadGraphFileAction(networkView));
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_G, ActionEvent.CTRL_MASK));
//mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_I, ActionEvent.CTRL_MASK));
//JMenuItem mi = loadSubMenu.add(new LoadInteractionFileAction(networkView));
//mi = loadSubMenu.add(new LoadGMLFileAction(networkView));
//mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_G, ActionEvent.CTRL_MASK));
mi = loadSubMenu.add(new LoadNodeAttributesAction(networkView));
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK|ActionEvent.SHIFT_MASK));
mi = loadSubMenu.add(new LoadEdgeAttributesAction(networkView));
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, ActionEvent.CTRL_MASK|ActionEvent.SHIFT_MASK));
mi = loadSubMenu.add(new LoadExpressionMatrixAction(networkView));
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, ActionEvent.CTRL_MASK));
mi = loadSubMenu.add(new LoadBioDataServerAction(networkView));
//fill the Save submenu
saveSubMenu.add(new SaveAsGMLAction(networkView));
saveSubMenu.add(new SaveAsInteractionsAction(networkView));
saveSubMenu.add(new SaveVisibleNodesAction(networkView));
saveSubMenu.add(new SaveSelectedNodesAction(networkView));
fileMenu.add(new PrintAction(networkView));
//mi = fileMenu.add(new CloseWindowAction(cyWindow)); removed 2004-03-08
//mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ActionEvent.CTRL_MASK));
if (cytoscapeObj.getParentApp() != null) {
mi = fileMenu.add(new ExitAction(cyWindow));
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, ActionEvent.CTRL_MASK));
}
//fill the Edit menu
//editing the graph not fully supported in Giny mode
//deleteSelectionMenuItem = editMenu.add(new DeleteSelectedAction(networkView));
//deleteSelectionMenuItem.setEnabled(false);
editMenu.add( new SquiggleAction( networkView ) );
//fill the Data menu
mi = dataMenu.add(new DisplayBrowserAction(networkView));
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, ActionEvent.CTRL_MASK));
menuBar.addAction( new GraphObjectSelectionAction( networkView ) );
mi = dataMenu.add(new EdgeManipulationAction(networkView));
//fill the Select menu
JMenu selectNodesSubMenu = new JMenu("Nodes");
selectMenu.add(selectNodesSubMenu);
JMenu selectEdgesSubMenu = new JMenu("Edges");
selectMenu.add(selectEdgesSubMenu);
JMenu displayNWSubMenu = new JMenu("To New Window");
selectMenu.add(displayNWSubMenu);
// mi = selectEdgesSubMenu.add(new EdgeTypeDialogAction());
mi = selectNodesSubMenu.add(new InvertSelectedNodesAction(networkView));
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.CTRL_MASK));
mi = selectNodesSubMenu.add(new HideSelectedNodesAction(networkView));
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H, ActionEvent.CTRL_MASK));
// added by larissa 10/09/03
mi = selectNodesSubMenu.add(new UnHideSelectedNodesAction(networkView));
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_U, ActionEvent.CTRL_MASK));
mi = selectNodesSubMenu.add(new SelectAllNodesAction(networkView));
mi = selectNodesSubMenu.add(new DeSelectAllNodesAction(networkView));
mi = selectNodesSubMenu.add(new SelectFirstNeighborsAction(networkView));
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F, ActionEvent.CTRL_MASK));
selectNodesSubMenu.add(new AlphabeticalSelectionAction(networkView));
selectNodesSubMenu.add(new ListFromFileSelectionAction(networkView));
//mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_D, ActionEvent.CTRL_MASK));
mi = selectEdgesSubMenu.add(new InvertSelectedEdgesAction(networkView));
mi = selectEdgesSubMenu.add(new HideSelectedEdgesAction(networkView));
mi = selectEdgesSubMenu.add(new UnHideSelectedEdgesAction(networkView));
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_U, ActionEvent.CTRL_MASK));
mi = selectEdgesSubMenu.add(new SelectAllEdgesAction(networkView));
mi = selectEdgesSubMenu.add(new DeSelectAllEdgesAction(networkView));
mi = selectNodesSubMenu.add(new SelectFirstNeighborsAction(networkView));
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F, ActionEvent.CTRL_MASK));
// RHC Added Menu Items
//selectNodesSubMenu.add(new GraphObjectSelectionAction(networkView));
menuBar.addAction( new GraphObjectSelectionAction( networkView ) );
//editMenu.add( new SquiggleAction( networkView ) );
vizMenu.add( new BirdsEyeViewAction( networkView ) );
menuBar.addAction( new AnimatedLayoutAction( networkView ) );
vizMenu.add ( new BackgroundColorAction (networkView) );
selectNodesSubMenu.add(new AlphabeticalSelectionAction(networkView));
selectNodesSubMenu.add(new ListFromFileSelectionAction(networkView));
mi = displayNWSubMenu.add(new NewWindowSelectedNodesOnlyAction(cyWindow));
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK));
mi = displayNWSubMenu.add(new NewWindowSelectedNodesEdgesAction(cyWindow));
mi = displayNWSubMenu.add(new CloneGraphInNewWindowAction(cyWindow));
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_K, ActionEvent.CTRL_MASK));
mi = selectMenu.add(new SelectAllAction(networkView));
mi = selectMenu.add(new DeselectAllAction(networkView));
//fill the Layout menu
//need to add Giny layout operations
//layoutMenu.addSeparator();
//mi = layoutMenu.add(new LayoutAction(networkView));
//mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, ActionEvent.CTRL_MASK));
layoutMenu.add(new SpringEmbeddedLayoutAction(networkView));
layoutMenu.addSeparator();
JMenu alignSubMenu = new JMenu("Align Selected Nodes");
layoutMenu.add(alignSubMenu);
alignSubMenu.add(new AlignHorizontalAction(networkView));
alignSubMenu.add(new AlignVerticalAction(networkView));
layoutMenu.add(new RotateSelectedNodesAction(networkView));
//layoutMenu.add(new ReduceEquivalentNodesAction(networkView));
ShrinkExpandGraphUI shrinkExpand =
new ShrinkExpandGraphUI(cyWindow, layoutMenu);
//fill the Visualization menu
vizMenu.add( new BirdsEyeViewAction( networkView ) );
JMenu showExpressionData = new JMenu ("Show Expression Data" );
vizMenu.add ( new BackgroundColorAction (networkView) );
this.vizMenuItem = vizMenu.add(new SetVisualPropertiesAction(cyWindow));
this.disableVizMapperItem = vizMenu.add(new ToggleVisualMapperAction(cyWindow, false));
this.enableVizMapperItem = vizMenu.add(new ToggleVisualMapperAction(cyWindow, true));
this.enableVizMapperItem.setEnabled(false);
menuBar.addAction( new AnimatedLayoutAction( networkView ) );
}
| private void fillMenuBar() {
NetworkView networkView = cyWindow; //restricted interface
CytoscapeObj cytoscapeObj = cyWindow.getCytoscapeObj();
//fill the Load submenu
JMenuItem mi = loadSubMenu.add(new LoadGraphFileAction(networkView));
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_G, ActionEvent.CTRL_MASK));
//mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_I, ActionEvent.CTRL_MASK));
//JMenuItem mi = loadSubMenu.add(new LoadInteractionFileAction(networkView));
//mi = loadSubMenu.add(new LoadGMLFileAction(networkView));
//mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_G, ActionEvent.CTRL_MASK));
mi = loadSubMenu.add(new LoadNodeAttributesAction(networkView));
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK|ActionEvent.SHIFT_MASK));
mi = loadSubMenu.add(new LoadEdgeAttributesAction(networkView));
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, ActionEvent.CTRL_MASK|ActionEvent.SHIFT_MASK));
mi = loadSubMenu.add(new LoadExpressionMatrixAction(networkView));
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, ActionEvent.CTRL_MASK));
mi = loadSubMenu.add(new LoadBioDataServerAction(networkView));
//fill the Save submenu
saveSubMenu.add(new SaveAsGMLAction(networkView));
saveSubMenu.add(new SaveAsInteractionsAction(networkView));
saveSubMenu.add(new SaveVisibleNodesAction(networkView));
saveSubMenu.add(new SaveSelectedNodesAction(networkView));
fileMenu.add(new PrintAction(networkView));
//mi = fileMenu.add(new CloseWindowAction(cyWindow)); removed 2004-03-08
//mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ActionEvent.CTRL_MASK));
if (cytoscapeObj.getParentApp() != null) {
mi = fileMenu.add(new ExitAction(cyWindow));
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, ActionEvent.CTRL_MASK));
}
//fill the Edit menu
//editing the graph not fully supported in Giny mode
//deleteSelectionMenuItem = editMenu.add(new DeleteSelectedAction(networkView));
//deleteSelectionMenuItem.setEnabled(false);
editMenu.add( new SquiggleAction( networkView ) );
//fill the Data menu
mi = dataMenu.add(new DisplayBrowserAction(networkView));
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, ActionEvent.CTRL_MASK));
menuBar.addAction( new GraphObjectSelectionAction( networkView ) );
mi = dataMenu.add(new EdgeManipulationAction(networkView));
//fill the Select menu
JMenu selectNodesSubMenu = new JMenu("Nodes");
selectMenu.add(selectNodesSubMenu);
JMenu selectEdgesSubMenu = new JMenu("Edges");
selectMenu.add(selectEdgesSubMenu);
JMenu displayNWSubMenu = new JMenu("To New Window");
selectMenu.add(displayNWSubMenu);
// mi = selectEdgesSubMenu.add(new EdgeTypeDialogAction());
mi = selectNodesSubMenu.add(new InvertSelectedNodesAction(networkView));
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.CTRL_MASK));
mi = selectNodesSubMenu.add(new HideSelectedNodesAction(networkView));
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H, ActionEvent.CTRL_MASK));
// added by larissa 10/09/03
mi = selectNodesSubMenu.add(new UnHideSelectedNodesAction(networkView));
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_U, ActionEvent.CTRL_MASK));
mi = selectNodesSubMenu.add(new SelectAllNodesAction(networkView));
mi = selectNodesSubMenu.add(new DeSelectAllNodesAction(networkView));
mi = selectNodesSubMenu.add(new SelectFirstNeighborsAction(networkView));
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F, ActionEvent.CTRL_MASK));
selectNodesSubMenu.add(new AlphabeticalSelectionAction(networkView));
selectNodesSubMenu.add(new ListFromFileSelectionAction(networkView));
//mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_D, ActionEvent.CTRL_MASK));
mi = selectEdgesSubMenu.add(new InvertSelectedEdgesAction(networkView));
mi = selectEdgesSubMenu.add(new HideSelectedEdgesAction(networkView));
mi = selectEdgesSubMenu.add(new UnHideSelectedEdgesAction(networkView));
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_U, ActionEvent.CTRL_MASK));
mi = selectEdgesSubMenu.add(new SelectAllEdgesAction(networkView));
mi = selectEdgesSubMenu.add(new DeSelectAllEdgesAction(networkView));
mi = selectNodesSubMenu.add(new SelectFirstNeighborsAction(networkView));
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F, ActionEvent.CTRL_MASK));
// RHC Added Menu Items
//selectNodesSubMenu.add(new GraphObjectSelectionAction(networkView));
menuBar.addAction( new GraphObjectSelectionAction( networkView ) );
//editMenu.add( new SquiggleAction( networkView ) );
vizMenu.add( new BirdsEyeViewAction( networkView ) );
menuBar.addAction( new AnimatedLayoutAction( networkView ) );
vizMenu.add ( new BackgroundColorAction (networkView) );
selectNodesSubMenu.add(new AlphabeticalSelectionAction(networkView));
selectNodesSubMenu.add(new ListFromFileSelectionAction(networkView));
mi = displayNWSubMenu.add(new NewWindowSelectedNodesOnlyAction(cyWindow));
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ActionEvent.SHIFT_MASK|ActionEvent.CTRL_MASK));
mi = displayNWSubMenu.add(new NewWindowSelectedNodesEdgesAction(cyWindow));
mi = displayNWSubMenu.add(new CloneGraphInNewWindowAction(cyWindow));
mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ActionEvent.CTRL_MASK));
mi = selectMenu.add(new SelectAllAction(networkView));
mi = selectMenu.add(new DeselectAllAction(networkView));
//fill the Layout menu
//need to add Giny layout operations
//layoutMenu.addSeparator();
//mi = layoutMenu.add(new LayoutAction(networkView));
//mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, ActionEvent.CTRL_MASK));
layoutMenu.add(new SpringEmbeddedLayoutAction(networkView));
layoutMenu.addSeparator();
JMenu alignSubMenu = new JMenu("Align Selected Nodes");
layoutMenu.add(alignSubMenu);
alignSubMenu.add(new AlignHorizontalAction(networkView));
alignSubMenu.add(new AlignVerticalAction(networkView));
layoutMenu.add(new RotateSelectedNodesAction(networkView));
//layoutMenu.add(new ReduceEquivalentNodesAction(networkView));
ShrinkExpandGraphUI shrinkExpand =
new ShrinkExpandGraphUI(cyWindow, layoutMenu);
//fill the Visualization menu
vizMenu.add( new BirdsEyeViewAction( networkView ) );
JMenu showExpressionData = new JMenu ("Show Expression Data" );
vizMenu.add ( new BackgroundColorAction (networkView) );
this.vizMenuItem = vizMenu.add(new SetVisualPropertiesAction(cyWindow));
this.disableVizMapperItem = vizMenu.add(new ToggleVisualMapperAction(cyWindow, false));
this.enableVizMapperItem = vizMenu.add(new ToggleVisualMapperAction(cyWindow, true));
this.enableVizMapperItem.setEnabled(false);
menuBar.addAction( new AnimatedLayoutAction( networkView ) );
}
|
diff --git a/src/no/runsafe/warpdrive/portals/PortalRepository.java b/src/no/runsafe/warpdrive/portals/PortalRepository.java
index 840a3cd..ad621ea 100644
--- a/src/no/runsafe/warpdrive/portals/PortalRepository.java
+++ b/src/no/runsafe/warpdrive/portals/PortalRepository.java
@@ -1,116 +1,116 @@
package no.runsafe.warpdrive.portals;
import no.runsafe.framework.database.IDatabase;
import no.runsafe.framework.database.Repository;
import no.runsafe.framework.output.IOutput;
import no.runsafe.framework.server.RunsafeLocation;
import no.runsafe.framework.server.RunsafeServer;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class PortalRepository extends Repository
{
public PortalRepository(IDatabase database, IOutput console)
{
this.database = database;
this.console = console;
}
public String getTableName()
{
return "warpdrive_portals";
}
public List<PortalWarp> getPortalWarps()
{
List<PortalWarp> warps = new ArrayList<PortalWarp>();
PreparedStatement query = this.database.prepare(
- "SELECT" +
+ "SELECT " +
"ID," +
"permission," +
"type," +
"world," +
"x," +
"y," +
"z," +
"destWorld," +
"destX," +
"destY," +
"destZ," +
"destYaw," +
"destPitch," +
"innerRadius," +
"outerRadius" +
"FROM warpdrive_portals"
);
try
{
ResultSet result = query.executeQuery();
while (result.next())
{
warps.add(new PortalWarp(
result.getString("ID"),
new RunsafeLocation(
RunsafeServer.Instance.getWorld(result.getString("world")),
result.getDouble("x"),
result.getDouble("y"),
result.getDouble("z")
),
new RunsafeLocation(
RunsafeServer.Instance.getWorld(result.getString("destWorld")),
result.getDouble("destX"),
result.getDouble("destY"),
result.getDouble("destZ"),
result.getFloat("destYaw"),
result.getFloat("destPitch")
),
PortalType.getPortalType(result.getInt("type"))
));
}
}
catch (SQLException e)
{
console.write(e.getMessage());
}
return warps;
}
@Override
public HashMap<Integer, List<String>> getSchemaUpdateQueries()
{
HashMap<Integer, List<String>> queries = new HashMap<Integer, List<String>>();
ArrayList<String> sql = new ArrayList<String>();
sql.add(
"CREATE TABLE `warpdrive_portals` (" +
"`ID` VARCHAR(50) NOT NULL," +
"`permission` VARCHAR(255) NOT NULL DEFAULT ''," +
"`type` TINYINT NOT NULL DEFAULT '0'," +
"`world` VARCHAR(255) NOT NULL," +
"`x` DOUBLE NOT NULL," +
"`y` DOUBLE NOT NULL," +
"`z` DOUBLE NOT NULL," +
"`destWorld` VARCHAR(255) NOT NULL," +
"`destX` DOUBLE NOT NULL," +
"`destY` DOUBLE NOT NULL," +
"`destZ` DOUBLE NOT NULL," +
"`destYaw` DOUBLE NOT NULL," +
"`destPitch` DOUBLE NOT NULL," +
"`innerRadius` INT NOT NULL," +
"`outerRadius` INT NOT NULL," +
"PRIMARY KEY (`ID`)" +
")"
);
queries.put(1, sql);
return queries;
}
private IDatabase database;
private IOutput console;
}
| true | true | public List<PortalWarp> getPortalWarps()
{
List<PortalWarp> warps = new ArrayList<PortalWarp>();
PreparedStatement query = this.database.prepare(
"SELECT" +
"ID," +
"permission," +
"type," +
"world," +
"x," +
"y," +
"z," +
"destWorld," +
"destX," +
"destY," +
"destZ," +
"destYaw," +
"destPitch," +
"innerRadius," +
"outerRadius" +
"FROM warpdrive_portals"
);
try
{
ResultSet result = query.executeQuery();
while (result.next())
{
warps.add(new PortalWarp(
result.getString("ID"),
new RunsafeLocation(
RunsafeServer.Instance.getWorld(result.getString("world")),
result.getDouble("x"),
result.getDouble("y"),
result.getDouble("z")
),
new RunsafeLocation(
RunsafeServer.Instance.getWorld(result.getString("destWorld")),
result.getDouble("destX"),
result.getDouble("destY"),
result.getDouble("destZ"),
result.getFloat("destYaw"),
result.getFloat("destPitch")
),
PortalType.getPortalType(result.getInt("type"))
));
}
}
catch (SQLException e)
{
console.write(e.getMessage());
}
return warps;
}
| public List<PortalWarp> getPortalWarps()
{
List<PortalWarp> warps = new ArrayList<PortalWarp>();
PreparedStatement query = this.database.prepare(
"SELECT " +
"ID," +
"permission," +
"type," +
"world," +
"x," +
"y," +
"z," +
"destWorld," +
"destX," +
"destY," +
"destZ," +
"destYaw," +
"destPitch," +
"innerRadius," +
"outerRadius" +
"FROM warpdrive_portals"
);
try
{
ResultSet result = query.executeQuery();
while (result.next())
{
warps.add(new PortalWarp(
result.getString("ID"),
new RunsafeLocation(
RunsafeServer.Instance.getWorld(result.getString("world")),
result.getDouble("x"),
result.getDouble("y"),
result.getDouble("z")
),
new RunsafeLocation(
RunsafeServer.Instance.getWorld(result.getString("destWorld")),
result.getDouble("destX"),
result.getDouble("destY"),
result.getDouble("destZ"),
result.getFloat("destYaw"),
result.getFloat("destPitch")
),
PortalType.getPortalType(result.getInt("type"))
));
}
}
catch (SQLException e)
{
console.write(e.getMessage());
}
return warps;
}
|
diff --git a/org.eclipse.mylyn.commons.ui/src/org/eclipse/mylyn/internal/provisional/commons/ui/DatePicker.java b/org.eclipse.mylyn.commons.ui/src/org/eclipse/mylyn/internal/provisional/commons/ui/DatePicker.java
index b90748c3..4951ca82 100644
--- a/org.eclipse.mylyn.commons.ui/src/org/eclipse/mylyn/internal/provisional/commons/ui/DatePicker.java
+++ b/org.eclipse.mylyn.commons.ui/src/org/eclipse/mylyn/internal/provisional/commons/ui/DatePicker.java
@@ -1,338 +1,339 @@
/*******************************************************************************
* Copyright (c) 2004, 2009 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.provisional.commons.ui;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import org.eclipse.jface.window.Window;
import org.eclipse.mylyn.internal.commons.ui.Messages;
import org.eclipse.mylyn.internal.provisional.commons.ui.dialogs.AbstractInPlaceDialog;
import org.eclipse.mylyn.internal.provisional.commons.ui.dialogs.IInPlaceDialogListener;
import org.eclipse.mylyn.internal.provisional.commons.ui.dialogs.InPlaceDateSelectionDialog;
import org.eclipse.mylyn.internal.provisional.commons.ui.dialogs.InPlaceDialogEvent;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Color;
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.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.forms.events.HyperlinkAdapter;
import org.eclipse.ui.forms.events.HyperlinkEvent;
import org.eclipse.ui.forms.widgets.ImageHyperlink;
/**
* Temporary date picker from patch posted to: https://bugs.eclipse.org/bugs/show_bug.cgi?taskId=19945 see bug# 19945
* TODO: remove this class when an SWT date picker is added
*
* @author Bahadir Yagan
* @author Mik Kersten
* @since 1.0
*/
public class DatePicker extends Composite {
public final static String TITLE_DIALOG = Messages.DatePicker_Choose_Date;
public static final String LABEL_CHOOSE = Messages.DatePicker_Choose_Date;
private Text dateText;
private Button pickButton;
private Calendar date;
private final List<SelectionListener> pickerListeners = new LinkedList<SelectionListener>();
private DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT);
private String initialText = LABEL_CHOOSE;
private final boolean includeTimeOfday;
private final int hourOfDay = 0;
private int selectedHourOfDay = 0;
private ImageHyperlink clearControl;
public DatePicker(Composite parent, int style, String initialText, boolean includeHours, int selectedHourOfDay) {
super(parent, style);
this.initialText = initialText;
this.includeTimeOfday = includeHours;
this.selectedHourOfDay = selectedHourOfDay;
initialize((style & SWT.FLAT) != 0 ? SWT.FLAT : 0);
}
public DateFormat getDateFormat() {
return dateFormat;
}
public void setDatePattern(String pattern) {
this.dateFormat = new SimpleDateFormat(pattern);
}
public void setDateFormat(DateFormat dateFormat) {
this.dateFormat = dateFormat;
}
private void initialize(int style) {
GridLayout gridLayout = new GridLayout(3, false);
gridLayout.horizontalSpacing = 0;
gridLayout.verticalSpacing = 0;
gridLayout.marginWidth = 0;
gridLayout.marginHeight = 0;
this.setLayout(gridLayout);
dateText = new Text(this, style);
GridData dateTextGridData = new GridData(SWT.FILL, SWT.FILL, false, false);
dateTextGridData.grabExcessHorizontalSpace = true;
dateTextGridData.verticalAlignment = SWT.FILL;
dateText.setLayoutData(dateTextGridData);
dateText.setText(initialText);
dateText.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
// key listener used because setting of date picker text causes
// modify listener to fire which results in perpetual dirty
// editor
notifyPickerListeners();
}
});
dateText.addFocusListener(new FocusAdapter() {
Calendar calendar = Calendar.getInstance();
@Override
public void focusLost(FocusEvent e) {
Date reminderDate;
try {
reminderDate = dateFormat.parse(dateText.getText());
calendar.setTime(reminderDate);
date = calendar;
updateDateText();
} catch (ParseException e1) {
updateDateText();
}
}
});
clearControl = new ImageHyperlink(this, SWT.NONE);
clearControl.setImage(CommonImages.getImage(CommonImages.FIND_CLEAR_DISABLED));
clearControl.setHoverImage(CommonImages.getImage(CommonImages.FIND_CLEAR));
clearControl.setToolTipText(Messages.DatePicker_Clear);
clearControl.addHyperlinkListener(new HyperlinkAdapter() {
@Override
public void linkActivated(HyperlinkEvent e) {
dateSelected(false, null);
}
});
clearControl.setBackground(clearControl.getDisplay().getSystemColor(SWT.COLOR_WHITE));
GridData clearButtonGridData = new GridData();
clearButtonGridData.horizontalIndent = 3;
clearControl.setLayoutData(clearButtonGridData);
pickButton = new Button(this, style | SWT.ARROW | SWT.DOWN);
GridData pickButtonGridData = new GridData(SWT.RIGHT, SWT.FILL, false, true);
pickButtonGridData.verticalIndent = 0;
pickButtonGridData.horizontalIndent = 3;
pickButton.setLayoutData(pickButtonGridData);
pickButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
final Calendar newCalendar = Calendar.getInstance();
newCalendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
newCalendar.set(Calendar.MINUTE, 0);
newCalendar.set(Calendar.SECOND, 0);
newCalendar.set(Calendar.MILLISECOND, 0);
if (date != null) {
newCalendar.setTime(date.getTime());
}
Shell shell = pickButton.getShell();
if (shell == null) {
//fall back
if (PlatformUI.getWorkbench().getActiveWorkbenchWindow() != null) {
shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
} else {
shell = new Shell(PlatformUI.getWorkbench().getDisplay());
}
}
final InPlaceDateSelectionDialog dialog = new InPlaceDateSelectionDialog(shell, pickButton,
newCalendar, DatePicker.TITLE_DIALOG, includeTimeOfday, selectedHourOfDay);
dialog.addEventListener(new IInPlaceDialogListener() {
public void buttonPressed(InPlaceDialogEvent event) {
Calendar selectedCalendar = newCalendar;
if (event.getReturnCode() == AbstractInPlaceDialog.ID_CLEAR) {
dateSelected(event.getReturnCode() == Window.CANCEL, null);
} else if (event.getReturnCode() == Window.OK) {
if (dialog.getDate() != null) {
if (selectedCalendar == null) {
selectedCalendar = Calendar.getInstance();
}
selectedCalendar.setTime(dialog.getDate());
} else {
selectedCalendar = null;
}
dateSelected(event.getReturnCode() == Window.CANCEL, selectedCalendar);
}
}
});
dialog.open();
}
});
updateClearControlVisibility();
pack();
+ setBackground(getDisplay().getSystemColor(SWT.COLOR_WHITE));
}
public void addPickerSelectionListener(SelectionListener listener) {
pickerListeners.add(listener);
}
/**
* must check for null return value
*
* @return Calendar
*/
public Calendar getDate() {
return date;
}
@Override
public void setBackground(Color backgroundColor) {
dateText.setBackground(backgroundColor);
pickButton.setBackground(backgroundColor);
super.setBackground(backgroundColor);
}
public void setDate(Calendar date) {
this.date = date;
updateDateText();
}
// private void showDatePicker(int x, int y) {
// pickerShell = new Shell(SWT.APPLICATION_MODAL);//| SWT.ON_TOP
// pickerShell.setText("Shell");
// pickerShell.setLayout(new FillLayout());
// if (date == null) {
// date = new GregorianCalendar();
// }
// // datePickerPanel.setDate(date);
// datePickerPanel = new DatePickerPanel(pickerShell, SWT.NONE, date);
// datePickerPanel.addSelectionChangedListener(new
// ISelectionChangedListener() {
//
// public void selectionChanged(SelectionChangedEvent event) {
// if(!event.getSelection().isEmpty()) {
// dateSelected(event.getSelection().isEmpty(),
// ((DateSelection)event.getSelection()).getDate());
// } else {
// dateSelected(false, null);
// }
// }});
//
// pickerShell.setSize(new Point(240, 180));
// pickerShell.setLocation(new Point(x, y));
//
// datePickerPanel.addKeyListener(new KeyListener() {
// public void keyPressed(KeyEvent e) {
// if (e.keyCode == SWT.ESC) {
// dateSelected(true, null);
// }
// }
//
// public void keyReleased(KeyEvent e) {
// }
// });
//
// pickerShell.addFocusListener(new FocusListener() {
//
// public void focusGained(FocusEvent e) {
//
// }
//
// public void focusLost(FocusEvent e) {
//
// }});
//
// pickerShell.pack();
// pickerShell.open();
// }
/** Called when the user has selected a date */
protected void dateSelected(boolean canceled, Calendar selectedDate) {
if (!canceled) {
this.date = selectedDate != null ? selectedDate : null;
updateDateText();
notifyPickerListeners();
}
}
private void notifyPickerListeners() {
for (SelectionListener listener : pickerListeners) {
listener.widgetSelected(null);
}
}
private void updateDateText() {
if (date != null) {
Date currentDate = new Date(date.getTimeInMillis());
dateText.setText(dateFormat.format(currentDate));
} else {
dateText.setEnabled(false);
dateText.setText(LABEL_CHOOSE);
dateText.setEnabled(true);
}
updateClearControlVisibility();
}
private void updateClearControlVisibility() {
if (clearControl != null && clearControl.getLayoutData() instanceof GridData) {
GridData gd = (GridData) clearControl.getLayoutData();
gd.exclude = date == null;
clearControl.getParent().layout();
}
}
@Override
public void setEnabled(boolean enabled) {
dateText.setEnabled(enabled);
pickButton.setEnabled(enabled);
clearControl.setEnabled(enabled);
super.setEnabled(enabled);
}
}
| true | true | private void initialize(int style) {
GridLayout gridLayout = new GridLayout(3, false);
gridLayout.horizontalSpacing = 0;
gridLayout.verticalSpacing = 0;
gridLayout.marginWidth = 0;
gridLayout.marginHeight = 0;
this.setLayout(gridLayout);
dateText = new Text(this, style);
GridData dateTextGridData = new GridData(SWT.FILL, SWT.FILL, false, false);
dateTextGridData.grabExcessHorizontalSpace = true;
dateTextGridData.verticalAlignment = SWT.FILL;
dateText.setLayoutData(dateTextGridData);
dateText.setText(initialText);
dateText.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
// key listener used because setting of date picker text causes
// modify listener to fire which results in perpetual dirty
// editor
notifyPickerListeners();
}
});
dateText.addFocusListener(new FocusAdapter() {
Calendar calendar = Calendar.getInstance();
@Override
public void focusLost(FocusEvent e) {
Date reminderDate;
try {
reminderDate = dateFormat.parse(dateText.getText());
calendar.setTime(reminderDate);
date = calendar;
updateDateText();
} catch (ParseException e1) {
updateDateText();
}
}
});
clearControl = new ImageHyperlink(this, SWT.NONE);
clearControl.setImage(CommonImages.getImage(CommonImages.FIND_CLEAR_DISABLED));
clearControl.setHoverImage(CommonImages.getImage(CommonImages.FIND_CLEAR));
clearControl.setToolTipText(Messages.DatePicker_Clear);
clearControl.addHyperlinkListener(new HyperlinkAdapter() {
@Override
public void linkActivated(HyperlinkEvent e) {
dateSelected(false, null);
}
});
clearControl.setBackground(clearControl.getDisplay().getSystemColor(SWT.COLOR_WHITE));
GridData clearButtonGridData = new GridData();
clearButtonGridData.horizontalIndent = 3;
clearControl.setLayoutData(clearButtonGridData);
pickButton = new Button(this, style | SWT.ARROW | SWT.DOWN);
GridData pickButtonGridData = new GridData(SWT.RIGHT, SWT.FILL, false, true);
pickButtonGridData.verticalIndent = 0;
pickButtonGridData.horizontalIndent = 3;
pickButton.setLayoutData(pickButtonGridData);
pickButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
final Calendar newCalendar = Calendar.getInstance();
newCalendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
newCalendar.set(Calendar.MINUTE, 0);
newCalendar.set(Calendar.SECOND, 0);
newCalendar.set(Calendar.MILLISECOND, 0);
if (date != null) {
newCalendar.setTime(date.getTime());
}
Shell shell = pickButton.getShell();
if (shell == null) {
//fall back
if (PlatformUI.getWorkbench().getActiveWorkbenchWindow() != null) {
shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
} else {
shell = new Shell(PlatformUI.getWorkbench().getDisplay());
}
}
final InPlaceDateSelectionDialog dialog = new InPlaceDateSelectionDialog(shell, pickButton,
newCalendar, DatePicker.TITLE_DIALOG, includeTimeOfday, selectedHourOfDay);
dialog.addEventListener(new IInPlaceDialogListener() {
public void buttonPressed(InPlaceDialogEvent event) {
Calendar selectedCalendar = newCalendar;
if (event.getReturnCode() == AbstractInPlaceDialog.ID_CLEAR) {
dateSelected(event.getReturnCode() == Window.CANCEL, null);
} else if (event.getReturnCode() == Window.OK) {
if (dialog.getDate() != null) {
if (selectedCalendar == null) {
selectedCalendar = Calendar.getInstance();
}
selectedCalendar.setTime(dialog.getDate());
} else {
selectedCalendar = null;
}
dateSelected(event.getReturnCode() == Window.CANCEL, selectedCalendar);
}
}
});
dialog.open();
}
});
updateClearControlVisibility();
pack();
}
| private void initialize(int style) {
GridLayout gridLayout = new GridLayout(3, false);
gridLayout.horizontalSpacing = 0;
gridLayout.verticalSpacing = 0;
gridLayout.marginWidth = 0;
gridLayout.marginHeight = 0;
this.setLayout(gridLayout);
dateText = new Text(this, style);
GridData dateTextGridData = new GridData(SWT.FILL, SWT.FILL, false, false);
dateTextGridData.grabExcessHorizontalSpace = true;
dateTextGridData.verticalAlignment = SWT.FILL;
dateText.setLayoutData(dateTextGridData);
dateText.setText(initialText);
dateText.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
// key listener used because setting of date picker text causes
// modify listener to fire which results in perpetual dirty
// editor
notifyPickerListeners();
}
});
dateText.addFocusListener(new FocusAdapter() {
Calendar calendar = Calendar.getInstance();
@Override
public void focusLost(FocusEvent e) {
Date reminderDate;
try {
reminderDate = dateFormat.parse(dateText.getText());
calendar.setTime(reminderDate);
date = calendar;
updateDateText();
} catch (ParseException e1) {
updateDateText();
}
}
});
clearControl = new ImageHyperlink(this, SWT.NONE);
clearControl.setImage(CommonImages.getImage(CommonImages.FIND_CLEAR_DISABLED));
clearControl.setHoverImage(CommonImages.getImage(CommonImages.FIND_CLEAR));
clearControl.setToolTipText(Messages.DatePicker_Clear);
clearControl.addHyperlinkListener(new HyperlinkAdapter() {
@Override
public void linkActivated(HyperlinkEvent e) {
dateSelected(false, null);
}
});
clearControl.setBackground(clearControl.getDisplay().getSystemColor(SWT.COLOR_WHITE));
GridData clearButtonGridData = new GridData();
clearButtonGridData.horizontalIndent = 3;
clearControl.setLayoutData(clearButtonGridData);
pickButton = new Button(this, style | SWT.ARROW | SWT.DOWN);
GridData pickButtonGridData = new GridData(SWT.RIGHT, SWT.FILL, false, true);
pickButtonGridData.verticalIndent = 0;
pickButtonGridData.horizontalIndent = 3;
pickButton.setLayoutData(pickButtonGridData);
pickButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
final Calendar newCalendar = Calendar.getInstance();
newCalendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
newCalendar.set(Calendar.MINUTE, 0);
newCalendar.set(Calendar.SECOND, 0);
newCalendar.set(Calendar.MILLISECOND, 0);
if (date != null) {
newCalendar.setTime(date.getTime());
}
Shell shell = pickButton.getShell();
if (shell == null) {
//fall back
if (PlatformUI.getWorkbench().getActiveWorkbenchWindow() != null) {
shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
} else {
shell = new Shell(PlatformUI.getWorkbench().getDisplay());
}
}
final InPlaceDateSelectionDialog dialog = new InPlaceDateSelectionDialog(shell, pickButton,
newCalendar, DatePicker.TITLE_DIALOG, includeTimeOfday, selectedHourOfDay);
dialog.addEventListener(new IInPlaceDialogListener() {
public void buttonPressed(InPlaceDialogEvent event) {
Calendar selectedCalendar = newCalendar;
if (event.getReturnCode() == AbstractInPlaceDialog.ID_CLEAR) {
dateSelected(event.getReturnCode() == Window.CANCEL, null);
} else if (event.getReturnCode() == Window.OK) {
if (dialog.getDate() != null) {
if (selectedCalendar == null) {
selectedCalendar = Calendar.getInstance();
}
selectedCalendar.setTime(dialog.getDate());
} else {
selectedCalendar = null;
}
dateSelected(event.getReturnCode() == Window.CANCEL, selectedCalendar);
}
}
});
dialog.open();
}
});
updateClearControlVisibility();
pack();
setBackground(getDisplay().getSystemColor(SWT.COLOR_WHITE));
}
|
diff --git a/Meat-Loaf/src/com/cs301w01/meatload/activities/ViewTagsActivity.java b/Meat-Loaf/src/com/cs301w01/meatload/activities/ViewTagsActivity.java
index c6ae425..a99ad26 100644
--- a/Meat-Loaf/src/com/cs301w01/meatload/activities/ViewTagsActivity.java
+++ b/Meat-Loaf/src/com/cs301w01/meatload/activities/ViewTagsActivity.java
@@ -1,98 +1,98 @@
package com.cs301w01.meatload.activities;
import java.util.ArrayList;
import com.cs301w01.meatload.R;
import com.cs301w01.meatload.adapters.AlbumAdapter;
import com.cs301w01.meatload.adapters.TagAdapter;
import com.cs301w01.meatload.controllers.MainManager;
import com.cs301w01.meatload.model.Album;
import com.cs301w01.meatload.model.Tag;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
/**
* Implements the logic in the Tags view of the Tab layout in Skindex.
* @author Joel Burford
*/
public class ViewTagsActivity extends Skindactivity {
private MainManager mainManager;
private TagAdapter adapter;
//arraylist needed for second listview
private ArrayList<Tag> selectedTags;
//list views
private ListView allTagsLV;
private ListView selectedTagsLV;
//auto complete view
private AutoCompleteTextView searchField;
//current picture count view
private TextView pictureCount;
//@Override
public void update(Object model) {
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.viewtags);
mainManager = new MainManager();
mainManager.setContext(this);
selectedTags = new ArrayList<Tag>();
createListeners();
refreshScreen();
}
protected void createListeners() {
- final Button viewPicturesButton = (Button) findViewById(R.id.viewSelectections);
+ final Button viewPicturesButton = (Button) findViewById(R.id.viewSelections);
viewPicturesButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
}
});
allTagsLV.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
View temp = v;
allTagsLV.removeView(temp);
selectedTagsLV.addView(temp);
}
});
//tagListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
}
public void refreshScreen() {
//set top list
allTagsLV= (ListView) findViewById(R.id.tagListView);
ArrayList<Tag> tagList = mainManager.getAllTags();
adapter = new TagAdapter(this, R.layout.list_item, tagList);
allTagsLV.setAdapter(adapter);
//create bottom list
selectedTagsLV = (ListView) findViewById(R.id.selectedTagsListView);
TagAdapter sTadapter = new TagAdapter(this, R.layout.list_item, selectedTags);
selectedTagsLV.setAdapter(sTadapter);
}
}
| true | true | protected void createListeners() {
final Button viewPicturesButton = (Button) findViewById(R.id.viewSelectections);
viewPicturesButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
}
});
allTagsLV.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
View temp = v;
allTagsLV.removeView(temp);
selectedTagsLV.addView(temp);
}
});
//tagListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
}
| protected void createListeners() {
final Button viewPicturesButton = (Button) findViewById(R.id.viewSelections);
viewPicturesButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
}
});
allTagsLV.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
View temp = v;
allTagsLV.removeView(temp);
selectedTagsLV.addView(temp);
}
});
//tagListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
}
|
diff --git a/org.dawb.workbench.ui/src/org/dawb/workbench/ui/views/DiffractionCalibrationPlottingView.java b/org.dawb.workbench.ui/src/org/dawb/workbench/ui/views/DiffractionCalibrationPlottingView.java
index 60c373b4a..1238bd0cb 100644
--- a/org.dawb.workbench.ui/src/org/dawb/workbench/ui/views/DiffractionCalibrationPlottingView.java
+++ b/org.dawb.workbench.ui/src/org/dawb/workbench/ui/views/DiffractionCalibrationPlottingView.java
@@ -1,1265 +1,1272 @@
/*-
* Copyright 2013 Diamond Light Source Ltd.
*
* 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.dawb.workbench.ui.views;
import java.io.File;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import javax.measure.quantity.Length;
import javax.measure.unit.NonSI;
import javax.measure.unit.SI;
import org.dawb.common.services.ILoaderService;
import org.dawb.common.ui.widgets.ActionBarWrapper;
import org.dawb.workbench.ui.Activator;
import org.dawb.workbench.ui.views.DiffractionCalibrationUtils.ManipulateMode;
import org.dawnsci.common.widgets.spinner.FloatSpinner;
import org.dawnsci.common.widgets.tree.NumericNode;
import org.dawnsci.common.widgets.utils.RadioUtils;
import org.dawnsci.plotting.api.IPlottingSystem;
import org.dawnsci.plotting.api.PlotType;
import org.dawnsci.plotting.api.PlottingFactory;
import org.dawnsci.plotting.api.tool.IToolPage.ToolPageRole;
import org.dawnsci.plotting.api.tool.IToolPageSystem;
import org.dawnsci.plotting.tools.diffraction.DiffractionImageAugmenter;
import org.dawnsci.plotting.tools.diffraction.DiffractionTool;
import org.dawnsci.plotting.tools.diffraction.DiffractionTreeModel;
import org.dawnsci.plotting.util.PlottingUtils;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.jobs.IJobChangeEvent;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.core.runtime.jobs.JobChangeAdapter;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.util.LocalSelectionTransfer;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.CheckboxCellEditor;
import org.eclipse.jface.viewers.EditingSupport;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.jface.viewers.TreeSelection;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DropTarget;
import org.eclipse.swt.dnd.DropTargetAdapter;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.dnd.FileTransfer;
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.ResourceTransfer;
import org.eclipse.ui.part.ViewPart;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import uk.ac.diamond.scisoft.analysis.crystallography.CalibrationFactory;
import uk.ac.diamond.scisoft.analysis.crystallography.CalibrationStandards;
import uk.ac.diamond.scisoft.analysis.dataset.IDataset;
import uk.ac.diamond.scisoft.analysis.diffraction.DetectorProperties;
import uk.ac.diamond.scisoft.analysis.diffraction.DetectorPropertyEvent;
import uk.ac.diamond.scisoft.analysis.diffraction.DiffractionCrystalEnvironment;
import uk.ac.diamond.scisoft.analysis.diffraction.DiffractionCrystalEnvironmentEvent;
import uk.ac.diamond.scisoft.analysis.diffraction.IDetectorPropertyListener;
import uk.ac.diamond.scisoft.analysis.diffraction.IDiffractionCrystalEnvironmentListener;
import uk.ac.diamond.scisoft.analysis.hdf5.HDF5NodeLink;
import uk.ac.diamond.scisoft.analysis.io.IDiffractionMetadata;
/**
* This listens for a selected editor (of a diffraction image) and allows
*
* 1) selection of calibrant
* 2) movement, scaling and tilting of rings
* 3) refinement of fit
* 4) calibration (other images too?)
*
* Should display relevant metadata, allow a number of files to contribute to final calibration
*/
public class DiffractionCalibrationPlottingView extends ViewPart {
private static Logger logger = LoggerFactory.getLogger(DiffractionCalibrationPlottingView.class);
private DiffractionTableData currentData;
private final String DIFFRACTION_ID = "org.dawb.workbench.plotting.tools.diffraction.Diffraction";
private final String WAVELENGTH_NODE_PATH = "/Experimental Information/Wavelength";
private final String BEAM_CENTRE_XPATH = "/Detector/Beam Centre/X";
private final String BEAM_CENTRE_YPATH = "/Detector/Beam Centre/Y";
private final String DISTANCE_NODE_PATH = "/Experimental Information/Distance";
private List<DiffractionTableData> model = new ArrayList<DiffractionTableData>();
private ILoaderService service;
private Composite parent;
private ScrolledComposite scrollComposite;
private Composite scrollHolder;
private TableViewer tableViewer;
private Button calibrateImages;
private Combo calibrant;
private Action deleteAction;
private IPlottingSystem plottingSystem;
private ISelectionChangedListener selectionChangeListener;
private DropTargetAdapter dropListener;
private IDiffractionCrystalEnvironmentListener diffractionCrystEnvListener;
private IDetectorPropertyListener detectorPropertyListener;
private List<String> pathsList = new ArrayList<String>();
private double wavelength;
private FloatSpinner wavelengthDistanceSpinner;
private FloatSpinner wavelengthEnergySpinner;
private IToolPageSystem toolSystem;
private Action resetAction;
// private boolean doNotRefineWavelength = true;
private boolean refineAfterDistance = false;
private boolean refineWithDistance = false;
public DiffractionCalibrationPlottingView() {
service = (ILoaderService) PlatformUI.getWorkbench().getService(ILoaderService.class);
}
private static final String DATA_PATH = "DataPath";
@Override
public void init(IViewSite site, IMemento memento) throws PartInitException {
init(site);
setSite(site);
setPartName("Diffraction Calibration View");
if (memento != null) {
for (String k : memento.getAttributeKeys()) {
if (k.startsWith(DATA_PATH)) {
int i = Integer.parseInt(k.substring(DATA_PATH.length()));
pathsList.add(i, memento.getString(k));
}
}
}
}
@Override
public void saveState(IMemento memento) {
if (memento != null) {
int i = 0;
for (TableItem t : tableViewer.getTable().getItems()) {
DiffractionTableData data = (DiffractionTableData) t.getData();
memento.putString(DATA_PATH + String.valueOf(i++), data.path);
}
}
}
@Override
public void createPartControl(final Composite parent) {
parent.setLayout(new FillLayout());
this.parent = parent;
resetAction = new Action() {
@Override
public void run() {
// select last item in table
if (model != null && model.size() > 0) {
tableViewer.setSelection(new StructuredSelection(model.get(model.size() - 1)));
for (int i = 0; i < model.size(); i++) {
// Restore original metadata
DetectorProperties originalProps = model.get(i).md.getOriginalDetector2DProperties();
DiffractionCrystalEnvironment originalEnvironment = model.get(i).md.getOriginalDiffractionCrystalEnvironment();
model.get(i).md.getDetector2DProperties().restore(originalProps);
model.get(i).md.getDiffractionCrystalEnvironment().restore(originalEnvironment);
}
// update diffraction tool viewer
updateDiffTool(BEAM_CENTRE_XPATH, currentData.md.getDetector2DProperties().getBeamCentreCoords()[0]);
updateDiffTool(BEAM_CENTRE_YPATH, currentData.md.getDetector2DProperties().getBeamCentreCoords()[1]);
updateDiffTool(DISTANCE_NODE_PATH, currentData.md.getDetector2DProperties().getBeamCentreDistance());
// update wavelength
double wavelength = currentData.md.getDiffractionCrystalEnvironment().getWavelength();
wavelengthEnergySpinner.setDouble(getWavelengthEnergy(wavelength));
wavelengthDistanceSpinner.setDouble(wavelength);
// update wavelength in diffraction tool tree viewer
NumericNode<Length> node = getDiffractionTreeNode(WAVELENGTH_NODE_PATH);
if (node.getUnit().equals(NonSI.ANGSTROM)) {
updateDiffTool(WAVELENGTH_NODE_PATH, wavelength);
} else if (node.getUnit().equals(NonSI.ELECTRON_VOLT)) {
updateDiffTool(WAVELENGTH_NODE_PATH, getWavelengthEnergy(wavelength) * 1000);
} else if (node.getUnit().equals(SI.KILO(NonSI.ELECTRON_VOLT))) {
updateDiffTool(WAVELENGTH_NODE_PATH, getWavelengthEnergy(wavelength));
}
tableViewer.refresh();
}
}
};
resetAction.setText("Reset");
resetAction.setToolTipText("Reset metadata");
resetAction.setImageDescriptor(Activator.getImageDescriptor("icons/table_delete.png"));
// selection change listener for table viewer
selectionChangeListener = new ISelectionChangedListener() {
@Override
public void selectionChanged(SelectionChangedEvent event) {
ISelection is = event.getSelection();
if (is instanceof StructuredSelection) {
StructuredSelection structSelection = (StructuredSelection) is;
DiffractionTableData selectedData = (DiffractionTableData) structSelection.getFirstElement();
if (selectedData == null || selectedData == currentData)
return;
drawSelectedData(selectedData);
}
}
};
final Display display = parent.getDisplay();
diffractionCrystEnvListener = new IDiffractionCrystalEnvironmentListener() {
@Override
public void diffractionCrystalEnvironmentChanged(
final DiffractionCrystalEnvironmentEvent evt) {
display.asyncExec(new Runnable() {
@Override
public void run() {
tableViewer.refresh();
}
});
}
};
detectorPropertyListener = new IDetectorPropertyListener() {
@Override
public void detectorPropertiesChanged(DetectorPropertyEvent evt) {
display.asyncExec(new Runnable() {
@Override
public void run() {
tableViewer.refresh();
}
});
}
};
dropListener = new DropTargetAdapter() {
@Override
public void drop(DropTargetEvent event) {
Object dropData = event.data;
DiffractionTableData good = null;
if (dropData instanceof IResource[]) {
IResource[] res = (IResource[]) dropData;
for (int i = 0; i < res.length; i++) {
DiffractionTableData d = createData(res[i].getRawLocation().toOSString(), null);
if (d != null){
good = d;
setWavelength(d);
}
}
} else if (dropData instanceof TreeSelection) {
TreeSelection selectedNode = (TreeSelection) dropData;
Object obj[] = selectedNode.toArray();
for (int i = 0; i < obj.length; i++) {
DiffractionTableData d = null;
if (obj[i] instanceof HDF5NodeLink) {
HDF5NodeLink node = (HDF5NodeLink) obj[i];
if (node == null)
return;
d = createData(node.getFile().getFilename(), node.getFullName());
} else if (obj[i] instanceof IFile) {
IFile file = (IFile) obj[i];
d = createData(file.getLocation().toOSString(), null);
}
if (d != null){
good = d;
setWavelength(d);
}
}
} else if (dropData instanceof String[]) {
String[] selectedData = (String[]) dropData;
for (int i = 0; i < selectedData.length; i++) {
DiffractionTableData d = createData(selectedData[i], null);
if (d != null){
good = d;
setWavelength(d);
}
}
}
tableViewer.refresh();
if (currentData == null && good != null) {
tableViewer.getTable().deselectAll();
tableViewer.setSelection(new StructuredSelection(good));
}
if (model.size() > 0) {
wavelengthDistanceSpinner.setEnabled(true);
wavelengthEnergySpinner.setEnabled(true);
}
}
};
deleteAction = new Action("Delete item", Activator.getImageDescriptor("icons/delete_obj.png")) {
@Override
public void run() {
StructuredSelection selection = (StructuredSelection) tableViewer.getSelection();
DiffractionTableData selectedData = (DiffractionTableData) selection.getFirstElement();
if (model.size() > 0) {
if (model.remove(selectedData)) {
selectedData.augmenter.deactivate();
selectedData.md.getDetector2DProperties().removeDetectorPropertyListener(detectorPropertyListener);
selectedData.md.getDiffractionCrystalEnvironment().removeDiffractionCrystalEnvironmentListener(diffractionCrystEnvListener);
tableViewer.refresh();
}
}
if (!model.isEmpty()) {
drawSelectedData((DiffractionTableData) tableViewer.getElementAt(0));
} else {
currentData = null; // need to reset this
plottingSystem.clear();
wavelengthDistanceSpinner.setEnabled(false);
wavelengthEnergySpinner.setEnabled(false);
}
}
};
// main sash form which contains the left sash and the plotting system
SashForm mainSash = new SashForm(parent, SWT.HORIZONTAL);
mainSash.setBackground(new Color(display, 192, 192, 192));
mainSash.setLayout(new FillLayout());
// left sash form which contains the diffraction calibration controls and the diffraction tool
SashForm leftSash = new SashForm(mainSash, SWT.VERTICAL);
leftSash.setBackground(new Color(display, 192, 192, 192));
leftSash.setLayout(new GridLayout(1, false));
leftSash.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
Composite controlComp = new Composite(leftSash, SWT.NONE);
controlComp.setLayout(new GridLayout(1, false));
Label instructionLabel = new Label(controlComp, SWT.WRAP);
instructionLabel.setText("Drag/drop a file/data to the table below, choose a type of calibrant, " +
"modify the rings using the controls below and tick the checkbox near to the corresponding " +
"image before pressing the calibration buttons.");
instructionLabel.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, true, false));
// make a scrolled composite
scrollComposite = new ScrolledComposite(controlComp, SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
scrollComposite.setLayout(new GridLayout(1, false));
scrollComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
scrollHolder = new Composite(scrollComposite, SWT.NONE);
GridLayout gl = new GridLayout(1, false);
scrollHolder.setLayout(gl);
scrollHolder.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, true));
// table of images and found rings
tableViewer = new TableViewer(scrollHolder, SWT.FULL_SELECTION | SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
createColumns(tableViewer);
tableViewer.getTable().setHeaderVisible(true);
tableViewer.getTable().setLinesVisible(true);
tableViewer.getTable().setToolTipText("Drag/drop file(s)/data to this table");
tableViewer.setContentProvider(new MyContentProvider());
tableViewer.setLabelProvider(new MyLabelProvider());
tableViewer.setInput(model);
tableViewer.getControl().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
tableViewer.addSelectionChangedListener(selectionChangeListener);
tableViewer.refresh();
final MenuManager mgr = new MenuManager();
mgr.setRemoveAllWhenShown(true);
mgr.addMenuListener(new IMenuListener() {
@Override
public void menuAboutToShow(IMenuManager manager) {
IStructuredSelection selection = (IStructuredSelection) tableViewer.getSelection();
if (!selection.isEmpty()) {
deleteAction.setText("Delete "
+ ((DiffractionTableData) selection.getFirstElement()).name);
mgr.add(deleteAction);
}
}
});
tableViewer.getControl().setMenu(mgr.createContextMenu(tableViewer.getControl()));
//add drop support
DropTarget dt = new DropTarget(tableViewer.getControl(), DND.DROP_MOVE| DND.DROP_DEFAULT| DND.DROP_COPY);
dt.setTransfer(new Transfer[] { TextTransfer.getInstance (), FileTransfer.getInstance(),
ResourceTransfer.getInstance(), LocalSelectionTransfer.getTransfer()});
dt.addDropListener(dropListener);
Composite calibrantHolder = new Composite(scrollHolder, SWT.NONE);
calibrantHolder.setLayout(new GridLayout(1, false));
calibrantHolder.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, true));
Composite mainControlComp = new Composite(calibrantHolder, SWT.NONE);
mainControlComp.setLayout(new GridLayout(2, false));
mainControlComp.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false));
Group controllerHolder = new Group(mainControlComp, SWT.BORDER);
controllerHolder.setText("Calibrant selection and positioning");
controllerHolder.setLayout(new GridLayout(2, false));
controllerHolder.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false));
// create calibrant combo
Label l = new Label(controllerHolder, SWT.NONE);
l.setText("Calibrant:");
l.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
calibrant = new Combo(controllerHolder, SWT.READ_ONLY);
final CalibrationStandards standards = CalibrationFactory.getCalibrationStandards();
calibrant.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
+ if (currentData == null) return;
standards.setSelectedCalibrant(calibrant.getItem(calibrant.getSelectionIndex()));
DiffractionCalibrationUtils.drawCalibrantRings(currentData.augmenter);
}
});
for (String c : standards.getCalibrantList()) {
calibrant.add(c);
}
String s = standards.getSelectedCalibrant();
if (s != null) {
calibrant.setText(s);
}
calibrant.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false));
Composite padComp = new Composite(controllerHolder, SWT.BORDER);
padComp.setLayout(new GridLayout(5, false));
padComp.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false));
padComp.setToolTipText("Move calibrant");
l = new Label(padComp, SWT.NONE);
l = new Label(padComp, SWT.NONE);
Button upButton = new Button(padComp, SWT.ARROW | SWT.UP);
upButton.setToolTipText("Move rings up");
upButton.addMouseListener(new RepeatingMouseAdapter(display, new SlowFastRunnable() {
@Override
public void run() {
DiffractionCalibrationUtils.changeRings(currentData, ManipulateMode.UP, isFast());
}
@Override
public void stop() {
+ if (currentData == null) return;
updateDiffTool(BEAM_CENTRE_YPATH, currentData.md.getDetector2DProperties().getBeamCentreCoords()[1]);
refreshTable();
}
}));
upButton.setLayoutData(new GridData(SWT.CENTER, SWT.BOTTOM, false, false));
l = new Label(padComp, SWT.NONE);
l = new Label(padComp, SWT.NONE);
l = new Label(padComp, SWT.NONE);
Button leftButton = new Button(padComp, SWT.ARROW | SWT.LEFT);
leftButton.setToolTipText("Shift rings left");
leftButton.addMouseListener(new RepeatingMouseAdapter(display, new SlowFastRunnable() {
@Override
public void run() {
DiffractionCalibrationUtils.changeRings(currentData, ManipulateMode.LEFT, isFast());
}
@Override
public void stop() {
+ if (currentData == null) return;
updateDiffTool(BEAM_CENTRE_XPATH, currentData.md.getDetector2DProperties().getBeamCentreCoords()[0]);
refreshTable();
}
}));
leftButton.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
l = new Label(padComp, SWT.NONE);
Button rightButton = new Button(padComp, SWT.ARROW | SWT.RIGHT);
rightButton.setToolTipText("Shift rings right");
rightButton.addMouseListener(new RepeatingMouseAdapter(display, new SlowFastRunnable() {
@Override
public void run() {
DiffractionCalibrationUtils.changeRings(currentData, ManipulateMode.RIGHT, isFast());
}
@Override
public void stop() {
+ if (currentData == null) return;
updateDiffTool(BEAM_CENTRE_XPATH, currentData.md.getDetector2DProperties().getBeamCentreCoords()[0]);
refreshTable();
}
}));
rightButton.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false));
l = new Label(padComp, SWT.NONE);
l = new Label(padComp, SWT.NONE);
l = new Label(padComp, SWT.NONE);
Button downButton = new Button(padComp, SWT.ARROW | SWT.DOWN);
downButton.setToolTipText("Move rings down");
downButton.addMouseListener(new RepeatingMouseAdapter(display, new SlowFastRunnable() {
@Override
public void run() {
DiffractionCalibrationUtils.changeRings(currentData, ManipulateMode.DOWN, isFast());
}
@Override
public void stop() {
+ if (currentData == null) return;
updateDiffTool(BEAM_CENTRE_YPATH, currentData.md.getDetector2DProperties().getBeamCentreCoords()[1]);
refreshTable();
}
}));
downButton.setLayoutData(new GridData(SWT.CENTER, SWT.TOP, false, false));
l = new Label(padComp, SWT.NONE);
l = new Label(padComp, SWT.NONE);
Composite actionComp = new Composite(controllerHolder, SWT.NONE);
actionComp.setLayout(new GridLayout(3, false));
actionComp.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, true));
Composite sizeComp = new Composite(actionComp, SWT.BORDER);
sizeComp.setLayout(new GridLayout(1, false));
sizeComp.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, true));
sizeComp.setToolTipText("Change size");
Button plusButton = new Button(sizeComp, SWT.PUSH);
plusButton.setImage(Activator.getImage("icons/arrow_out.png"));
plusButton.setToolTipText("Make rings larger");
plusButton.addMouseListener(new RepeatingMouseAdapter(display, new SlowFastRunnable() {
@Override
public void run() {
DiffractionCalibrationUtils.changeRings(currentData, ManipulateMode.ENLARGE, isFast());
}
@Override
public void stop() {
+ if (currentData == null) return;
updateDiffTool(DISTANCE_NODE_PATH, currentData.md.getDetector2DProperties().getBeamCentreDistance());
refreshTable();
}
}));
plusButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, true));
Button minusButton = new Button(sizeComp, SWT.PUSH);
minusButton.setImage(Activator.getImage("icons/arrow_in.png"));
minusButton.setToolTipText("Make rings smaller");
minusButton.addMouseListener(new RepeatingMouseAdapter(display, new SlowFastRunnable() {
@Override
public void run() {
DiffractionCalibrationUtils.changeRings(currentData, ManipulateMode.SHRINK, isFast());
}
@Override
public void stop() {
+ if (currentData == null) return;
updateDiffTool(DISTANCE_NODE_PATH, currentData.md.getDetector2DProperties().getBeamCentreDistance());
refreshTable();
}
}));
minusButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, true));
Composite shapeComp = new Composite(actionComp, SWT.BORDER);
shapeComp.setLayout(new GridLayout(1, false));
shapeComp.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, true));
shapeComp.setToolTipText("Change shape");
Button elongateButton = new Button(shapeComp, SWT.PUSH);
elongateButton.setText("Elongate");
elongateButton.setToolTipText("Make rings more elliptical");
elongateButton.addMouseListener(new RepeatingMouseAdapter(display, new SlowFastRunnable() {
@Override
public void run() {
DiffractionCalibrationUtils.changeRings(currentData, ManipulateMode.ELONGATE, isFast());
}
@Override
public void stop() {
// updateDiffTool(DISTANCE_NODE_PATH, currentData.md.getDetector2DProperties().getDetectorDistance());
refreshTable();
}
}));
elongateButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, true));
Button squashButton = new Button(shapeComp, SWT.PUSH | SWT.FILL);
squashButton.setText("Squash");
squashButton.setToolTipText("Make rings more circular");
squashButton.addMouseListener(new RepeatingMouseAdapter(display, new SlowFastRunnable() {
@Override
public void run() {
DiffractionCalibrationUtils.changeRings(currentData, ManipulateMode.SQUASH, isFast());
}
@Override
public void stop() {
// updateDiffTool(DISTANCE_NODE_PATH, currentData.md.getDetector2DProperties().getDetectorDistance());
refreshTable();
}
}));
squashButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, true));
Composite rotateComp = new Composite(actionComp, SWT.BORDER);
rotateComp.setLayout(new GridLayout(1, false));
rotateComp.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, true));
rotateComp.setToolTipText("Change rotation");
Button clockButton = new Button(rotateComp, SWT.PUSH);
clockButton.setImage(Activator.getImage("icons/arrow_rotate_clockwise.png"));
clockButton.setToolTipText("Rotate rings clockwise");
clockButton.addMouseListener(new RepeatingMouseAdapter(display, new SlowFastRunnable() {
@Override
public void run() {
DiffractionCalibrationUtils.changeRings(currentData, ManipulateMode.CLOCKWISE, isFast());
}
@Override
public void stop() {
refreshTable();
}
}));
clockButton.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false));
Button antiClockButton = new Button(rotateComp, SWT.PUSH);
antiClockButton.setImage(Activator.getImage("icons/arrow_rotate_anticlockwise.png"));
antiClockButton.setToolTipText("Rotate rings anti-clockwise");
antiClockButton.addMouseListener(new RepeatingMouseAdapter(display, new SlowFastRunnable() {
@Override
public void run() {
DiffractionCalibrationUtils.changeRings(currentData, ManipulateMode.ANTICLOCKWISE, isFast());
}
@Override
public void stop() {
refreshTable();
}
}));
antiClockButton.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false));
Composite calibrateComp = new Composite(mainControlComp, SWT.NONE);
calibrateComp.setLayout(new GridLayout(1, false));
calibrateComp.setLayoutData(new GridData(SWT.FILL, SWT.TOP, false, false));
try{
RadioUtils.createRadioControls(calibrateComp, createWavelengthRadioActions());
} catch (Exception e) {
logger.error("Could not create controls:"+e);
}
Group wavelengthComp = new Group(calibrateComp, SWT.NONE);
wavelengthComp.setText("X-Rays");
wavelengthComp.setToolTipText("Set the wavelength / energy");
wavelengthComp.setLayout(new GridLayout(3, false));
wavelengthComp.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false));
Label wavelengthLabel = new Label(wavelengthComp, SWT.NONE);
wavelengthLabel.setText("Wavelength");
wavelengthDistanceSpinner = new FloatSpinner(wavelengthComp, SWT.BORDER);
wavelengthDistanceSpinner.setDouble(0);
wavelengthDistanceSpinner.setFormat(7, 5);
wavelengthDistanceSpinner.setMinimum(0);
wavelengthDistanceSpinner.setMaximum(Double.MAX_VALUE);
wavelengthDistanceSpinner.setIncrement(0.001);
wavelengthDistanceSpinner.setToolTipText("Set the wavelength in Angstrom");
wavelengthDistanceSpinner.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
// update wavelength of each image
for(int i = 0; i < model.size(); i++){
model.get(i).md.getDiffractionCrystalEnvironment().setWavelength(wavelengthDistanceSpinner.getDouble());
}
// update wavelength in keV
wavelengthEnergySpinner.setDouble(getWavelengthEnergy(wavelengthDistanceSpinner.getDouble()));
// update wavelength in diffraction tool tree viewer
NumericNode<Length> node = getDiffractionTreeNode(WAVELENGTH_NODE_PATH);
if (node.getUnit().equals(NonSI.ANGSTROM)) {
updateDiffTool(WAVELENGTH_NODE_PATH, wavelengthDistanceSpinner.getDouble());
} else if (node.getUnit().equals(NonSI.ELECTRON_VOLT)) {
updateDiffTool(WAVELENGTH_NODE_PATH, getWavelengthEnergy(wavelengthDistanceSpinner.getDouble()) * 1000);
} else if (node.getUnit().equals(SI.KILO(NonSI.ELECTRON_VOLT))) {
updateDiffTool(WAVELENGTH_NODE_PATH, getWavelengthEnergy(wavelengthDistanceSpinner.getDouble()));
}
}
});
wavelengthDistanceSpinner.setEnabled(false);
Label unitDistanceLabel = new Label(wavelengthComp, SWT.NONE);
unitDistanceLabel.setText(NonSI.ANGSTROM.toString());
Label energyLabel = new Label(wavelengthComp, SWT.NONE);
energyLabel.setText("Energy");
wavelengthEnergySpinner = new FloatSpinner(wavelengthComp, SWT.BORDER);
wavelengthEnergySpinner.setDouble(0);
wavelengthEnergySpinner.setFormat(7, 5);
wavelengthEnergySpinner.setMinimum(0);
wavelengthEnergySpinner.setMaximum(Double.MAX_VALUE);
wavelengthEnergySpinner.setIncrement(0.001);
wavelengthEnergySpinner.setToolTipText("Set the wavelength in keV");
wavelengthEnergySpinner.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
// update wavelength of each image
for(int i = 0; i < model.size(); i++){
model.get(i).md.getDiffractionCrystalEnvironment().setWavelength(getWavelengthDistance(wavelengthEnergySpinner.getDouble()));
}
// update wavelength in Angstrom
wavelengthDistanceSpinner.setDouble(getWavelengthDistance(wavelengthEnergySpinner.getDouble()));
// update wavelength in Diffraction tool tree viewer
NumericNode<Length> node = getDiffractionTreeNode(WAVELENGTH_NODE_PATH);
if (node.getUnit().equals(NonSI.ANGSTROM)) {
updateDiffTool(WAVELENGTH_NODE_PATH, getWavelengthDistance(wavelengthEnergySpinner.getDouble()));
} else if (node.getUnit().equals(NonSI.ELECTRON_VOLT)) {
updateDiffTool(WAVELENGTH_NODE_PATH, wavelengthEnergySpinner.getDouble() * 1000);
} else if (node.getUnit().equals(SI.KILO(NonSI.ELECTRON_VOLT))) {
updateDiffTool(WAVELENGTH_NODE_PATH, wavelengthEnergySpinner.getDouble());
}
}
});
wavelengthEnergySpinner.setEnabled(false);
Label unitEnergyLabel = new Label(wavelengthComp, SWT.NONE);
unitEnergyLabel.setText(SI.KILO(NonSI.ELECTRON_VOLT).toString());
Composite processComp = new Composite(calibrantHolder, SWT.NONE);
processComp.setLayout(new GridLayout(2, false));
processComp.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false));
Button findRingButton = new Button(processComp, SWT.PUSH);
findRingButton.setText("Find rings in image");
findRingButton.setToolTipText("Use pixel values to find rings in image near calibration rings");
findRingButton.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false));
findRingButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
Job findRingsJob = DiffractionCalibrationUtils.findRings(display, plottingSystem, currentData);
if (findRingsJob == null)
return;
findRingsJob.addJobChangeListener(new JobChangeAdapter() {
@Override
public void done(IJobChangeEvent event) {
display.asyncExec(new Runnable() {
@Override
public void run() {
if (currentData != null && currentData.nrois > 0) {
setCalibrateButtons();
}
refreshTable();
}
});
}
});
findRingsJob.schedule();
}
});
calibrateImages = new Button(processComp, SWT.PUSH);
calibrateImages.setText("Run Calibration Process");
calibrateImages.setToolTipText("Calibrate detector in chosen images");
calibrateImages.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false));
calibrateImages.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (model.size() <= 0)
return;
Job calibrateJob = DiffractionCalibrationUtils.calibrateImages(display, plottingSystem, model, currentData,
refineWithDistance || refineAfterDistance,
refineAfterDistance);
if (calibrateJob == null)
return;
calibrateJob.addJobChangeListener(new JobChangeAdapter() {
@Override
public void done(IJobChangeEvent event) {
display.asyncExec(new Runnable() {
public void run() {
refreshTable();
setCalibrateButtons();
}
});
}
});
calibrateJob.schedule();
}
});
calibrateImages.setEnabled(false);
scrollHolder.layout();
scrollComposite.setContent(scrollHolder);
scrollComposite.setExpandHorizontal(true);
scrollComposite.setExpandVertical(true);
scrollComposite.setMinSize(scrollHolder.computeSize(SWT.DEFAULT, SWT.DEFAULT));
scrollComposite.layout();
// end of Diffraction Calibration controls
// start plotting system
Composite plotComp = new Composite(mainSash, SWT.NONE);
plotComp.setLayout(new GridLayout(1, false));
plotComp.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
try {
ActionBarWrapper actionBarWrapper = ActionBarWrapper.createActionBars(plotComp, null);
plottingSystem = PlottingFactory.createPlottingSystem();
plottingSystem.createPlotPart(plotComp, "", actionBarWrapper, PlotType.IMAGE, this);
plottingSystem.setTitle("");
plottingSystem.getPlotComposite().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
} catch (Exception e1) {
logger.error("Could not create plotting system:"+ e1);
}
// try to load the previous data saved in the memento
DiffractionTableData good = null;
for (String p : pathsList) {
if (!p.endsWith(".nxs")) {
DiffractionTableData d = createData(p, null);
if (good == null && d != null) {
good = d;
setWavelength(d);
}
}
}
tableViewer.refresh();
if (good != null) {
final DiffractionTableData g = good;
display.asyncExec(new Runnable() { // this is necessary to give the plotting system time to lay out itself
@Override
public void run() {
tableViewer.setSelection(new StructuredSelection(g));
}
});
}
if (model.size() > 0) {
wavelengthDistanceSpinner.setEnabled(true);
wavelengthEnergySpinner.setEnabled(true);
}
// start diffraction tool
Composite diffractionToolComp = new Composite(leftSash, SWT.BORDER);
diffractionToolComp.setLayout(new FillLayout());
try {
toolSystem = (IToolPageSystem)plottingSystem.getAdapter(IToolPageSystem.class);
// Show tools here, not on a page.
toolSystem.setToolComposite(diffractionToolComp);
toolSystem.setToolVisible(DIFFRACTION_ID, ToolPageRole.ROLE_2D, null);
} catch (Exception e2) {
logger.error("Could not open diffraction tool:"+ e2);
}
IActionBars bars = getViewSite().getActionBars();
bars.getToolBarManager().add(resetAction);
//mainSash.setWeights(new int[] { 1, 2});
}
private List<Entry<String, Action>> createWavelengthRadioActions(){
List<Entry<String, Action>> radioActions = new ArrayList<Entry<String, Action>>();
Entry<String, Action> noNormalisation = new AbstractMap.SimpleEntry<String, Action>("Do not refine wavelength",
new Action("NoRefine") {
@Override
public void run() {
refineAfterDistance = false;
refineWithDistance = false;
}
}
);
Entry<String, Action> roiNormalisation = new AbstractMap.SimpleEntry<String, Action>("Refine wavelength after distance",
new Action("AfterDistance") {
@Override
public void run() {
refineAfterDistance = true;
refineWithDistance = false;
}
}
);
Entry<String, Action> auxNormalisation = new AbstractMap.SimpleEntry<String, Action>("Refine wavelength with distance",
new Action("WithDistance") {
@Override
public void run() {
refineAfterDistance = false;
refineWithDistance = true;
}
}
);
radioActions.add(noNormalisation);
radioActions.add(roiNormalisation);
radioActions.add(auxNormalisation);
return radioActions;
}
private void updateDiffTool(String nodePath, double value) {
DiffractionTool diffTool = (DiffractionTool) toolSystem.getToolPage(DIFFRACTION_ID);
DiffractionTreeModel treeModel = diffTool.getModel();
NumericNode<Length> distanceNode = getDiffractionTreeNode(nodePath);
distanceNode.setDoubleValue(value);
treeModel.setNode(distanceNode, nodePath);
diffTool.refresh();
}
@SuppressWarnings("unchecked")
private NumericNode<Length> getDiffractionTreeNode(String nodePath) {
NumericNode<Length> node = null;
if (toolSystem == null)
return node;
DiffractionTool diffTool = (DiffractionTool) toolSystem.getToolPage(DIFFRACTION_ID);
DiffractionTreeModel treeModel = diffTool.getModel();
if(treeModel == null)
return node;
node = (NumericNode<Length>) treeModel.getNode(nodePath);
return node;
}
private void setWavelength(DiffractionTableData data){
// set the wavelength
if(wavelengthDistanceSpinner.getDouble() == 0 && wavelengthEnergySpinner.getDouble() == 0){
if(data != null){
wavelength = data.md.getOriginalDiffractionCrystalEnvironment().getWavelength();
wavelengthDistanceSpinner.setDouble(wavelength);
wavelengthEnergySpinner.setDouble(getWavelengthEnergy(wavelength));
}
}
}
private double getWavelengthEnergy(double angstrom) {
return 1./(0.0806554465 * angstrom); // constant from NIST CODATA 2006
}
private double getWavelengthDistance(double keV) {
return 1./(0.0806554465*keV); // constant from NIST CODATA 2006
}
private DiffractionTableData createData(String filePath, String dataFullName) {
// Test if the selection has already been loaded and is in the model
DiffractionTableData data = null;
if (filePath == null)
return data;
for (DiffractionTableData d : model) {
if (filePath.equals(d.path)) {
data = d;
break;
}
}
if (data == null) {
IDataset image = PlottingUtils.loadData(filePath, dataFullName);
if (image == null)
return data;
int j = filePath.lastIndexOf(File.separator);
String fileName = j > 0 ? filePath.substring(j + 1) : null;
image.setName(fileName + ":" + image.getName());
data = new DiffractionTableData();
data.path = filePath;
data.name = fileName;
data.image = image;
String[] statusString = new String[1];
data.md = DiffractionTool.getDiffractionMetadata(image, filePath, service, statusString);
model.add(data);
}
return data;
}
private void drawSelectedData(DiffractionTableData data) {
if (currentData != null) {
DiffractionImageAugmenter aug = currentData.augmenter;
if (aug != null)
aug.deactivate();
}
if (data.image == null)
return;
plottingSystem.clear();
plottingSystem.updatePlot2D(data.image, null, null);
plottingSystem.setTitle(data.name);
plottingSystem.getAxes().get(0).setTitle("");
plottingSystem.getAxes().get(1).setTitle("");
plottingSystem.setKeepAspect(true);
plottingSystem.setShowIntensity(false);
currentData = data;
DiffractionImageAugmenter aug = data.augmenter;
if (aug == null) {
aug = new DiffractionImageAugmenter(plottingSystem);
data.augmenter = aug;
}
aug.activate();
if (data.md != null) {
aug.setDiffractionMetadata(data.md);
// Add listeners to monitor metadata changes in diffraction tool
data.md.getDetector2DProperties().addDetectorPropertyListener(detectorPropertyListener);
data.md.getDiffractionCrystalEnvironment().addDiffractionCrystalEnvironmentListener(diffractionCrystEnvListener);
}
DiffractionCalibrationUtils.hideFoundRings(plottingSystem);
DiffractionCalibrationUtils.drawCalibrantRings(aug);
}
@SuppressWarnings("rawtypes")
@Override
public Object getAdapter(Class key) {
if (key==IPlottingSystem.class) {
return plottingSystem;
} else if (key==IToolPageSystem.class) {
return plottingSystem.getAdapter(IToolPageSystem.class);
}
return super.getAdapter(key);
}
class MyContentProvider implements IStructuredContentProvider {
@Override
public void dispose() {
}
@Override
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
}
@Override
public Object[] getElements(Object inputElement) {
if (inputElement == null) {
return null;
}
return ((List<?>) inputElement).toArray();
}
}
private static final Image TICKED = Activator.getImageDescriptor("icons/ticked.png").createImage();
private static final Image UNTICKED = Activator.getImageDescriptor("icons/unticked.gif").createImage();
class MyLabelProvider implements ITableLabelProvider {
@Override
public void addListener(ILabelProviderListener listener) {}
@Override
public void dispose() {}
@Override
public boolean isLabelProperty(Object element, String property) {
return true;
}
@Override
public void removeListener(ILabelProviderListener listener) {
}
@Override
public Image getColumnImage(Object element, int columnIndex) {
if (columnIndex != 0)
return null;
if (element == null)
return null;
DiffractionTableData data = (DiffractionTableData) element;
if (data.use)
return TICKED;
return UNTICKED;
}
@Override
public String getColumnText(Object element, int columnIndex) {
if (columnIndex == 0)
return null;
if (element == null)
return null;
DiffractionTableData data = (DiffractionTableData) element;
if (columnIndex == 1) {
return data.name;
} else if (columnIndex == 2) {
if (data.rois == null)
return null;
return String.valueOf(data.nrois);
}
IDiffractionMetadata md = data.md;
if (md == null)
return null;
if (columnIndex == 3) {
DetectorProperties dp = md.getDetector2DProperties();
if (dp == null)
return null;
return String.format("%.2f", dp.getDetectorDistance());
} else if (columnIndex == 4) {
DetectorProperties dp = md.getDetector2DProperties();
if (dp == null)
return null;
return String.format("%.0f", dp.getBeamCentreCoords()[0]);
} else if (columnIndex == 5) {
DetectorProperties dp = md.getDetector2DProperties();
if (dp == null)
return null;
return String.format("%.0f", dp.getBeamCentreCoords()[1]);
} else if (columnIndex == 6) {
if (data.use && data.q != null) {
return String.format("%.2f", Math.sqrt(data.q.getResidual()));
}
}
return null;
}
}
class MyEditingSupport extends EditingSupport {
private TableViewer tv;
private int column;
public MyEditingSupport(TableViewer viewer, int col) {
super(viewer);
tv = viewer;
this.column = col;
}
@Override
protected CellEditor getCellEditor(Object element) {
return new CheckboxCellEditor(null, SWT.CHECK);
}
@Override
protected boolean canEdit(Object element) {
if(column == 0)
return true;
else
return false;
}
@Override
protected Object getValue(Object element) {
DiffractionTableData data = (DiffractionTableData) element;
return data.use;
}
@Override
protected void setValue(Object element, Object value) {
if(column == 0){
DiffractionTableData data = (DiffractionTableData) element;
data.use = (Boolean) value;
tv.refresh();
setCalibrateButtons();
}
}
}
private void createColumns(TableViewer tv) {
TableViewerColumn tvc = new TableViewerColumn(tv, SWT.NONE);
tvc.setEditingSupport(new MyEditingSupport(tv, 0));
TableColumn tc = tvc.getColumn();
tc.setText("Use");
tc.setWidth(40);
tvc = new TableViewerColumn(tv, SWT.NONE);
tc = tvc.getColumn();
tc.setText("Image");
tc.setWidth(200);
tvc.setEditingSupport(new MyEditingSupport(tv, 1));
tvc = new TableViewerColumn(tv, SWT.NONE);
tc = tvc.getColumn();
tc.setText("# of rings");
tc.setWidth(75);
tvc.setEditingSupport(new MyEditingSupport(tv, 2));
tvc = new TableViewerColumn(tv, SWT.NONE);
tc = tvc.getColumn();
tc.setText("Distance");
tc.setToolTipText("in mm");
tc.setWidth(70);
tvc.setEditingSupport(new MyEditingSupport(tv, 3));
tvc = new TableViewerColumn(tv, SWT.NONE);
tc = tvc.getColumn();
tc.setText("X Position");
tc.setToolTipText("in Pixel");
tc.setWidth(80);
tvc.setEditingSupport(new MyEditingSupport(tv, 4));
tvc = new TableViewerColumn(tv, SWT.NONE);
tc = tvc.getColumn();
tc.setText("Y Position");
tc.setToolTipText("in Pixel");
tc.setWidth(80);
tvc.setEditingSupport(new MyEditingSupport(tv, 5));
tvc = new TableViewerColumn(tv, SWT.NONE);
tc = tvc.getColumn();
tc.setText("Residuals");
tc.setToolTipText("Root mean of squared residuals from fit");
tc.setWidth(80);
tvc.setEditingSupport(new MyEditingSupport(tv, 5));
}
private void refreshTable() {
if (tableViewer == null)
return;
tableViewer.refresh();
// reset the scroll composite
Rectangle r = scrollHolder.getClientArea();
scrollComposite.setMinSize(scrollHolder.computeSize(r.width, SWT.DEFAULT));
scrollHolder.layout();
}
private void setCalibrateButtons() {
// enable/disable calibrate button according to use column
int used = 0;
for (DiffractionTableData d : model) {
if (d.use) {
used++;
}
}
calibrateImages.setEnabled(used > 0);
}
private void removeListeners() {
tableViewer.removeSelectionChangedListener(selectionChangeListener);
for (DiffractionTableData d : model) {
if (d.augmenter != null)
d.augmenter.deactivate();
d.md.getDetector2DProperties().removeDetectorPropertyListener(detectorPropertyListener);
d.md.getDiffractionCrystalEnvironment().removeDiffractionCrystalEnvironmentListener(diffractionCrystEnvListener);
}
model.clear();
logger.debug("model emptied");
}
@Override
public void dispose() {
super.dispose();
removeListeners();
// FIXME Clear
}
@Override
public void setFocus() {
if(parent != null && !parent.isDisposed())
parent.setFocus();
}
}
| false | true | public void createPartControl(final Composite parent) {
parent.setLayout(new FillLayout());
this.parent = parent;
resetAction = new Action() {
@Override
public void run() {
// select last item in table
if (model != null && model.size() > 0) {
tableViewer.setSelection(new StructuredSelection(model.get(model.size() - 1)));
for (int i = 0; i < model.size(); i++) {
// Restore original metadata
DetectorProperties originalProps = model.get(i).md.getOriginalDetector2DProperties();
DiffractionCrystalEnvironment originalEnvironment = model.get(i).md.getOriginalDiffractionCrystalEnvironment();
model.get(i).md.getDetector2DProperties().restore(originalProps);
model.get(i).md.getDiffractionCrystalEnvironment().restore(originalEnvironment);
}
// update diffraction tool viewer
updateDiffTool(BEAM_CENTRE_XPATH, currentData.md.getDetector2DProperties().getBeamCentreCoords()[0]);
updateDiffTool(BEAM_CENTRE_YPATH, currentData.md.getDetector2DProperties().getBeamCentreCoords()[1]);
updateDiffTool(DISTANCE_NODE_PATH, currentData.md.getDetector2DProperties().getBeamCentreDistance());
// update wavelength
double wavelength = currentData.md.getDiffractionCrystalEnvironment().getWavelength();
wavelengthEnergySpinner.setDouble(getWavelengthEnergy(wavelength));
wavelengthDistanceSpinner.setDouble(wavelength);
// update wavelength in diffraction tool tree viewer
NumericNode<Length> node = getDiffractionTreeNode(WAVELENGTH_NODE_PATH);
if (node.getUnit().equals(NonSI.ANGSTROM)) {
updateDiffTool(WAVELENGTH_NODE_PATH, wavelength);
} else if (node.getUnit().equals(NonSI.ELECTRON_VOLT)) {
updateDiffTool(WAVELENGTH_NODE_PATH, getWavelengthEnergy(wavelength) * 1000);
} else if (node.getUnit().equals(SI.KILO(NonSI.ELECTRON_VOLT))) {
updateDiffTool(WAVELENGTH_NODE_PATH, getWavelengthEnergy(wavelength));
}
tableViewer.refresh();
}
}
};
resetAction.setText("Reset");
resetAction.setToolTipText("Reset metadata");
resetAction.setImageDescriptor(Activator.getImageDescriptor("icons/table_delete.png"));
// selection change listener for table viewer
selectionChangeListener = new ISelectionChangedListener() {
@Override
public void selectionChanged(SelectionChangedEvent event) {
ISelection is = event.getSelection();
if (is instanceof StructuredSelection) {
StructuredSelection structSelection = (StructuredSelection) is;
DiffractionTableData selectedData = (DiffractionTableData) structSelection.getFirstElement();
if (selectedData == null || selectedData == currentData)
return;
drawSelectedData(selectedData);
}
}
};
final Display display = parent.getDisplay();
diffractionCrystEnvListener = new IDiffractionCrystalEnvironmentListener() {
@Override
public void diffractionCrystalEnvironmentChanged(
final DiffractionCrystalEnvironmentEvent evt) {
display.asyncExec(new Runnable() {
@Override
public void run() {
tableViewer.refresh();
}
});
}
};
detectorPropertyListener = new IDetectorPropertyListener() {
@Override
public void detectorPropertiesChanged(DetectorPropertyEvent evt) {
display.asyncExec(new Runnable() {
@Override
public void run() {
tableViewer.refresh();
}
});
}
};
dropListener = new DropTargetAdapter() {
@Override
public void drop(DropTargetEvent event) {
Object dropData = event.data;
DiffractionTableData good = null;
if (dropData instanceof IResource[]) {
IResource[] res = (IResource[]) dropData;
for (int i = 0; i < res.length; i++) {
DiffractionTableData d = createData(res[i].getRawLocation().toOSString(), null);
if (d != null){
good = d;
setWavelength(d);
}
}
} else if (dropData instanceof TreeSelection) {
TreeSelection selectedNode = (TreeSelection) dropData;
Object obj[] = selectedNode.toArray();
for (int i = 0; i < obj.length; i++) {
DiffractionTableData d = null;
if (obj[i] instanceof HDF5NodeLink) {
HDF5NodeLink node = (HDF5NodeLink) obj[i];
if (node == null)
return;
d = createData(node.getFile().getFilename(), node.getFullName());
} else if (obj[i] instanceof IFile) {
IFile file = (IFile) obj[i];
d = createData(file.getLocation().toOSString(), null);
}
if (d != null){
good = d;
setWavelength(d);
}
}
} else if (dropData instanceof String[]) {
String[] selectedData = (String[]) dropData;
for (int i = 0; i < selectedData.length; i++) {
DiffractionTableData d = createData(selectedData[i], null);
if (d != null){
good = d;
setWavelength(d);
}
}
}
tableViewer.refresh();
if (currentData == null && good != null) {
tableViewer.getTable().deselectAll();
tableViewer.setSelection(new StructuredSelection(good));
}
if (model.size() > 0) {
wavelengthDistanceSpinner.setEnabled(true);
wavelengthEnergySpinner.setEnabled(true);
}
}
};
deleteAction = new Action("Delete item", Activator.getImageDescriptor("icons/delete_obj.png")) {
@Override
public void run() {
StructuredSelection selection = (StructuredSelection) tableViewer.getSelection();
DiffractionTableData selectedData = (DiffractionTableData) selection.getFirstElement();
if (model.size() > 0) {
if (model.remove(selectedData)) {
selectedData.augmenter.deactivate();
selectedData.md.getDetector2DProperties().removeDetectorPropertyListener(detectorPropertyListener);
selectedData.md.getDiffractionCrystalEnvironment().removeDiffractionCrystalEnvironmentListener(diffractionCrystEnvListener);
tableViewer.refresh();
}
}
if (!model.isEmpty()) {
drawSelectedData((DiffractionTableData) tableViewer.getElementAt(0));
} else {
currentData = null; // need to reset this
plottingSystem.clear();
wavelengthDistanceSpinner.setEnabled(false);
wavelengthEnergySpinner.setEnabled(false);
}
}
};
// main sash form which contains the left sash and the plotting system
SashForm mainSash = new SashForm(parent, SWT.HORIZONTAL);
mainSash.setBackground(new Color(display, 192, 192, 192));
mainSash.setLayout(new FillLayout());
// left sash form which contains the diffraction calibration controls and the diffraction tool
SashForm leftSash = new SashForm(mainSash, SWT.VERTICAL);
leftSash.setBackground(new Color(display, 192, 192, 192));
leftSash.setLayout(new GridLayout(1, false));
leftSash.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
Composite controlComp = new Composite(leftSash, SWT.NONE);
controlComp.setLayout(new GridLayout(1, false));
Label instructionLabel = new Label(controlComp, SWT.WRAP);
instructionLabel.setText("Drag/drop a file/data to the table below, choose a type of calibrant, " +
"modify the rings using the controls below and tick the checkbox near to the corresponding " +
"image before pressing the calibration buttons.");
instructionLabel.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, true, false));
// make a scrolled composite
scrollComposite = new ScrolledComposite(controlComp, SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
scrollComposite.setLayout(new GridLayout(1, false));
scrollComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
scrollHolder = new Composite(scrollComposite, SWT.NONE);
GridLayout gl = new GridLayout(1, false);
scrollHolder.setLayout(gl);
scrollHolder.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, true));
// table of images and found rings
tableViewer = new TableViewer(scrollHolder, SWT.FULL_SELECTION | SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
createColumns(tableViewer);
tableViewer.getTable().setHeaderVisible(true);
tableViewer.getTable().setLinesVisible(true);
tableViewer.getTable().setToolTipText("Drag/drop file(s)/data to this table");
tableViewer.setContentProvider(new MyContentProvider());
tableViewer.setLabelProvider(new MyLabelProvider());
tableViewer.setInput(model);
tableViewer.getControl().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
tableViewer.addSelectionChangedListener(selectionChangeListener);
tableViewer.refresh();
final MenuManager mgr = new MenuManager();
mgr.setRemoveAllWhenShown(true);
mgr.addMenuListener(new IMenuListener() {
@Override
public void menuAboutToShow(IMenuManager manager) {
IStructuredSelection selection = (IStructuredSelection) tableViewer.getSelection();
if (!selection.isEmpty()) {
deleteAction.setText("Delete "
+ ((DiffractionTableData) selection.getFirstElement()).name);
mgr.add(deleteAction);
}
}
});
tableViewer.getControl().setMenu(mgr.createContextMenu(tableViewer.getControl()));
//add drop support
DropTarget dt = new DropTarget(tableViewer.getControl(), DND.DROP_MOVE| DND.DROP_DEFAULT| DND.DROP_COPY);
dt.setTransfer(new Transfer[] { TextTransfer.getInstance (), FileTransfer.getInstance(),
ResourceTransfer.getInstance(), LocalSelectionTransfer.getTransfer()});
dt.addDropListener(dropListener);
Composite calibrantHolder = new Composite(scrollHolder, SWT.NONE);
calibrantHolder.setLayout(new GridLayout(1, false));
calibrantHolder.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, true));
Composite mainControlComp = new Composite(calibrantHolder, SWT.NONE);
mainControlComp.setLayout(new GridLayout(2, false));
mainControlComp.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false));
Group controllerHolder = new Group(mainControlComp, SWT.BORDER);
controllerHolder.setText("Calibrant selection and positioning");
controllerHolder.setLayout(new GridLayout(2, false));
controllerHolder.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false));
// create calibrant combo
Label l = new Label(controllerHolder, SWT.NONE);
l.setText("Calibrant:");
l.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
calibrant = new Combo(controllerHolder, SWT.READ_ONLY);
final CalibrationStandards standards = CalibrationFactory.getCalibrationStandards();
calibrant.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
standards.setSelectedCalibrant(calibrant.getItem(calibrant.getSelectionIndex()));
DiffractionCalibrationUtils.drawCalibrantRings(currentData.augmenter);
}
});
for (String c : standards.getCalibrantList()) {
calibrant.add(c);
}
String s = standards.getSelectedCalibrant();
if (s != null) {
calibrant.setText(s);
}
calibrant.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false));
Composite padComp = new Composite(controllerHolder, SWT.BORDER);
padComp.setLayout(new GridLayout(5, false));
padComp.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false));
padComp.setToolTipText("Move calibrant");
l = new Label(padComp, SWT.NONE);
l = new Label(padComp, SWT.NONE);
Button upButton = new Button(padComp, SWT.ARROW | SWT.UP);
upButton.setToolTipText("Move rings up");
upButton.addMouseListener(new RepeatingMouseAdapter(display, new SlowFastRunnable() {
@Override
public void run() {
DiffractionCalibrationUtils.changeRings(currentData, ManipulateMode.UP, isFast());
}
@Override
public void stop() {
updateDiffTool(BEAM_CENTRE_YPATH, currentData.md.getDetector2DProperties().getBeamCentreCoords()[1]);
refreshTable();
}
}));
upButton.setLayoutData(new GridData(SWT.CENTER, SWT.BOTTOM, false, false));
l = new Label(padComp, SWT.NONE);
l = new Label(padComp, SWT.NONE);
l = new Label(padComp, SWT.NONE);
Button leftButton = new Button(padComp, SWT.ARROW | SWT.LEFT);
leftButton.setToolTipText("Shift rings left");
leftButton.addMouseListener(new RepeatingMouseAdapter(display, new SlowFastRunnable() {
@Override
public void run() {
DiffractionCalibrationUtils.changeRings(currentData, ManipulateMode.LEFT, isFast());
}
@Override
public void stop() {
updateDiffTool(BEAM_CENTRE_XPATH, currentData.md.getDetector2DProperties().getBeamCentreCoords()[0]);
refreshTable();
}
}));
leftButton.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
l = new Label(padComp, SWT.NONE);
Button rightButton = new Button(padComp, SWT.ARROW | SWT.RIGHT);
rightButton.setToolTipText("Shift rings right");
rightButton.addMouseListener(new RepeatingMouseAdapter(display, new SlowFastRunnable() {
@Override
public void run() {
DiffractionCalibrationUtils.changeRings(currentData, ManipulateMode.RIGHT, isFast());
}
@Override
public void stop() {
updateDiffTool(BEAM_CENTRE_XPATH, currentData.md.getDetector2DProperties().getBeamCentreCoords()[0]);
refreshTable();
}
}));
rightButton.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false));
l = new Label(padComp, SWT.NONE);
l = new Label(padComp, SWT.NONE);
l = new Label(padComp, SWT.NONE);
Button downButton = new Button(padComp, SWT.ARROW | SWT.DOWN);
downButton.setToolTipText("Move rings down");
downButton.addMouseListener(new RepeatingMouseAdapter(display, new SlowFastRunnable() {
@Override
public void run() {
DiffractionCalibrationUtils.changeRings(currentData, ManipulateMode.DOWN, isFast());
}
@Override
public void stop() {
updateDiffTool(BEAM_CENTRE_YPATH, currentData.md.getDetector2DProperties().getBeamCentreCoords()[1]);
refreshTable();
}
}));
downButton.setLayoutData(new GridData(SWT.CENTER, SWT.TOP, false, false));
l = new Label(padComp, SWT.NONE);
l = new Label(padComp, SWT.NONE);
Composite actionComp = new Composite(controllerHolder, SWT.NONE);
actionComp.setLayout(new GridLayout(3, false));
actionComp.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, true));
Composite sizeComp = new Composite(actionComp, SWT.BORDER);
sizeComp.setLayout(new GridLayout(1, false));
sizeComp.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, true));
sizeComp.setToolTipText("Change size");
Button plusButton = new Button(sizeComp, SWT.PUSH);
plusButton.setImage(Activator.getImage("icons/arrow_out.png"));
plusButton.setToolTipText("Make rings larger");
plusButton.addMouseListener(new RepeatingMouseAdapter(display, new SlowFastRunnable() {
@Override
public void run() {
DiffractionCalibrationUtils.changeRings(currentData, ManipulateMode.ENLARGE, isFast());
}
@Override
public void stop() {
updateDiffTool(DISTANCE_NODE_PATH, currentData.md.getDetector2DProperties().getBeamCentreDistance());
refreshTable();
}
}));
plusButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, true));
Button minusButton = new Button(sizeComp, SWT.PUSH);
minusButton.setImage(Activator.getImage("icons/arrow_in.png"));
minusButton.setToolTipText("Make rings smaller");
minusButton.addMouseListener(new RepeatingMouseAdapter(display, new SlowFastRunnable() {
@Override
public void run() {
DiffractionCalibrationUtils.changeRings(currentData, ManipulateMode.SHRINK, isFast());
}
@Override
public void stop() {
updateDiffTool(DISTANCE_NODE_PATH, currentData.md.getDetector2DProperties().getBeamCentreDistance());
refreshTable();
}
}));
minusButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, true));
Composite shapeComp = new Composite(actionComp, SWT.BORDER);
shapeComp.setLayout(new GridLayout(1, false));
shapeComp.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, true));
shapeComp.setToolTipText("Change shape");
Button elongateButton = new Button(shapeComp, SWT.PUSH);
elongateButton.setText("Elongate");
elongateButton.setToolTipText("Make rings more elliptical");
elongateButton.addMouseListener(new RepeatingMouseAdapter(display, new SlowFastRunnable() {
@Override
public void run() {
DiffractionCalibrationUtils.changeRings(currentData, ManipulateMode.ELONGATE, isFast());
}
@Override
public void stop() {
// updateDiffTool(DISTANCE_NODE_PATH, currentData.md.getDetector2DProperties().getDetectorDistance());
refreshTable();
}
}));
elongateButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, true));
Button squashButton = new Button(shapeComp, SWT.PUSH | SWT.FILL);
squashButton.setText("Squash");
squashButton.setToolTipText("Make rings more circular");
squashButton.addMouseListener(new RepeatingMouseAdapter(display, new SlowFastRunnable() {
@Override
public void run() {
DiffractionCalibrationUtils.changeRings(currentData, ManipulateMode.SQUASH, isFast());
}
@Override
public void stop() {
// updateDiffTool(DISTANCE_NODE_PATH, currentData.md.getDetector2DProperties().getDetectorDistance());
refreshTable();
}
}));
squashButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, true));
Composite rotateComp = new Composite(actionComp, SWT.BORDER);
rotateComp.setLayout(new GridLayout(1, false));
rotateComp.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, true));
rotateComp.setToolTipText("Change rotation");
Button clockButton = new Button(rotateComp, SWT.PUSH);
clockButton.setImage(Activator.getImage("icons/arrow_rotate_clockwise.png"));
clockButton.setToolTipText("Rotate rings clockwise");
clockButton.addMouseListener(new RepeatingMouseAdapter(display, new SlowFastRunnable() {
@Override
public void run() {
DiffractionCalibrationUtils.changeRings(currentData, ManipulateMode.CLOCKWISE, isFast());
}
@Override
public void stop() {
refreshTable();
}
}));
clockButton.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false));
Button antiClockButton = new Button(rotateComp, SWT.PUSH);
antiClockButton.setImage(Activator.getImage("icons/arrow_rotate_anticlockwise.png"));
antiClockButton.setToolTipText("Rotate rings anti-clockwise");
antiClockButton.addMouseListener(new RepeatingMouseAdapter(display, new SlowFastRunnable() {
@Override
public void run() {
DiffractionCalibrationUtils.changeRings(currentData, ManipulateMode.ANTICLOCKWISE, isFast());
}
@Override
public void stop() {
refreshTable();
}
}));
antiClockButton.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false));
Composite calibrateComp = new Composite(mainControlComp, SWT.NONE);
calibrateComp.setLayout(new GridLayout(1, false));
calibrateComp.setLayoutData(new GridData(SWT.FILL, SWT.TOP, false, false));
try{
RadioUtils.createRadioControls(calibrateComp, createWavelengthRadioActions());
} catch (Exception e) {
logger.error("Could not create controls:"+e);
}
Group wavelengthComp = new Group(calibrateComp, SWT.NONE);
wavelengthComp.setText("X-Rays");
wavelengthComp.setToolTipText("Set the wavelength / energy");
wavelengthComp.setLayout(new GridLayout(3, false));
wavelengthComp.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false));
Label wavelengthLabel = new Label(wavelengthComp, SWT.NONE);
wavelengthLabel.setText("Wavelength");
wavelengthDistanceSpinner = new FloatSpinner(wavelengthComp, SWT.BORDER);
wavelengthDistanceSpinner.setDouble(0);
wavelengthDistanceSpinner.setFormat(7, 5);
wavelengthDistanceSpinner.setMinimum(0);
wavelengthDistanceSpinner.setMaximum(Double.MAX_VALUE);
wavelengthDistanceSpinner.setIncrement(0.001);
wavelengthDistanceSpinner.setToolTipText("Set the wavelength in Angstrom");
wavelengthDistanceSpinner.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
// update wavelength of each image
for(int i = 0; i < model.size(); i++){
model.get(i).md.getDiffractionCrystalEnvironment().setWavelength(wavelengthDistanceSpinner.getDouble());
}
// update wavelength in keV
wavelengthEnergySpinner.setDouble(getWavelengthEnergy(wavelengthDistanceSpinner.getDouble()));
// update wavelength in diffraction tool tree viewer
NumericNode<Length> node = getDiffractionTreeNode(WAVELENGTH_NODE_PATH);
if (node.getUnit().equals(NonSI.ANGSTROM)) {
updateDiffTool(WAVELENGTH_NODE_PATH, wavelengthDistanceSpinner.getDouble());
} else if (node.getUnit().equals(NonSI.ELECTRON_VOLT)) {
updateDiffTool(WAVELENGTH_NODE_PATH, getWavelengthEnergy(wavelengthDistanceSpinner.getDouble()) * 1000);
} else if (node.getUnit().equals(SI.KILO(NonSI.ELECTRON_VOLT))) {
updateDiffTool(WAVELENGTH_NODE_PATH, getWavelengthEnergy(wavelengthDistanceSpinner.getDouble()));
}
}
});
wavelengthDistanceSpinner.setEnabled(false);
Label unitDistanceLabel = new Label(wavelengthComp, SWT.NONE);
unitDistanceLabel.setText(NonSI.ANGSTROM.toString());
Label energyLabel = new Label(wavelengthComp, SWT.NONE);
energyLabel.setText("Energy");
wavelengthEnergySpinner = new FloatSpinner(wavelengthComp, SWT.BORDER);
wavelengthEnergySpinner.setDouble(0);
wavelengthEnergySpinner.setFormat(7, 5);
wavelengthEnergySpinner.setMinimum(0);
wavelengthEnergySpinner.setMaximum(Double.MAX_VALUE);
wavelengthEnergySpinner.setIncrement(0.001);
wavelengthEnergySpinner.setToolTipText("Set the wavelength in keV");
wavelengthEnergySpinner.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
// update wavelength of each image
for(int i = 0; i < model.size(); i++){
model.get(i).md.getDiffractionCrystalEnvironment().setWavelength(getWavelengthDistance(wavelengthEnergySpinner.getDouble()));
}
// update wavelength in Angstrom
wavelengthDistanceSpinner.setDouble(getWavelengthDistance(wavelengthEnergySpinner.getDouble()));
// update wavelength in Diffraction tool tree viewer
NumericNode<Length> node = getDiffractionTreeNode(WAVELENGTH_NODE_PATH);
if (node.getUnit().equals(NonSI.ANGSTROM)) {
updateDiffTool(WAVELENGTH_NODE_PATH, getWavelengthDistance(wavelengthEnergySpinner.getDouble()));
} else if (node.getUnit().equals(NonSI.ELECTRON_VOLT)) {
updateDiffTool(WAVELENGTH_NODE_PATH, wavelengthEnergySpinner.getDouble() * 1000);
} else if (node.getUnit().equals(SI.KILO(NonSI.ELECTRON_VOLT))) {
updateDiffTool(WAVELENGTH_NODE_PATH, wavelengthEnergySpinner.getDouble());
}
}
});
wavelengthEnergySpinner.setEnabled(false);
Label unitEnergyLabel = new Label(wavelengthComp, SWT.NONE);
unitEnergyLabel.setText(SI.KILO(NonSI.ELECTRON_VOLT).toString());
Composite processComp = new Composite(calibrantHolder, SWT.NONE);
processComp.setLayout(new GridLayout(2, false));
processComp.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false));
Button findRingButton = new Button(processComp, SWT.PUSH);
findRingButton.setText("Find rings in image");
findRingButton.setToolTipText("Use pixel values to find rings in image near calibration rings");
findRingButton.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false));
findRingButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
Job findRingsJob = DiffractionCalibrationUtils.findRings(display, plottingSystem, currentData);
if (findRingsJob == null)
return;
findRingsJob.addJobChangeListener(new JobChangeAdapter() {
@Override
public void done(IJobChangeEvent event) {
display.asyncExec(new Runnable() {
@Override
public void run() {
if (currentData != null && currentData.nrois > 0) {
setCalibrateButtons();
}
refreshTable();
}
});
}
});
findRingsJob.schedule();
}
});
calibrateImages = new Button(processComp, SWT.PUSH);
calibrateImages.setText("Run Calibration Process");
calibrateImages.setToolTipText("Calibrate detector in chosen images");
calibrateImages.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false));
calibrateImages.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (model.size() <= 0)
return;
Job calibrateJob = DiffractionCalibrationUtils.calibrateImages(display, plottingSystem, model, currentData,
refineWithDistance || refineAfterDistance,
refineAfterDistance);
if (calibrateJob == null)
return;
calibrateJob.addJobChangeListener(new JobChangeAdapter() {
@Override
public void done(IJobChangeEvent event) {
display.asyncExec(new Runnable() {
public void run() {
refreshTable();
setCalibrateButtons();
}
});
}
});
calibrateJob.schedule();
}
});
calibrateImages.setEnabled(false);
scrollHolder.layout();
scrollComposite.setContent(scrollHolder);
scrollComposite.setExpandHorizontal(true);
scrollComposite.setExpandVertical(true);
scrollComposite.setMinSize(scrollHolder.computeSize(SWT.DEFAULT, SWT.DEFAULT));
scrollComposite.layout();
// end of Diffraction Calibration controls
// start plotting system
Composite plotComp = new Composite(mainSash, SWT.NONE);
plotComp.setLayout(new GridLayout(1, false));
plotComp.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
try {
ActionBarWrapper actionBarWrapper = ActionBarWrapper.createActionBars(plotComp, null);
plottingSystem = PlottingFactory.createPlottingSystem();
plottingSystem.createPlotPart(plotComp, "", actionBarWrapper, PlotType.IMAGE, this);
plottingSystem.setTitle("");
plottingSystem.getPlotComposite().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
} catch (Exception e1) {
logger.error("Could not create plotting system:"+ e1);
}
// try to load the previous data saved in the memento
DiffractionTableData good = null;
for (String p : pathsList) {
if (!p.endsWith(".nxs")) {
DiffractionTableData d = createData(p, null);
if (good == null && d != null) {
good = d;
setWavelength(d);
}
}
}
tableViewer.refresh();
if (good != null) {
final DiffractionTableData g = good;
display.asyncExec(new Runnable() { // this is necessary to give the plotting system time to lay out itself
@Override
public void run() {
tableViewer.setSelection(new StructuredSelection(g));
}
});
}
if (model.size() > 0) {
wavelengthDistanceSpinner.setEnabled(true);
wavelengthEnergySpinner.setEnabled(true);
}
// start diffraction tool
Composite diffractionToolComp = new Composite(leftSash, SWT.BORDER);
diffractionToolComp.setLayout(new FillLayout());
try {
toolSystem = (IToolPageSystem)plottingSystem.getAdapter(IToolPageSystem.class);
// Show tools here, not on a page.
toolSystem.setToolComposite(diffractionToolComp);
toolSystem.setToolVisible(DIFFRACTION_ID, ToolPageRole.ROLE_2D, null);
} catch (Exception e2) {
logger.error("Could not open diffraction tool:"+ e2);
}
IActionBars bars = getViewSite().getActionBars();
bars.getToolBarManager().add(resetAction);
//mainSash.setWeights(new int[] { 1, 2});
}
| public void createPartControl(final Composite parent) {
parent.setLayout(new FillLayout());
this.parent = parent;
resetAction = new Action() {
@Override
public void run() {
// select last item in table
if (model != null && model.size() > 0) {
tableViewer.setSelection(new StructuredSelection(model.get(model.size() - 1)));
for (int i = 0; i < model.size(); i++) {
// Restore original metadata
DetectorProperties originalProps = model.get(i).md.getOriginalDetector2DProperties();
DiffractionCrystalEnvironment originalEnvironment = model.get(i).md.getOriginalDiffractionCrystalEnvironment();
model.get(i).md.getDetector2DProperties().restore(originalProps);
model.get(i).md.getDiffractionCrystalEnvironment().restore(originalEnvironment);
}
// update diffraction tool viewer
updateDiffTool(BEAM_CENTRE_XPATH, currentData.md.getDetector2DProperties().getBeamCentreCoords()[0]);
updateDiffTool(BEAM_CENTRE_YPATH, currentData.md.getDetector2DProperties().getBeamCentreCoords()[1]);
updateDiffTool(DISTANCE_NODE_PATH, currentData.md.getDetector2DProperties().getBeamCentreDistance());
// update wavelength
double wavelength = currentData.md.getDiffractionCrystalEnvironment().getWavelength();
wavelengthEnergySpinner.setDouble(getWavelengthEnergy(wavelength));
wavelengthDistanceSpinner.setDouble(wavelength);
// update wavelength in diffraction tool tree viewer
NumericNode<Length> node = getDiffractionTreeNode(WAVELENGTH_NODE_PATH);
if (node.getUnit().equals(NonSI.ANGSTROM)) {
updateDiffTool(WAVELENGTH_NODE_PATH, wavelength);
} else if (node.getUnit().equals(NonSI.ELECTRON_VOLT)) {
updateDiffTool(WAVELENGTH_NODE_PATH, getWavelengthEnergy(wavelength) * 1000);
} else if (node.getUnit().equals(SI.KILO(NonSI.ELECTRON_VOLT))) {
updateDiffTool(WAVELENGTH_NODE_PATH, getWavelengthEnergy(wavelength));
}
tableViewer.refresh();
}
}
};
resetAction.setText("Reset");
resetAction.setToolTipText("Reset metadata");
resetAction.setImageDescriptor(Activator.getImageDescriptor("icons/table_delete.png"));
// selection change listener for table viewer
selectionChangeListener = new ISelectionChangedListener() {
@Override
public void selectionChanged(SelectionChangedEvent event) {
ISelection is = event.getSelection();
if (is instanceof StructuredSelection) {
StructuredSelection structSelection = (StructuredSelection) is;
DiffractionTableData selectedData = (DiffractionTableData) structSelection.getFirstElement();
if (selectedData == null || selectedData == currentData)
return;
drawSelectedData(selectedData);
}
}
};
final Display display = parent.getDisplay();
diffractionCrystEnvListener = new IDiffractionCrystalEnvironmentListener() {
@Override
public void diffractionCrystalEnvironmentChanged(
final DiffractionCrystalEnvironmentEvent evt) {
display.asyncExec(new Runnable() {
@Override
public void run() {
tableViewer.refresh();
}
});
}
};
detectorPropertyListener = new IDetectorPropertyListener() {
@Override
public void detectorPropertiesChanged(DetectorPropertyEvent evt) {
display.asyncExec(new Runnable() {
@Override
public void run() {
tableViewer.refresh();
}
});
}
};
dropListener = new DropTargetAdapter() {
@Override
public void drop(DropTargetEvent event) {
Object dropData = event.data;
DiffractionTableData good = null;
if (dropData instanceof IResource[]) {
IResource[] res = (IResource[]) dropData;
for (int i = 0; i < res.length; i++) {
DiffractionTableData d = createData(res[i].getRawLocation().toOSString(), null);
if (d != null){
good = d;
setWavelength(d);
}
}
} else if (dropData instanceof TreeSelection) {
TreeSelection selectedNode = (TreeSelection) dropData;
Object obj[] = selectedNode.toArray();
for (int i = 0; i < obj.length; i++) {
DiffractionTableData d = null;
if (obj[i] instanceof HDF5NodeLink) {
HDF5NodeLink node = (HDF5NodeLink) obj[i];
if (node == null)
return;
d = createData(node.getFile().getFilename(), node.getFullName());
} else if (obj[i] instanceof IFile) {
IFile file = (IFile) obj[i];
d = createData(file.getLocation().toOSString(), null);
}
if (d != null){
good = d;
setWavelength(d);
}
}
} else if (dropData instanceof String[]) {
String[] selectedData = (String[]) dropData;
for (int i = 0; i < selectedData.length; i++) {
DiffractionTableData d = createData(selectedData[i], null);
if (d != null){
good = d;
setWavelength(d);
}
}
}
tableViewer.refresh();
if (currentData == null && good != null) {
tableViewer.getTable().deselectAll();
tableViewer.setSelection(new StructuredSelection(good));
}
if (model.size() > 0) {
wavelengthDistanceSpinner.setEnabled(true);
wavelengthEnergySpinner.setEnabled(true);
}
}
};
deleteAction = new Action("Delete item", Activator.getImageDescriptor("icons/delete_obj.png")) {
@Override
public void run() {
StructuredSelection selection = (StructuredSelection) tableViewer.getSelection();
DiffractionTableData selectedData = (DiffractionTableData) selection.getFirstElement();
if (model.size() > 0) {
if (model.remove(selectedData)) {
selectedData.augmenter.deactivate();
selectedData.md.getDetector2DProperties().removeDetectorPropertyListener(detectorPropertyListener);
selectedData.md.getDiffractionCrystalEnvironment().removeDiffractionCrystalEnvironmentListener(diffractionCrystEnvListener);
tableViewer.refresh();
}
}
if (!model.isEmpty()) {
drawSelectedData((DiffractionTableData) tableViewer.getElementAt(0));
} else {
currentData = null; // need to reset this
plottingSystem.clear();
wavelengthDistanceSpinner.setEnabled(false);
wavelengthEnergySpinner.setEnabled(false);
}
}
};
// main sash form which contains the left sash and the plotting system
SashForm mainSash = new SashForm(parent, SWT.HORIZONTAL);
mainSash.setBackground(new Color(display, 192, 192, 192));
mainSash.setLayout(new FillLayout());
// left sash form which contains the diffraction calibration controls and the diffraction tool
SashForm leftSash = new SashForm(mainSash, SWT.VERTICAL);
leftSash.setBackground(new Color(display, 192, 192, 192));
leftSash.setLayout(new GridLayout(1, false));
leftSash.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
Composite controlComp = new Composite(leftSash, SWT.NONE);
controlComp.setLayout(new GridLayout(1, false));
Label instructionLabel = new Label(controlComp, SWT.WRAP);
instructionLabel.setText("Drag/drop a file/data to the table below, choose a type of calibrant, " +
"modify the rings using the controls below and tick the checkbox near to the corresponding " +
"image before pressing the calibration buttons.");
instructionLabel.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, true, false));
// make a scrolled composite
scrollComposite = new ScrolledComposite(controlComp, SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
scrollComposite.setLayout(new GridLayout(1, false));
scrollComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
scrollHolder = new Composite(scrollComposite, SWT.NONE);
GridLayout gl = new GridLayout(1, false);
scrollHolder.setLayout(gl);
scrollHolder.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, true));
// table of images and found rings
tableViewer = new TableViewer(scrollHolder, SWT.FULL_SELECTION | SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
createColumns(tableViewer);
tableViewer.getTable().setHeaderVisible(true);
tableViewer.getTable().setLinesVisible(true);
tableViewer.getTable().setToolTipText("Drag/drop file(s)/data to this table");
tableViewer.setContentProvider(new MyContentProvider());
tableViewer.setLabelProvider(new MyLabelProvider());
tableViewer.setInput(model);
tableViewer.getControl().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
tableViewer.addSelectionChangedListener(selectionChangeListener);
tableViewer.refresh();
final MenuManager mgr = new MenuManager();
mgr.setRemoveAllWhenShown(true);
mgr.addMenuListener(new IMenuListener() {
@Override
public void menuAboutToShow(IMenuManager manager) {
IStructuredSelection selection = (IStructuredSelection) tableViewer.getSelection();
if (!selection.isEmpty()) {
deleteAction.setText("Delete "
+ ((DiffractionTableData) selection.getFirstElement()).name);
mgr.add(deleteAction);
}
}
});
tableViewer.getControl().setMenu(mgr.createContextMenu(tableViewer.getControl()));
//add drop support
DropTarget dt = new DropTarget(tableViewer.getControl(), DND.DROP_MOVE| DND.DROP_DEFAULT| DND.DROP_COPY);
dt.setTransfer(new Transfer[] { TextTransfer.getInstance (), FileTransfer.getInstance(),
ResourceTransfer.getInstance(), LocalSelectionTransfer.getTransfer()});
dt.addDropListener(dropListener);
Composite calibrantHolder = new Composite(scrollHolder, SWT.NONE);
calibrantHolder.setLayout(new GridLayout(1, false));
calibrantHolder.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, true));
Composite mainControlComp = new Composite(calibrantHolder, SWT.NONE);
mainControlComp.setLayout(new GridLayout(2, false));
mainControlComp.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false));
Group controllerHolder = new Group(mainControlComp, SWT.BORDER);
controllerHolder.setText("Calibrant selection and positioning");
controllerHolder.setLayout(new GridLayout(2, false));
controllerHolder.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false));
// create calibrant combo
Label l = new Label(controllerHolder, SWT.NONE);
l.setText("Calibrant:");
l.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
calibrant = new Combo(controllerHolder, SWT.READ_ONLY);
final CalibrationStandards standards = CalibrationFactory.getCalibrationStandards();
calibrant.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (currentData == null) return;
standards.setSelectedCalibrant(calibrant.getItem(calibrant.getSelectionIndex()));
DiffractionCalibrationUtils.drawCalibrantRings(currentData.augmenter);
}
});
for (String c : standards.getCalibrantList()) {
calibrant.add(c);
}
String s = standards.getSelectedCalibrant();
if (s != null) {
calibrant.setText(s);
}
calibrant.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false));
Composite padComp = new Composite(controllerHolder, SWT.BORDER);
padComp.setLayout(new GridLayout(5, false));
padComp.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false));
padComp.setToolTipText("Move calibrant");
l = new Label(padComp, SWT.NONE);
l = new Label(padComp, SWT.NONE);
Button upButton = new Button(padComp, SWT.ARROW | SWT.UP);
upButton.setToolTipText("Move rings up");
upButton.addMouseListener(new RepeatingMouseAdapter(display, new SlowFastRunnable() {
@Override
public void run() {
DiffractionCalibrationUtils.changeRings(currentData, ManipulateMode.UP, isFast());
}
@Override
public void stop() {
if (currentData == null) return;
updateDiffTool(BEAM_CENTRE_YPATH, currentData.md.getDetector2DProperties().getBeamCentreCoords()[1]);
refreshTable();
}
}));
upButton.setLayoutData(new GridData(SWT.CENTER, SWT.BOTTOM, false, false));
l = new Label(padComp, SWT.NONE);
l = new Label(padComp, SWT.NONE);
l = new Label(padComp, SWT.NONE);
Button leftButton = new Button(padComp, SWT.ARROW | SWT.LEFT);
leftButton.setToolTipText("Shift rings left");
leftButton.addMouseListener(new RepeatingMouseAdapter(display, new SlowFastRunnable() {
@Override
public void run() {
DiffractionCalibrationUtils.changeRings(currentData, ManipulateMode.LEFT, isFast());
}
@Override
public void stop() {
if (currentData == null) return;
updateDiffTool(BEAM_CENTRE_XPATH, currentData.md.getDetector2DProperties().getBeamCentreCoords()[0]);
refreshTable();
}
}));
leftButton.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
l = new Label(padComp, SWT.NONE);
Button rightButton = new Button(padComp, SWT.ARROW | SWT.RIGHT);
rightButton.setToolTipText("Shift rings right");
rightButton.addMouseListener(new RepeatingMouseAdapter(display, new SlowFastRunnable() {
@Override
public void run() {
DiffractionCalibrationUtils.changeRings(currentData, ManipulateMode.RIGHT, isFast());
}
@Override
public void stop() {
if (currentData == null) return;
updateDiffTool(BEAM_CENTRE_XPATH, currentData.md.getDetector2DProperties().getBeamCentreCoords()[0]);
refreshTable();
}
}));
rightButton.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false));
l = new Label(padComp, SWT.NONE);
l = new Label(padComp, SWT.NONE);
l = new Label(padComp, SWT.NONE);
Button downButton = new Button(padComp, SWT.ARROW | SWT.DOWN);
downButton.setToolTipText("Move rings down");
downButton.addMouseListener(new RepeatingMouseAdapter(display, new SlowFastRunnable() {
@Override
public void run() {
DiffractionCalibrationUtils.changeRings(currentData, ManipulateMode.DOWN, isFast());
}
@Override
public void stop() {
if (currentData == null) return;
updateDiffTool(BEAM_CENTRE_YPATH, currentData.md.getDetector2DProperties().getBeamCentreCoords()[1]);
refreshTable();
}
}));
downButton.setLayoutData(new GridData(SWT.CENTER, SWT.TOP, false, false));
l = new Label(padComp, SWT.NONE);
l = new Label(padComp, SWT.NONE);
Composite actionComp = new Composite(controllerHolder, SWT.NONE);
actionComp.setLayout(new GridLayout(3, false));
actionComp.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, true));
Composite sizeComp = new Composite(actionComp, SWT.BORDER);
sizeComp.setLayout(new GridLayout(1, false));
sizeComp.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, true));
sizeComp.setToolTipText("Change size");
Button plusButton = new Button(sizeComp, SWT.PUSH);
plusButton.setImage(Activator.getImage("icons/arrow_out.png"));
plusButton.setToolTipText("Make rings larger");
plusButton.addMouseListener(new RepeatingMouseAdapter(display, new SlowFastRunnable() {
@Override
public void run() {
DiffractionCalibrationUtils.changeRings(currentData, ManipulateMode.ENLARGE, isFast());
}
@Override
public void stop() {
if (currentData == null) return;
updateDiffTool(DISTANCE_NODE_PATH, currentData.md.getDetector2DProperties().getBeamCentreDistance());
refreshTable();
}
}));
plusButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, true));
Button minusButton = new Button(sizeComp, SWT.PUSH);
minusButton.setImage(Activator.getImage("icons/arrow_in.png"));
minusButton.setToolTipText("Make rings smaller");
minusButton.addMouseListener(new RepeatingMouseAdapter(display, new SlowFastRunnable() {
@Override
public void run() {
DiffractionCalibrationUtils.changeRings(currentData, ManipulateMode.SHRINK, isFast());
}
@Override
public void stop() {
if (currentData == null) return;
updateDiffTool(DISTANCE_NODE_PATH, currentData.md.getDetector2DProperties().getBeamCentreDistance());
refreshTable();
}
}));
minusButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, true));
Composite shapeComp = new Composite(actionComp, SWT.BORDER);
shapeComp.setLayout(new GridLayout(1, false));
shapeComp.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, true));
shapeComp.setToolTipText("Change shape");
Button elongateButton = new Button(shapeComp, SWT.PUSH);
elongateButton.setText("Elongate");
elongateButton.setToolTipText("Make rings more elliptical");
elongateButton.addMouseListener(new RepeatingMouseAdapter(display, new SlowFastRunnable() {
@Override
public void run() {
DiffractionCalibrationUtils.changeRings(currentData, ManipulateMode.ELONGATE, isFast());
}
@Override
public void stop() {
// updateDiffTool(DISTANCE_NODE_PATH, currentData.md.getDetector2DProperties().getDetectorDistance());
refreshTable();
}
}));
elongateButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, true));
Button squashButton = new Button(shapeComp, SWT.PUSH | SWT.FILL);
squashButton.setText("Squash");
squashButton.setToolTipText("Make rings more circular");
squashButton.addMouseListener(new RepeatingMouseAdapter(display, new SlowFastRunnable() {
@Override
public void run() {
DiffractionCalibrationUtils.changeRings(currentData, ManipulateMode.SQUASH, isFast());
}
@Override
public void stop() {
// updateDiffTool(DISTANCE_NODE_PATH, currentData.md.getDetector2DProperties().getDetectorDistance());
refreshTable();
}
}));
squashButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, true));
Composite rotateComp = new Composite(actionComp, SWT.BORDER);
rotateComp.setLayout(new GridLayout(1, false));
rotateComp.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, true));
rotateComp.setToolTipText("Change rotation");
Button clockButton = new Button(rotateComp, SWT.PUSH);
clockButton.setImage(Activator.getImage("icons/arrow_rotate_clockwise.png"));
clockButton.setToolTipText("Rotate rings clockwise");
clockButton.addMouseListener(new RepeatingMouseAdapter(display, new SlowFastRunnable() {
@Override
public void run() {
DiffractionCalibrationUtils.changeRings(currentData, ManipulateMode.CLOCKWISE, isFast());
}
@Override
public void stop() {
refreshTable();
}
}));
clockButton.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false));
Button antiClockButton = new Button(rotateComp, SWT.PUSH);
antiClockButton.setImage(Activator.getImage("icons/arrow_rotate_anticlockwise.png"));
antiClockButton.setToolTipText("Rotate rings anti-clockwise");
antiClockButton.addMouseListener(new RepeatingMouseAdapter(display, new SlowFastRunnable() {
@Override
public void run() {
DiffractionCalibrationUtils.changeRings(currentData, ManipulateMode.ANTICLOCKWISE, isFast());
}
@Override
public void stop() {
refreshTable();
}
}));
antiClockButton.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false));
Composite calibrateComp = new Composite(mainControlComp, SWT.NONE);
calibrateComp.setLayout(new GridLayout(1, false));
calibrateComp.setLayoutData(new GridData(SWT.FILL, SWT.TOP, false, false));
try{
RadioUtils.createRadioControls(calibrateComp, createWavelengthRadioActions());
} catch (Exception e) {
logger.error("Could not create controls:"+e);
}
Group wavelengthComp = new Group(calibrateComp, SWT.NONE);
wavelengthComp.setText("X-Rays");
wavelengthComp.setToolTipText("Set the wavelength / energy");
wavelengthComp.setLayout(new GridLayout(3, false));
wavelengthComp.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false));
Label wavelengthLabel = new Label(wavelengthComp, SWT.NONE);
wavelengthLabel.setText("Wavelength");
wavelengthDistanceSpinner = new FloatSpinner(wavelengthComp, SWT.BORDER);
wavelengthDistanceSpinner.setDouble(0);
wavelengthDistanceSpinner.setFormat(7, 5);
wavelengthDistanceSpinner.setMinimum(0);
wavelengthDistanceSpinner.setMaximum(Double.MAX_VALUE);
wavelengthDistanceSpinner.setIncrement(0.001);
wavelengthDistanceSpinner.setToolTipText("Set the wavelength in Angstrom");
wavelengthDistanceSpinner.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
// update wavelength of each image
for(int i = 0; i < model.size(); i++){
model.get(i).md.getDiffractionCrystalEnvironment().setWavelength(wavelengthDistanceSpinner.getDouble());
}
// update wavelength in keV
wavelengthEnergySpinner.setDouble(getWavelengthEnergy(wavelengthDistanceSpinner.getDouble()));
// update wavelength in diffraction tool tree viewer
NumericNode<Length> node = getDiffractionTreeNode(WAVELENGTH_NODE_PATH);
if (node.getUnit().equals(NonSI.ANGSTROM)) {
updateDiffTool(WAVELENGTH_NODE_PATH, wavelengthDistanceSpinner.getDouble());
} else if (node.getUnit().equals(NonSI.ELECTRON_VOLT)) {
updateDiffTool(WAVELENGTH_NODE_PATH, getWavelengthEnergy(wavelengthDistanceSpinner.getDouble()) * 1000);
} else if (node.getUnit().equals(SI.KILO(NonSI.ELECTRON_VOLT))) {
updateDiffTool(WAVELENGTH_NODE_PATH, getWavelengthEnergy(wavelengthDistanceSpinner.getDouble()));
}
}
});
wavelengthDistanceSpinner.setEnabled(false);
Label unitDistanceLabel = new Label(wavelengthComp, SWT.NONE);
unitDistanceLabel.setText(NonSI.ANGSTROM.toString());
Label energyLabel = new Label(wavelengthComp, SWT.NONE);
energyLabel.setText("Energy");
wavelengthEnergySpinner = new FloatSpinner(wavelengthComp, SWT.BORDER);
wavelengthEnergySpinner.setDouble(0);
wavelengthEnergySpinner.setFormat(7, 5);
wavelengthEnergySpinner.setMinimum(0);
wavelengthEnergySpinner.setMaximum(Double.MAX_VALUE);
wavelengthEnergySpinner.setIncrement(0.001);
wavelengthEnergySpinner.setToolTipText("Set the wavelength in keV");
wavelengthEnergySpinner.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
// update wavelength of each image
for(int i = 0; i < model.size(); i++){
model.get(i).md.getDiffractionCrystalEnvironment().setWavelength(getWavelengthDistance(wavelengthEnergySpinner.getDouble()));
}
// update wavelength in Angstrom
wavelengthDistanceSpinner.setDouble(getWavelengthDistance(wavelengthEnergySpinner.getDouble()));
// update wavelength in Diffraction tool tree viewer
NumericNode<Length> node = getDiffractionTreeNode(WAVELENGTH_NODE_PATH);
if (node.getUnit().equals(NonSI.ANGSTROM)) {
updateDiffTool(WAVELENGTH_NODE_PATH, getWavelengthDistance(wavelengthEnergySpinner.getDouble()));
} else if (node.getUnit().equals(NonSI.ELECTRON_VOLT)) {
updateDiffTool(WAVELENGTH_NODE_PATH, wavelengthEnergySpinner.getDouble() * 1000);
} else if (node.getUnit().equals(SI.KILO(NonSI.ELECTRON_VOLT))) {
updateDiffTool(WAVELENGTH_NODE_PATH, wavelengthEnergySpinner.getDouble());
}
}
});
wavelengthEnergySpinner.setEnabled(false);
Label unitEnergyLabel = new Label(wavelengthComp, SWT.NONE);
unitEnergyLabel.setText(SI.KILO(NonSI.ELECTRON_VOLT).toString());
Composite processComp = new Composite(calibrantHolder, SWT.NONE);
processComp.setLayout(new GridLayout(2, false));
processComp.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false));
Button findRingButton = new Button(processComp, SWT.PUSH);
findRingButton.setText("Find rings in image");
findRingButton.setToolTipText("Use pixel values to find rings in image near calibration rings");
findRingButton.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false));
findRingButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
Job findRingsJob = DiffractionCalibrationUtils.findRings(display, plottingSystem, currentData);
if (findRingsJob == null)
return;
findRingsJob.addJobChangeListener(new JobChangeAdapter() {
@Override
public void done(IJobChangeEvent event) {
display.asyncExec(new Runnable() {
@Override
public void run() {
if (currentData != null && currentData.nrois > 0) {
setCalibrateButtons();
}
refreshTable();
}
});
}
});
findRingsJob.schedule();
}
});
calibrateImages = new Button(processComp, SWT.PUSH);
calibrateImages.setText("Run Calibration Process");
calibrateImages.setToolTipText("Calibrate detector in chosen images");
calibrateImages.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false));
calibrateImages.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (model.size() <= 0)
return;
Job calibrateJob = DiffractionCalibrationUtils.calibrateImages(display, plottingSystem, model, currentData,
refineWithDistance || refineAfterDistance,
refineAfterDistance);
if (calibrateJob == null)
return;
calibrateJob.addJobChangeListener(new JobChangeAdapter() {
@Override
public void done(IJobChangeEvent event) {
display.asyncExec(new Runnable() {
public void run() {
refreshTable();
setCalibrateButtons();
}
});
}
});
calibrateJob.schedule();
}
});
calibrateImages.setEnabled(false);
scrollHolder.layout();
scrollComposite.setContent(scrollHolder);
scrollComposite.setExpandHorizontal(true);
scrollComposite.setExpandVertical(true);
scrollComposite.setMinSize(scrollHolder.computeSize(SWT.DEFAULT, SWT.DEFAULT));
scrollComposite.layout();
// end of Diffraction Calibration controls
// start plotting system
Composite plotComp = new Composite(mainSash, SWT.NONE);
plotComp.setLayout(new GridLayout(1, false));
plotComp.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
try {
ActionBarWrapper actionBarWrapper = ActionBarWrapper.createActionBars(plotComp, null);
plottingSystem = PlottingFactory.createPlottingSystem();
plottingSystem.createPlotPart(plotComp, "", actionBarWrapper, PlotType.IMAGE, this);
plottingSystem.setTitle("");
plottingSystem.getPlotComposite().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
} catch (Exception e1) {
logger.error("Could not create plotting system:"+ e1);
}
// try to load the previous data saved in the memento
DiffractionTableData good = null;
for (String p : pathsList) {
if (!p.endsWith(".nxs")) {
DiffractionTableData d = createData(p, null);
if (good == null && d != null) {
good = d;
setWavelength(d);
}
}
}
tableViewer.refresh();
if (good != null) {
final DiffractionTableData g = good;
display.asyncExec(new Runnable() { // this is necessary to give the plotting system time to lay out itself
@Override
public void run() {
tableViewer.setSelection(new StructuredSelection(g));
}
});
}
if (model.size() > 0) {
wavelengthDistanceSpinner.setEnabled(true);
wavelengthEnergySpinner.setEnabled(true);
}
// start diffraction tool
Composite diffractionToolComp = new Composite(leftSash, SWT.BORDER);
diffractionToolComp.setLayout(new FillLayout());
try {
toolSystem = (IToolPageSystem)plottingSystem.getAdapter(IToolPageSystem.class);
// Show tools here, not on a page.
toolSystem.setToolComposite(diffractionToolComp);
toolSystem.setToolVisible(DIFFRACTION_ID, ToolPageRole.ROLE_2D, null);
} catch (Exception e2) {
logger.error("Could not open diffraction tool:"+ e2);
}
IActionBars bars = getViewSite().getActionBars();
bars.getToolBarManager().add(resetAction);
//mainSash.setWeights(new int[] { 1, 2});
}
|
diff --git a/classes/com/sapienter/jbilling/server/user/EntitySignup.java b/classes/com/sapienter/jbilling/server/user/EntitySignup.java
index 0989f590..a4155ed8 100644
--- a/classes/com/sapienter/jbilling/server/user/EntitySignup.java
+++ b/classes/com/sapienter/jbilling/server/user/EntitySignup.java
@@ -1,866 +1,866 @@
/*
The contents of this file are subject to the Jbilling Public License
Version 1.1 (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.jbilling.com/JPL/
Software distributed under the License is distributed on an "AS IS"
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
License for the specific language governing rights and limitations
under the License.
The Original Code is jbilling.
The Initial Developer of the Original Code is Emiliano Conde.
Portions created by Sapienter Billing Software Corp. are Copyright
(C) Sapienter Billing Software Corp. All Rights Reserved.
Contributor(s): ______________________________________.
*/
package com.sapienter.jbilling.server.user;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Calendar;
import org.apache.log4j.Logger;
import com.sapienter.jbilling.common.CommonConstants;
import com.sapienter.jbilling.common.JBCrypto;
import com.sapienter.jbilling.common.JNDILookup;
import com.sapienter.jbilling.common.Util;
import com.sapienter.jbilling.server.entity.ContactDTO;
import com.sapienter.jbilling.server.util.Constants;
/**
* @author emilc
*/
public final class EntitySignup {
private Connection conn = null;
private UserDTOEx user;
private ContactDTO contact;
private Integer languageId;
class Table {
String name;
String columns[];
String data[][];
String international_columns[][][];
boolean isMassive;
int maxRows;
int minRows;
Column columnsMetaData[];
int nextId;
int index;
}
class Column {
String dataType;
int intRange1;
int intRange2;
String dateRange1;
int dateRangeDays;
boolean isNull;
String constantValue;
float floatFactor;
}
/**
*
* @param root
* It uses only the user name and password
* @param contact
* @param languageId
*/
public EntitySignup(UserDTOEx root, ContactDTO contact,
Integer languageId) {
checkMainRole(root);
this.user = root;
this.contact = contact;
this.languageId = languageId;
}
public int process() throws Exception {
try {
JNDILookup jndi = JNDILookup.getFactory();
// the connection will be closed by the RowSet as soon as it
// finished executing the command
conn = jndi.lookUpDataSource().getConnection();
int newEntity = initData();
conn.close();
return newEntity;
} catch (Exception e) {
try {
conn.close();
} catch(Exception x) {}
throw new Exception(e);
}
}
void processTable(Table table)
throws Exception {
StringBuffer sql = new StringBuffer();
if (table.columns[0].equals("i_id")) {
initTable(table);
}
int rowIdx = table.nextId;
try {
System.out.println("Now processing " +
table.name + " [" + table.index + "]");
// generate the INSERT string with this table's columns
sql.append("insert into " + table.name + " (");
for (int columnsIdx = 0; columnsIdx < table.columns.length;) {
sql.append(table.columns[columnsIdx].substring(2));
columnsIdx++;
if (columnsIdx < table.columns.length) {
sql.append(",");
}
}
sql.append(") values (");
for (int columnsIdx = 0; columnsIdx < table.columns.length;) {
sql.append("?");
columnsIdx++;
if (columnsIdx < table.columns.length) {
sql.append(",");
}
}
sql.append(")");
System.out.println(sql.toString());
PreparedStatement stmt = conn.prepareStatement(sql.toString());
// for each row to be inserted, apply the data to the '?'
int rowCount = 0;
for (rowCount = 0; table.data != null && rowCount < table.data.length;
rowCount++, rowIdx++) {
// normal tables don't have data for the first column (the id)
// but map tables have data for every column
int idxDifference = 0; // this will be for a map table
for (int columnIdx = 0;
columnIdx < table.columns.length;
columnIdx++) {
String field;
if (table.columns[columnIdx].equals("i_id")) {
// this is the id, which is automatically generated
idxDifference = 1; // this is a normal table
stmt.setInt(columnIdx + 1, rowIdx);
} else {
String type = table.columns[columnIdx].substring(0, 2);
field = table.data[rowCount][columnIdx - idxDifference];
if (type.equals("d_")) {
if (field == null) {
stmt.setNull(columnIdx + 1, Types.DATE);
} else {
java.sql.Date dateField = new Date(Util.parseDate(field).getTime());
stmt.setDate(columnIdx + 1, dateField);
}
} else if (type.equals("s_")) {
if (field == null) {
stmt.setNull(columnIdx + 1, Types.VARCHAR);
} else {
stmt.setString(columnIdx + 1, field);
}
} else if (type.equals("i_")) {
if (field == null) {
stmt.setNull(columnIdx + 1, Types.INTEGER);
} else {
stmt.setInt(columnIdx + 1, Integer.valueOf(field));
}
} else if (type.equals("f_")) {
if (field == null) {
stmt.setNull(columnIdx + 1, Types.FLOAT);
} else {
stmt.setFloat(columnIdx + 1, Float.valueOf(field));
}
} else {
throw new Exception("Don't know the type " + type);
}
}
}
if (stmt.executeUpdate() != 1) {
throw new Exception(
"insert failed. Row "
+ rowIdx
+ " table "
+ table.name);
}
// now take care of the pseudo columns with international
// text
if (table.international_columns != null) {
insertPseudoColumns(
table.index,
rowIdx,
table.international_columns[rowCount]);
}
}
System.out.println("inserted " + rowCount + " rows");
stmt.close();
updateBettyTablesRows(table.index, rowIdx);
table.nextId = rowIdx;
} catch (Exception e) {
e.printStackTrace();
System.err.println(e.getMessage());
throw new Exception("Error inserting table " + table.name +
" row " + (rowIdx + 1));
}
}
Table addTable(String name, String columns[],
String data[][], boolean massive) {
return addTable(name, columns, data, null, massive);
}
Table addTable(String name, String columns[], String data[][],
String intColumns[][][], boolean massive) {
return addTable(name, columns, data, intColumns, massive, null, 0, 0);
}
Table addTable(
String name,
String columns[],
String data[][],
String intColumns[][][],
boolean massive,
Column metaData[],
int min, int max) {
Table table;
table = new Table();
table.name = name;
table.columns = columns;
table.data = data;
table.international_columns = intColumns;
table.isMassive = massive;
table.columnsMetaData = metaData;
table.maxRows = max;
table.minRows = min;
return table;
}
void updateBettyTablesRows(int tableId, int totalRows)
throws SQLException {
PreparedStatement stmt =
conn.prepareStatement(
"update jbilling_table set next_id = ? " + " where id = ?");
stmt.setInt(1, totalRows);
stmt.setInt(2, tableId);
stmt.executeUpdate();
stmt.close();
}
void initTable(Table table)
throws SQLException {
PreparedStatement stmt = conn.prepareStatement(
"select next_id, id from jbilling_table " +
" where name = ?");
stmt.setString(1, table.name);
ResultSet res = stmt.executeQuery();
if (res.next()) {
table.nextId = res.getInt(1);
table.index = res.getInt(2);
stmt = conn.prepareStatement(
"select max(id) from " + table.name);
res = stmt.executeQuery();
res.next();
int maxId = res.getInt(1);
if (table.nextId <= maxId) {
table.nextId = maxId + 1;
}
} else {
throw new SQLException("No rows for table " + table.name);
}
res.close();
stmt.close();
}
void insertPseudoColumns(int tableId, int rowId, String data[][])
throws SQLException {
String sql = "insert into international_description "
+ "(table_id, foreign_id, psudo_column,language_id,content) "
+ "values (?, ?, ?, ?, ?)";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setInt(1, tableId);
stmt.setInt(2, rowId);
for (int entry = 0; entry < data.length; entry++) {
// this would be the pseudo column
stmt.setString(3, data[entry][0]);
// and this the actual content
stmt.setString(5, data[entry][1]);
String language = null;
if (data[entry].length < 3 || data[entry][2] == null) {
language = "1"; //defaults to english
} else {
language = data[entry][2];
}
stmt.setInt(4, Integer.valueOf(language));
if (stmt.executeUpdate() != 1) {
throw new SQLException("Should've insterted one row into international_description");
}
}
stmt.close();
}
// idealy, this should be loaded from betty-schema.xml
int initData() throws Exception {
String now = Util.parseDate(Calendar.getInstance().getTime());
//ENTITY
// defaults currency to US dollars
String entityColumns[] =
{ "i_id", "i_external_id", "s_description", "d_create_datetime", "i_language_id", "i_currency_id" };
String entityData[][] = {
{ null, contact.getOrganizationName(), now, languageId.toString(), "1" },
};
Table table = addTable(Constants.TABLE_ENTITY, entityColumns,
entityData, false);
processTable(table);
int newEntityId = table.nextId - 1;
//BASE_USER
String userColumns[] = {
"i_id",
"i_entity_id",
"s_user_name",
"s_password",
"i_deleted",
"i_status_id",
"i_currency_id",
"d_create_datetime",
"d_last_status_change",
"i_language_id"
};
String userData[][] = {
{ String.valueOf(newEntityId), user.getUserName(),
getDBPassword(user), "0", "1", "1", now, null,
languageId.toString() }, //1
};
table = addTable(Constants.TABLE_BASE_USER, userColumns, userData, false);
processTable(table);
int rootUserId = table.nextId - 1;
//USER_ROLE_MAP
String userRoleColumns[] =
{
"i_user_id",
"i_role_id",
};
String userRoleData[][] = {
{ String.valueOf(rootUserId), "2"},
};
table = addTable(Constants.TABLE_USER_ROLE_MAP,
userRoleColumns, userRoleData, false);
processTable(table);
//CONTACT_TYPE
String contactType[] = { "i_id", "i_entity_id", "i_is_primary" };
String contactTypeData[][] = new String[1][2];
String contactTypeIntColumns[][][] = new String [1][1][2];
contactTypeData[0][0] = String.valueOf(newEntityId);
contactTypeData[0][1] = "1";
contactTypeIntColumns[0][0][0] = "description";
contactTypeIntColumns[0][0][1] = "Primary";
table = addTable(Constants.TABLE_CONTACT_TYPE, contactType, contactTypeData,
contactTypeIntColumns, false);
processTable(table);
int pContactType = table.nextId - 1;
//CONTACT
String contactColumns[] = {
"i_id",
"s_ORGANIZATION_NAME",
"s_STREET_ADDRES1",
"s_STREET_ADDRES2",
"s_CITY",
"s_STATE_PROVINCE",
"s_POSTAL_CODE",
"s_COUNTRY_CODE",
"s_LAST_NAME",
"s_FIRST_NAME",
"s_PERSON_INITIAL",
"s_PERSON_TITLE",
"i_PHONE_COUNTRY_CODE",
"i_PHONE_AREA_CODE",
"s_PHONE_PHONE_NUMBER",
"i_FAX_COUNTRY_CODE",
"i_FAX_AREA_CODE",
"s_FAX_PHONE_NUMBER",
"s_EMAIL",
"d_CREATE_DATETIME",
"i_deleted",
"i_user_id"
};
String contactData[][] = {
{
contact.getOrganizationName(),
contact.getAddress1(),
contact.getAddress2(),
contact.getCity(),
contact.getStateProvince(),
contact.getPostalCode(),
contact.getCountryCode(),
null,
null,
null,
null,
(contact.getPhoneCountryCode() == null) ? null :
contact.getPhoneCountryCode().toString(),
(contact.getPhoneAreaCode() == null) ? null :
contact.getPhoneAreaCode().toString(),
contact.getPhoneNumber(),
null, //fax
null,
null,
contact.getEmail(),
now,
"0",
null
},
{
contact.getOrganizationName(),
contact.getAddress1(),
contact.getAddress2(),
contact.getCity(),
contact.getStateProvince(),
contact.getPostalCode(),
contact.getCountryCode(),
contact.getLastName(),
contact.getFirstName(),
null,
null,
(contact.getPhoneCountryCode() == null) ? null :
contact.getPhoneCountryCode().toString(),
(contact.getPhoneAreaCode() == null) ? null :
contact.getPhoneAreaCode().toString(),
contact.getPhoneNumber(),
null, //fax
null,
null,
contact.getEmail(),
now,
"0",
String.valueOf(rootUserId)
},
};
table = addTable(Constants.TABLE_CONTACT, contactColumns, contactData, false);
processTable(table);
int contactId = table.nextId - 2;
//CONTACT_MAP
String contactMapColumns[] =
{ "i_id", "i_contact_id", "i_type_id", "i_table_id", "i_foreign_id" };
String contactMapData[][] = {
{ String.valueOf(contactId), "1", "5", String.valueOf(newEntityId) }, // the contact for the entity
{ String.valueOf(contactId + 1), String.valueOf(pContactType), "10", String.valueOf(rootUserId) },
};
table = addTable(Constants.TABLE_CONTACT_MAP, contactMapColumns, contactMapData, false);
processTable(table);
//ORDER_PERIODS
// puts only monthly now
String orderPeriod[] = { "i_id", "i_entity_id", "i_value", "i_unit_id" };
String orderPeriodData[][] = new String[1][3];
String orderPeriodIntColumns[][][] = new String [1][1][2];
orderPeriodData[0][0] = String.valueOf(newEntityId);
orderPeriodData[0][1] = "1";
orderPeriodData[0][2] = "1"; // month
orderPeriodIntColumns[0][0][0] = "description";
orderPeriodIntColumns[0][0][1] = "Monthly";
table = addTable(Constants.TABLE_ORDER_PERIOD, orderPeriod, orderPeriodData,
orderPeriodIntColumns, false);
processTable(table);
//PLUGGABLE_TASK
String pluggableTaskColumns[] =
{ "i_id", "i_entity_id", "i_type_id", "i_processing_order" };
String pluggableTaskData[][] =
{
{ String.valueOf(newEntityId), "21","1" }, // Fake payment processor
{ String.valueOf(newEntityId), "1", "1" }, // BasicLineTotalTask
{ String.valueOf(newEntityId), "3", "1" }, // CalculateDueDate
{ String.valueOf(newEntityId), "4", "2" }, // BasicCompositionTask
{ String.valueOf(newEntityId), "5", "1" }, // BasicOrderFilterTask
{ String.valueOf(newEntityId), "6", "1" }, // BasicInvoiceFilterTask
{ String.valueOf(newEntityId), "7", "1" }, // BasicOrderPeriodTask
{ String.valueOf(newEntityId), "9", "1" }, // BasicEmailNotificationTask
{ String.valueOf(newEntityId), "10","1" }, // BasicPaymentInfoTask cc info fetcher
{ String.valueOf(newEntityId), "12","2" }, // Paper invoice (for download PDF).
{ String.valueOf(newEntityId), "23","1" }, // Subscriber status manager
{ String.valueOf(newEntityId), "25","1" }, // Async payment processing (no parameters)
};
table = addTable(Constants.TABLE_PLUGGABLE_TASK, pluggableTaskColumns, pluggableTaskData, false);
processTable(table);
int lastCommonPT = table.nextId - 1;
updateBettyTablesRows(table.index, table.nextId);
// the parameters of these tasks
//PLUGGABLE_TASK_PARAMETER
String pluggableTaskParameterColumns[] =
{
"i_id",
"i_task_id",
"s_name",
"i_int_value",
"s_str_value",
"f_float_value"
};
// paper invoice
String pluggableTaskParameterData[][] = {
{ String.valueOf(lastCommonPT - 1), "design", null, "simple_invoice_b2b", null},
};
table = addTable(Constants.TABLE_PLUGGABLE_TASK_PARAMETER, pluggableTaskParameterColumns,
pluggableTaskParameterData, false);
processTable(table);
// fake payment processor
- addTaskParameter(table,lastCommonPT - 10, "all", null, "yes", null);
+ addTaskParameter(table,lastCommonPT - 11, "all", null, "yes", null);
// email parameters. They are all optional
addTaskParameter(table, lastCommonPT - 3, "smtp_server", null,
null, null);
addTaskParameter(table, lastCommonPT - 3, "from", null,
contact.getEmail(), null);
addTaskParameter(table, lastCommonPT - 3, "username", null,
null, null);
addTaskParameter(table, lastCommonPT - 3, "password", null,
null, null);
addTaskParameter(table, lastCommonPT - 3, "port", null,
null, null);
addTaskParameter(table, lastCommonPT - 3, "reply_to", null,
null, null);
addTaskParameter(table, lastCommonPT - 3, "bcc_to", null,
null, null);
addTaskParameter(table, lastCommonPT - 3, "from_name", null,
contact.getOrganizationName(), null);
updateBettyTablesRows(table.index, table.nextId);
// PAYMENT METHODS
//ENTITY_PAYMENT_METHOD_MAP
String entityPaymentMethodMapColumns[] =
{
"i_entity_id",
"i_payment_method_id",
};
String entityPaymentMethodMapData[][] = new String[3][2];
entityPaymentMethodMapData[0][0] = String.valueOf(newEntityId);
entityPaymentMethodMapData[0][1] = "1"; // cheque
entityPaymentMethodMapData[1][0] = String.valueOf(newEntityId);
entityPaymentMethodMapData[1][1] = "2"; // visa
entityPaymentMethodMapData[2][0] = String.valueOf(newEntityId);
entityPaymentMethodMapData[2][1] = "3"; // mc
table = addTable(Constants.TABLE_ENTITY_PAYMENT_METHOD_MAP,
entityPaymentMethodMapColumns,
entityPaymentMethodMapData, false);
processTable(table);
//PREFERENCE
String preferenceColumns[] =
{
"i_id",
"i_type_id",
"i_table_id",
"i_foreign_id",
"i_int_value",
"s_str_value",
"f_float_value"
};
// the table_id = 5, foregin_id = 1, means entity = 1
String preferenceData[][] = {
{"1", "5", String.valueOf(newEntityId), "0", null, null }, // no automatic processing by default
{"2", "5", String.valueOf(newEntityId), null, "/billing/css/jbilling.css", null },
{"3", "5", String.valueOf(newEntityId), null, "/billing/graphics/jbilling.jpg", null },
{"4", "5", String.valueOf(newEntityId), "5", null, null }, // grace period
{"5", "5", String.valueOf(newEntityId), null, null, "10" },
{"6", "5", String.valueOf(newEntityId), null, null, "0" },
{"7", "5", String.valueOf(newEntityId), "0", null, null },
{"8", "5", String.valueOf(newEntityId), "1", null, null },
{"9", "5", String.valueOf(newEntityId), "1", null, null },
{"10","5", String.valueOf(newEntityId), "0", null, null },
{"11","5", String.valueOf(newEntityId), String.valueOf(rootUserId), null, null },
{"12","5", String.valueOf(newEntityId), "1", null, null },
{"13","5", String.valueOf(newEntityId), "1", null, null },
{"14","5", String.valueOf(newEntityId), "0", null, null },
};
table = addTable(Constants.TABLE_PREFERENCE, preferenceColumns,
preferenceData, false);
processTable(table);
//REPORT_ENTITY_MAP
String reportEntityColumns[] =
{
"i_entity_id",
"i_report_id",
};
String reportEntityData[][] = {
{String.valueOf(newEntityId),"1"},
{String.valueOf(newEntityId),"2"},
{String.valueOf(newEntityId),"3"},
{String.valueOf(newEntityId),"4"},
{String.valueOf(newEntityId),"5"},
{String.valueOf(newEntityId),"6"},
{String.valueOf(newEntityId),"7"},
{String.valueOf(newEntityId),"8"},
{String.valueOf(newEntityId),"9"},
{String.valueOf(newEntityId),"10"},
{String.valueOf(newEntityId),"11"},
{String.valueOf(newEntityId),"12"},
{String.valueOf(newEntityId),"13"},
{String.valueOf(newEntityId),"14"},
{String.valueOf(newEntityId),"15"},
{String.valueOf(newEntityId),"16"},
{String.valueOf(newEntityId),"17"},
{String.valueOf(newEntityId),"18"},
{String.valueOf(newEntityId),"20"},
{String.valueOf(newEntityId),"22"},
};
table = addTable(Constants.TABLE_REPORT_ENTITY_MAP,
reportEntityColumns,
reportEntityData, false);
processTable(table);
//AGEING_ENTITY_STEP
String ageingEntityStepColumns[] =
{"i_id", "i_entity_id", "i_status_id", "i_days"};
String ageingEntityStepMessageData[][] = {
{String.valueOf(newEntityId), "1", "0"}, // active (for the welcome message)
};
String ageingEntityStepIntColumns[][][] =
{
{ { "welcome_message", "<div> <br/> <p style='font-size:19px; font-weight: bold;'>Welcome to " +
contact.getOrganizationName() + " Billing!</p> <br/> <p style='font-size:14px; text-align=left; padding-left: 15;'>From here, you can review your latest invoice and get it paid instantly. You can also view all your previous invoices and payments, and set up the system for automatic payment with your credit card.</p> <p style='font-size:14px; text-align=left; padding-left: 15;'>What would you like to do today? </p> <ul style='font-size:13px; text-align=left; padding-left: 25;'> <li >To submit a credit card payment, follow the link on the left bar.</li> <li >To view a list of your invoices, click on the �Invoices� menu option. The first invoice on the list is your latest invoice. Click on it to see its details.</li> <li>To view a list of your payments, click on the �Payments� menu option. The first payment on the list is your latest payment. Click on it to see its details.</li> <li>To provide a credit card to enable automatic payment, click on the menu option 'Account', and then on 'Edit Credit Card'.</li> </ul> </div>" }, }, // act
};
table = addTable(Constants.TABLE_AGEING_ENTITY_STEP,
ageingEntityStepColumns,
ageingEntityStepMessageData,
ageingEntityStepIntColumns, false);
processTable(table);
//BILLING_PROCESS_CONFIGURATION
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, 1);
String inAMonth = Util.parseDate(cal.getTime());
String billingProcessConfigurationColumns[] =
{
"i_id",
"i_entity_id",
"d_next_run_date",
"i_generate_report",
"i_retries",
"i_days_for_retry",
"i_days_for_report",
"i_review_status",
"i_period_unit_id",
"i_period_value",
"i_due_date_unit_id",
"i_due_date_value",
"i_only_recurring",
"i_invoice_date_process",
"i_auto_payment"
};
String billingProcessConfigurationData[][] = {
{ String.valueOf(newEntityId), inAMonth,
"1", "0", "1", "3", "1", "2", "1", "1", "1", "1", "0", "0" },
};
table = addTable(Constants.TABLE_BILLING_PROCESS_CONFIGURATION,
billingProcessConfigurationColumns,
billingProcessConfigurationData, false);
processTable(table);
// CURRENCY_ENTITY_MAP
String currencyEntityMapColumns[] =
{ "i_entity_id", "i_currency_id", };
String currencyEntityMapData[][] = {
{ String.valueOf(newEntityId), "1", },
};
table = addTable(Constants.TABLE_CURRENCY_ENTITY_MAP, currencyEntityMapColumns,
currencyEntityMapData, false);
processTable(table);
//NOTIFICATION_MESSAGE
String messageColumns[] = {
"i_id",
"i_type_id",
"i_entity_id",
"i_language_id",
};
// we provide at least those for english
String messageData[][] = {
{ "1", String.valueOf(newEntityId), "1"}, // invoice email
{ "2", String.valueOf(newEntityId), "1"}, // user reactivatesd
{ "3", String.valueOf(newEntityId), "1"}, // user overdue
{ "13", String.valueOf(newEntityId), "1"}, // order expiring
{ "16", String.valueOf(newEntityId), "1"}, // payment ok
{ "17", String.valueOf(newEntityId), "1"}, // payment failed
{ "18", String.valueOf(newEntityId), "1"}, // invoice reminder
{ "19", String.valueOf(newEntityId), "1"}, // credit card expi
};
table = addTable(Constants.TABLE_NOTIFICATION_MESSAGE, messageColumns,
messageData, false);
processTable(table);
int messageId = table.nextId - 8;
//NOTIFICATION_MESSAGE_SECTION
String sectionColumns[] = {
"i_id",
"i_message_id",
"i_section",
};
String sectionData[][] = {
{ String.valueOf(messageId), "1"},
{ String.valueOf(messageId), "2"},
{ String.valueOf(messageId + 1), "1"},
{ String.valueOf(messageId + 1), "2"},
{ String.valueOf(messageId + 2), "1"},
{ String.valueOf(messageId + 2), "2"},
{ String.valueOf(messageId + 3), "1"},
{ String.valueOf(messageId + 3), "2"},
{ String.valueOf(messageId + 4), "1"},
{ String.valueOf(messageId + 4), "2"},
{ String.valueOf(messageId + 5), "1"},
{ String.valueOf(messageId + 5), "2"},
{ String.valueOf(messageId + 6), "1"},
{ String.valueOf(messageId + 6), "2"},
{ String.valueOf(messageId + 7), "1"},
{ String.valueOf(messageId + 7), "2"},
};
table = addTable(Constants.TABLE_NOTIFICATION_MESSAGE_SECTION,
sectionColumns, sectionData, false);
processTable(table);
int sectionId = table.nextId - 16;
//NOTIFICATION_MESSAGE_LINE
String lineColumns[] = {
"i_id",
"i_message_section_id",
"s_content",
};
String lineData[][] = {
{ String.valueOf(sectionId), "Billing Statement from |company_name|"},
{ String.valueOf(sectionId + 1), "Dear |first_name| |last_name|,\n\n This is to notify you that your latest invoice (number |number|) is now available. The total amount due is: |total|. You can view it by login in to:\n\n" + Util.getSysProp("url") + "/billing/user/login.jsp?entityId=|company_id|\n\nFor security reasons, your statement is password protected.\nTo login in, you will need your user name: |username| and your account password: |password|\n \n After logging in, please click on the menu option �List�, to see all your invoices. You can also see your payment history, your current purchase orders, as well as update your payment information and submit online payments.\n\n\nThank you for choosing |company_name|, we appreciate your business,\n\nBilling Department\n|company_name|"},
{ String.valueOf(sectionId + 2), "You account is now up to date"},
{ String.valueOf(sectionId + 3), "Dear |first_name| |last_name|,\n\n This email is to notify you that we have received your latest payment and your account no longer has an overdue balance.\n\n Thank you for keeping your account up to date,\n\n\nBilling Department\n|company_name|"},
{ String.valueOf(sectionId + 4), "Overdue Balance"},
{ String.valueOf(sectionId + 5), "Dear |first_name| |last_name|,\n\nOur records show that you have an overdue balance on your account. Please submit a payment as soon as possible.\n\nBest regards,\n\nBilling Department\n|company_name|"},
{ String.valueOf(sectionId + 6), "Your service from |company_name| is about to expire"},
{ String.valueOf(sectionId + 7), "Dear |first_name| |last_name|,\n\nYour service with us will expire on |period_end|. Please make sure to contact customer service for a renewal.\n\nRegards,\n\nBilling Department\n|company_name|"},
{ String.valueOf(sectionId + 8), "Thank you for your payment"},
{ String.valueOf(sectionId + 9), "Dear |first_name| |last_name|\n\n We have received your payment made with |method| for a total of |total|.\n\n Thank you, we appreciate your business,\n\nBilling Department\n|company_name|"},
{ String.valueOf(sectionId + 10), "Payment failed"},
{ String.valueOf(sectionId + 11), "Dear |first_name| |last_name|\n\n A payment with |method| was attempted for a total of |total|, but it has been rejected by the payment processor.\nYou can update your payment information and submit an online payment by login into :\n" + Util.getSysProp("url") + "/billing/user/login.jsp?entityId=|company_id|\n\nFor security reasons, your statement is password protected.\nTo login in, you will need your user name: |username| and your account password: |password|\n\nThank you,\n\nBilling Department\n|company_name|"},
{ String.valueOf(sectionId + 12), "Invoice reminder"},
{ String.valueOf(sectionId + 13), "Dear |first_name| |last_name|\n\n This is a reminder that the invoice number |number| remains unpaid. It was sent to you on |date|, and its total is |total|. Although you still have |days| days to pay it (its due date is |dueDate|), we would greatly appreciate if you can pay it at your earliest convenience.\n\nYours truly,\n\nBilling Department\n|company_name|"},
{ String.valueOf(sectionId + 14), "It is time to update your credit card"},
{ String.valueOf(sectionId + 15), "Dear |first_name| |last_name|,\n\nWe want to remind you that the credit card that we have in our records for your account is about to expire. Its expiration date is |expiry_date|.\n\nUpdating your credit card is easy. Just login into " + Util.getSysProp("url") + "/billing/user/login.jsp?entityId=|company_id|. using your user name: |username| and password: |password|. After logging in, click on 'Account' and then 'Edit Credit Card'. \nThank you for keeping your account up to date.\n\nBilling Department\n|company_name|"},
};
table = addTable(Constants.TABLE_NOTIFICATION_MESSAGE_LINE,
lineColumns, lineData, false);
processTable(table);
//ENTITY_DELIVERY_METHOD_MAP
String methodsColumns[] = {
"i_entity_id",
"i_method_id",
};
String methodsData[][] = {
{ String.valueOf(newEntityId), "1"},
{ String.valueOf(newEntityId), "2"},
{ String.valueOf(newEntityId), "3"},
};
table = addTable(Constants.TABLE_ENTITY_DELIVERY_METHOD_MAP,
methodsColumns, methodsData, false);
processTable(table);
return newEntityId;
}
void addTaskParameter(Table ptTable, int taskId,
String desc, Integer intP, String strP, Float floP)
throws SQLException {
PreparedStatement stmt = conn.prepareStatement(
"insert into pluggable_task_parameter " +
"(id, task_id, name, int_value, str_value, float_value)" +
" values(?, ?, ?, ?, ?, ?)");
stmt.setInt(1, ptTable.nextId);
stmt.setInt(2, taskId);
stmt.setString(3, desc);
if (intP != null) {
stmt.setInt(4, intP.intValue());
} else {
stmt.setNull(4, Types.INTEGER);
}
stmt.setString(5, strP);
if (floP != null) {
stmt.setFloat(6, floP.floatValue());
} else {
stmt.setNull(6, Types.FLOAT);
}
stmt.executeUpdate();
stmt.close();
ptTable.nextId++;
}
void addTask(Table ptTable, int entityId, int type, int position)
throws SQLException {
PreparedStatement stmt = conn.prepareStatement(
"insert into pluggable_task (id, entity_id, type_id, processing_order)" +
" values(?, ?, ?, ?)");
stmt.setInt(1, ptTable.nextId);
stmt.setInt(2, entityId);
stmt.setInt(3, type);
stmt.setInt(4, position);
stmt.executeUpdate();
stmt.close();
ptTable.nextId++;
}
private static void checkMainRole(UserDTOEx root){
if (CommonConstants.TYPE_ROOT.equals(root.getMainRoleId())){
Logger.getLogger(EntitySignup.class).warn("Attention: Root user passed with roleId: " + root.getMainRoleId());
}
root.setMainRoleId(CommonConstants.TYPE_ROOT);
}
private static String getDBPassword(UserDTOEx root){
checkMainRole(root);
JBCrypto crypto = JBCrypto.getPasswordCrypto(root.getMainRoleId());
return crypto.encrypt(root.getPassword());
}
}
| true | true | int initData() throws Exception {
String now = Util.parseDate(Calendar.getInstance().getTime());
//ENTITY
// defaults currency to US dollars
String entityColumns[] =
{ "i_id", "i_external_id", "s_description", "d_create_datetime", "i_language_id", "i_currency_id" };
String entityData[][] = {
{ null, contact.getOrganizationName(), now, languageId.toString(), "1" },
};
Table table = addTable(Constants.TABLE_ENTITY, entityColumns,
entityData, false);
processTable(table);
int newEntityId = table.nextId - 1;
//BASE_USER
String userColumns[] = {
"i_id",
"i_entity_id",
"s_user_name",
"s_password",
"i_deleted",
"i_status_id",
"i_currency_id",
"d_create_datetime",
"d_last_status_change",
"i_language_id"
};
String userData[][] = {
{ String.valueOf(newEntityId), user.getUserName(),
getDBPassword(user), "0", "1", "1", now, null,
languageId.toString() }, //1
};
table = addTable(Constants.TABLE_BASE_USER, userColumns, userData, false);
processTable(table);
int rootUserId = table.nextId - 1;
//USER_ROLE_MAP
String userRoleColumns[] =
{
"i_user_id",
"i_role_id",
};
String userRoleData[][] = {
{ String.valueOf(rootUserId), "2"},
};
table = addTable(Constants.TABLE_USER_ROLE_MAP,
userRoleColumns, userRoleData, false);
processTable(table);
//CONTACT_TYPE
String contactType[] = { "i_id", "i_entity_id", "i_is_primary" };
String contactTypeData[][] = new String[1][2];
String contactTypeIntColumns[][][] = new String [1][1][2];
contactTypeData[0][0] = String.valueOf(newEntityId);
contactTypeData[0][1] = "1";
contactTypeIntColumns[0][0][0] = "description";
contactTypeIntColumns[0][0][1] = "Primary";
table = addTable(Constants.TABLE_CONTACT_TYPE, contactType, contactTypeData,
contactTypeIntColumns, false);
processTable(table);
int pContactType = table.nextId - 1;
//CONTACT
String contactColumns[] = {
"i_id",
"s_ORGANIZATION_NAME",
"s_STREET_ADDRES1",
"s_STREET_ADDRES2",
"s_CITY",
"s_STATE_PROVINCE",
"s_POSTAL_CODE",
"s_COUNTRY_CODE",
"s_LAST_NAME",
"s_FIRST_NAME",
"s_PERSON_INITIAL",
"s_PERSON_TITLE",
"i_PHONE_COUNTRY_CODE",
"i_PHONE_AREA_CODE",
"s_PHONE_PHONE_NUMBER",
"i_FAX_COUNTRY_CODE",
"i_FAX_AREA_CODE",
"s_FAX_PHONE_NUMBER",
"s_EMAIL",
"d_CREATE_DATETIME",
"i_deleted",
"i_user_id"
};
String contactData[][] = {
{
contact.getOrganizationName(),
contact.getAddress1(),
contact.getAddress2(),
contact.getCity(),
contact.getStateProvince(),
contact.getPostalCode(),
contact.getCountryCode(),
null,
null,
null,
null,
(contact.getPhoneCountryCode() == null) ? null :
contact.getPhoneCountryCode().toString(),
(contact.getPhoneAreaCode() == null) ? null :
contact.getPhoneAreaCode().toString(),
contact.getPhoneNumber(),
null, //fax
null,
null,
contact.getEmail(),
now,
"0",
null
},
{
contact.getOrganizationName(),
contact.getAddress1(),
contact.getAddress2(),
contact.getCity(),
contact.getStateProvince(),
contact.getPostalCode(),
contact.getCountryCode(),
contact.getLastName(),
contact.getFirstName(),
null,
null,
(contact.getPhoneCountryCode() == null) ? null :
contact.getPhoneCountryCode().toString(),
(contact.getPhoneAreaCode() == null) ? null :
contact.getPhoneAreaCode().toString(),
contact.getPhoneNumber(),
null, //fax
null,
null,
contact.getEmail(),
now,
"0",
String.valueOf(rootUserId)
},
};
table = addTable(Constants.TABLE_CONTACT, contactColumns, contactData, false);
processTable(table);
int contactId = table.nextId - 2;
//CONTACT_MAP
String contactMapColumns[] =
{ "i_id", "i_contact_id", "i_type_id", "i_table_id", "i_foreign_id" };
String contactMapData[][] = {
{ String.valueOf(contactId), "1", "5", String.valueOf(newEntityId) }, // the contact for the entity
{ String.valueOf(contactId + 1), String.valueOf(pContactType), "10", String.valueOf(rootUserId) },
};
table = addTable(Constants.TABLE_CONTACT_MAP, contactMapColumns, contactMapData, false);
processTable(table);
//ORDER_PERIODS
// puts only monthly now
String orderPeriod[] = { "i_id", "i_entity_id", "i_value", "i_unit_id" };
String orderPeriodData[][] = new String[1][3];
String orderPeriodIntColumns[][][] = new String [1][1][2];
orderPeriodData[0][0] = String.valueOf(newEntityId);
orderPeriodData[0][1] = "1";
orderPeriodData[0][2] = "1"; // month
orderPeriodIntColumns[0][0][0] = "description";
orderPeriodIntColumns[0][0][1] = "Monthly";
table = addTable(Constants.TABLE_ORDER_PERIOD, orderPeriod, orderPeriodData,
orderPeriodIntColumns, false);
processTable(table);
//PLUGGABLE_TASK
String pluggableTaskColumns[] =
{ "i_id", "i_entity_id", "i_type_id", "i_processing_order" };
String pluggableTaskData[][] =
{
{ String.valueOf(newEntityId), "21","1" }, // Fake payment processor
{ String.valueOf(newEntityId), "1", "1" }, // BasicLineTotalTask
{ String.valueOf(newEntityId), "3", "1" }, // CalculateDueDate
{ String.valueOf(newEntityId), "4", "2" }, // BasicCompositionTask
{ String.valueOf(newEntityId), "5", "1" }, // BasicOrderFilterTask
{ String.valueOf(newEntityId), "6", "1" }, // BasicInvoiceFilterTask
{ String.valueOf(newEntityId), "7", "1" }, // BasicOrderPeriodTask
{ String.valueOf(newEntityId), "9", "1" }, // BasicEmailNotificationTask
{ String.valueOf(newEntityId), "10","1" }, // BasicPaymentInfoTask cc info fetcher
{ String.valueOf(newEntityId), "12","2" }, // Paper invoice (for download PDF).
{ String.valueOf(newEntityId), "23","1" }, // Subscriber status manager
{ String.valueOf(newEntityId), "25","1" }, // Async payment processing (no parameters)
};
table = addTable(Constants.TABLE_PLUGGABLE_TASK, pluggableTaskColumns, pluggableTaskData, false);
processTable(table);
int lastCommonPT = table.nextId - 1;
updateBettyTablesRows(table.index, table.nextId);
// the parameters of these tasks
//PLUGGABLE_TASK_PARAMETER
String pluggableTaskParameterColumns[] =
{
"i_id",
"i_task_id",
"s_name",
"i_int_value",
"s_str_value",
"f_float_value"
};
// paper invoice
String pluggableTaskParameterData[][] = {
{ String.valueOf(lastCommonPT - 1), "design", null, "simple_invoice_b2b", null},
};
table = addTable(Constants.TABLE_PLUGGABLE_TASK_PARAMETER, pluggableTaskParameterColumns,
pluggableTaskParameterData, false);
processTable(table);
// fake payment processor
addTaskParameter(table,lastCommonPT - 10, "all", null, "yes", null);
// email parameters. They are all optional
addTaskParameter(table, lastCommonPT - 3, "smtp_server", null,
null, null);
addTaskParameter(table, lastCommonPT - 3, "from", null,
contact.getEmail(), null);
addTaskParameter(table, lastCommonPT - 3, "username", null,
null, null);
addTaskParameter(table, lastCommonPT - 3, "password", null,
null, null);
addTaskParameter(table, lastCommonPT - 3, "port", null,
null, null);
addTaskParameter(table, lastCommonPT - 3, "reply_to", null,
null, null);
addTaskParameter(table, lastCommonPT - 3, "bcc_to", null,
null, null);
addTaskParameter(table, lastCommonPT - 3, "from_name", null,
contact.getOrganizationName(), null);
updateBettyTablesRows(table.index, table.nextId);
// PAYMENT METHODS
//ENTITY_PAYMENT_METHOD_MAP
String entityPaymentMethodMapColumns[] =
{
"i_entity_id",
"i_payment_method_id",
};
String entityPaymentMethodMapData[][] = new String[3][2];
entityPaymentMethodMapData[0][0] = String.valueOf(newEntityId);
entityPaymentMethodMapData[0][1] = "1"; // cheque
entityPaymentMethodMapData[1][0] = String.valueOf(newEntityId);
entityPaymentMethodMapData[1][1] = "2"; // visa
entityPaymentMethodMapData[2][0] = String.valueOf(newEntityId);
entityPaymentMethodMapData[2][1] = "3"; // mc
table = addTable(Constants.TABLE_ENTITY_PAYMENT_METHOD_MAP,
entityPaymentMethodMapColumns,
entityPaymentMethodMapData, false);
processTable(table);
//PREFERENCE
String preferenceColumns[] =
{
"i_id",
"i_type_id",
"i_table_id",
"i_foreign_id",
"i_int_value",
"s_str_value",
"f_float_value"
};
// the table_id = 5, foregin_id = 1, means entity = 1
String preferenceData[][] = {
{"1", "5", String.valueOf(newEntityId), "0", null, null }, // no automatic processing by default
{"2", "5", String.valueOf(newEntityId), null, "/billing/css/jbilling.css", null },
{"3", "5", String.valueOf(newEntityId), null, "/billing/graphics/jbilling.jpg", null },
{"4", "5", String.valueOf(newEntityId), "5", null, null }, // grace period
{"5", "5", String.valueOf(newEntityId), null, null, "10" },
{"6", "5", String.valueOf(newEntityId), null, null, "0" },
{"7", "5", String.valueOf(newEntityId), "0", null, null },
{"8", "5", String.valueOf(newEntityId), "1", null, null },
{"9", "5", String.valueOf(newEntityId), "1", null, null },
{"10","5", String.valueOf(newEntityId), "0", null, null },
{"11","5", String.valueOf(newEntityId), String.valueOf(rootUserId), null, null },
{"12","5", String.valueOf(newEntityId), "1", null, null },
{"13","5", String.valueOf(newEntityId), "1", null, null },
{"14","5", String.valueOf(newEntityId), "0", null, null },
};
table = addTable(Constants.TABLE_PREFERENCE, preferenceColumns,
preferenceData, false);
processTable(table);
//REPORT_ENTITY_MAP
String reportEntityColumns[] =
{
"i_entity_id",
"i_report_id",
};
String reportEntityData[][] = {
{String.valueOf(newEntityId),"1"},
{String.valueOf(newEntityId),"2"},
{String.valueOf(newEntityId),"3"},
{String.valueOf(newEntityId),"4"},
{String.valueOf(newEntityId),"5"},
{String.valueOf(newEntityId),"6"},
{String.valueOf(newEntityId),"7"},
{String.valueOf(newEntityId),"8"},
{String.valueOf(newEntityId),"9"},
{String.valueOf(newEntityId),"10"},
{String.valueOf(newEntityId),"11"},
{String.valueOf(newEntityId),"12"},
{String.valueOf(newEntityId),"13"},
{String.valueOf(newEntityId),"14"},
{String.valueOf(newEntityId),"15"},
{String.valueOf(newEntityId),"16"},
{String.valueOf(newEntityId),"17"},
{String.valueOf(newEntityId),"18"},
{String.valueOf(newEntityId),"20"},
{String.valueOf(newEntityId),"22"},
};
table = addTable(Constants.TABLE_REPORT_ENTITY_MAP,
reportEntityColumns,
reportEntityData, false);
processTable(table);
//AGEING_ENTITY_STEP
String ageingEntityStepColumns[] =
{"i_id", "i_entity_id", "i_status_id", "i_days"};
String ageingEntityStepMessageData[][] = {
{String.valueOf(newEntityId), "1", "0"}, // active (for the welcome message)
};
String ageingEntityStepIntColumns[][][] =
{
{ { "welcome_message", "<div> <br/> <p style='font-size:19px; font-weight: bold;'>Welcome to " +
contact.getOrganizationName() + " Billing!</p> <br/> <p style='font-size:14px; text-align=left; padding-left: 15;'>From here, you can review your latest invoice and get it paid instantly. You can also view all your previous invoices and payments, and set up the system for automatic payment with your credit card.</p> <p style='font-size:14px; text-align=left; padding-left: 15;'>What would you like to do today? </p> <ul style='font-size:13px; text-align=left; padding-left: 25;'> <li >To submit a credit card payment, follow the link on the left bar.</li> <li >To view a list of your invoices, click on the �Invoices� menu option. The first invoice on the list is your latest invoice. Click on it to see its details.</li> <li>To view a list of your payments, click on the �Payments� menu option. The first payment on the list is your latest payment. Click on it to see its details.</li> <li>To provide a credit card to enable automatic payment, click on the menu option 'Account', and then on 'Edit Credit Card'.</li> </ul> </div>" }, }, // act
};
table = addTable(Constants.TABLE_AGEING_ENTITY_STEP,
ageingEntityStepColumns,
ageingEntityStepMessageData,
ageingEntityStepIntColumns, false);
processTable(table);
//BILLING_PROCESS_CONFIGURATION
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, 1);
String inAMonth = Util.parseDate(cal.getTime());
String billingProcessConfigurationColumns[] =
{
"i_id",
"i_entity_id",
"d_next_run_date",
"i_generate_report",
"i_retries",
"i_days_for_retry",
"i_days_for_report",
"i_review_status",
"i_period_unit_id",
"i_period_value",
"i_due_date_unit_id",
"i_due_date_value",
"i_only_recurring",
"i_invoice_date_process",
"i_auto_payment"
};
String billingProcessConfigurationData[][] = {
{ String.valueOf(newEntityId), inAMonth,
"1", "0", "1", "3", "1", "2", "1", "1", "1", "1", "0", "0" },
};
table = addTable(Constants.TABLE_BILLING_PROCESS_CONFIGURATION,
billingProcessConfigurationColumns,
billingProcessConfigurationData, false);
processTable(table);
// CURRENCY_ENTITY_MAP
String currencyEntityMapColumns[] =
{ "i_entity_id", "i_currency_id", };
String currencyEntityMapData[][] = {
{ String.valueOf(newEntityId), "1", },
};
table = addTable(Constants.TABLE_CURRENCY_ENTITY_MAP, currencyEntityMapColumns,
currencyEntityMapData, false);
processTable(table);
//NOTIFICATION_MESSAGE
String messageColumns[] = {
"i_id",
"i_type_id",
"i_entity_id",
"i_language_id",
};
// we provide at least those for english
String messageData[][] = {
{ "1", String.valueOf(newEntityId), "1"}, // invoice email
{ "2", String.valueOf(newEntityId), "1"}, // user reactivatesd
{ "3", String.valueOf(newEntityId), "1"}, // user overdue
{ "13", String.valueOf(newEntityId), "1"}, // order expiring
{ "16", String.valueOf(newEntityId), "1"}, // payment ok
{ "17", String.valueOf(newEntityId), "1"}, // payment failed
{ "18", String.valueOf(newEntityId), "1"}, // invoice reminder
{ "19", String.valueOf(newEntityId), "1"}, // credit card expi
};
table = addTable(Constants.TABLE_NOTIFICATION_MESSAGE, messageColumns,
messageData, false);
processTable(table);
int messageId = table.nextId - 8;
//NOTIFICATION_MESSAGE_SECTION
String sectionColumns[] = {
"i_id",
"i_message_id",
"i_section",
};
String sectionData[][] = {
{ String.valueOf(messageId), "1"},
{ String.valueOf(messageId), "2"},
{ String.valueOf(messageId + 1), "1"},
{ String.valueOf(messageId + 1), "2"},
{ String.valueOf(messageId + 2), "1"},
{ String.valueOf(messageId + 2), "2"},
{ String.valueOf(messageId + 3), "1"},
{ String.valueOf(messageId + 3), "2"},
{ String.valueOf(messageId + 4), "1"},
{ String.valueOf(messageId + 4), "2"},
{ String.valueOf(messageId + 5), "1"},
{ String.valueOf(messageId + 5), "2"},
{ String.valueOf(messageId + 6), "1"},
{ String.valueOf(messageId + 6), "2"},
{ String.valueOf(messageId + 7), "1"},
{ String.valueOf(messageId + 7), "2"},
};
table = addTable(Constants.TABLE_NOTIFICATION_MESSAGE_SECTION,
sectionColumns, sectionData, false);
processTable(table);
int sectionId = table.nextId - 16;
//NOTIFICATION_MESSAGE_LINE
String lineColumns[] = {
"i_id",
"i_message_section_id",
"s_content",
};
String lineData[][] = {
{ String.valueOf(sectionId), "Billing Statement from |company_name|"},
{ String.valueOf(sectionId + 1), "Dear |first_name| |last_name|,\n\n This is to notify you that your latest invoice (number |number|) is now available. The total amount due is: |total|. You can view it by login in to:\n\n" + Util.getSysProp("url") + "/billing/user/login.jsp?entityId=|company_id|\n\nFor security reasons, your statement is password protected.\nTo login in, you will need your user name: |username| and your account password: |password|\n \n After logging in, please click on the menu option �List�, to see all your invoices. You can also see your payment history, your current purchase orders, as well as update your payment information and submit online payments.\n\n\nThank you for choosing |company_name|, we appreciate your business,\n\nBilling Department\n|company_name|"},
{ String.valueOf(sectionId + 2), "You account is now up to date"},
{ String.valueOf(sectionId + 3), "Dear |first_name| |last_name|,\n\n This email is to notify you that we have received your latest payment and your account no longer has an overdue balance.\n\n Thank you for keeping your account up to date,\n\n\nBilling Department\n|company_name|"},
{ String.valueOf(sectionId + 4), "Overdue Balance"},
{ String.valueOf(sectionId + 5), "Dear |first_name| |last_name|,\n\nOur records show that you have an overdue balance on your account. Please submit a payment as soon as possible.\n\nBest regards,\n\nBilling Department\n|company_name|"},
{ String.valueOf(sectionId + 6), "Your service from |company_name| is about to expire"},
{ String.valueOf(sectionId + 7), "Dear |first_name| |last_name|,\n\nYour service with us will expire on |period_end|. Please make sure to contact customer service for a renewal.\n\nRegards,\n\nBilling Department\n|company_name|"},
{ String.valueOf(sectionId + 8), "Thank you for your payment"},
{ String.valueOf(sectionId + 9), "Dear |first_name| |last_name|\n\n We have received your payment made with |method| for a total of |total|.\n\n Thank you, we appreciate your business,\n\nBilling Department\n|company_name|"},
{ String.valueOf(sectionId + 10), "Payment failed"},
{ String.valueOf(sectionId + 11), "Dear |first_name| |last_name|\n\n A payment with |method| was attempted for a total of |total|, but it has been rejected by the payment processor.\nYou can update your payment information and submit an online payment by login into :\n" + Util.getSysProp("url") + "/billing/user/login.jsp?entityId=|company_id|\n\nFor security reasons, your statement is password protected.\nTo login in, you will need your user name: |username| and your account password: |password|\n\nThank you,\n\nBilling Department\n|company_name|"},
{ String.valueOf(sectionId + 12), "Invoice reminder"},
{ String.valueOf(sectionId + 13), "Dear |first_name| |last_name|\n\n This is a reminder that the invoice number |number| remains unpaid. It was sent to you on |date|, and its total is |total|. Although you still have |days| days to pay it (its due date is |dueDate|), we would greatly appreciate if you can pay it at your earliest convenience.\n\nYours truly,\n\nBilling Department\n|company_name|"},
{ String.valueOf(sectionId + 14), "It is time to update your credit card"},
{ String.valueOf(sectionId + 15), "Dear |first_name| |last_name|,\n\nWe want to remind you that the credit card that we have in our records for your account is about to expire. Its expiration date is |expiry_date|.\n\nUpdating your credit card is easy. Just login into " + Util.getSysProp("url") + "/billing/user/login.jsp?entityId=|company_id|. using your user name: |username| and password: |password|. After logging in, click on 'Account' and then 'Edit Credit Card'. \nThank you for keeping your account up to date.\n\nBilling Department\n|company_name|"},
};
table = addTable(Constants.TABLE_NOTIFICATION_MESSAGE_LINE,
lineColumns, lineData, false);
processTable(table);
//ENTITY_DELIVERY_METHOD_MAP
String methodsColumns[] = {
"i_entity_id",
"i_method_id",
};
String methodsData[][] = {
{ String.valueOf(newEntityId), "1"},
{ String.valueOf(newEntityId), "2"},
{ String.valueOf(newEntityId), "3"},
};
table = addTable(Constants.TABLE_ENTITY_DELIVERY_METHOD_MAP,
methodsColumns, methodsData, false);
processTable(table);
return newEntityId;
}
| int initData() throws Exception {
String now = Util.parseDate(Calendar.getInstance().getTime());
//ENTITY
// defaults currency to US dollars
String entityColumns[] =
{ "i_id", "i_external_id", "s_description", "d_create_datetime", "i_language_id", "i_currency_id" };
String entityData[][] = {
{ null, contact.getOrganizationName(), now, languageId.toString(), "1" },
};
Table table = addTable(Constants.TABLE_ENTITY, entityColumns,
entityData, false);
processTable(table);
int newEntityId = table.nextId - 1;
//BASE_USER
String userColumns[] = {
"i_id",
"i_entity_id",
"s_user_name",
"s_password",
"i_deleted",
"i_status_id",
"i_currency_id",
"d_create_datetime",
"d_last_status_change",
"i_language_id"
};
String userData[][] = {
{ String.valueOf(newEntityId), user.getUserName(),
getDBPassword(user), "0", "1", "1", now, null,
languageId.toString() }, //1
};
table = addTable(Constants.TABLE_BASE_USER, userColumns, userData, false);
processTable(table);
int rootUserId = table.nextId - 1;
//USER_ROLE_MAP
String userRoleColumns[] =
{
"i_user_id",
"i_role_id",
};
String userRoleData[][] = {
{ String.valueOf(rootUserId), "2"},
};
table = addTable(Constants.TABLE_USER_ROLE_MAP,
userRoleColumns, userRoleData, false);
processTable(table);
//CONTACT_TYPE
String contactType[] = { "i_id", "i_entity_id", "i_is_primary" };
String contactTypeData[][] = new String[1][2];
String contactTypeIntColumns[][][] = new String [1][1][2];
contactTypeData[0][0] = String.valueOf(newEntityId);
contactTypeData[0][1] = "1";
contactTypeIntColumns[0][0][0] = "description";
contactTypeIntColumns[0][0][1] = "Primary";
table = addTable(Constants.TABLE_CONTACT_TYPE, contactType, contactTypeData,
contactTypeIntColumns, false);
processTable(table);
int pContactType = table.nextId - 1;
//CONTACT
String contactColumns[] = {
"i_id",
"s_ORGANIZATION_NAME",
"s_STREET_ADDRES1",
"s_STREET_ADDRES2",
"s_CITY",
"s_STATE_PROVINCE",
"s_POSTAL_CODE",
"s_COUNTRY_CODE",
"s_LAST_NAME",
"s_FIRST_NAME",
"s_PERSON_INITIAL",
"s_PERSON_TITLE",
"i_PHONE_COUNTRY_CODE",
"i_PHONE_AREA_CODE",
"s_PHONE_PHONE_NUMBER",
"i_FAX_COUNTRY_CODE",
"i_FAX_AREA_CODE",
"s_FAX_PHONE_NUMBER",
"s_EMAIL",
"d_CREATE_DATETIME",
"i_deleted",
"i_user_id"
};
String contactData[][] = {
{
contact.getOrganizationName(),
contact.getAddress1(),
contact.getAddress2(),
contact.getCity(),
contact.getStateProvince(),
contact.getPostalCode(),
contact.getCountryCode(),
null,
null,
null,
null,
(contact.getPhoneCountryCode() == null) ? null :
contact.getPhoneCountryCode().toString(),
(contact.getPhoneAreaCode() == null) ? null :
contact.getPhoneAreaCode().toString(),
contact.getPhoneNumber(),
null, //fax
null,
null,
contact.getEmail(),
now,
"0",
null
},
{
contact.getOrganizationName(),
contact.getAddress1(),
contact.getAddress2(),
contact.getCity(),
contact.getStateProvince(),
contact.getPostalCode(),
contact.getCountryCode(),
contact.getLastName(),
contact.getFirstName(),
null,
null,
(contact.getPhoneCountryCode() == null) ? null :
contact.getPhoneCountryCode().toString(),
(contact.getPhoneAreaCode() == null) ? null :
contact.getPhoneAreaCode().toString(),
contact.getPhoneNumber(),
null, //fax
null,
null,
contact.getEmail(),
now,
"0",
String.valueOf(rootUserId)
},
};
table = addTable(Constants.TABLE_CONTACT, contactColumns, contactData, false);
processTable(table);
int contactId = table.nextId - 2;
//CONTACT_MAP
String contactMapColumns[] =
{ "i_id", "i_contact_id", "i_type_id", "i_table_id", "i_foreign_id" };
String contactMapData[][] = {
{ String.valueOf(contactId), "1", "5", String.valueOf(newEntityId) }, // the contact for the entity
{ String.valueOf(contactId + 1), String.valueOf(pContactType), "10", String.valueOf(rootUserId) },
};
table = addTable(Constants.TABLE_CONTACT_MAP, contactMapColumns, contactMapData, false);
processTable(table);
//ORDER_PERIODS
// puts only monthly now
String orderPeriod[] = { "i_id", "i_entity_id", "i_value", "i_unit_id" };
String orderPeriodData[][] = new String[1][3];
String orderPeriodIntColumns[][][] = new String [1][1][2];
orderPeriodData[0][0] = String.valueOf(newEntityId);
orderPeriodData[0][1] = "1";
orderPeriodData[0][2] = "1"; // month
orderPeriodIntColumns[0][0][0] = "description";
orderPeriodIntColumns[0][0][1] = "Monthly";
table = addTable(Constants.TABLE_ORDER_PERIOD, orderPeriod, orderPeriodData,
orderPeriodIntColumns, false);
processTable(table);
//PLUGGABLE_TASK
String pluggableTaskColumns[] =
{ "i_id", "i_entity_id", "i_type_id", "i_processing_order" };
String pluggableTaskData[][] =
{
{ String.valueOf(newEntityId), "21","1" }, // Fake payment processor
{ String.valueOf(newEntityId), "1", "1" }, // BasicLineTotalTask
{ String.valueOf(newEntityId), "3", "1" }, // CalculateDueDate
{ String.valueOf(newEntityId), "4", "2" }, // BasicCompositionTask
{ String.valueOf(newEntityId), "5", "1" }, // BasicOrderFilterTask
{ String.valueOf(newEntityId), "6", "1" }, // BasicInvoiceFilterTask
{ String.valueOf(newEntityId), "7", "1" }, // BasicOrderPeriodTask
{ String.valueOf(newEntityId), "9", "1" }, // BasicEmailNotificationTask
{ String.valueOf(newEntityId), "10","1" }, // BasicPaymentInfoTask cc info fetcher
{ String.valueOf(newEntityId), "12","2" }, // Paper invoice (for download PDF).
{ String.valueOf(newEntityId), "23","1" }, // Subscriber status manager
{ String.valueOf(newEntityId), "25","1" }, // Async payment processing (no parameters)
};
table = addTable(Constants.TABLE_PLUGGABLE_TASK, pluggableTaskColumns, pluggableTaskData, false);
processTable(table);
int lastCommonPT = table.nextId - 1;
updateBettyTablesRows(table.index, table.nextId);
// the parameters of these tasks
//PLUGGABLE_TASK_PARAMETER
String pluggableTaskParameterColumns[] =
{
"i_id",
"i_task_id",
"s_name",
"i_int_value",
"s_str_value",
"f_float_value"
};
// paper invoice
String pluggableTaskParameterData[][] = {
{ String.valueOf(lastCommonPT - 1), "design", null, "simple_invoice_b2b", null},
};
table = addTable(Constants.TABLE_PLUGGABLE_TASK_PARAMETER, pluggableTaskParameterColumns,
pluggableTaskParameterData, false);
processTable(table);
// fake payment processor
addTaskParameter(table,lastCommonPT - 11, "all", null, "yes", null);
// email parameters. They are all optional
addTaskParameter(table, lastCommonPT - 3, "smtp_server", null,
null, null);
addTaskParameter(table, lastCommonPT - 3, "from", null,
contact.getEmail(), null);
addTaskParameter(table, lastCommonPT - 3, "username", null,
null, null);
addTaskParameter(table, lastCommonPT - 3, "password", null,
null, null);
addTaskParameter(table, lastCommonPT - 3, "port", null,
null, null);
addTaskParameter(table, lastCommonPT - 3, "reply_to", null,
null, null);
addTaskParameter(table, lastCommonPT - 3, "bcc_to", null,
null, null);
addTaskParameter(table, lastCommonPT - 3, "from_name", null,
contact.getOrganizationName(), null);
updateBettyTablesRows(table.index, table.nextId);
// PAYMENT METHODS
//ENTITY_PAYMENT_METHOD_MAP
String entityPaymentMethodMapColumns[] =
{
"i_entity_id",
"i_payment_method_id",
};
String entityPaymentMethodMapData[][] = new String[3][2];
entityPaymentMethodMapData[0][0] = String.valueOf(newEntityId);
entityPaymentMethodMapData[0][1] = "1"; // cheque
entityPaymentMethodMapData[1][0] = String.valueOf(newEntityId);
entityPaymentMethodMapData[1][1] = "2"; // visa
entityPaymentMethodMapData[2][0] = String.valueOf(newEntityId);
entityPaymentMethodMapData[2][1] = "3"; // mc
table = addTable(Constants.TABLE_ENTITY_PAYMENT_METHOD_MAP,
entityPaymentMethodMapColumns,
entityPaymentMethodMapData, false);
processTable(table);
//PREFERENCE
String preferenceColumns[] =
{
"i_id",
"i_type_id",
"i_table_id",
"i_foreign_id",
"i_int_value",
"s_str_value",
"f_float_value"
};
// the table_id = 5, foregin_id = 1, means entity = 1
String preferenceData[][] = {
{"1", "5", String.valueOf(newEntityId), "0", null, null }, // no automatic processing by default
{"2", "5", String.valueOf(newEntityId), null, "/billing/css/jbilling.css", null },
{"3", "5", String.valueOf(newEntityId), null, "/billing/graphics/jbilling.jpg", null },
{"4", "5", String.valueOf(newEntityId), "5", null, null }, // grace period
{"5", "5", String.valueOf(newEntityId), null, null, "10" },
{"6", "5", String.valueOf(newEntityId), null, null, "0" },
{"7", "5", String.valueOf(newEntityId), "0", null, null },
{"8", "5", String.valueOf(newEntityId), "1", null, null },
{"9", "5", String.valueOf(newEntityId), "1", null, null },
{"10","5", String.valueOf(newEntityId), "0", null, null },
{"11","5", String.valueOf(newEntityId), String.valueOf(rootUserId), null, null },
{"12","5", String.valueOf(newEntityId), "1", null, null },
{"13","5", String.valueOf(newEntityId), "1", null, null },
{"14","5", String.valueOf(newEntityId), "0", null, null },
};
table = addTable(Constants.TABLE_PREFERENCE, preferenceColumns,
preferenceData, false);
processTable(table);
//REPORT_ENTITY_MAP
String reportEntityColumns[] =
{
"i_entity_id",
"i_report_id",
};
String reportEntityData[][] = {
{String.valueOf(newEntityId),"1"},
{String.valueOf(newEntityId),"2"},
{String.valueOf(newEntityId),"3"},
{String.valueOf(newEntityId),"4"},
{String.valueOf(newEntityId),"5"},
{String.valueOf(newEntityId),"6"},
{String.valueOf(newEntityId),"7"},
{String.valueOf(newEntityId),"8"},
{String.valueOf(newEntityId),"9"},
{String.valueOf(newEntityId),"10"},
{String.valueOf(newEntityId),"11"},
{String.valueOf(newEntityId),"12"},
{String.valueOf(newEntityId),"13"},
{String.valueOf(newEntityId),"14"},
{String.valueOf(newEntityId),"15"},
{String.valueOf(newEntityId),"16"},
{String.valueOf(newEntityId),"17"},
{String.valueOf(newEntityId),"18"},
{String.valueOf(newEntityId),"20"},
{String.valueOf(newEntityId),"22"},
};
table = addTable(Constants.TABLE_REPORT_ENTITY_MAP,
reportEntityColumns,
reportEntityData, false);
processTable(table);
//AGEING_ENTITY_STEP
String ageingEntityStepColumns[] =
{"i_id", "i_entity_id", "i_status_id", "i_days"};
String ageingEntityStepMessageData[][] = {
{String.valueOf(newEntityId), "1", "0"}, // active (for the welcome message)
};
String ageingEntityStepIntColumns[][][] =
{
{ { "welcome_message", "<div> <br/> <p style='font-size:19px; font-weight: bold;'>Welcome to " +
contact.getOrganizationName() + " Billing!</p> <br/> <p style='font-size:14px; text-align=left; padding-left: 15;'>From here, you can review your latest invoice and get it paid instantly. You can also view all your previous invoices and payments, and set up the system for automatic payment with your credit card.</p> <p style='font-size:14px; text-align=left; padding-left: 15;'>What would you like to do today? </p> <ul style='font-size:13px; text-align=left; padding-left: 25;'> <li >To submit a credit card payment, follow the link on the left bar.</li> <li >To view a list of your invoices, click on the �Invoices� menu option. The first invoice on the list is your latest invoice. Click on it to see its details.</li> <li>To view a list of your payments, click on the �Payments� menu option. The first payment on the list is your latest payment. Click on it to see its details.</li> <li>To provide a credit card to enable automatic payment, click on the menu option 'Account', and then on 'Edit Credit Card'.</li> </ul> </div>" }, }, // act
};
table = addTable(Constants.TABLE_AGEING_ENTITY_STEP,
ageingEntityStepColumns,
ageingEntityStepMessageData,
ageingEntityStepIntColumns, false);
processTable(table);
//BILLING_PROCESS_CONFIGURATION
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, 1);
String inAMonth = Util.parseDate(cal.getTime());
String billingProcessConfigurationColumns[] =
{
"i_id",
"i_entity_id",
"d_next_run_date",
"i_generate_report",
"i_retries",
"i_days_for_retry",
"i_days_for_report",
"i_review_status",
"i_period_unit_id",
"i_period_value",
"i_due_date_unit_id",
"i_due_date_value",
"i_only_recurring",
"i_invoice_date_process",
"i_auto_payment"
};
String billingProcessConfigurationData[][] = {
{ String.valueOf(newEntityId), inAMonth,
"1", "0", "1", "3", "1", "2", "1", "1", "1", "1", "0", "0" },
};
table = addTable(Constants.TABLE_BILLING_PROCESS_CONFIGURATION,
billingProcessConfigurationColumns,
billingProcessConfigurationData, false);
processTable(table);
// CURRENCY_ENTITY_MAP
String currencyEntityMapColumns[] =
{ "i_entity_id", "i_currency_id", };
String currencyEntityMapData[][] = {
{ String.valueOf(newEntityId), "1", },
};
table = addTable(Constants.TABLE_CURRENCY_ENTITY_MAP, currencyEntityMapColumns,
currencyEntityMapData, false);
processTable(table);
//NOTIFICATION_MESSAGE
String messageColumns[] = {
"i_id",
"i_type_id",
"i_entity_id",
"i_language_id",
};
// we provide at least those for english
String messageData[][] = {
{ "1", String.valueOf(newEntityId), "1"}, // invoice email
{ "2", String.valueOf(newEntityId), "1"}, // user reactivatesd
{ "3", String.valueOf(newEntityId), "1"}, // user overdue
{ "13", String.valueOf(newEntityId), "1"}, // order expiring
{ "16", String.valueOf(newEntityId), "1"}, // payment ok
{ "17", String.valueOf(newEntityId), "1"}, // payment failed
{ "18", String.valueOf(newEntityId), "1"}, // invoice reminder
{ "19", String.valueOf(newEntityId), "1"}, // credit card expi
};
table = addTable(Constants.TABLE_NOTIFICATION_MESSAGE, messageColumns,
messageData, false);
processTable(table);
int messageId = table.nextId - 8;
//NOTIFICATION_MESSAGE_SECTION
String sectionColumns[] = {
"i_id",
"i_message_id",
"i_section",
};
String sectionData[][] = {
{ String.valueOf(messageId), "1"},
{ String.valueOf(messageId), "2"},
{ String.valueOf(messageId + 1), "1"},
{ String.valueOf(messageId + 1), "2"},
{ String.valueOf(messageId + 2), "1"},
{ String.valueOf(messageId + 2), "2"},
{ String.valueOf(messageId + 3), "1"},
{ String.valueOf(messageId + 3), "2"},
{ String.valueOf(messageId + 4), "1"},
{ String.valueOf(messageId + 4), "2"},
{ String.valueOf(messageId + 5), "1"},
{ String.valueOf(messageId + 5), "2"},
{ String.valueOf(messageId + 6), "1"},
{ String.valueOf(messageId + 6), "2"},
{ String.valueOf(messageId + 7), "1"},
{ String.valueOf(messageId + 7), "2"},
};
table = addTable(Constants.TABLE_NOTIFICATION_MESSAGE_SECTION,
sectionColumns, sectionData, false);
processTable(table);
int sectionId = table.nextId - 16;
//NOTIFICATION_MESSAGE_LINE
String lineColumns[] = {
"i_id",
"i_message_section_id",
"s_content",
};
String lineData[][] = {
{ String.valueOf(sectionId), "Billing Statement from |company_name|"},
{ String.valueOf(sectionId + 1), "Dear |first_name| |last_name|,\n\n This is to notify you that your latest invoice (number |number|) is now available. The total amount due is: |total|. You can view it by login in to:\n\n" + Util.getSysProp("url") + "/billing/user/login.jsp?entityId=|company_id|\n\nFor security reasons, your statement is password protected.\nTo login in, you will need your user name: |username| and your account password: |password|\n \n After logging in, please click on the menu option �List�, to see all your invoices. You can also see your payment history, your current purchase orders, as well as update your payment information and submit online payments.\n\n\nThank you for choosing |company_name|, we appreciate your business,\n\nBilling Department\n|company_name|"},
{ String.valueOf(sectionId + 2), "You account is now up to date"},
{ String.valueOf(sectionId + 3), "Dear |first_name| |last_name|,\n\n This email is to notify you that we have received your latest payment and your account no longer has an overdue balance.\n\n Thank you for keeping your account up to date,\n\n\nBilling Department\n|company_name|"},
{ String.valueOf(sectionId + 4), "Overdue Balance"},
{ String.valueOf(sectionId + 5), "Dear |first_name| |last_name|,\n\nOur records show that you have an overdue balance on your account. Please submit a payment as soon as possible.\n\nBest regards,\n\nBilling Department\n|company_name|"},
{ String.valueOf(sectionId + 6), "Your service from |company_name| is about to expire"},
{ String.valueOf(sectionId + 7), "Dear |first_name| |last_name|,\n\nYour service with us will expire on |period_end|. Please make sure to contact customer service for a renewal.\n\nRegards,\n\nBilling Department\n|company_name|"},
{ String.valueOf(sectionId + 8), "Thank you for your payment"},
{ String.valueOf(sectionId + 9), "Dear |first_name| |last_name|\n\n We have received your payment made with |method| for a total of |total|.\n\n Thank you, we appreciate your business,\n\nBilling Department\n|company_name|"},
{ String.valueOf(sectionId + 10), "Payment failed"},
{ String.valueOf(sectionId + 11), "Dear |first_name| |last_name|\n\n A payment with |method| was attempted for a total of |total|, but it has been rejected by the payment processor.\nYou can update your payment information and submit an online payment by login into :\n" + Util.getSysProp("url") + "/billing/user/login.jsp?entityId=|company_id|\n\nFor security reasons, your statement is password protected.\nTo login in, you will need your user name: |username| and your account password: |password|\n\nThank you,\n\nBilling Department\n|company_name|"},
{ String.valueOf(sectionId + 12), "Invoice reminder"},
{ String.valueOf(sectionId + 13), "Dear |first_name| |last_name|\n\n This is a reminder that the invoice number |number| remains unpaid. It was sent to you on |date|, and its total is |total|. Although you still have |days| days to pay it (its due date is |dueDate|), we would greatly appreciate if you can pay it at your earliest convenience.\n\nYours truly,\n\nBilling Department\n|company_name|"},
{ String.valueOf(sectionId + 14), "It is time to update your credit card"},
{ String.valueOf(sectionId + 15), "Dear |first_name| |last_name|,\n\nWe want to remind you that the credit card that we have in our records for your account is about to expire. Its expiration date is |expiry_date|.\n\nUpdating your credit card is easy. Just login into " + Util.getSysProp("url") + "/billing/user/login.jsp?entityId=|company_id|. using your user name: |username| and password: |password|. After logging in, click on 'Account' and then 'Edit Credit Card'. \nThank you for keeping your account up to date.\n\nBilling Department\n|company_name|"},
};
table = addTable(Constants.TABLE_NOTIFICATION_MESSAGE_LINE,
lineColumns, lineData, false);
processTable(table);
//ENTITY_DELIVERY_METHOD_MAP
String methodsColumns[] = {
"i_entity_id",
"i_method_id",
};
String methodsData[][] = {
{ String.valueOf(newEntityId), "1"},
{ String.valueOf(newEntityId), "2"},
{ String.valueOf(newEntityId), "3"},
};
table = addTable(Constants.TABLE_ENTITY_DELIVERY_METHOD_MAP,
methodsColumns, methodsData, false);
processTable(table);
return newEntityId;
}
|
diff --git a/common/src/main/java/com/sishuok/es/common/web/bind/method/annotation/FormModelMethodArgumentResolver.java b/common/src/main/java/com/sishuok/es/common/web/bind/method/annotation/FormModelMethodArgumentResolver.java
index f842d67..2cf07f7 100644
--- a/common/src/main/java/com/sishuok/es/common/web/bind/method/annotation/FormModelMethodArgumentResolver.java
+++ b/common/src/main/java/com/sishuok/es/common/web/bind/method/annotation/FormModelMethodArgumentResolver.java
@@ -1,527 +1,527 @@
package com.sishuok.es.common.web.bind.method.annotation;
import com.sishuok.es.common.web.bind.annotation.FormModel;
import com.sishuok.es.common.web.bind.util.MapWapper;
import org.springframework.beans.BeanUtils;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockMultipartHttpServletRequest;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.validation.DataBinder;
import org.springframework.validation.Errors;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.ServletRequestParameterPropertyValues;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.multipart.MultipartRequest;
import org.springframework.web.util.WebUtils;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.lang.annotation.Annotation;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.*;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* <p>用于绑定@FormModel的方法参数解析器
* <p>User: Zhang Kaitao
* <p>Date: 13-1-12 下午5:01
* <p>Version: 1.0
*
* @since 3.1
*/
public class FormModelMethodArgumentResolver extends BaseMethodArgumentResolver {
/**
* 提取索引的模式 如[0].
*/
private final Pattern INDEX_PATTERN = Pattern.compile("\\[(\\d+)\\]\\.?");
private int autoGrowCollectionLimit = Integer.MAX_VALUE;
public FormModelMethodArgumentResolver() {
}
@Override
public boolean supportsParameter(MethodParameter parameter) {
if (parameter.hasParameterAnnotation(FormModel.class)) {
return true;
}
return false;
}
/**
* Resolve the argument from the model or if not found instantiate it with
* its default if it is available. The model attribute is then populated
* with request values via data binding and optionally validated
* if {@code @java.validation.Valid} is present on the argument.
*
* @throws org.springframework.validation.BindException
* if data binding and validation result in an error
* and the next method parameter is not of type {@link org.springframework.validation.Errors}.
* @throws Exception if WebDataBinder initialization fails.
*/
public final Object resolveArgument(MethodParameter parameter,
ModelAndViewContainer mavContainer,
NativeWebRequest request,
WebDataBinderFactory binderFactory) throws Exception {
String name = parameter.getParameterAnnotation(FormModel.class).value();
Object target = (mavContainer.containsAttribute(name)) ?
mavContainer.getModel().get(name) : createAttribute(name, parameter, binderFactory, request);
WebDataBinder binder = binderFactory.createBinder(request, target, name);
target = binder.getTarget();
if (target != null) {
bindRequestParameters(mavContainer, binderFactory, binder, request, parameter);
validateIfApplicable(binder, parameter);
if (binder.getBindingResult().hasErrors()) {
if (isBindExceptionRequired(binder, parameter)) {
throw new BindException(binder.getBindingResult());
}
}
}
target = binder.convertIfNecessary(binder.getTarget(), parameter.getParameterType());
mavContainer.addAttribute(name, target);
return target;
}
/**
* Extension point to create the model attribute if not found in the model.
* The default implementation uses the default constructor.
*
* @param attributeName the name of the attribute, never {@code null}
* @param parameter the method parameter
* @param binderFactory for creating WebDataBinder instance
* @param request the current request
* @return the created model attribute, never {@code null}
*/
protected Object createAttribute(String attributeName, MethodParameter parameter,
WebDataBinderFactory binderFactory, NativeWebRequest request) throws Exception {
String value = getRequestValueForAttribute(attributeName, request);
if (value != null) {
Object attribute = createAttributeFromRequestValue(value, attributeName, parameter, binderFactory, request);
if (attribute != null) {
return attribute;
}
}
Class<?> parameterType = parameter.getParameterType();
if (parameterType.isArray() || List.class.isAssignableFrom(parameterType)) {
return ArrayList.class.newInstance();
}
if (Set.class.isAssignableFrom(parameterType)) {
return HashSet.class.newInstance();
}
if (MapWapper.class.isAssignableFrom(parameterType)) {
return MapWapper.class.newInstance();
}
return BeanUtils.instantiateClass(parameter.getParameterType());
}
/**
* Obtain a value from the request that may be used to instantiate the
* model attribute through type conversion from String to the target type.
* <p>The default implementation looks for the attribute name to match
* a URI variable first and then a request parameter.
*
* @param attributeName the model attribute name
* @param request the current request
* @return the request value to try to convert or {@code null}
*/
protected String getRequestValueForAttribute(String attributeName, NativeWebRequest request) {
Map<String, String> variables = getUriTemplateVariables(request);
if (StringUtils.hasText(variables.get(attributeName))) {
return variables.get(attributeName);
} else if (StringUtils.hasText(request.getParameter(attributeName))) {
return request.getParameter(attributeName);
} else {
return null;
}
}
/**
* Create a model attribute from a String request value (e.g. URI template
* variable, request parameter) using type conversion.
* <p>The default implementation converts only if there a registered
* {@link org.springframework.core.convert.converter.Converter} that can perform the conversion.
*
* @param sourceValue the source value to create the model attribute from
* @param attributeName the name of the attribute, never {@code null}
* @param parameter the method parameter
* @param binderFactory for creating WebDataBinder instance
* @param request the current request
* @return the created model attribute, or {@code null}
* @throws Exception
*/
protected Object createAttributeFromRequestValue(String sourceValue,
String attributeName,
MethodParameter parameter,
WebDataBinderFactory binderFactory,
NativeWebRequest request) throws Exception {
DataBinder binder = binderFactory.createBinder(request, null, attributeName);
ConversionService conversionService = binder.getConversionService();
if (conversionService != null) {
TypeDescriptor source = TypeDescriptor.valueOf(String.class);
TypeDescriptor target = new TypeDescriptor(parameter);
if (conversionService.canConvert(source, target)) {
return binder.convertIfNecessary(sourceValue, parameter.getParameterType(), parameter);
}
}
return null;
}
/**
* {@inheritDoc}
* <p>Downcast {@link org.springframework.web.bind.WebDataBinder} to {@link org.springframework.web.bind.ServletRequestDataBinder} before binding.
*
* @throws Exception
* @see org.springframework.web.servlet.mvc.method.annotation.ServletRequestDataBinderFactory
*/
protected void bindRequestParameters(
ModelAndViewContainer mavContainer,
WebDataBinderFactory binderFactory,
WebDataBinder binder,
NativeWebRequest request,
MethodParameter parameter) throws Exception {
Map<String, Boolean> hasProcessedPrefixMap = new HashMap<String, Boolean>();
Class<?> targetType = binder.getTarget().getClass();
ServletRequest servletRequest = prepareServletRequest(binder.getTarget(), request, parameter);
WebDataBinder simpleBinder = binderFactory.createBinder(request, null, null);
if (Collection.class.isAssignableFrom(targetType)) {//bind collection or array
Type type = parameter.getGenericParameterType();
Class<?> componentType = Object.class;
Collection target = (Collection) binder.getTarget();
List targetList = new ArrayList(target);
if (type instanceof ParameterizedType) {
componentType = (Class<?>) ((ParameterizedType) type).getActualTypeArguments()[0];
}
if (parameter.getParameterType().isArray()) {
componentType = parameter.getParameterType().getComponentType();
}
for (Object key : servletRequest.getParameterMap().keySet()) {
String prefixName = getPrefixName((String) key);
//每个prefix 只处理一次
if (hasProcessedPrefixMap.containsKey(prefixName)) {
continue;
} else {
hasProcessedPrefixMap.put(prefixName, Boolean.TRUE);
}
if (isSimpleComponent(prefixName)) { //bind simple type
Map<String, Object> paramValues = WebUtils.getParametersStartingWith(servletRequest, prefixName);
Matcher matcher = INDEX_PATTERN.matcher(prefixName);
if(!matcher.matches()) { //处理如 array=1&array=2的情况
for (Object value : paramValues.values()) {
targetList.add(simpleBinder.convertIfNecessary(value, componentType));
}
} else { //处理如 array[0]=1&array[1]=2的情况
int index = Integer.valueOf(matcher.group(1));
if (targetList.size() <= index) {
growCollectionIfNecessary(targetList, index);
}
targetList.set(index, simpleBinder.convertIfNecessary(paramValues.values(), componentType));
}
} else { //处理如 votes[1].title=votes[1].title&votes[0].title=votes[0].title&votes[0].id=0&votes[1].id=1
Object component = null;
//先查找老的 即已经在集合中的数据(而不是新添加一个)
Matcher matcher = INDEX_PATTERN.matcher(prefixName);
if(!matcher.matches()) {
throw new IllegalArgumentException("bind collection error, need integer index, key:" + key);
}
int index = Integer.valueOf(matcher.group(1));
if (targetList.size() <= index) {
growCollectionIfNecessary(targetList, index);
}
Iterator iterator = targetList.iterator();
for (int i = 0; i < index; i++) {
iterator.next();
}
component = iterator.next();
if(component == null) {
component = BeanUtils.instantiate(componentType);
}
WebDataBinder componentBinder = binderFactory.createBinder(request, component, null);
component = componentBinder.getTarget();
if (component != null) {
ServletRequestParameterPropertyValues pvs = new ServletRequestParameterPropertyValues(servletRequest, prefixName, "");
componentBinder.bind(pvs);
validateIfApplicable(componentBinder, parameter);
if (componentBinder.getBindingResult().hasErrors()) {
if (isBindExceptionRequired(componentBinder, parameter)) {
throw new BindException(componentBinder.getBindingResult());
}
}
targetList.set(index, component);
}
}
target.clear();
target.addAll(targetList);
}
} else if (MapWapper.class.isAssignableFrom(targetType)) {
Type type = parameter.getGenericParameterType();
Class<?> keyType = Object.class;
Class<?> valueType = Object.class;
if (type instanceof ParameterizedType) {
keyType = (Class<?>) ((ParameterizedType) type).getActualTypeArguments()[0];
valueType = (Class<?>) ((ParameterizedType) type).getActualTypeArguments()[1];
}
MapWapper mapWapper = ((MapWapper) binder.getTarget());
Map target = mapWapper.getInnerMap();
if(target == null) {
target = new HashMap();
mapWapper.setInnerMap(target);
}
for (Object key : servletRequest.getParameterMap().keySet()) {
String prefixName = getPrefixName((String) key);
//每个prefix 只处理一次
if (hasProcessedPrefixMap.containsKey(prefixName)) {
continue;
} else {
hasProcessedPrefixMap.put(prefixName, Boolean.TRUE);
}
Object keyValue = simpleBinder.convertIfNecessary(getMapKey(prefixName), keyType);
if (isSimpleComponent(prefixName)) { //bind simple type
Map<String, Object> paramValues = WebUtils.getParametersStartingWith(servletRequest, prefixName);
for (Object value : paramValues.values()) {
target.put(keyValue, simpleBinder.convertIfNecessary(value, valueType));
}
} else {
Object component = target.get(keyValue);
if(component == null) {
- BeanUtils.instantiate(valueType);
+ component = BeanUtils.instantiate(valueType);
}
WebDataBinder componentBinder = binderFactory.createBinder(request, component, null);
component = componentBinder.getTarget();
if (component != null) {
ServletRequestParameterPropertyValues pvs = new ServletRequestParameterPropertyValues(servletRequest, prefixName, "");
componentBinder.bind(pvs);
validateComponent(componentBinder, parameter);
target.put(keyValue, component);
}
}
}
} else {//bind model
ServletRequestDataBinder servletBinder = (ServletRequestDataBinder) binder;
servletBinder.bind(servletRequest);
}
}
private void growCollectionIfNecessary(final Collection collection, final int index) {
if(index >= collection.size() && index < this.autoGrowCollectionLimit) {
for (int i = collection.size(); i <= index; i++) {
collection.add(null);
}
}
}
private Object getMapKey(String prefixName) {
String key = prefixName;
if (key.startsWith("['")) {
key = key.replaceAll("\\[\'", "").replaceAll("\'\\]", "");
}
if (key.startsWith("[\"")) {
key = key.replaceAll("\\[\"", "").replaceAll("\"\\]", "");
}
if (key.endsWith(".")) {
key = key.substring(0, key.length() - 1);
}
return key;
}
private boolean isSimpleComponent(String prefixName) {
return !prefixName.endsWith(".");
}
private String getPrefixName(String name) {
int begin = 0;
int end = name.indexOf("]") + 1;
if (name.indexOf("].") >= 0) {
end = end + 1;
}
return name.substring(begin, end);
}
private ServletRequest prepareServletRequest(Object target, NativeWebRequest request, MethodParameter parameter) {
String modelPrefixName = parameter.getParameterAnnotation(FormModel.class).value();
HttpServletRequest nativeRequest = (HttpServletRequest) request.getNativeRequest();
MultipartRequest multipartRequest = WebUtils.getNativeRequest(nativeRequest, MultipartRequest.class);
MockHttpServletRequest mockRequest = null;
if (multipartRequest != null) {
MockMultipartHttpServletRequest mockMultipartRequest = new MockMultipartHttpServletRequest();
mockMultipartRequest.getMultiFileMap().putAll(multipartRequest.getMultiFileMap());
} else {
mockRequest = new MockHttpServletRequest();
}
for (Entry<String, String> entry : getUriTemplateVariables(request).entrySet()) {
String parameterName = entry.getKey();
String value = entry.getValue();
if (isFormModelAttribute(parameterName, modelPrefixName)) {
mockRequest.setParameter(getNewParameterName(parameterName, modelPrefixName), value);
}
}
for (Object parameterEntry : nativeRequest.getParameterMap().entrySet()) {
Entry<String, String[]> entry = (Entry<String, String[]>) parameterEntry;
String parameterName = entry.getKey();
String[] value = entry.getValue();
if (isFormModelAttribute(parameterName, modelPrefixName)) {
mockRequest.setParameter(getNewParameterName(parameterName, modelPrefixName), value);
}
}
return mockRequest;
}
private String getNewParameterName(String parameterName, String modelPrefixName) {
int modelPrefixNameLength = modelPrefixName.length();
if (parameterName.charAt(modelPrefixNameLength) == '.') {
return parameterName.substring(modelPrefixNameLength + 1);
}
if (parameterName.charAt(modelPrefixNameLength) == '[') {
return parameterName.substring(modelPrefixNameLength);
}
throw new IllegalArgumentException("illegal request parameter, can not binding to @FormBean(" + modelPrefixName + ")");
}
private boolean isFormModelAttribute(String parameterName, String modelPrefixName) {
int modelPrefixNameLength = modelPrefixName.length();
if (parameterName.length() == modelPrefixNameLength) {
return false;
}
if (!parameterName.startsWith(modelPrefixName)) {
return false;
}
char ch = (char) parameterName.charAt(modelPrefixNameLength);
if (ch == '.' || ch == '[') {
return true;
}
return false;
}
protected void validateComponent(WebDataBinder binder, MethodParameter parameter) throws BindException {
boolean validateParameter = validateParameter(parameter);
Annotation[] annotations = binder.getTarget().getClass().getAnnotations();
for (Annotation annot : annotations) {
if (annot.annotationType().getSimpleName().startsWith("Valid") && validateParameter) {
Object hints = AnnotationUtils.getValue(annot);
binder.validate(hints instanceof Object[] ? (Object[]) hints : new Object[]{hints});
}
}
if (binder.getBindingResult().hasErrors()) {
if (isBindExceptionRequired(binder, parameter)) {
throw new BindException(binder.getBindingResult());
}
}
}
private boolean validateParameter(MethodParameter parameter) {
Annotation[] annotations = parameter.getParameterAnnotations();
for (Annotation annot : annotations) {
if (annot.annotationType().getSimpleName().startsWith("Valid")) {
return true;
}
}
return false;
}
/**
* Validate the model attribute if applicable.
* <p>The default implementation checks for {@code @javax.validation.Valid}.
*
* @param binder the DataBinder to be used
* @param parameter the method parameter
*/
protected void validateIfApplicable(WebDataBinder binder, MethodParameter parameter) {
Annotation[] annotations = parameter.getParameterAnnotations();
for (Annotation annot : annotations) {
if (annot.annotationType().getSimpleName().startsWith("Valid")) {
Object hints = AnnotationUtils.getValue(annot);
binder.validate(hints instanceof Object[] ? (Object[]) hints : new Object[]{hints});
}
}
}
/**
* Whether to raise a {@link org.springframework.validation.BindException} on bind or validation errors.
* The default implementation returns {@code true} if the next method
* argument is not of type {@link org.springframework.validation.Errors}.
*
* @param binder the data binder used to perform data binding
* @param parameter the method argument
*/
protected boolean isBindExceptionRequired(WebDataBinder binder, MethodParameter parameter) {
int i = parameter.getParameterIndex();
Class<?>[] paramTypes = parameter.getMethod().getParameterTypes();
boolean hasBindingResult = (paramTypes.length > (i + 1) && Errors.class.isAssignableFrom(paramTypes[i + 1]));
return !hasBindingResult;
}
}
| true | true | protected void bindRequestParameters(
ModelAndViewContainer mavContainer,
WebDataBinderFactory binderFactory,
WebDataBinder binder,
NativeWebRequest request,
MethodParameter parameter) throws Exception {
Map<String, Boolean> hasProcessedPrefixMap = new HashMap<String, Boolean>();
Class<?> targetType = binder.getTarget().getClass();
ServletRequest servletRequest = prepareServletRequest(binder.getTarget(), request, parameter);
WebDataBinder simpleBinder = binderFactory.createBinder(request, null, null);
if (Collection.class.isAssignableFrom(targetType)) {//bind collection or array
Type type = parameter.getGenericParameterType();
Class<?> componentType = Object.class;
Collection target = (Collection) binder.getTarget();
List targetList = new ArrayList(target);
if (type instanceof ParameterizedType) {
componentType = (Class<?>) ((ParameterizedType) type).getActualTypeArguments()[0];
}
if (parameter.getParameterType().isArray()) {
componentType = parameter.getParameterType().getComponentType();
}
for (Object key : servletRequest.getParameterMap().keySet()) {
String prefixName = getPrefixName((String) key);
//每个prefix 只处理一次
if (hasProcessedPrefixMap.containsKey(prefixName)) {
continue;
} else {
hasProcessedPrefixMap.put(prefixName, Boolean.TRUE);
}
if (isSimpleComponent(prefixName)) { //bind simple type
Map<String, Object> paramValues = WebUtils.getParametersStartingWith(servletRequest, prefixName);
Matcher matcher = INDEX_PATTERN.matcher(prefixName);
if(!matcher.matches()) { //处理如 array=1&array=2的情况
for (Object value : paramValues.values()) {
targetList.add(simpleBinder.convertIfNecessary(value, componentType));
}
} else { //处理如 array[0]=1&array[1]=2的情况
int index = Integer.valueOf(matcher.group(1));
if (targetList.size() <= index) {
growCollectionIfNecessary(targetList, index);
}
targetList.set(index, simpleBinder.convertIfNecessary(paramValues.values(), componentType));
}
} else { //处理如 votes[1].title=votes[1].title&votes[0].title=votes[0].title&votes[0].id=0&votes[1].id=1
Object component = null;
//先查找老的 即已经在集合中的数据(而不是新添加一个)
Matcher matcher = INDEX_PATTERN.matcher(prefixName);
if(!matcher.matches()) {
throw new IllegalArgumentException("bind collection error, need integer index, key:" + key);
}
int index = Integer.valueOf(matcher.group(1));
if (targetList.size() <= index) {
growCollectionIfNecessary(targetList, index);
}
Iterator iterator = targetList.iterator();
for (int i = 0; i < index; i++) {
iterator.next();
}
component = iterator.next();
if(component == null) {
component = BeanUtils.instantiate(componentType);
}
WebDataBinder componentBinder = binderFactory.createBinder(request, component, null);
component = componentBinder.getTarget();
if (component != null) {
ServletRequestParameterPropertyValues pvs = new ServletRequestParameterPropertyValues(servletRequest, prefixName, "");
componentBinder.bind(pvs);
validateIfApplicable(componentBinder, parameter);
if (componentBinder.getBindingResult().hasErrors()) {
if (isBindExceptionRequired(componentBinder, parameter)) {
throw new BindException(componentBinder.getBindingResult());
}
}
targetList.set(index, component);
}
}
target.clear();
target.addAll(targetList);
}
} else if (MapWapper.class.isAssignableFrom(targetType)) {
Type type = parameter.getGenericParameterType();
Class<?> keyType = Object.class;
Class<?> valueType = Object.class;
if (type instanceof ParameterizedType) {
keyType = (Class<?>) ((ParameterizedType) type).getActualTypeArguments()[0];
valueType = (Class<?>) ((ParameterizedType) type).getActualTypeArguments()[1];
}
MapWapper mapWapper = ((MapWapper) binder.getTarget());
Map target = mapWapper.getInnerMap();
if(target == null) {
target = new HashMap();
mapWapper.setInnerMap(target);
}
for (Object key : servletRequest.getParameterMap().keySet()) {
String prefixName = getPrefixName((String) key);
//每个prefix 只处理一次
if (hasProcessedPrefixMap.containsKey(prefixName)) {
continue;
} else {
hasProcessedPrefixMap.put(prefixName, Boolean.TRUE);
}
Object keyValue = simpleBinder.convertIfNecessary(getMapKey(prefixName), keyType);
if (isSimpleComponent(prefixName)) { //bind simple type
Map<String, Object> paramValues = WebUtils.getParametersStartingWith(servletRequest, prefixName);
for (Object value : paramValues.values()) {
target.put(keyValue, simpleBinder.convertIfNecessary(value, valueType));
}
} else {
Object component = target.get(keyValue);
if(component == null) {
BeanUtils.instantiate(valueType);
}
WebDataBinder componentBinder = binderFactory.createBinder(request, component, null);
component = componentBinder.getTarget();
if (component != null) {
ServletRequestParameterPropertyValues pvs = new ServletRequestParameterPropertyValues(servletRequest, prefixName, "");
componentBinder.bind(pvs);
validateComponent(componentBinder, parameter);
target.put(keyValue, component);
}
}
}
} else {//bind model
ServletRequestDataBinder servletBinder = (ServletRequestDataBinder) binder;
servletBinder.bind(servletRequest);
}
}
| protected void bindRequestParameters(
ModelAndViewContainer mavContainer,
WebDataBinderFactory binderFactory,
WebDataBinder binder,
NativeWebRequest request,
MethodParameter parameter) throws Exception {
Map<String, Boolean> hasProcessedPrefixMap = new HashMap<String, Boolean>();
Class<?> targetType = binder.getTarget().getClass();
ServletRequest servletRequest = prepareServletRequest(binder.getTarget(), request, parameter);
WebDataBinder simpleBinder = binderFactory.createBinder(request, null, null);
if (Collection.class.isAssignableFrom(targetType)) {//bind collection or array
Type type = parameter.getGenericParameterType();
Class<?> componentType = Object.class;
Collection target = (Collection) binder.getTarget();
List targetList = new ArrayList(target);
if (type instanceof ParameterizedType) {
componentType = (Class<?>) ((ParameterizedType) type).getActualTypeArguments()[0];
}
if (parameter.getParameterType().isArray()) {
componentType = parameter.getParameterType().getComponentType();
}
for (Object key : servletRequest.getParameterMap().keySet()) {
String prefixName = getPrefixName((String) key);
//每个prefix 只处理一次
if (hasProcessedPrefixMap.containsKey(prefixName)) {
continue;
} else {
hasProcessedPrefixMap.put(prefixName, Boolean.TRUE);
}
if (isSimpleComponent(prefixName)) { //bind simple type
Map<String, Object> paramValues = WebUtils.getParametersStartingWith(servletRequest, prefixName);
Matcher matcher = INDEX_PATTERN.matcher(prefixName);
if(!matcher.matches()) { //处理如 array=1&array=2的情况
for (Object value : paramValues.values()) {
targetList.add(simpleBinder.convertIfNecessary(value, componentType));
}
} else { //处理如 array[0]=1&array[1]=2的情况
int index = Integer.valueOf(matcher.group(1));
if (targetList.size() <= index) {
growCollectionIfNecessary(targetList, index);
}
targetList.set(index, simpleBinder.convertIfNecessary(paramValues.values(), componentType));
}
} else { //处理如 votes[1].title=votes[1].title&votes[0].title=votes[0].title&votes[0].id=0&votes[1].id=1
Object component = null;
//先查找老的 即已经在集合中的数据(而不是新添加一个)
Matcher matcher = INDEX_PATTERN.matcher(prefixName);
if(!matcher.matches()) {
throw new IllegalArgumentException("bind collection error, need integer index, key:" + key);
}
int index = Integer.valueOf(matcher.group(1));
if (targetList.size() <= index) {
growCollectionIfNecessary(targetList, index);
}
Iterator iterator = targetList.iterator();
for (int i = 0; i < index; i++) {
iterator.next();
}
component = iterator.next();
if(component == null) {
component = BeanUtils.instantiate(componentType);
}
WebDataBinder componentBinder = binderFactory.createBinder(request, component, null);
component = componentBinder.getTarget();
if (component != null) {
ServletRequestParameterPropertyValues pvs = new ServletRequestParameterPropertyValues(servletRequest, prefixName, "");
componentBinder.bind(pvs);
validateIfApplicable(componentBinder, parameter);
if (componentBinder.getBindingResult().hasErrors()) {
if (isBindExceptionRequired(componentBinder, parameter)) {
throw new BindException(componentBinder.getBindingResult());
}
}
targetList.set(index, component);
}
}
target.clear();
target.addAll(targetList);
}
} else if (MapWapper.class.isAssignableFrom(targetType)) {
Type type = parameter.getGenericParameterType();
Class<?> keyType = Object.class;
Class<?> valueType = Object.class;
if (type instanceof ParameterizedType) {
keyType = (Class<?>) ((ParameterizedType) type).getActualTypeArguments()[0];
valueType = (Class<?>) ((ParameterizedType) type).getActualTypeArguments()[1];
}
MapWapper mapWapper = ((MapWapper) binder.getTarget());
Map target = mapWapper.getInnerMap();
if(target == null) {
target = new HashMap();
mapWapper.setInnerMap(target);
}
for (Object key : servletRequest.getParameterMap().keySet()) {
String prefixName = getPrefixName((String) key);
//每个prefix 只处理一次
if (hasProcessedPrefixMap.containsKey(prefixName)) {
continue;
} else {
hasProcessedPrefixMap.put(prefixName, Boolean.TRUE);
}
Object keyValue = simpleBinder.convertIfNecessary(getMapKey(prefixName), keyType);
if (isSimpleComponent(prefixName)) { //bind simple type
Map<String, Object> paramValues = WebUtils.getParametersStartingWith(servletRequest, prefixName);
for (Object value : paramValues.values()) {
target.put(keyValue, simpleBinder.convertIfNecessary(value, valueType));
}
} else {
Object component = target.get(keyValue);
if(component == null) {
component = BeanUtils.instantiate(valueType);
}
WebDataBinder componentBinder = binderFactory.createBinder(request, component, null);
component = componentBinder.getTarget();
if (component != null) {
ServletRequestParameterPropertyValues pvs = new ServletRequestParameterPropertyValues(servletRequest, prefixName, "");
componentBinder.bind(pvs);
validateComponent(componentBinder, parameter);
target.put(keyValue, component);
}
}
}
} else {//bind model
ServletRequestDataBinder servletBinder = (ServletRequestDataBinder) binder;
servletBinder.bind(servletRequest);
}
}
|
diff --git a/src/org/apache/xerces/dom/DOMNormalizer.java b/src/org/apache/xerces/dom/DOMNormalizer.java
index d0a9b1f5..ec75fcff 100644
--- a/src/org/apache/xerces/dom/DOMNormalizer.java
+++ b/src/org/apache/xerces/dom/DOMNormalizer.java
@@ -1,1119 +1,1119 @@
/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999-2002 The Apache Software Foundation. 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. 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 "Xerces" 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 (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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 2002, International
* Business Machines, Inc., http://www.apache.org. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.xerces.dom;
import org.w3c.dom.DOMErrorHandler;
import org.apache.xerces.impl.Constants;
import org.apache.xerces.impl.RevalidationHandler;
import org.apache.xerces.util.AugmentationsImpl;
import org.apache.xerces.util.NamespaceSupport;
import org.apache.xerces.util.SymbolTable;
import org.apache.xerces.util.XMLSymbols;
import org.apache.xerces.parsers.AbstractXMLDocumentParser;
import org.apache.xerces.xni.Augmentations;
import org.apache.xerces.xni.QName;
import org.apache.xerces.xni.XMLDocumentHandler;
import org.apache.xerces.xni.XMLAttributes;
import org.apache.xerces.xni.XMLString;
import org.apache.xerces.xni.XNIException;
import org.apache.xerces.xni.parser.XMLComponent;
import org.apache.xerces.xni.parser.XMLComponentManager;
import org.apache.xerces.xni.parser.XMLErrorHandler;
import org.apache.xerces.xni.grammars.XMLGrammarDescription;
import org.apache.xerces.xni.grammars.XMLGrammarPool;
import org.apache.xerces.xni.grammars.Grammar;
import java.util.Vector;
import org.w3c.dom.*;
/**
* This class adds implementation for normalizeDocument method.
* It acts as if the document was going through a save and load cycle, putting
* the document in a "normal" form. The actual result depends on the features being set
* and governing what operations actually take place. See setNormalizationFeature for details.
* Noticeably this method normalizes Text nodes, makes the document "namespace wellformed",
* according to the algorithm described below in pseudo code, by adding missing namespace
* declaration attributes and adding or changing namespace prefixes, updates the replacement
* tree of EntityReference nodes, normalizes attribute values, etc.
* Mutation events, when supported, are generated to reflect the changes occuring on the
* document.
* See Namespace normalization for details on how namespace declaration attributes and prefixes
* are normalized.
*
* NOTE: There is an initial support for DOM revalidation with XML Schema as a grammar.
* The tree might not be validated correctly if entityReferences, CDATA sections are
* present in the tree. The PSVI information is not exposed, normalized data (including element
* default content is not available).
*
* @author Elena Litani, IBM
* @version $Id$
*/
public class DOMNormalizer implements XMLGrammarPool {
//
// REVISIT:
// 1. Send all appropriate calls for entity reference content.
// 2. If datatype-normalization feature is on:
// a) replace values of text nodes with normalized value:
// need to pass to documentHandler augmentations that will be filled in
// during validation process.
// b) add element default content: retrieve from augementations (PSVI Element schemaDefault)
// c) replace values of attributes: the augmentations for attributes have the values.
//
//
// constants
//
/** Debug normalize document*/
protected final static boolean DEBUG_ND = false;
/** Debug namespace fix up algorithm*/
protected final static boolean DEBUG = false;
/** prefix added by namespace fixup algorithm should follow a pattern "NS" + index*/
protected final static String PREFIX = "NS";
/** Property identifier: error handler. */
protected static final String ERROR_HANDLER =
Constants.XERCES_PROPERTY_PREFIX + Constants.ERROR_HANDLER_PROPERTY;
/** Property identifier: symbol table. */
protected static final String SYMBOL_TABLE =
Constants.XERCES_PROPERTY_PREFIX + Constants.SYMBOL_TABLE_PROPERTY;
//
// Data
//
protected CoreDocumentImpl fDocument = null;
protected final XMLAttributesProxy fAttrProxy = new XMLAttributesProxy();
protected final QName fQName = new QName();
/** Validation handler represents validator instance. */
protected RevalidationHandler fValidationHandler;
/** symbol table */
protected SymbolTable fSymbolTable;
/** error handler */
protected DOMErrorHandler fErrorHandler;
// counter for new prefix names
protected int fNamespaceCounter = 1;
// Validation against namespace aware grammar
protected boolean fNamespaceValidation = false;
/** stores namespaces in scope */
protected final NamespaceSupport fNamespaceBinder = new NamespaceSupport();
/** stores all namespace bindings on the current element */
protected final NamespaceSupport fLocalNSBinder = new NamespaceSupport();
/** list of attributes */
protected final Vector fAttributeList = new Vector(5,10);
/** DOM Error object */
protected final DOMErrorImpl fDOMError = new DOMErrorImpl();
/** DOM Locator - for namespace fixup algorithm */
protected final DOMLocatorImpl fLocator = new DOMLocatorImpl();
//
// Constructor
//
public DOMNormalizer(){}
protected void reset(XMLComponentManager componentManager){
if (componentManager == null) {
fSymbolTable = null;
fValidationHandler = null;
return;
}
fSymbolTable = (SymbolTable)componentManager.getProperty(SYMBOL_TABLE);
if (fSymbolTable == null) {
fSymbolTable = new SymbolTable();
}
fNamespaceValidation = componentManager.getFeature(DOMValidationConfiguration.SCHEMA);
fNamespaceBinder.reset();
fNamespaceBinder.declarePrefix(XMLSymbols.EMPTY_STRING, XMLSymbols.EMPTY_STRING);
fNamespaceCounter = 1;
if (fValidationHandler != null) {
((XMLComponent)fValidationHandler).reset(componentManager);
// REVISIT: how to pass and reuse namespace binder in the XML Schema validator?
}
}
protected final void setValidationHandler (RevalidationHandler validator){
this.fValidationHandler = validator;
}
/**
* Normalizes document.
* Note: reset() must be called before this method.
*/
protected final void normalizeDocument(CoreDocumentImpl document){
if (fSymbolTable == null) {
// reset was not called
return;
}
fDocument = document;
fErrorHandler = fDocument.getErrorHandler();
if (fValidationHandler != null) {
fValidationHandler.setBaseURI(fDocument.fDocumentURI);
fValidationHandler.startDocument(null, fDocument.encoding, null);
}
Node kid, next;
for (kid = fDocument.getFirstChild(); kid != null; kid = next) {
next = kid.getNextSibling();
kid = normalizeNode(kid);
if (kid != null) { // don't advance
next = kid;
}
}
if (fValidationHandler != null) {
fValidationHandler.endDocument(null);
}
// reset symbol table
fSymbolTable = null;
}
/**
*
* This method acts as if the document was going through a save
* and load cycle, putting the document in a "normal" form. The actual result
* depends on the features being set and governing what operations actually
* take place. See setNormalizationFeature for details. Noticeably this method
* normalizes Text nodes, makes the document "namespace wellformed",
* according to the algorithm described below in pseudo code, by adding missing
* namespace declaration attributes and adding or changing namespace prefixes, updates
* the replacement tree of EntityReference nodes,normalizes attribute values, etc.
*
* @param node Modified node or null. If node is returned, we need
* to normalize again starting on the node returned.
* @return
*/
protected final Node normalizeNode (Node node){
// REVISIT: should we support other DOM implementations?
// if so we should not depend on Xerces specific classes
int type = node.getNodeType();
switch (type) {
case Node.DOCUMENT_TYPE_NODE: {
if (DEBUG_ND) {
System.out.println("==>normalizeNode:{doctype}");
}
if ((fDocument.features & CoreDocumentImpl.ENTITIES) == 0) {
// remove all entity nodes
((DocumentTypeImpl)node).entities.removeAll();
}
break;
}
case Node.ELEMENT_NODE: {
if (DEBUG_ND) {
System.out.println("==>normalizeNode:{element} "+node.getNodeName());
}
// push namespace context
fNamespaceBinder.pushContext();
ElementImpl elem = (ElementImpl)node;
if (elem.needsSyncChildren()) {
elem.synchronizeChildren();
}
// REVISIT: need to optimize for the cases there normalization is not
// needed and an element could be skipped.
// Normalize all of the attributes & remove defaults
AttributeMap attributes = (elem.hasAttributes()) ? (AttributeMap) elem.getAttributes() : null;
// fix namespaces and remove default attributes
if ((fDocument.features & CoreDocumentImpl.NAMESPACES) !=0) {
// fix namespaces
// normalize attribute values
// remove default attributes
namespaceFixUp(elem, attributes);
} else {
if ( attributes!=null ) {
for ( int i=0; i<attributes.getLength(); ++i ) {
Attr attr = (Attr)attributes.item(i);
removeDefault(attr, attributes);
attr.normalize();
}
}
}
if (fValidationHandler != null) {
// REVISIT: possible solutions to discard default content are:
// either we pass some flag to XML Schema validator
// or rely on the PSVI information.
fAttrProxy.setAttributes(attributes, fDocument, elem);
updateQName(elem, fQName); // updates global qname
//
// set error node in the dom error wrapper
// so if error occurs we can report an error node
fDocument.fErrorHandlerWrapper.fCurrentNode = node;
// call re-validation handler
fValidationHandler.startElement(fQName, fAttrProxy, null);
}
// normalize children
Node kid, next;
for (kid = elem.getFirstChild(); kid != null; kid = next) {
next = kid.getNextSibling();
kid = normalizeNode(kid);
if (kid !=null) {
next = kid; // don't advance
}
}
if (DEBUG_ND) {
// normalized subtree
System.out.println(" normalized children for{"+node.getNodeName()+"}");
for (kid = elem.getFirstChild(); kid != null; kid = next) {
next = kid.getNextSibling();
System.out.println(kid.getNodeName() +": "+kid.getNodeValue());
}
}
if (fValidationHandler != null) {
updateQName(elem, fQName); // updates global qname
//
// set error node in the dom error wrapper
// so if error occurs we can report an error node
fDocument.fErrorHandlerWrapper.fCurrentNode = node;
fValidationHandler.endElement(fQName, null);
int count = fNamespaceBinder.getDeclaredPrefixCount();
for (int i = count - 1; i >= 0; i--) {
String prefix = fNamespaceBinder.getDeclaredPrefixAt(i);
fValidationHandler.endPrefixMapping(prefix, null);
}
}
// pop namespace context
fNamespaceBinder.popContext();
break;
}
case Node.COMMENT_NODE: {
if (DEBUG_ND) {
System.out.println("==>normalizeNode:{comments}");
}
if ((fDocument.features & CoreDocumentImpl.COMMENTS) == 0) {
Node prevSibling = node.getPreviousSibling();
Node parent = node.getParentNode();
// remove the comment node
parent.removeChild(node);
if (prevSibling != null && prevSibling.getNodeType() == Node.TEXT_NODE) {
Node nextSibling = prevSibling.getNextSibling();
if (nextSibling != null && nextSibling.getNodeType() == Node.TEXT_NODE) {
((TextImpl)nextSibling).insertData(0, prevSibling.getNodeValue());
parent.removeChild(prevSibling);
return nextSibling;
}
}
}
break;
}
case Node.ENTITY_REFERENCE_NODE: {
if (DEBUG_ND) {
System.out.println("==>normalizeNode:{entityRef} "+node.getNodeName());
}
if ((fDocument.features & CoreDocumentImpl.ENTITIES) == 0) {
Node prevSibling = node.getPreviousSibling();
Node parent = node.getParentNode();
((EntityReferenceImpl)node).setReadOnly(false, true);
expandEntityRef (node, parent, node);
parent.removeChild(node);
Node next = (prevSibling != null)?prevSibling.getNextSibling():parent.getFirstChild();
// The list of children #text -> &ent;
// and entity has a first child as a text
// we should not advance
if (prevSibling !=null && prevSibling.getNodeType() == Node.TEXT_NODE &&
next.getNodeType() == Node.TEXT_NODE) {
return prevSibling; // Don't advance
}
return next;
} else {
// REVISIT: traverse entity reference and send appropriate calls to the validator
// (no normalization should be performed for the children).
}
break;
}
case Node.CDATA_SECTION_NODE: {
if (DEBUG_ND) {
System.out.println("==>normalizeNode:{cdata}");
}
if ((fDocument.features & CoreDocumentImpl.CDATA) == 0) {
// convert CDATA to TEXT nodes
Text text = fDocument.createTextNode(node.getNodeValue());
Node parent = node.getParentNode();
Node prevSibling = node.getPreviousSibling();
node = parent.replaceChild(text, node);
if (prevSibling != null && prevSibling.getNodeType() == Node.TEXT_NODE) {
text.insertData(0, prevSibling.getNodeValue());
parent.removeChild(prevSibling);
}
return text; // Don't advance;
}
// send characters call for CDATA
if (fValidationHandler != null) {
//
// set error node in the dom error wrapper
// so if error occurs we can report an error node
fDocument.fErrorHandlerWrapper.fCurrentNode = node;
fValidationHandler.startCDATA(null);
fValidationHandler.characterData(node.getNodeValue(), null);
fValidationHandler.endCDATA(null);
}
if ((fDocument.features & CoreDocumentImpl.SPLITCDATA) != 0) {
String value = node.getNodeValue();
int index = value.indexOf("]]>");
if (index >= 0) {
// REVISIT: issue warning
}
Node parent = node.getParentNode();
while ( index >= 0 ) {
node.setNodeValue(value.substring(0, index+2));
value = value.substring(index +2);
node = fDocument.createCDATASection(value);
parent.insertBefore(node, node.getNextSibling());
index = value.indexOf("]]>");
}
}
break;
}
case Node.TEXT_NODE: {
if (DEBUG_ND) {
System.out.println("==>normalizeNode(text):{"+node.getNodeValue()+"}");
}
// If node is a text node, we need to check for one of two
// conditions:
// 1) There is an adjacent text node
// 2) There is no adjacent text node, but node is
// an empty text node.
Node next = node.getNextSibling();
// If an adjacent text node, merge it with this node
if ( next!=null && next.getNodeType() == Node.TEXT_NODE ) {
((Text)node).appendData(next.getNodeValue());
node.getParentNode().removeChild( next );
return node; // Don't advance;
} else if (node.getNodeValue().length()==0) {
// If kid is empty, remove it
node.getParentNode().removeChild( node );
} else {
// validator.characters() call
// Don't send characters in the following cases:
// 1. entities is false, next child is entity reference: expand tree first
// 2. comments is false, and next child is comment
// 3. cdata is false, and next child is cdata
if (fValidationHandler != null) {
short nextType = (next != null)?next.getNodeType():-1;
if (!(((fDocument.features & CoreDocumentImpl.ENTITIES) == 0 &&
nextType == Node.ENTITY_NODE) ||
((fDocument.features & CoreDocumentImpl.COMMENTS) == 0 &&
nextType == Node.COMMENT_NODE) ||
((fDocument.features & CoreDocumentImpl.CDATA) == 0) &&
nextType == Node.CDATA_SECTION_NODE)) {
//
// set error node in the dom error wrapper
// so if error occurs we can report an error node
fDocument.fErrorHandlerWrapper.fCurrentNode = node;
fValidationHandler.characterData(node.getNodeValue(), null);
if (DEBUG_ND) {
System.out.println("=====>characterData(),"+nextType);
}
} else {
if (DEBUG_ND) {
System.out.println("=====>don't send characters(),"+nextType);
}
}
}
}
break;
}
}
return null;
}
protected final void expandEntityRef (Node node, Node parent, Node reference){
Node kid, next;
for (kid = node.getFirstChild(); kid != null; kid = next) {
next = kid.getNextSibling();
if (node.getNodeType() == Node.TEXT_NODE) {
expandEntityRef(kid, parent, reference);
} else {
parent.insertBefore(kid, reference);
}
}
}
protected final void namespaceFixUp (ElementImpl element, AttributeMap attributes){
if (DEBUG) {
System.out.println("[ns-fixup] element:" +element.getNodeName()+
" uri: "+element.getNamespaceURI());
}
// ------------------------------------
// pick up local namespace declarations
// <xsl:stylesheet xmlns:xsl="http://xslt">
// <!-- add the following via DOM
// body is bound to http://xslt
// -->
// <xsl:body xmlns:xsl="http://bound"/>
//
// ------------------------------------
String localUri, value, name, uri, prefix;
if (attributes != null) {
// Record all valid local declarations
for (int k=0; k < attributes.getLength(); k++) {
Attr attr = (Attr)attributes.getItem(k);
uri = attr.getNamespaceURI();
if (uri != null && uri.equals(NamespaceSupport.XMLNS_URI)) {
// namespace attribute
value = attr.getNodeValue();
if (value == null) {
value=XMLSymbols.EMPTY_STRING;
}
// Check for invalid namespace declaration:
if (value.equals(NamespaceSupport.XMLNS_URI)) {
if (fErrorHandler != null) {
modifyDOMError("No prefix other than 'xmlns' can be bound to 'http://www.w3.org/2000/xmlns/' namespace name",
DOMError.SEVERITY_ERROR, attr);
boolean continueProcess = fErrorHandler.handleError(fDOMError);
if (!continueProcess) {
// stop the namespace fixup and validation
throw new RuntimeException("Stopped at user request");
}
}
} else {
prefix = attr.getPrefix();
prefix = (prefix == null ||
prefix.length() == 0) ? XMLSymbols.EMPTY_STRING :fSymbolTable.addSymbol(prefix);
String localpart = fSymbolTable.addSymbol( attr.getLocalName());
- if (prefix == XMLSymbols.EMPTY_STRING) { //xmlns:prefix
+ if (prefix == XMLSymbols.PREFIX_XMLNS) { //xmlns:prefix
value = fSymbolTable.addSymbol(value);
if (value.length() != 0) {
fNamespaceBinder.declarePrefix(localpart, value);
fLocalNSBinder.declarePrefix(localpart, value);
if (fValidationHandler != null) {
fValidationHandler.startPrefixMapping(localpart, value, null);
}
} else {
// REVISIT: issue error on invalid declarations
// xmlns:foo = ""
}
removeDefault (attr, attributes);
continue;
} else { // (localpart == fXmlnsSymbol && prefix == fEmptySymbol) -- xmlns
// empty prefix is always bound ("" or some string)
value = fSymbolTable.addSymbol(value);
fLocalNSBinder.declarePrefix(XMLSymbols.EMPTY_STRING, value);
fNamespaceBinder.declarePrefix(XMLSymbols.EMPTY_STRING, value);
if (fValidationHandler != null) {
fValidationHandler.startPrefixMapping(XMLSymbols.EMPTY_STRING, value, null);
}
removeDefault (attr, attributes);
continue;
}
} // end-else: valid declaration
} // end-if: namespace attribute
}
}
// ---------------------------------------------------------
// Fix up namespaces for element: per DOM L3
// Need to consider the following cases:
//
// case 1: <xsl:stylesheet xmlns:xsl="http://xsl">
// We create another element body bound to the "http://xsl" namespace
// as well as namespace attribute rebounding xsl to another namespace.
// <xsl:body xmlns:xsl="http://another">
// Need to make sure that the new namespace decl value is changed to
// "http://xsl"
//
// ---------------------------------------------------------
// check if prefix/namespace is correct for current element
// ---------------------------------------------------------
uri = element.getNamespaceURI();
prefix = element.getPrefix();
if (uri != null) { // Element has a namespace
uri = fSymbolTable.addSymbol(uri);
prefix = (prefix == null ||
prefix.length() == 0) ? XMLSymbols.EMPTY_STRING :fSymbolTable.addSymbol(prefix);
if (fNamespaceBinder.getURI(prefix) == uri) {
// The xmlns:prefix=namespace or xmlns="default" was declared at parent.
// The binder always stores mapping of empty prefix to "".
} else {
// the prefix is either undeclared
// or
// conflict: the prefix is bound to another URI
addNamespaceDecl(prefix, uri, element);
fLocalNSBinder.declarePrefix(prefix, uri);
fNamespaceBinder.declarePrefix(prefix, uri);
// send startPrefixMapping call
if (fValidationHandler != null) {
fValidationHandler.startPrefixMapping(prefix, uri, null);
}
}
} else { // Element has no namespace
String tagName = element.getNodeName();
int colon = tagName.indexOf(':');
if (colon > -1) {
// Error situation: DOM Level 1 node!
boolean continueProcess = true;
if (fErrorHandler != null) {
if (fNamespaceValidation) {
modifyDOMError("DOM Level 1 node: "+tagName, DOMError.SEVERITY_FATAL_ERROR, element);
fErrorHandler.handleError(fDOMError);
} else {
modifyDOMError("DOM Level 1 node: "+tagName, DOMError.SEVERITY_ERROR, element);
continueProcess = fErrorHandler.handleError(fDOMError);
}
}
if (fNamespaceValidation || !continueProcess) {
// stop the namespace fixup and validation
throw new RuntimeException("DOM Level 1 node: "+tagName);
}
} else { // uri=null and no colon (DOM L2 node)
uri = fNamespaceBinder.getURI(XMLSymbols.EMPTY_STRING);
if (uri !=null && uri.length() > 0) {
// undeclare default namespace declaration (before that element
// bound to non-zero length uir), but adding xmlns="" decl
addNamespaceDecl (XMLSymbols.EMPTY_STRING, XMLSymbols.EMPTY_STRING, element);
fLocalNSBinder.declarePrefix(XMLSymbols.EMPTY_STRING, XMLSymbols.EMPTY_STRING);
fNamespaceBinder.declarePrefix(XMLSymbols.EMPTY_STRING, XMLSymbols.EMPTY_STRING);
if (fValidationHandler != null) {
fValidationHandler.startPrefixMapping(XMLSymbols.EMPTY_STRING, XMLSymbols.EMPTY_STRING, null);
}
}
}
}
// -----------------------------------------
// Fix up namespaces for attributes: per DOM L3
// check if prefix/namespace is correct the attributes
// -----------------------------------------
if (attributes != null) {
// clone content of the attributes
attributes.cloneMap(fAttributeList);
for (int i = 0; i < fAttributeList.size(); i++) {
Attr attr = (Attr) fAttributeList.elementAt(i);
// normalize attribute value
attr.normalize();
if (DEBUG) {
System.out.println("==>[ns-fixup] process attribute: "+attr.getNodeName());
}
value = attr.getValue();
name = attr.getNodeName();
uri = attr.getNamespaceURI();
// make sure that value is never null.
if (value == null) {
value=XMLSymbols.EMPTY_STRING;
}
if (uri != null) { // attribute has namespace !=null
prefix = attr.getPrefix();
prefix = (prefix == null ||
prefix.length() == 0) ? XMLSymbols.EMPTY_STRING :fSymbolTable.addSymbol(prefix);
String localpart = fSymbolTable.addSymbol( attr.getLocalName());
// ---------------------------------------
// skip namespace declarations
// ---------------------------------------
// REVISIT: can we assume that "uri" is from some symbol
// table, and compare by reference? -SG
if (uri != null && uri.equals(NamespaceSupport.XMLNS_URI)) {
continue;
}
// ---------------------------------------
// remove default attributes
// ---------------------------------------
if (removeDefault(attr, attributes)) {
continue;
}
uri = fSymbolTable.addSymbol(uri);
// find if for this prefix a URI was already declared
String declaredURI = fNamespaceBinder.getURI(prefix);
if (prefix == XMLSymbols.EMPTY_STRING || declaredURI != uri) {
// attribute has no prefix (default namespace decl does not apply to attributes)
// OR
// attribute prefix is not declared
// OR
// conflict: attribute has a prefix that conficlicts with a binding
// already active in scope
name = attr.getNodeName();
// Find if any prefix for attributes namespace URI is available
// in the scope
String declaredPrefix = fNamespaceBinder.getPrefix(uri);
if (declaredPrefix !=null && declaredPrefix !=XMLSymbols.EMPTY_STRING) {
// use the prefix that was found (declared previously for this URI
prefix = declaredPrefix;
} else {
if (prefix != XMLSymbols.EMPTY_STRING && fLocalNSBinder.getURI(prefix) == null) {
// the current prefix is not null and it has no in scope declaration
// use this prefix
} else {
// find a prefix following the pattern "NS" +index (starting at 1)
// make sure this prefix is not declared in the current scope.
prefix = fSymbolTable.addSymbol(PREFIX +fNamespaceCounter++);
while (fLocalNSBinder.getURI(prefix)!=null) {
prefix = fSymbolTable.addSymbol(PREFIX +fNamespaceCounter++);
}
}
// add declaration for the new prefix
addNamespaceDecl(prefix, uri, element);
value = fSymbolTable.addSymbol(value);
fLocalNSBinder.declarePrefix(prefix, value);
fNamespaceBinder.declarePrefix(prefix, uri);
if (fValidationHandler != null) {
fValidationHandler.startPrefixMapping(prefix, uri, null);
}
}
// change prefix for this attribute
attr.setPrefix(prefix);
}
} else { // attribute uri == null
// data
int colon = name.indexOf(':');
if (colon > -1) {
// It is an error if document has DOM L1 nodes.
boolean continueProcess = true;
if (fErrorHandler != null) {
if (fNamespaceValidation) {
modifyDOMError("DOM Level 1 node: "+name, DOMError.SEVERITY_FATAL_ERROR, attr);
fErrorHandler.handleError(fDOMError);
} else {
modifyDOMError("DOM Level 1 node: "+name, DOMError.SEVERITY_ERROR, attr);
continueProcess = fErrorHandler.handleError(fDOMError);
}
}
if (fNamespaceValidation || !continueProcess) {
// stop the namespace fixup and validation
throw new RuntimeException("DOM Level 1 node");
}
} else {
// uri=null and no colon
// no fix up is needed: default namespace decl does not
// ---------------------------------------
// remove default attributes
// ---------------------------------------
removeDefault(attr, attributes);
}
}
}
} // end loop for attributes
}
/**
* Adds a namespace attribute or replaces the value of existing namespace
* attribute with the given prefix and value for URI.
* In case prefix is empty will add/update default namespace declaration.
*
* @param prefix
* @param uri
* @exception IOException
*/
protected final void addNamespaceDecl(String prefix, String uri, ElementImpl element){
if (DEBUG) {
System.out.println("[ns-fixup] addNamespaceDecl ["+prefix+"]");
}
if (prefix == XMLSymbols.EMPTY_STRING) {
if (DEBUG) {
System.out.println("=>add xmlns=\""+uri+"\" declaration");
}
element.setAttributeNS(NamespaceSupport.XMLNS_URI, XMLSymbols.PREFIX_XMLNS, uri);
} else {
if (DEBUG) {
System.out.println("=>add xmlns:"+prefix+"=\""+uri+"\" declaration");
}
element.setAttributeNS(NamespaceSupport.XMLNS_URI, "xmlns:"+prefix, uri);
}
}
protected final boolean removeDefault (Attr attribute, AttributeMap attrMap){
if ((fDocument.features & CoreDocumentImpl.DEFAULTS) != 0) {
// remove default attributes
if (!attribute.getSpecified()) {
if (DEBUG_ND) {
System.out.println("==>remove default attr: "+attribute.getNodeName());
}
attrMap.removeItem(attribute, false);
return true;
}
}
return false;
}
protected final DOMError modifyDOMError(String message, short severity, Node node){
fDOMError.reset();
fDOMError.fMessage = message;
fDOMError.fSeverity = severity;
fDOMError.fLocator = fLocator;
fLocator.fErrorNode = node;
return fDOMError;
}
protected final void updateQName (Node node, QName qname){
String prefix = node.getPrefix();
String namespace = node.getNamespaceURI();
String localName = node.getLocalName();
// REVISIT: the symbols are added too often: start/endElement
// and in the namespaceFixup. Should reduce number of calls to symbol table.
qname.prefix = (prefix!=null && prefix.length()!=0)?fSymbolTable.addSymbol(prefix):null;
qname.localpart = (localName != null)?fSymbolTable.addSymbol(localName):null;
qname.rawname = fSymbolTable.addSymbol(node.getNodeName());
qname.uri = (namespace != null)?fSymbolTable.addSymbol(namespace):null;
}
protected final class XMLAttributesProxy
implements XMLAttributes {
protected AttributeMap fAttributes;
protected CoreDocumentImpl fDocument;
protected ElementImpl fElement;
protected final Vector fAugmentations = new Vector(5);
public void setAttributes(AttributeMap attributes, CoreDocumentImpl doc, ElementImpl elem) {
fDocument = doc;
fAttributes = attributes;
fElement = elem;
if (attributes != null) {
int length = attributes.getLength();
fAugmentations.setSize(length);
// REVISIT: this implementation does not store any value in augmentations
// and basically not keeping augs in parallel to attributes map
// untill all attributes are added (default attributes)
for (int i = 0; i < length; i++) {
fAugmentations.setElementAt(new AugmentationsImpl(), i);
}
} else {
fAugmentations.setSize(0);
}
}
public int addAttribute(QName attrQName, String attrType, String attrValue){
Attr attr = fDocument.createAttributeNS(attrQName.uri,
attrQName.rawname,
attrQName.localpart);
attr.setValue(attrValue);
if (fAttributes == null) {
fAttributes = (AttributeMap)fElement.getAttributes();
}
int index = fElement.setXercesAttributeNode(attr);
fAugmentations.insertElementAt(new AugmentationsImpl(), index);
return index;
}
public void removeAllAttributes(){
// REVISIT: implement
}
public void removeAttributeAt(int attrIndex){
// REVISIT: implement
}
public int getLength(){
return(fAttributes != null)?fAttributes.getLength():0;
}
public int getIndex(String qName){
// REVISIT: implement
return -1;
}
public int getIndex(String uri, String localPart){
// REVISIT: implement
return -1;
}
public void setName(int attrIndex, QName attrName){
// REVISIT: implement
}
public void getName(int attrIndex, QName attrName){
if (fAttributes !=null) {
updateQName((Node)fAttributes.getItem(attrIndex), attrName);
}
}
public String getPrefix(int index){
// REVISIT: implement
return null;
}
public String getURI(int index){
// REVISIT: implement
return null;
}
public String getLocalName(int index){
// REVISIT: implement
return null;
}
public String getQName(int index){
// REVISIT: implement
return null;
}
public void setType(int attrIndex, String attrType){
// REVISIT: implement
}
public String getType(int index){
return "CDATA";
}
public String getType(String qName){
return "CDATA";
}
public String getType(String uri, String localName){
return "CDATA";
}
public void setValue(int attrIndex, String attrValue){
// REVISIT: implement
}
public String getValue(int index){
return fAttributes.item(index).getNodeValue();
}
public String getValue(String qName){
// REVISIT: implement
return null;
}
public String getValue(String uri, String localName){
if (fAttributes != null) {
Node node = fAttributes.getNamedItemNS(uri, localName);
return(node != null)? node.getNodeValue():null;
}
return null;
}
public void setNonNormalizedValue(int attrIndex, String attrValue){
// REVISIT: implement
}
public String getNonNormalizedValue(int attrIndex){
// REVISIT: implement
return null;
}
public void setSpecified(int attrIndex, boolean specified){
// REVISIT: this will be called after add attributes is called
AttrImpl attr = (AttrImpl)fAttributes.getItem(attrIndex);
attr.setSpecified(specified);
}
public boolean isSpecified(int attrIndex){
return((Attr)fAttributes.getItem(attrIndex)).getSpecified();
}
public Augmentations getAugmentations (int attributeIndex){
return(Augmentations)fAugmentations.elementAt(attributeIndex);
}
public Augmentations getAugmentations (String uri, String localPart){
// REVISIT: implement
return null;
}
public Augmentations getAugmentations(String qName){
// REVISIT: implement
return null;
}
}
//
// XML GrammarPool methods
//
protected final Grammar[] fGrammarPool = new Grammar[1];
public Grammar[] retrieveInitialGrammarSet(String grammarType){
// REVISIT: should take into account grammarType
fGrammarPool[0] = fDocument.fGrammar;
return null;
}
public void cacheGrammars(String grammarType, Grammar[] grammars){
// REVISIT: implement
}
public Grammar retrieveGrammar(XMLGrammarDescription desc){
return null;
}
public void lockPool(){
// REVISIT: implement
}
public void unlockPool(){
// REVISIT: implement
}
public void clear(){
// REVISIT: implement
}
//
// XMLDocumentHandler methods
//
} // DOMNormalizer class
| true | true | protected final void namespaceFixUp (ElementImpl element, AttributeMap attributes){
if (DEBUG) {
System.out.println("[ns-fixup] element:" +element.getNodeName()+
" uri: "+element.getNamespaceURI());
}
// ------------------------------------
// pick up local namespace declarations
// <xsl:stylesheet xmlns:xsl="http://xslt">
// <!-- add the following via DOM
// body is bound to http://xslt
// -->
// <xsl:body xmlns:xsl="http://bound"/>
//
// ------------------------------------
String localUri, value, name, uri, prefix;
if (attributes != null) {
// Record all valid local declarations
for (int k=0; k < attributes.getLength(); k++) {
Attr attr = (Attr)attributes.getItem(k);
uri = attr.getNamespaceURI();
if (uri != null && uri.equals(NamespaceSupport.XMLNS_URI)) {
// namespace attribute
value = attr.getNodeValue();
if (value == null) {
value=XMLSymbols.EMPTY_STRING;
}
// Check for invalid namespace declaration:
if (value.equals(NamespaceSupport.XMLNS_URI)) {
if (fErrorHandler != null) {
modifyDOMError("No prefix other than 'xmlns' can be bound to 'http://www.w3.org/2000/xmlns/' namespace name",
DOMError.SEVERITY_ERROR, attr);
boolean continueProcess = fErrorHandler.handleError(fDOMError);
if (!continueProcess) {
// stop the namespace fixup and validation
throw new RuntimeException("Stopped at user request");
}
}
} else {
prefix = attr.getPrefix();
prefix = (prefix == null ||
prefix.length() == 0) ? XMLSymbols.EMPTY_STRING :fSymbolTable.addSymbol(prefix);
String localpart = fSymbolTable.addSymbol( attr.getLocalName());
if (prefix == XMLSymbols.EMPTY_STRING) { //xmlns:prefix
value = fSymbolTable.addSymbol(value);
if (value.length() != 0) {
fNamespaceBinder.declarePrefix(localpart, value);
fLocalNSBinder.declarePrefix(localpart, value);
if (fValidationHandler != null) {
fValidationHandler.startPrefixMapping(localpart, value, null);
}
} else {
// REVISIT: issue error on invalid declarations
// xmlns:foo = ""
}
removeDefault (attr, attributes);
continue;
} else { // (localpart == fXmlnsSymbol && prefix == fEmptySymbol) -- xmlns
// empty prefix is always bound ("" or some string)
value = fSymbolTable.addSymbol(value);
fLocalNSBinder.declarePrefix(XMLSymbols.EMPTY_STRING, value);
fNamespaceBinder.declarePrefix(XMLSymbols.EMPTY_STRING, value);
if (fValidationHandler != null) {
fValidationHandler.startPrefixMapping(XMLSymbols.EMPTY_STRING, value, null);
}
removeDefault (attr, attributes);
continue;
}
} // end-else: valid declaration
} // end-if: namespace attribute
}
}
// ---------------------------------------------------------
// Fix up namespaces for element: per DOM L3
// Need to consider the following cases:
//
// case 1: <xsl:stylesheet xmlns:xsl="http://xsl">
// We create another element body bound to the "http://xsl" namespace
// as well as namespace attribute rebounding xsl to another namespace.
// <xsl:body xmlns:xsl="http://another">
// Need to make sure that the new namespace decl value is changed to
// "http://xsl"
//
// ---------------------------------------------------------
// check if prefix/namespace is correct for current element
// ---------------------------------------------------------
uri = element.getNamespaceURI();
prefix = element.getPrefix();
if (uri != null) { // Element has a namespace
uri = fSymbolTable.addSymbol(uri);
prefix = (prefix == null ||
prefix.length() == 0) ? XMLSymbols.EMPTY_STRING :fSymbolTable.addSymbol(prefix);
if (fNamespaceBinder.getURI(prefix) == uri) {
// The xmlns:prefix=namespace or xmlns="default" was declared at parent.
// The binder always stores mapping of empty prefix to "".
} else {
// the prefix is either undeclared
// or
// conflict: the prefix is bound to another URI
addNamespaceDecl(prefix, uri, element);
fLocalNSBinder.declarePrefix(prefix, uri);
fNamespaceBinder.declarePrefix(prefix, uri);
// send startPrefixMapping call
if (fValidationHandler != null) {
fValidationHandler.startPrefixMapping(prefix, uri, null);
}
}
} else { // Element has no namespace
String tagName = element.getNodeName();
int colon = tagName.indexOf(':');
if (colon > -1) {
// Error situation: DOM Level 1 node!
boolean continueProcess = true;
if (fErrorHandler != null) {
if (fNamespaceValidation) {
modifyDOMError("DOM Level 1 node: "+tagName, DOMError.SEVERITY_FATAL_ERROR, element);
fErrorHandler.handleError(fDOMError);
} else {
modifyDOMError("DOM Level 1 node: "+tagName, DOMError.SEVERITY_ERROR, element);
continueProcess = fErrorHandler.handleError(fDOMError);
}
}
if (fNamespaceValidation || !continueProcess) {
// stop the namespace fixup and validation
throw new RuntimeException("DOM Level 1 node: "+tagName);
}
} else { // uri=null and no colon (DOM L2 node)
uri = fNamespaceBinder.getURI(XMLSymbols.EMPTY_STRING);
if (uri !=null && uri.length() > 0) {
// undeclare default namespace declaration (before that element
// bound to non-zero length uir), but adding xmlns="" decl
addNamespaceDecl (XMLSymbols.EMPTY_STRING, XMLSymbols.EMPTY_STRING, element);
fLocalNSBinder.declarePrefix(XMLSymbols.EMPTY_STRING, XMLSymbols.EMPTY_STRING);
fNamespaceBinder.declarePrefix(XMLSymbols.EMPTY_STRING, XMLSymbols.EMPTY_STRING);
if (fValidationHandler != null) {
fValidationHandler.startPrefixMapping(XMLSymbols.EMPTY_STRING, XMLSymbols.EMPTY_STRING, null);
}
}
}
}
// -----------------------------------------
// Fix up namespaces for attributes: per DOM L3
// check if prefix/namespace is correct the attributes
// -----------------------------------------
if (attributes != null) {
// clone content of the attributes
attributes.cloneMap(fAttributeList);
for (int i = 0; i < fAttributeList.size(); i++) {
Attr attr = (Attr) fAttributeList.elementAt(i);
// normalize attribute value
attr.normalize();
if (DEBUG) {
System.out.println("==>[ns-fixup] process attribute: "+attr.getNodeName());
}
value = attr.getValue();
name = attr.getNodeName();
uri = attr.getNamespaceURI();
// make sure that value is never null.
if (value == null) {
value=XMLSymbols.EMPTY_STRING;
}
if (uri != null) { // attribute has namespace !=null
prefix = attr.getPrefix();
prefix = (prefix == null ||
prefix.length() == 0) ? XMLSymbols.EMPTY_STRING :fSymbolTable.addSymbol(prefix);
String localpart = fSymbolTable.addSymbol( attr.getLocalName());
// ---------------------------------------
// skip namespace declarations
// ---------------------------------------
// REVISIT: can we assume that "uri" is from some symbol
// table, and compare by reference? -SG
if (uri != null && uri.equals(NamespaceSupport.XMLNS_URI)) {
continue;
}
// ---------------------------------------
// remove default attributes
// ---------------------------------------
if (removeDefault(attr, attributes)) {
continue;
}
uri = fSymbolTable.addSymbol(uri);
// find if for this prefix a URI was already declared
String declaredURI = fNamespaceBinder.getURI(prefix);
if (prefix == XMLSymbols.EMPTY_STRING || declaredURI != uri) {
// attribute has no prefix (default namespace decl does not apply to attributes)
// OR
// attribute prefix is not declared
// OR
// conflict: attribute has a prefix that conficlicts with a binding
// already active in scope
name = attr.getNodeName();
// Find if any prefix for attributes namespace URI is available
// in the scope
String declaredPrefix = fNamespaceBinder.getPrefix(uri);
if (declaredPrefix !=null && declaredPrefix !=XMLSymbols.EMPTY_STRING) {
// use the prefix that was found (declared previously for this URI
prefix = declaredPrefix;
} else {
if (prefix != XMLSymbols.EMPTY_STRING && fLocalNSBinder.getURI(prefix) == null) {
// the current prefix is not null and it has no in scope declaration
// use this prefix
} else {
// find a prefix following the pattern "NS" +index (starting at 1)
// make sure this prefix is not declared in the current scope.
prefix = fSymbolTable.addSymbol(PREFIX +fNamespaceCounter++);
while (fLocalNSBinder.getURI(prefix)!=null) {
prefix = fSymbolTable.addSymbol(PREFIX +fNamespaceCounter++);
}
}
// add declaration for the new prefix
addNamespaceDecl(prefix, uri, element);
value = fSymbolTable.addSymbol(value);
fLocalNSBinder.declarePrefix(prefix, value);
fNamespaceBinder.declarePrefix(prefix, uri);
if (fValidationHandler != null) {
fValidationHandler.startPrefixMapping(prefix, uri, null);
}
}
// change prefix for this attribute
attr.setPrefix(prefix);
}
} else { // attribute uri == null
// data
int colon = name.indexOf(':');
if (colon > -1) {
// It is an error if document has DOM L1 nodes.
boolean continueProcess = true;
if (fErrorHandler != null) {
if (fNamespaceValidation) {
modifyDOMError("DOM Level 1 node: "+name, DOMError.SEVERITY_FATAL_ERROR, attr);
fErrorHandler.handleError(fDOMError);
} else {
modifyDOMError("DOM Level 1 node: "+name, DOMError.SEVERITY_ERROR, attr);
continueProcess = fErrorHandler.handleError(fDOMError);
}
}
if (fNamespaceValidation || !continueProcess) {
// stop the namespace fixup and validation
throw new RuntimeException("DOM Level 1 node");
}
} else {
// uri=null and no colon
// no fix up is needed: default namespace decl does not
// ---------------------------------------
// remove default attributes
// ---------------------------------------
removeDefault(attr, attributes);
}
}
}
} // end loop for attributes
}
| protected final void namespaceFixUp (ElementImpl element, AttributeMap attributes){
if (DEBUG) {
System.out.println("[ns-fixup] element:" +element.getNodeName()+
" uri: "+element.getNamespaceURI());
}
// ------------------------------------
// pick up local namespace declarations
// <xsl:stylesheet xmlns:xsl="http://xslt">
// <!-- add the following via DOM
// body is bound to http://xslt
// -->
// <xsl:body xmlns:xsl="http://bound"/>
//
// ------------------------------------
String localUri, value, name, uri, prefix;
if (attributes != null) {
// Record all valid local declarations
for (int k=0; k < attributes.getLength(); k++) {
Attr attr = (Attr)attributes.getItem(k);
uri = attr.getNamespaceURI();
if (uri != null && uri.equals(NamespaceSupport.XMLNS_URI)) {
// namespace attribute
value = attr.getNodeValue();
if (value == null) {
value=XMLSymbols.EMPTY_STRING;
}
// Check for invalid namespace declaration:
if (value.equals(NamespaceSupport.XMLNS_URI)) {
if (fErrorHandler != null) {
modifyDOMError("No prefix other than 'xmlns' can be bound to 'http://www.w3.org/2000/xmlns/' namespace name",
DOMError.SEVERITY_ERROR, attr);
boolean continueProcess = fErrorHandler.handleError(fDOMError);
if (!continueProcess) {
// stop the namespace fixup and validation
throw new RuntimeException("Stopped at user request");
}
}
} else {
prefix = attr.getPrefix();
prefix = (prefix == null ||
prefix.length() == 0) ? XMLSymbols.EMPTY_STRING :fSymbolTable.addSymbol(prefix);
String localpart = fSymbolTable.addSymbol( attr.getLocalName());
if (prefix == XMLSymbols.PREFIX_XMLNS) { //xmlns:prefix
value = fSymbolTable.addSymbol(value);
if (value.length() != 0) {
fNamespaceBinder.declarePrefix(localpart, value);
fLocalNSBinder.declarePrefix(localpart, value);
if (fValidationHandler != null) {
fValidationHandler.startPrefixMapping(localpart, value, null);
}
} else {
// REVISIT: issue error on invalid declarations
// xmlns:foo = ""
}
removeDefault (attr, attributes);
continue;
} else { // (localpart == fXmlnsSymbol && prefix == fEmptySymbol) -- xmlns
// empty prefix is always bound ("" or some string)
value = fSymbolTable.addSymbol(value);
fLocalNSBinder.declarePrefix(XMLSymbols.EMPTY_STRING, value);
fNamespaceBinder.declarePrefix(XMLSymbols.EMPTY_STRING, value);
if (fValidationHandler != null) {
fValidationHandler.startPrefixMapping(XMLSymbols.EMPTY_STRING, value, null);
}
removeDefault (attr, attributes);
continue;
}
} // end-else: valid declaration
} // end-if: namespace attribute
}
}
// ---------------------------------------------------------
// Fix up namespaces for element: per DOM L3
// Need to consider the following cases:
//
// case 1: <xsl:stylesheet xmlns:xsl="http://xsl">
// We create another element body bound to the "http://xsl" namespace
// as well as namespace attribute rebounding xsl to another namespace.
// <xsl:body xmlns:xsl="http://another">
// Need to make sure that the new namespace decl value is changed to
// "http://xsl"
//
// ---------------------------------------------------------
// check if prefix/namespace is correct for current element
// ---------------------------------------------------------
uri = element.getNamespaceURI();
prefix = element.getPrefix();
if (uri != null) { // Element has a namespace
uri = fSymbolTable.addSymbol(uri);
prefix = (prefix == null ||
prefix.length() == 0) ? XMLSymbols.EMPTY_STRING :fSymbolTable.addSymbol(prefix);
if (fNamespaceBinder.getURI(prefix) == uri) {
// The xmlns:prefix=namespace or xmlns="default" was declared at parent.
// The binder always stores mapping of empty prefix to "".
} else {
// the prefix is either undeclared
// or
// conflict: the prefix is bound to another URI
addNamespaceDecl(prefix, uri, element);
fLocalNSBinder.declarePrefix(prefix, uri);
fNamespaceBinder.declarePrefix(prefix, uri);
// send startPrefixMapping call
if (fValidationHandler != null) {
fValidationHandler.startPrefixMapping(prefix, uri, null);
}
}
} else { // Element has no namespace
String tagName = element.getNodeName();
int colon = tagName.indexOf(':');
if (colon > -1) {
// Error situation: DOM Level 1 node!
boolean continueProcess = true;
if (fErrorHandler != null) {
if (fNamespaceValidation) {
modifyDOMError("DOM Level 1 node: "+tagName, DOMError.SEVERITY_FATAL_ERROR, element);
fErrorHandler.handleError(fDOMError);
} else {
modifyDOMError("DOM Level 1 node: "+tagName, DOMError.SEVERITY_ERROR, element);
continueProcess = fErrorHandler.handleError(fDOMError);
}
}
if (fNamespaceValidation || !continueProcess) {
// stop the namespace fixup and validation
throw new RuntimeException("DOM Level 1 node: "+tagName);
}
} else { // uri=null and no colon (DOM L2 node)
uri = fNamespaceBinder.getURI(XMLSymbols.EMPTY_STRING);
if (uri !=null && uri.length() > 0) {
// undeclare default namespace declaration (before that element
// bound to non-zero length uir), but adding xmlns="" decl
addNamespaceDecl (XMLSymbols.EMPTY_STRING, XMLSymbols.EMPTY_STRING, element);
fLocalNSBinder.declarePrefix(XMLSymbols.EMPTY_STRING, XMLSymbols.EMPTY_STRING);
fNamespaceBinder.declarePrefix(XMLSymbols.EMPTY_STRING, XMLSymbols.EMPTY_STRING);
if (fValidationHandler != null) {
fValidationHandler.startPrefixMapping(XMLSymbols.EMPTY_STRING, XMLSymbols.EMPTY_STRING, null);
}
}
}
}
// -----------------------------------------
// Fix up namespaces for attributes: per DOM L3
// check if prefix/namespace is correct the attributes
// -----------------------------------------
if (attributes != null) {
// clone content of the attributes
attributes.cloneMap(fAttributeList);
for (int i = 0; i < fAttributeList.size(); i++) {
Attr attr = (Attr) fAttributeList.elementAt(i);
// normalize attribute value
attr.normalize();
if (DEBUG) {
System.out.println("==>[ns-fixup] process attribute: "+attr.getNodeName());
}
value = attr.getValue();
name = attr.getNodeName();
uri = attr.getNamespaceURI();
// make sure that value is never null.
if (value == null) {
value=XMLSymbols.EMPTY_STRING;
}
if (uri != null) { // attribute has namespace !=null
prefix = attr.getPrefix();
prefix = (prefix == null ||
prefix.length() == 0) ? XMLSymbols.EMPTY_STRING :fSymbolTable.addSymbol(prefix);
String localpart = fSymbolTable.addSymbol( attr.getLocalName());
// ---------------------------------------
// skip namespace declarations
// ---------------------------------------
// REVISIT: can we assume that "uri" is from some symbol
// table, and compare by reference? -SG
if (uri != null && uri.equals(NamespaceSupport.XMLNS_URI)) {
continue;
}
// ---------------------------------------
// remove default attributes
// ---------------------------------------
if (removeDefault(attr, attributes)) {
continue;
}
uri = fSymbolTable.addSymbol(uri);
// find if for this prefix a URI was already declared
String declaredURI = fNamespaceBinder.getURI(prefix);
if (prefix == XMLSymbols.EMPTY_STRING || declaredURI != uri) {
// attribute has no prefix (default namespace decl does not apply to attributes)
// OR
// attribute prefix is not declared
// OR
// conflict: attribute has a prefix that conficlicts with a binding
// already active in scope
name = attr.getNodeName();
// Find if any prefix for attributes namespace URI is available
// in the scope
String declaredPrefix = fNamespaceBinder.getPrefix(uri);
if (declaredPrefix !=null && declaredPrefix !=XMLSymbols.EMPTY_STRING) {
// use the prefix that was found (declared previously for this URI
prefix = declaredPrefix;
} else {
if (prefix != XMLSymbols.EMPTY_STRING && fLocalNSBinder.getURI(prefix) == null) {
// the current prefix is not null and it has no in scope declaration
// use this prefix
} else {
// find a prefix following the pattern "NS" +index (starting at 1)
// make sure this prefix is not declared in the current scope.
prefix = fSymbolTable.addSymbol(PREFIX +fNamespaceCounter++);
while (fLocalNSBinder.getURI(prefix)!=null) {
prefix = fSymbolTable.addSymbol(PREFIX +fNamespaceCounter++);
}
}
// add declaration for the new prefix
addNamespaceDecl(prefix, uri, element);
value = fSymbolTable.addSymbol(value);
fLocalNSBinder.declarePrefix(prefix, value);
fNamespaceBinder.declarePrefix(prefix, uri);
if (fValidationHandler != null) {
fValidationHandler.startPrefixMapping(prefix, uri, null);
}
}
// change prefix for this attribute
attr.setPrefix(prefix);
}
} else { // attribute uri == null
// data
int colon = name.indexOf(':');
if (colon > -1) {
// It is an error if document has DOM L1 nodes.
boolean continueProcess = true;
if (fErrorHandler != null) {
if (fNamespaceValidation) {
modifyDOMError("DOM Level 1 node: "+name, DOMError.SEVERITY_FATAL_ERROR, attr);
fErrorHandler.handleError(fDOMError);
} else {
modifyDOMError("DOM Level 1 node: "+name, DOMError.SEVERITY_ERROR, attr);
continueProcess = fErrorHandler.handleError(fDOMError);
}
}
if (fNamespaceValidation || !continueProcess) {
// stop the namespace fixup and validation
throw new RuntimeException("DOM Level 1 node");
}
} else {
// uri=null and no colon
// no fix up is needed: default namespace decl does not
// ---------------------------------------
// remove default attributes
// ---------------------------------------
removeDefault(attr, attributes);
}
}
}
} // end loop for attributes
}
|
diff --git a/src/net/minecraft/src/mod_StatusEffectHUD.java b/src/net/minecraft/src/mod_StatusEffectHUD.java
index fabc498..c579432 100644
--- a/src/net/minecraft/src/mod_StatusEffectHUD.java
+++ b/src/net/minecraft/src/mod_StatusEffectHUD.java
@@ -1,248 +1,248 @@
package net.minecraft.src;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiChat;
import net.minecraft.client.gui.ScaledResolution;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.StatCollector;
import org.lwjgl.opengl.GL11;
import bspkrs.client.util.HUDUtils;
import bspkrs.util.BSProp;
import bspkrs.util.BSPropRegistry;
import bspkrs.util.Const;
import bspkrs.util.ModVersionChecker;
public class mod_StatusEffectHUD extends BaseMod
{
protected float zLevel = -150.0F;
private ScaledResolution scaledResolution;
@BSProp(info = "Valid alignment strings are topleft, topcenter, topright, middleleft, middlecenter, middleright, bottomleft, bottomcenter (not recommended), bottomright")
public static String alignMode = "middleright";
// @BSProp(info="Valid list mode strings are horizontal and vertical")
// public static String listMode = "vertical";
@BSProp(info = "Set to true to see the effect background box, false to disable.")
public static boolean enableBackground = false;
@BSProp(info = "Set to true to show effect names, false to disable.")
public static boolean enableEffectName = true;
@BSProp(info = "Set to true to enable blinking for the icon when a potion/effect is nearly gone, false to disable.")
public static boolean enableIconBlink = true;
@BSProp(info = "When a potion/effect has this many seconds remaining the timer will begin to blink.")
public static int durationBlinkSeconds = 10;
@BSProp(info = "Valid color values are 0-9, a-f (color values can be found here: http://www.minecraftwiki.net/wiki/File:Colors.png).")
public static String effectNameColor = "f";
@BSProp(info = "Valid color values are 0-9, a-f (color values can be found here: http://www.minecraftwiki.net/wiki/File:Colors.png).")
public static String durationColor = "f";
@BSProp(info = "Horizontal offset from the edge of the screen (when using right alignments the x offset is relative to the right edge of the screen).")
public static int xOffset = 2;
@BSProp(info = "Vertical offset from the edge of the screen (when using bottom alignments the y offset is relative to the bottom edge of the screen).")
public static int yOffset = 2;
@BSProp(info = "Vertical offset used only for the bottomcenter alignment to avoid the vanilla HUD.")
public static int yOffsetBottomCenter = 41;
@BSProp(info = "Set to true if you want the xOffset value to be applied when using a center alignment.")
public static boolean applyXOffsetToCenter = false;
@BSProp(info = "Set to true if you want the yOffset value to be applied when using a middle alignment.")
public static boolean applyYOffsetToMiddle = false;
@BSProp(info = "Set to true to show info when chat is open, false to disable info when chat is open.\n\n**ONLY EDIT WHAT IS BELOW THIS**")
public static boolean showInChat = true;
private ModVersionChecker versionChecker;
private boolean allowUpdateCheck;
private final String versionURL = Const.VERSION_URL + "/Minecraft/" + Const.MCVERSION + "/statusEffectHUD.version";
private final String mcfTopic = "http://www.minecraftforum.net/topic/1114612-";
private Map<PotionEffect, Integer> potionMaxDurationMap;
public mod_StatusEffectHUD()
{
BSPropRegistry.registerPropHandler(this.getClass());
potionMaxDurationMap = new HashMap<PotionEffect, Integer>();
}
@Override
public String getName()
{
return "StatusEffectHUD";
}
@Override
public String getVersion()
{
return "v1.16(" + Const.MCVERSION + ")";
}
@Override
public String getPriorities()
{
return "required-after:mod_bspkrsCore";
}
@Override
public void load()
{
allowUpdateCheck = mod_bspkrsCore.allowUpdateCheck;
if (allowUpdateCheck)
{
versionChecker = new ModVersionChecker(getName(), getVersion(), versionURL, mcfTopic);
versionChecker.checkVersionWithLogging();
}
ModLoader.setInGameHook(this, true, false);
}
@Override
public boolean onTickInGame(float f, Minecraft mc)
{
if ((mc.inGameHasFocus || mc.currentScreen == null || (mc.currentScreen instanceof GuiChat && showInChat)) &&
!mc.gameSettings.showDebugInfo && !mc.gameSettings.keyBindPlayerList.pressed)
{
GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
//mc.renderEngine.resetBoundTexture();
scaledResolution = new ScaledResolution(mc.gameSettings, mc.displayWidth, mc.displayHeight);
displayStatusEffects(mc);
GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
//mc.renderEngine.resetBoundTexture();
}
if (allowUpdateCheck && versionChecker != null)
{
if (!versionChecker.isCurrentVersion())
for (String msg : versionChecker.getInGameMessage())
mc.thePlayer.addChatMessage(msg);
allowUpdateCheck = false;
GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
}
return true;
}
private int getX(int width)
{
if (alignMode.equalsIgnoreCase("topcenter") || alignMode.equalsIgnoreCase("middlecenter") || alignMode.equalsIgnoreCase("bottomcenter"))
return scaledResolution.getScaledWidth() / 2 - width / 2 + (applyXOffsetToCenter ? xOffset : 0);
else if (alignMode.equalsIgnoreCase("topright") || alignMode.equalsIgnoreCase("middleright") || alignMode.equalsIgnoreCase("bottomright"))
return scaledResolution.getScaledWidth() - width - xOffset;
else
return xOffset;
}
private int getY(int rowCount, int height)
{
if (alignMode.equalsIgnoreCase("middleleft") || alignMode.equalsIgnoreCase("middlecenter") || alignMode.equalsIgnoreCase("middleright"))
return (scaledResolution.getScaledHeight() / 2) - ((rowCount * height) / 2) + (applyYOffsetToMiddle ? yOffset : 0);
else if (alignMode.equalsIgnoreCase("bottomleft") || alignMode.equalsIgnoreCase("bottomright"))
return scaledResolution.getScaledHeight() - (rowCount * height) - yOffset;
else if (alignMode.equalsIgnoreCase("bottomcenter"))
return scaledResolution.getScaledHeight() - (rowCount * height) - yOffsetBottomCenter;
else
return yOffset;
}
private boolean shouldRender(PotionEffect pe, int ticksLeft, int thresholdSeconds)
{
if (potionMaxDurationMap.get(pe).intValue() > 400)
if (ticksLeft / 20 <= thresholdSeconds)
return ticksLeft % 20 < 10;
return true;
}
private void displayStatusEffects(Minecraft mc)
{
Collection<?> activeEffects = mc.thePlayer.getActivePotionEffects();
if (!activeEffects.isEmpty())
{
int yOffset = enableBackground ? 33 : enableEffectName ? 20 : 18;
if (activeEffects.size() > 5 && enableBackground)
yOffset = 132 / (activeEffects.size() - 1);
int yBase = getY(activeEffects.size(), yOffset);
for (Iterator<?> iteratorPotionEffect = activeEffects.iterator(); iteratorPotionEffect.hasNext(); yBase += yOffset)
{
PotionEffect potionEffect = (PotionEffect) iteratorPotionEffect.next();
// If we find a newly added potionEffect, add it and the current duration to the map to keep track of the max duration
if (!potionMaxDurationMap.containsKey(potionEffect) || potionMaxDurationMap.get(potionEffect).intValue() < potionEffect.getDuration())
potionMaxDurationMap.put(potionEffect, new Integer(potionEffect.getDuration()));
Potion potion = Potion.potionTypes[potionEffect.getPotionID()];
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
// func_110434_K = getTextureManager()
// func_110577_a = bindTexture()
mc.getTextureManager().bindTexture(new ResourceLocation("textures/gui/container/inventory.png"));
int xBase = getX(enableBackground ? 120 : 18 + 4 + mc.fontRenderer.getStringWidth("0:00"));
String potionName = "";
if (enableEffectName)
{
potionName = StatCollector.translateToLocal(potion.getName());
if (potionEffect.getAmplifier() == 1)
{
potionName = potionName + " II";
}
else if (potionEffect.getAmplifier() == 2)
{
potionName = potionName + " III";
}
else if (potionEffect.getAmplifier() == 3)
{
potionName = potionName + " IV";
}
xBase = getX(enableBackground ? 120 : 18 + 4 + mc.fontRenderer.getStringWidth(potionName));
}
String effectDuration = Potion.getDurationString(potionEffect);
if (enableBackground)
HUDUtils.drawTexturedModalRect(xBase, yBase, 0, 166, 140, 32, zLevel);
if (alignMode.toLowerCase().contains("right"))
{
xBase = getX(0);
if (potion.hasStatusIcon())
{
int potionStatusIcon = potion.getStatusIconIndex();
if (!enableIconBlink || (enableIconBlink && shouldRender(potionEffect, potionEffect.getDuration(), durationBlinkSeconds)))
HUDUtils.drawTexturedModalRect(xBase + (enableBackground ? -24 : -18), yBase + (enableBackground ? 7 : 0), 0 + potionStatusIcon % 8 * 18, 166 + 32 + potionStatusIcon / 8 * 18, 18, 18, zLevel);
}
int stringWidth = mc.fontRenderer.getStringWidth(potionName);
mc.fontRenderer.drawStringWithShadow("\247" + effectNameColor + potionName + "\247r", xBase + (enableBackground ? -10 : -4) - 18 - stringWidth, yBase + (enableBackground ? 6 : 0), 0xffffff);
stringWidth = mc.fontRenderer.getStringWidth(effectDuration);
if (shouldRender(potionEffect, potionEffect.getDuration(), durationBlinkSeconds))
mc.fontRenderer.drawStringWithShadow("\247" + durationColor + effectDuration + "\247r", xBase + (enableBackground ? -10 : -4) - 18 - stringWidth, yBase + (enableBackground ? 6 : 0) + (enableEffectName ? 10 : 5), 0xffffff);
}
else
{
if (potion.hasStatusIcon())
{
int potionStatusIcon = potion.getStatusIconIndex();
HUDUtils.drawTexturedModalRect(xBase + (enableBackground ? 6 : 0), yBase + (enableBackground ? 7 : 0), 0 + potionStatusIcon % 8 * 18, 166 + 32 + potionStatusIcon / 8 * 18, 18, 18, zLevel);
}
mc.fontRenderer.drawStringWithShadow("\247" + effectNameColor + potionName + "\247r", xBase + (enableBackground ? 10 : 4) + 18, yBase + (enableBackground ? 6 : 0), 0xffffff);
if (shouldRender(potionEffect, potionEffect.getDuration(), durationBlinkSeconds))
mc.fontRenderer.drawStringWithShadow("\247" + durationColor + effectDuration + "\247r", xBase + (enableBackground ? 10 : 4) + 18, yBase + (enableBackground ? 6 : 0) + (enableEffectName ? 10 : 5), 0xffffff);
}
}
// See if any potions have expired... if they have, remove them from the map
for (PotionEffect pe : potionMaxDurationMap.keySet())
if (!activeEffects.contains(pe))
- potionMaxDurationMap.remove(pe);
+ potionMaxDurationMap.put(pe, new Integer(0));
}
}
}
| true | true | private void displayStatusEffects(Minecraft mc)
{
Collection<?> activeEffects = mc.thePlayer.getActivePotionEffects();
if (!activeEffects.isEmpty())
{
int yOffset = enableBackground ? 33 : enableEffectName ? 20 : 18;
if (activeEffects.size() > 5 && enableBackground)
yOffset = 132 / (activeEffects.size() - 1);
int yBase = getY(activeEffects.size(), yOffset);
for (Iterator<?> iteratorPotionEffect = activeEffects.iterator(); iteratorPotionEffect.hasNext(); yBase += yOffset)
{
PotionEffect potionEffect = (PotionEffect) iteratorPotionEffect.next();
// If we find a newly added potionEffect, add it and the current duration to the map to keep track of the max duration
if (!potionMaxDurationMap.containsKey(potionEffect) || potionMaxDurationMap.get(potionEffect).intValue() < potionEffect.getDuration())
potionMaxDurationMap.put(potionEffect, new Integer(potionEffect.getDuration()));
Potion potion = Potion.potionTypes[potionEffect.getPotionID()];
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
// func_110434_K = getTextureManager()
// func_110577_a = bindTexture()
mc.getTextureManager().bindTexture(new ResourceLocation("textures/gui/container/inventory.png"));
int xBase = getX(enableBackground ? 120 : 18 + 4 + mc.fontRenderer.getStringWidth("0:00"));
String potionName = "";
if (enableEffectName)
{
potionName = StatCollector.translateToLocal(potion.getName());
if (potionEffect.getAmplifier() == 1)
{
potionName = potionName + " II";
}
else if (potionEffect.getAmplifier() == 2)
{
potionName = potionName + " III";
}
else if (potionEffect.getAmplifier() == 3)
{
potionName = potionName + " IV";
}
xBase = getX(enableBackground ? 120 : 18 + 4 + mc.fontRenderer.getStringWidth(potionName));
}
String effectDuration = Potion.getDurationString(potionEffect);
if (enableBackground)
HUDUtils.drawTexturedModalRect(xBase, yBase, 0, 166, 140, 32, zLevel);
if (alignMode.toLowerCase().contains("right"))
{
xBase = getX(0);
if (potion.hasStatusIcon())
{
int potionStatusIcon = potion.getStatusIconIndex();
if (!enableIconBlink || (enableIconBlink && shouldRender(potionEffect, potionEffect.getDuration(), durationBlinkSeconds)))
HUDUtils.drawTexturedModalRect(xBase + (enableBackground ? -24 : -18), yBase + (enableBackground ? 7 : 0), 0 + potionStatusIcon % 8 * 18, 166 + 32 + potionStatusIcon / 8 * 18, 18, 18, zLevel);
}
int stringWidth = mc.fontRenderer.getStringWidth(potionName);
mc.fontRenderer.drawStringWithShadow("\247" + effectNameColor + potionName + "\247r", xBase + (enableBackground ? -10 : -4) - 18 - stringWidth, yBase + (enableBackground ? 6 : 0), 0xffffff);
stringWidth = mc.fontRenderer.getStringWidth(effectDuration);
if (shouldRender(potionEffect, potionEffect.getDuration(), durationBlinkSeconds))
mc.fontRenderer.drawStringWithShadow("\247" + durationColor + effectDuration + "\247r", xBase + (enableBackground ? -10 : -4) - 18 - stringWidth, yBase + (enableBackground ? 6 : 0) + (enableEffectName ? 10 : 5), 0xffffff);
}
else
{
if (potion.hasStatusIcon())
{
int potionStatusIcon = potion.getStatusIconIndex();
HUDUtils.drawTexturedModalRect(xBase + (enableBackground ? 6 : 0), yBase + (enableBackground ? 7 : 0), 0 + potionStatusIcon % 8 * 18, 166 + 32 + potionStatusIcon / 8 * 18, 18, 18, zLevel);
}
mc.fontRenderer.drawStringWithShadow("\247" + effectNameColor + potionName + "\247r", xBase + (enableBackground ? 10 : 4) + 18, yBase + (enableBackground ? 6 : 0), 0xffffff);
if (shouldRender(potionEffect, potionEffect.getDuration(), durationBlinkSeconds))
mc.fontRenderer.drawStringWithShadow("\247" + durationColor + effectDuration + "\247r", xBase + (enableBackground ? 10 : 4) + 18, yBase + (enableBackground ? 6 : 0) + (enableEffectName ? 10 : 5), 0xffffff);
}
}
// See if any potions have expired... if they have, remove them from the map
for (PotionEffect pe : potionMaxDurationMap.keySet())
if (!activeEffects.contains(pe))
potionMaxDurationMap.remove(pe);
}
}
| private void displayStatusEffects(Minecraft mc)
{
Collection<?> activeEffects = mc.thePlayer.getActivePotionEffects();
if (!activeEffects.isEmpty())
{
int yOffset = enableBackground ? 33 : enableEffectName ? 20 : 18;
if (activeEffects.size() > 5 && enableBackground)
yOffset = 132 / (activeEffects.size() - 1);
int yBase = getY(activeEffects.size(), yOffset);
for (Iterator<?> iteratorPotionEffect = activeEffects.iterator(); iteratorPotionEffect.hasNext(); yBase += yOffset)
{
PotionEffect potionEffect = (PotionEffect) iteratorPotionEffect.next();
// If we find a newly added potionEffect, add it and the current duration to the map to keep track of the max duration
if (!potionMaxDurationMap.containsKey(potionEffect) || potionMaxDurationMap.get(potionEffect).intValue() < potionEffect.getDuration())
potionMaxDurationMap.put(potionEffect, new Integer(potionEffect.getDuration()));
Potion potion = Potion.potionTypes[potionEffect.getPotionID()];
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
// func_110434_K = getTextureManager()
// func_110577_a = bindTexture()
mc.getTextureManager().bindTexture(new ResourceLocation("textures/gui/container/inventory.png"));
int xBase = getX(enableBackground ? 120 : 18 + 4 + mc.fontRenderer.getStringWidth("0:00"));
String potionName = "";
if (enableEffectName)
{
potionName = StatCollector.translateToLocal(potion.getName());
if (potionEffect.getAmplifier() == 1)
{
potionName = potionName + " II";
}
else if (potionEffect.getAmplifier() == 2)
{
potionName = potionName + " III";
}
else if (potionEffect.getAmplifier() == 3)
{
potionName = potionName + " IV";
}
xBase = getX(enableBackground ? 120 : 18 + 4 + mc.fontRenderer.getStringWidth(potionName));
}
String effectDuration = Potion.getDurationString(potionEffect);
if (enableBackground)
HUDUtils.drawTexturedModalRect(xBase, yBase, 0, 166, 140, 32, zLevel);
if (alignMode.toLowerCase().contains("right"))
{
xBase = getX(0);
if (potion.hasStatusIcon())
{
int potionStatusIcon = potion.getStatusIconIndex();
if (!enableIconBlink || (enableIconBlink && shouldRender(potionEffect, potionEffect.getDuration(), durationBlinkSeconds)))
HUDUtils.drawTexturedModalRect(xBase + (enableBackground ? -24 : -18), yBase + (enableBackground ? 7 : 0), 0 + potionStatusIcon % 8 * 18, 166 + 32 + potionStatusIcon / 8 * 18, 18, 18, zLevel);
}
int stringWidth = mc.fontRenderer.getStringWidth(potionName);
mc.fontRenderer.drawStringWithShadow("\247" + effectNameColor + potionName + "\247r", xBase + (enableBackground ? -10 : -4) - 18 - stringWidth, yBase + (enableBackground ? 6 : 0), 0xffffff);
stringWidth = mc.fontRenderer.getStringWidth(effectDuration);
if (shouldRender(potionEffect, potionEffect.getDuration(), durationBlinkSeconds))
mc.fontRenderer.drawStringWithShadow("\247" + durationColor + effectDuration + "\247r", xBase + (enableBackground ? -10 : -4) - 18 - stringWidth, yBase + (enableBackground ? 6 : 0) + (enableEffectName ? 10 : 5), 0xffffff);
}
else
{
if (potion.hasStatusIcon())
{
int potionStatusIcon = potion.getStatusIconIndex();
HUDUtils.drawTexturedModalRect(xBase + (enableBackground ? 6 : 0), yBase + (enableBackground ? 7 : 0), 0 + potionStatusIcon % 8 * 18, 166 + 32 + potionStatusIcon / 8 * 18, 18, 18, zLevel);
}
mc.fontRenderer.drawStringWithShadow("\247" + effectNameColor + potionName + "\247r", xBase + (enableBackground ? 10 : 4) + 18, yBase + (enableBackground ? 6 : 0), 0xffffff);
if (shouldRender(potionEffect, potionEffect.getDuration(), durationBlinkSeconds))
mc.fontRenderer.drawStringWithShadow("\247" + durationColor + effectDuration + "\247r", xBase + (enableBackground ? 10 : 4) + 18, yBase + (enableBackground ? 6 : 0) + (enableEffectName ? 10 : 5), 0xffffff);
}
}
// See if any potions have expired... if they have, remove them from the map
for (PotionEffect pe : potionMaxDurationMap.keySet())
if (!activeEffects.contains(pe))
potionMaxDurationMap.put(pe, new Integer(0));
}
}
|
diff --git a/src/org/joval/scap/oval/engine/Engine.java b/src/org/joval/scap/oval/engine/Engine.java
index 26f7f59e..c4a112d8 100755
--- a/src/org/joval/scap/oval/engine/Engine.java
+++ b/src/org/joval/scap/oval/engine/Engine.java
@@ -1,3513 +1,3510 @@
// Copyright (C) 2011 jOVAL.org. All rights reserved.
// This software is licensed under the AGPL 3.0 license available at http://www.joval.org/agpl_v3.txt
package org.joval.scap.oval.engine;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.charset.Charset;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Properties;
import java.util.Queue;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.MatchResult;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import javax.xml.bind.JAXBElement;
import jsaf.intf.util.ILoggable;
import jsaf.util.StringTools;
import org.slf4j.cal10n.LocLogger;
import scap.oval.common.CheckEnumeration;
import scap.oval.common.ComplexDatatypeEnumeration;
import scap.oval.common.ExistenceEnumeration;
import scap.oval.common.MessageLevelEnumeration;
import scap.oval.common.MessageType;
import scap.oval.common.OperatorEnumeration;
import scap.oval.common.OperationEnumeration;
import scap.oval.common.SimpleDatatypeEnumeration;
import scap.oval.definitions.core.ArithmeticEnumeration;
import scap.oval.definitions.core.ArithmeticFunctionType;
import scap.oval.definitions.core.BeginFunctionType;
import scap.oval.definitions.core.ConcatFunctionType;
import scap.oval.definitions.core.ConstantVariable;
import scap.oval.definitions.core.CountFunctionType;
import scap.oval.definitions.core.CriteriaType;
import scap.oval.definitions.core.CriterionType;
import scap.oval.definitions.core.DateTimeFormatEnumeration;
import scap.oval.definitions.core.DefinitionType;
import scap.oval.definitions.core.DefinitionsType;
import scap.oval.definitions.core.EndFunctionType;
import scap.oval.definitions.core.EntityComplexBaseType;
import scap.oval.definitions.core.EntityObjectFieldType;
import scap.oval.definitions.core.EntityObjectRecordType;
import scap.oval.definitions.core.EntityObjectStringType;
import scap.oval.definitions.core.EntitySimpleBaseType;
import scap.oval.definitions.core.EntityStateFieldType;
import scap.oval.definitions.core.EntityStateRecordType;
import scap.oval.definitions.core.EntityStateSimpleBaseType;
import scap.oval.definitions.core.EscapeRegexFunctionType;
import scap.oval.definitions.core.ExtendDefinitionType;
import scap.oval.definitions.core.ExternalVariable;
import scap.oval.definitions.core.Filter;
import scap.oval.definitions.core.LiteralComponentType;
import scap.oval.definitions.core.LocalVariable;
import scap.oval.definitions.core.ObjectComponentType;
import scap.oval.definitions.core.ObjectRefType;
import scap.oval.definitions.core.ObjectType;
import scap.oval.definitions.core.ObjectsType;
import scap.oval.definitions.core.OvalDefinitions;
import scap.oval.definitions.core.RegexCaptureFunctionType;
import scap.oval.definitions.core.Set;
import scap.oval.definitions.core.SetOperatorEnumeration;
import scap.oval.definitions.core.SplitFunctionType;
import scap.oval.definitions.core.StateRefType;
import scap.oval.definitions.core.StateType;
import scap.oval.definitions.core.StatesType;
import scap.oval.definitions.core.SubstringFunctionType;
import scap.oval.definitions.core.TestsType;
import scap.oval.definitions.core.TimeDifferenceFunctionType;
import scap.oval.definitions.core.UniqueFunctionType;
import scap.oval.definitions.core.ValueType;
import scap.oval.definitions.core.VariableComponentType;
import scap.oval.definitions.core.VariableType;
import scap.oval.definitions.core.VariablesType;
import scap.oval.definitions.independent.EntityObjectVariableRefType;
import scap.oval.definitions.independent.UnknownTest;
import scap.oval.definitions.independent.VariableObject;
import scap.oval.definitions.independent.VariableTest;
import scap.oval.results.ResultEnumeration;
import scap.oval.results.TestedItemType;
import scap.oval.results.TestedVariableType;
import scap.oval.results.TestType;
import scap.oval.systemcharacteristics.core.EntityItemAnySimpleType;
import scap.oval.systemcharacteristics.core.EntityItemFieldType;
import scap.oval.systemcharacteristics.core.EntityItemRecordType;
import scap.oval.systemcharacteristics.core.EntityItemSimpleBaseType;
import scap.oval.systemcharacteristics.core.FlagEnumeration;
import scap.oval.systemcharacteristics.core.ItemType;
import scap.oval.systemcharacteristics.core.StatusEnumeration;
import scap.oval.systemcharacteristics.core.VariableValueType;
import scap.oval.systemcharacteristics.independent.EntityItemVariableRefType;
import scap.oval.systemcharacteristics.independent.VariableItem;
import scap.oval.variables.OvalVariables;
import org.joval.intf.plugin.IPlugin;
import org.joval.intf.scap.oval.IBatch;
import org.joval.intf.scap.oval.IDefinitionFilter;
import org.joval.intf.scap.oval.IDefinitions;
import org.joval.intf.scap.oval.IOvalEngine;
import org.joval.intf.scap.oval.IProvider;
import org.joval.intf.scap.oval.IResults;
import org.joval.intf.scap.oval.ISystemCharacteristics;
import org.joval.intf.scap.oval.IType;
import org.joval.intf.scap.oval.IVariables;
import org.joval.intf.util.IObserver;
import org.joval.intf.util.IProducer;
import org.joval.scap.oval.Batch;
import org.joval.scap.oval.CollectException;
import org.joval.scap.oval.DefinitionFilter;
import org.joval.scap.oval.Definitions;
import org.joval.scap.oval.Factories;
import org.joval.scap.oval.ItemSet;
import org.joval.scap.oval.OvalException;
import org.joval.scap.oval.OvalFactory;
import org.joval.scap.oval.Results;
import org.joval.scap.oval.SystemCharacteristics;
import org.joval.scap.oval.types.IntType;
import org.joval.scap.oval.types.Ip4AddressType;
import org.joval.scap.oval.types.Ip6AddressType;
import org.joval.scap.oval.types.RecordType;
import org.joval.scap.oval.types.StringType;
import org.joval.scap.oval.types.TypeConversionException;
import org.joval.scap.oval.types.TypeFactory;
import org.joval.util.JOVALMsg;
import org.joval.util.JOVALSystem;
import org.joval.util.Producer;
import org.joval.util.Version;
import org.joval.xml.XSITools;
/**
* Engine that evaluates OVAL tests using an IPlugin.
*
* @author David A. Solin
* @version %I% %G%
*/
public class Engine implements IOvalEngine, IProvider {
//
// Initialize the static class mapping between OVAL object types and item types in the data model, as defined by
// the class resource "/ObjectItem.properties".
//
private static Map<Class<? extends ObjectType>, Class<? extends ItemType>> OBJECT_ITEM_MAP;
static {
OBJECT_ITEM_MAP = new HashMap<Class<? extends ObjectType>, Class<? extends ItemType>>();
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(Engine.class.getResourceAsStream("/ObjectItem.properties")));
String line = null;
while((line = reader.readLine()) != null) {
if (!line.startsWith("#")) {
int ptr = line.indexOf("=");
@SuppressWarnings("unchecked")
Class<? extends ObjectType> objClass = (Class<? extends ObjectType>)Class.forName(line.substring(0,ptr));
@SuppressWarnings("unchecked")
Class<? extends ItemType> itemClass = (Class<? extends ItemType>)Class.forName(line.substring(ptr+1));
OBJECT_ITEM_MAP.put(objClass, itemClass);
}
}
} catch (Exception e) {
JOVALMsg.getLogger().warn(JOVALMsg.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
}
}
}
}
private enum State {
CONFIGURE,
RUNNING,
COMPLETE_OK,
COMPLETE_ERR;
}
private Hashtable <String, Collection<IType>>variableMap;
private IVariables externalVariables = null;
private IDefinitions definitions = null;
private IPlugin plugin = null;
private ISystemCharacteristics sc = null;
private IDefinitionFilter filter = null;
private IOvalEngine.Mode mode;
private Map<String, ObjectGroup> scanQueue = null;
private Exception error;
private Results results;
private State state;
private boolean evalEnabled = true, abort = false;
private Producer<Message> producer;
private LocLogger logger;
/**
* Create an engine for evaluating OVAL definitions using a plugin.
*/
protected Engine(IOvalEngine.Mode mode, IPlugin plugin) {
if (plugin == null) {
logger = JOVALMsg.getLogger();
} else {
logger = plugin.getLogger();
this.plugin = plugin;
}
this.mode = mode;
producer = new Producer<Message>();
filter = new DefinitionFilter();
reset();
}
// Implement IProvider
public Collection<? extends ItemType> getItems(ObjectType obj, IProvider.IRequestContext rc) throws CollectException {
if (abort) {
throw new AbortException(JOVALMsg.getMessage(JOVALMsg.ERROR_ENGINE_ABORT));
}
if (obj instanceof VariableObject) {
VariableObject vObj = (VariableObject)obj;
Collection<VariableItem> items = new ArrayList<VariableItem>();
try {
Collection<IType> values = resolveVariable((String)vObj.getVarRef().getValue(), (RequestContext)rc);
if (values.size() > 0) {
VariableItem item = Factories.sc.independent.createVariableItem();
EntityItemVariableRefType ref = Factories.sc.independent.createEntityItemVariableRefType();
ref.setValue(vObj.getVarRef().getValue());
item.setVarRef(ref);
for (IType value : values) {
EntityItemAnySimpleType valueType = Factories.sc.core.createEntityItemAnySimpleType();
valueType.setValue(value.getString());
valueType.setDatatype(value.getType().getSimple().value());
item.getValue().add(valueType);
}
items.add(item);
}
} catch (UnsupportedOperationException e) {
logger.warn(JOVALMsg.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
throw new CollectException(e.getMessage(), FlagEnumeration.ERROR);
} catch (ResolveException e) {
throw new CollectException(e.getMessage(), FlagEnumeration.ERROR);
} catch (OvalException e) {
throw new CollectException(e.getMessage(), FlagEnumeration.ERROR);
}
return items;
} else if (plugin == null) {
throw new CollectException(JOVALMsg.getMessage(JOVALMsg.ERROR_MODE_SC), FlagEnumeration.NOT_COLLECTED);
} else {
return plugin.getOvalProvider().getItems(obj, rc);
}
}
// Implement IOvalEngine
public void setDefinitions(IDefinitions definitions) throws IllegalThreadStateException {
switch(state) {
case RUNNING:
throw new IllegalThreadStateException(JOVALMsg.getMessage(JOVALMsg.ERROR_ENGINE_STATE, state));
case COMPLETE_OK:
case COMPLETE_ERR:
reset();
// fall-through
default:
this.definitions = definitions;
break;
}
}
public void setDefinitionFilter(IDefinitionFilter filter) throws IllegalThreadStateException {
switch(state) {
case CONFIGURE:
mode = Mode.DIRECTED;
this.filter = filter;
break;
default:
throw new IllegalThreadStateException(JOVALMsg.getMessage(JOVALMsg.ERROR_ENGINE_STATE, state));
}
}
public void setSystemCharacteristics(ISystemCharacteristics sc) throws IllegalThreadStateException {
switch(state) {
case CONFIGURE:
mode = Mode.EXHAUSTIVE;
this.sc = sc;
break;
default:
throw new IllegalThreadStateException(JOVALMsg.getMessage(JOVALMsg.ERROR_ENGINE_STATE, state));
}
}
public void setExternalVariables(IVariables variables) throws IllegalThreadStateException {
switch(state) {
case CONFIGURE:
externalVariables = variables;
break;
default:
throw new IllegalThreadStateException(JOVALMsg.getMessage(JOVALMsg.ERROR_ENGINE_STATE, state));
}
}
public IProducer<Message> getNotificationProducer() {
return producer;
}
public Result getResult() throws IllegalThreadStateException {
switch(state) {
case COMPLETE_OK:
return Result.OK;
case COMPLETE_ERR:
return Result.ERR;
case CONFIGURE:
case RUNNING:
default:
throw new IllegalThreadStateException(JOVALMsg.getMessage(JOVALMsg.ERROR_ENGINE_STATE, state));
}
}
public IResults getResults() throws IllegalThreadStateException {
getResult();
return results;
}
public Exception getError() throws IllegalThreadStateException {
getResult();
return error;
}
public void destroy() {
if (state == State.RUNNING) {
abort = true;
}
}
public ResultEnumeration evaluateDefinition(String id)
throws IllegalStateException, NoSuchElementException, OvalException {
try {
if (definitions == null) {
throw new IllegalStateException(JOVALMsg.getMessage(JOVALMsg.ERROR_DEFINITIONS_NONE));
}
state = State.RUNNING;
if (sc == null) {
sc = new SystemCharacteristics(plugin.getSystemInfo());
((ILoggable)sc).setLogger(logger);
}
if (results == null) {
results = new Results(definitions, sc);
results.setLogger(logger);
}
return evaluateDefinition(definitions.getDefinition(id)).getResult();
} finally {
state = State.COMPLETE_OK;
}
}
// Implement Runnable
/**
* The engine runs differently depending on the mode that was used to initialize it:
*
* DIRECTED:
* The Engine will iterate through the [filtered] definitions and probe only the objects that must be collected in
* order to evaluate them.
*
* EXHAUSTIVE:
* First the Engine probes all the objects in the OVAL definitions, or it uses the supplied ISystemCharacteristics.
* Then, all the definitions are evaluated. This mirrors the way that ovaldi processes OVAL definitions.
*
* Note: if the plugin is connected before running, it will remain connected after the run has completed. If it
* was not connected before running, the engine will temporarily connect, then disconnect when finished.
*/
public void run() {
state = State.RUNNING;
boolean doDisconnect = false;
try {
//
// Connect if necessary
//
boolean scanRequired = sc == null;
if (scanRequired) {
if (plugin == null) {
throw new RuntimeException(JOVALMsg.getMessage(JOVALMsg.ERROR_SESSION_NONE));
}
if (!plugin.isConnected()) {
if (plugin.connect()) {
doDisconnect = true;
} else {
throw new RuntimeException(JOVALMsg.getMessage(JOVALMsg.ERROR_SESSION_CONNECT));
}
}
sc = new SystemCharacteristics(plugin.getSystemInfo());
((ILoggable)sc).setLogger(logger);
}
//
// Use the filter to separate the definitions into allowed and disallowed lists.
//
Collection<DefinitionType>allowed = new ArrayList<DefinitionType>();
Collection<DefinitionType>disallowed = new ArrayList<DefinitionType>();
definitions.filterDefinitions(filter, allowed, disallowed);
if (scanRequired) {
//
// First analyze the definitions:
// - Determine which objects will be scanned (depending on the mode)
// - Determine which of those objects relate to variables (so they can be scanned first)
//
HashSet<String> allowedObjectIds = new HashSet<String>();
HashSet<String> variableObjectIds = new HashSet<String>();
switch(mode) {
case EXHAUSTIVE:
for (ObjectType obj : definitions.getObjects()) {
allowedObjectIds.add(obj.getId());
}
for (VariableType var : definitions.getVariables()) {
variableObjectIds.addAll(getObjectReferences(var, true));
}
break;
case DIRECTED:
default:
for (DefinitionType def : allowed) {
allowedObjectIds.addAll(getObjectReferences(def, true));
}
for (VariableType var : definitions.getVariables()) {
for (String id : getObjectReferences(var, true)) {
if (allowedObjectIds.contains(id)) {
variableObjectIds.add(id);
}
}
}
break;
}
//
// Scan all the allowed objects. First, by collecting all the items for objects that are referenced by
// variables. Then, by collecting all the remaining objects by batching (which is potentially faster).
// Sets are deferred until the end, and run singly, since they cannot be batched easily.
//
// We could simply iterate through all the objects without this analysis, and objects and sets would be
// resolved when they're encountered, but proceeding methodically should be faster.
//
producer.sendNotify(Message.OBJECT_PHASE_START, null);
for (String id : variableObjectIds) {
scanObject(new RequestContext(definitions.getObject(id).getValue()));
}
HashSet<ObjectType> deferred = new HashSet<ObjectType>();
for (String id : allowedObjectIds) {
ObjectType obj = definitions.getObject(id).getValue();
if (getObjectSet(obj) == null) {
queueObject(new RequestContext(definitions.getObject(id).getValue()));
} else {
deferred.add(obj);
}
}
scanQueue();
for (ObjectType obj : deferred) {
scanObject(new RequestContext(obj));
}
producer.sendNotify(Message.OBJECT_PHASE_END, null);
producer.sendNotify(Message.SYSTEMCHARACTERISTICS, sc);
if (doDisconnect) {
plugin.disconnect();
doDisconnect = false;
}
//
// For directed-mode scans, we slim down the system characteristics by pruning out items that only
// pertain to indirectly-scanned objects. The objects that are directly referenced by tests will
// already have variable value notations and item references, so the indirectly-collected item data
// can be discarded as superfluous.
//
// This has been added specifically to prevent jOVAL from running out of memory when processing
// RedHat OpenSCAP content, which has an object that refers to all files on disk, which gets filtered
// several times by other objects that are directly referenced by tests.
//
switch(mode) {
case DIRECTED:
allowedObjectIds.clear();
for (DefinitionType def : allowed) {
allowedObjectIds.addAll(getObjectReferences(def, false));
}
results = new Results(definitions, sc.prune(allowedObjectIds));
break;
case EXHAUSTIVE:
default:
results = new Results(definitions, sc);
break;
}
} else if (sc.unmapped()) {
results = new Results(definitions, mapSystemCharacteristics());
} else {
results = new Results(definitions, sc);
}
results.setLogger(logger);
producer.sendNotify(Message.DEFINITION_PHASE_START, null);
//
// First evaluate all the allowed definitions, then go through the disallowed definitions. This makes it
// possible to cache both test and definition results without having to double-check if they were previously
// intentionally skipped.
//
evalEnabled = true;
for (DefinitionType definition : allowed) {
evaluateDefinition(definition);
}
evalEnabled = false;
for (DefinitionType definition : disallowed) {
evaluateDefinition(definition);
}
producer.sendNotify(Message.DEFINITION_PHASE_END, null);
state = State.COMPLETE_OK;
} catch (Exception e) {
error = e;
state = State.COMPLETE_ERR;
} finally {
if (doDisconnect) {
plugin.disconnect();
}
}
}
// Private
private void reset() {
sc = null;
state = State.CONFIGURE;
variableMap = new Hashtable<String, Collection<IType>>();
scanQueue = null;
error = null;
}
/**
* Generate object item references in the system-characteristics.
*/
private ISystemCharacteristics mapSystemCharacteristics() throws Exception {
//
// First, create a Queue of objects related to variables. These must be mapped first.
//
Queue<String> varObjQueue = new LinkedList<String>();
for (VariableType var : definitions.getVariables()) {
varObjQueue.addAll(getObjectReferences(var, true));
}
//
// Map objects in the queue if all their dependencies (if any) are already mapped, or if not, push to the
// end of the queue.
//
int counter = 0;
String objectId = null;
while((objectId = varObjQueue.poll()) != null) {
if (sc.containsObject(objectId)) {
// already mapped
} else if (hasUnmappedReferences(objectId)) {
// try again later
varObjQueue.add(objectId);
} else {
mapObject(objectId);
}
if (counter++ == 1000000) {
throw new Exception(JOVALMsg.getMessage(JOVALMsg.ERROR_SC_MAP_OVERFLOW));
}
}
//
// Map objects that are not already mapped.
//
for (ObjectType obj : definitions.getObjects()) {
objectId = obj.getId();
try {
sc.getObject(objectId);
} catch (NoSuchElementException e) {
mapObject(objectId);
}
}
return sc;
}
/**
* Returns true if the object with the specified ID has any object references not already in the S-C.
*
* TBD: Add a reference cache for improved performance?
*/
private boolean hasUnmappedReferences(String objectId) throws NoSuchElementException, OvalException {
for (String dependencyId : getObjectReferences(definitions.getObject(objectId).getValue(), true)) {
if (objectId.equals(dependencyId)) {
// ignore self
} else if (!sc.containsObject(dependencyId)) {
return true;
}
}
return false;
}
/**
* Compare all the items corresponding to the object's type to the object specification, and map them together
* in the System-Characteristics.
*/
private void mapObject(String objectId) throws Exception {
ObjectType obj = definitions.getObject(objectId).getValue();
if (!OBJECT_ITEM_MAP.containsKey(obj.getClass())) {
throw new OvalException(JOVALMsg.getMessage(JOVALMsg.ERROR_UNMAPPABLE_OBJECT, objectId, obj.getClass().getName()));
}
Collection<? extends ItemType> items = sc.getItemsByType(OBJECT_ITEM_MAP.get(obj.getClass()));
ObjectGroup group = new ObjectGroup(new RequestContext(definitions.getObject(objectId).getValue()));
Collection<IBatch.IResult> results = new ArrayList<IBatch.IResult>();
for (IBatch.IRequest request : group.getRequests()) {
RequestContext rc = (RequestContext)request.getContext();
Collection<ItemType> requestItems = new ArrayList<ItemType>();
for (ItemType item : items) {
switch(compare(request.getObject(), item, rc)) {
case TRUE:
requestItems.add(item);
break;
}
}
results.add(new Batch.Result(requestItems, request.getContext()));
}
items = group.combineItems(results, new FlagData());
if (items.size() == 0) {
logger.debug(JOVALMsg.STATUS_OBJECT_NOITEM_MAP, objectId);
sc.setObject(objectId, obj.getComment(), obj.getVersion(), FlagEnumeration.DOES_NOT_EXIST, null);
} else {
sc.setObject(objectId, obj.getComment(), obj.getVersion(), FlagEnumeration.COMPLETE, null);
for (ItemType item : items) {
logger.debug(JOVALMsg.STATUS_OBJECT_ITEM_MAP, objectId, item.getId().toString());
sc.relateItem(objectId, item.getId());
}
}
for (IBatch.IResult result : results) {
for (VariableValueType var : ((RequestContext)result.getContext()).getVars()) {
sc.storeVariable(var);
sc.relateVariable(objectId, var.getVariableId());
}
}
}
/**
* Scan an object immediately using an adapter, including crawling down any encountered Sets, variables, etc. Items
* are stored in the system-characteristics as they are collected.
*
* If for some reason (like an error) no items can be obtained, this method just returns an empty list so processing
* can continue.
*
* @throws Engine.AbortException if processing should cease because the scan is being cancelled
*/
private Collection<ItemType> scanObject(RequestContext rc) {
ObjectType obj = rc.getObject();
String objectId = obj.getId();
if (sc.containsObject(objectId)) {
ArrayList<ItemType> result = new ArrayList<ItemType>();
for (JAXBElement<? extends ItemType> elt : sc.getItemsByObjectId(objectId)) {
result.add(elt.getValue());
}
return result;
}
logger.debug(JOVALMsg.STATUS_OBJECT, objectId);
producer.sendNotify(Message.OBJECT, objectId);
Collection<ItemType> items = new ArrayList<ItemType>();
try {
Set s = getObjectSet(obj);
if (s == null) {
List<MessageType> messages = new ArrayList<MessageType>();
FlagData flags = new FlagData();
try {
items = new ObjectGroup(rc).getItems(flags);
messages.addAll(rc.getMessages());
sc.setObject(objectId, null, null, null, null);
for (VariableValueType var : rc.getVars()) {
sc.storeVariable(var);
sc.relateVariable(objectId, var.getVariableId());
}
} catch (ResolveException e) {
MessageType msg = Factories.common.createMessageType();
msg.setLevel(MessageLevelEnumeration.ERROR);
msg.setValue(e.getMessage());
messages.add(msg);
flags.add(FlagEnumeration.ERROR);
}
for (MessageType msg : messages) {
sc.setObject(objectId, null, null, null, msg);
switch(msg.getLevel()) {
case FATAL:
case ERROR:
flags.add(FlagEnumeration.INCOMPLETE);
break;
}
}
if (flags.getFlag() == FlagEnumeration.COMPLETE && items.size() == 0) {
sc.setObject(objectId, obj.getComment(), obj.getVersion(), FlagEnumeration.DOES_NOT_EXIST, null);
} else {
sc.setObject(objectId, obj.getComment(), obj.getVersion(), flags.getFlag(), null);
}
} else {
items = getSetItems(s, rc);
FlagEnumeration flag = FlagEnumeration.COMPLETE;
MessageType msg = null;
if (items.size() == 0) {
flag = FlagEnumeration.DOES_NOT_EXIST;
msg = Factories.common.createMessageType();
msg.setLevel(MessageLevelEnumeration.INFO);
msg.setValue(JOVALMsg.getMessage(JOVALMsg.STATUS_EMPTY_SET));
}
sc.setObject(objectId, obj.getComment(), obj.getVersion(), flag, msg);
}
for (ItemType item : items) {
sc.relateItem(objectId, sc.storeItem(item));
}
} catch (OvalException e) {
logger.warn(JOVALMsg.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
MessageType msg = Factories.common.createMessageType();
msg.setLevel(MessageLevelEnumeration.ERROR);
String err = JOVALMsg.getMessage(JOVALMsg.ERROR_OVAL, e.getMessage());
msg.setValue(err);
sc.setObject(objectId, obj.getComment(), obj.getVersion(), FlagEnumeration.ERROR, msg);
}
return items;
}
/**
* Attempt to queue an object request for batched scanning. If the object cannot be queued in a batch, then
* it is scanned immediately.
*/
private void queueObject(RequestContext rc) {
ObjectType obj = rc.getObject();
String id = obj.getId();
if (sc.containsObject(id)) {
// object has already been scanned
} else if (obj instanceof VariableObject) {
scanObject(rc);
} else if (getObjectSet(obj) == null) {
if (scanQueue == null) {
scanQueue = new HashMap<String, ObjectGroup>();
}
try {
IBatch batch = (IBatch)plugin.getOvalProvider();
ObjectGroup group = new ObjectGroup(rc);
boolean queued = false;
for (IBatch.IRequest request : group.getRequests()) {
if (batch.queue(request)) {
queued = true;
} else {
queued = false;
break;
}
}
if (queued) {
logger.debug(JOVALMsg.STATUS_OBJECT_QUEUE, id);
scanQueue.put(id, group);
} else {
scanObject(rc);
}
} catch (ResolveException e) {
logger.warn(JOVALMsg.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
MessageType msg = Factories.common.createMessageType();
msg.setLevel(MessageLevelEnumeration.ERROR);
msg.setValue(e.getMessage());
sc.setObject(id, obj.getComment(), obj.getVersion(), FlagEnumeration.ERROR, msg);
} catch (OvalException e) {
logger.warn(JOVALMsg.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
MessageType msg = Factories.common.createMessageType();
msg.setLevel(MessageLevelEnumeration.ERROR);
msg.setValue(JOVALMsg.getMessage(JOVALMsg.ERROR_OVAL, e.getMessage()));
sc.setObject(id, obj.getComment(), obj.getVersion(), FlagEnumeration.ERROR, msg);
}
} else {
//
// Set objects cannot be batched.
//
scanObject(rc);
}
}
/**
* Scan all the objects in the request queue in batch.
*/
private synchronized void scanQueue() throws OvalException {
if (scanQueue != null && scanQueue.size() > 0) {
//
// Organize results by object ID
//
Map<String, Collection<IBatch.IResult>> results = new HashMap<String, Collection<IBatch.IResult>>();
logger.debug(JOVALMsg.STATUS_OBJECT_BATCH, scanQueue.size());
ArrayList<String> ids = new ArrayList<String>();
ids.addAll(scanQueue.keySet());
producer.sendNotify(Message.OBJECTS, ids.toArray(new String[ids.size()]));
for (IBatch.IResult result : ((IBatch)plugin.getOvalProvider()).exec()) {
String id = ((RequestContext)result.getContext()).getObject().getId();
if (!results.containsKey(id)) {
results.put(id, new ArrayList<IBatch.IResult>());
}
results.get(id).add(result);
}
//
// Recombine result sets into discrete object item lists
//
for (Map.Entry<String, Collection<IBatch.IResult>> entry : results.entrySet()) {
String objectId = entry.getKey();
RequestContext rc = scanQueue.get(objectId).getContext();
ObjectType obj = rc.getObject();
if (!sc.containsObject(objectId)) {
Collection<ItemType> items = new ArrayList<ItemType>();
List<MessageType> messages = new ArrayList<MessageType>();
FlagData flags = new FlagData();
items = scanQueue.get(objectId).combineItems(entry.getValue(), flags);
messages.addAll(rc.getMessages());
sc.setObject(objectId, null, null, null, null);
for (VariableValueType var : rc.getVars()) {
sc.storeVariable(var);
sc.relateVariable(objectId, var.getVariableId());
}
for (MessageType msg : messages) {
sc.setObject(objectId, null, null, null, msg);
switch(msg.getLevel()) {
case FATAL:
case ERROR:
flags.add(FlagEnumeration.INCOMPLETE);
break;
}
}
if (flags.getFlag() == FlagEnumeration.COMPLETE && items.size() == 0) {
sc.setObject(objectId, obj.getComment(), obj.getVersion(), FlagEnumeration.DOES_NOT_EXIST, null);
} else {
sc.setObject(objectId, obj.getComment(), obj.getVersion(), flags.getFlag(), null);
}
for (ItemType item : items) {
sc.relateItem(objectId, sc.storeItem(item));
}
}
}
scanQueue = null;
}
}
/**
* An ObjectGroup is a container for ObjectType information, where the constituent entities of the ObjectType
* may be formed by references to multi-valued variables.
*/
class ObjectGroup {
RequestContext rc;
String id;
Class<?> clazz;
Object behaviors = null, factory;
Method create;
int size = 1;
Map<Collection<ObjectType>, CheckEnumeration> objects = null;
/**
* Lists of entity values, indexed by getter method name.
*/
Hashtable<String, List<Object>> entities;
/**
* Check operations to perform on entities, indexed by getter method name. Only set for entites sourced from
* variable references.
*/
Hashtable<String, CheckEnumeration> varChecks;
/**
* Create a new ObjectGroup for the specified request context.
*/
ObjectGroup(RequestContext rc) throws OvalException, ResolveException {
this.rc = rc;
ObjectType obj = rc.getObject();
id = obj.getId();
clazz = obj.getClass();
try {
//
// Collect everything necessary to manufacture new ObjectTypes
//
String pkgName = clazz.getPackage().getName();
Class<?> factoryClass = Class.forName(pkgName + ".ObjectFactory");
factory = factoryClass.newInstance();
String unqualClassName = clazz.getName().substring(pkgName.length() + 1);
create = factoryClass.getMethod("create" + unqualClassName);
behaviors = safeInvokeMethod(obj, "getBehaviors");
//
// Collect all the entity values
//
entities = new Hashtable<String, List<Object>>();
varChecks = new Hashtable<String, CheckEnumeration>();
for (Method method : getMethods(clazz).values()) {
String methodName = method.getName();
if (methodName.startsWith("get") && !OBJECT_METHOD_NAMES.contains(methodName)) {
Object entity = method.invoke(obj);
if (entity == null) {
//
// entity was unspeficied in the object definition, so it must be optional, and its absence
// will not impact the number of available permutations.
//
} else {
VarData vd = new VarData();
List<Object> values = resolveUnknownEntity(methodName, entity, rc, vd);
if (vd.isRef()) {
varChecks.put(methodName, vd.getCheck());
}
size = size * values.size();
if (values.size() == 0) {
MessageType message = Factories.common.createMessageType();
message.setLevel(MessageLevelEnumeration.INFO);
String entityName = methodName.substring(3).toLowerCase();
message.setValue(JOVALMsg.getMessage(JOVALMsg.STATUS_EMPTY_ENTITY, entityName));
rc.addMessage(message);
}
entities.put(methodName, values);
}
}
}
//
// For any NONE_SATISFY var_checks, invert all its entities, so it can be treated like an ALL.
//
for (String methodName : varChecks.keySet()) {
if (varChecks.get(methodName) == CheckEnumeration.NONE_SATISFY) {
for (Object entity : entities.get(methodName)) {
try {
invertEntity(rc.getObject(), methodName, entity);
} catch (Exception e) {
throw new ResolveException(e);
}
}
}
}
} catch (ClassNotFoundException e) {
logger.warn(JOVALMsg.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
throw new OvalException(JOVALMsg.getMessage(JOVALMsg.ERROR_REFLECTION, e.getMessage(), id));
} catch (InstantiationException e) {
logger.warn(JOVALMsg.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
throw new OvalException(JOVALMsg.getMessage(JOVALMsg.ERROR_REFLECTION, e.getMessage(), id));
} catch (NoSuchMethodException e) {
logger.warn(JOVALMsg.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
throw new OvalException(JOVALMsg.getMessage(JOVALMsg.ERROR_REFLECTION, e.getMessage(), id));
} catch (IllegalAccessException e) {
logger.warn(JOVALMsg.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
throw new OvalException(JOVALMsg.getMessage(JOVALMsg.ERROR_REFLECTION, e.getMessage(), id));
} catch (InvocationTargetException e) {
logger.warn(JOVALMsg.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
throw new OvalException(JOVALMsg.getMessage(JOVALMsg.ERROR_REFLECTION, e.getMessage(), id));
}
}
/**
* Get the object ID.
*/
String getId() {
return id;
}
RequestContext getContext() {
return rc;
}
/**
* Get all the items for this object group (immediately).
*/
Collection<ItemType> getItems(FlagData flags) throws OvalException {
if (varChecks.size() == 0) {
//
// There are no variables, so the group only contains the input object from the initializing context.
//
try {
@SuppressWarnings("unchecked")
Collection<ItemType> unfiltered = (Collection<ItemType>)Engine.this.getItems(rc.getObject(), rc);
List<Filter> filters = getObjectFilters(rc.getObject());
Collection<ItemType> filtered = filterItems(filters, unfiltered, rc);
flags.add(FlagEnumeration.COMPLETE);
return filtered;
} catch (CollectException e) {
MessageType msg = Factories.common.createMessageType();
msg.setLevel(MessageLevelEnumeration.INFO);
String err = JOVALMsg.getMessage(JOVALMsg.STATUS_ADAPTER_COLLECTION, e.getMessage());
msg.setValue(err);
rc.addMessage(msg);
flags.add(e.getFlag());
} catch (AbortException e) {
throw e;
} catch (Exception e) {
//
// Handle an uncaught, unexpected exception emanating from the adapter
//
logger.warn(JOVALMsg.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
MessageType msg = Factories.common.createMessageType();
msg.setLevel(MessageLevelEnumeration.ERROR);
if (e.getMessage() == null) {
msg.setValue(e.getClass().getName());
} else {
msg.setValue(e.getMessage());
}
rc.addMessage(msg);
flags.add(FlagEnumeration.ERROR);
}
} else if (size > 0) {
//
// Collect results from the object permutations, then combine them into a single result.
//
Collection<IBatch.IResult> results = new ArrayList<IBatch.IResult>();
for (IBatch.IRequest request : getRequests()) {
ObjectType obj = request.getObject();
RequestContext ctx = (RequestContext)request.getContext();
try {
@SuppressWarnings("unchecked")
Collection<ItemType> unfiltered = (Collection<ItemType>)Engine.this.getItems(obj, ctx);
List<Filter> filters = getObjectFilters(obj);
Collection<ItemType> filtered = filterItems(filters, unfiltered, ctx);
flags.add(FlagEnumeration.COMPLETE);
results.add(new Batch.Result(filtered, ctx));
} catch (CollectException e) {
results.add(new Batch.Result(e, ctx));
} catch (Exception e) {
results.add(new Batch.Result(new CollectException(e, FlagEnumeration.ERROR), ctx));
}
}
return combineItems(results, flags);
}
@SuppressWarnings("unchecked")
Collection<ItemType> empty = (Collection<ItemType>)Collections.EMPTY_LIST;
return empty;
}
/**
* Get all the requests needed to determine the matching items for this object group.
*/
Collection<IBatch.IRequest> getRequests() throws OvalException {
if (varChecks.size() == 0) {
Collection<IBatch.IRequest> requests = new ArrayList<IBatch.IRequest>();
requests.add(new Batch.Request(rc.getObject(), rc));
return requests;
} else if (size > 0) {
Collection<IBatch.IRequest> requests = new ArrayList<IBatch.IRequest>();
for (Map.Entry<String, CheckEnumeration> entry : varChecks.entrySet()) {
RequestContext vrc = rc.variant(entry.getKey(), entry.getValue());
for (Object value : entities.get(entry.getKey())) {
for (ObjectType obj : getPermutations(entry.getKey(), value)) {
requests.add(new Batch.Request(obj, vrc));
}
}
}
return requests;
} else {
@SuppressWarnings("unchecked")
Collection<IBatch.IRequest> empty = (Collection<IBatch.IRequest>)Collections.EMPTY_LIST;
return empty;
}
}
/**
* Combine batched permutation results into a single item list.
*/
Collection<ItemType> combineItems(Collection<IBatch.IResult> results, FlagData flags) {
try {
if (size > 0) {
Map<RequestContext, Collection<ItemSet<ItemType>>> sets = null;
sets = new HashMap<RequestContext, Collection<ItemSet<ItemType>>>();
for (IBatch.IResult result : results) {
RequestContext ctx = (RequestContext)result.getContext();
if (!sets.containsKey(ctx)) {
sets.put(ctx, new ArrayList<ItemSet<ItemType>>());
}
@SuppressWarnings("unchecked")
Collection<ItemType> unfiltered = (Collection<ItemType>)result.getItems();
List<Filter> filters = getObjectFilters(rc.getObject());
Collection<ItemType> filtered = filterItems(filters, unfiltered, rc);
flags.add(FlagEnumeration.COMPLETE);
sets.get(ctx).add(new ItemSet<ItemType>(filtered));
}
ItemSet<ItemType> items = new ItemSet<ItemType>();
for (Map.Entry<RequestContext, Collection<ItemSet<ItemType>>> entry : sets.entrySet()) {
ItemSet<ItemType> checked = null;
for (ItemSet<ItemType> set : entry.getValue()) {
if (checked == null) {
checked = set;
} else {
CheckEnumeration check = entry.getKey().getVariant().getCheck();
switch(check) {
case NONE_SATISFY:
case ALL:
checked = checked.intersection(set);
break;
case AT_LEAST_ONE:
checked = checked.union(set);
break;
case ONLY_ONE:
checked = checked.complement(set).union(set.complement(checked));
break;
default:
throw new OvalException(JOVALMsg.getMessage(JOVALMsg.ERROR_UNSUPPORTED_CHECK, check));
}
}
}
items = items.union(checked);
}
return items.toList();
}
} catch (CollectException e) {
MessageType msg = Factories.common.createMessageType();
msg.setLevel(MessageLevelEnumeration.INFO);
String err = JOVALMsg.getMessage(JOVALMsg.STATUS_ADAPTER_COLLECTION, e.getMessage());
msg.setValue(err);
rc.addMessage(msg);
flags.add(e.getFlag());
} catch (Exception e) {
//
// Handle an uncaught, unexpected exception emanating from the adapter
//
logger.warn(JOVALMsg.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
MessageType msg = Factories.common.createMessageType();
msg.setLevel(MessageLevelEnumeration.ERROR);
if (e.getMessage() == null) {
msg.setValue(e.getClass().getName());
} else {
msg.setValue(e.getMessage());
}
rc.addMessage(msg);
flags.add(FlagEnumeration.ERROR);
}
@SuppressWarnings("unchecked")
Collection<ItemType> empty = (Collection<ItemType>)Collections.EMPTY_LIST;
return empty;
}
// Private
/**
* Given a particular value of an entity, create a collection of all the possible resulting ObjectTypes.
*/
private Collection<ObjectType> getPermutations(String getter, Object value) throws OvalException {
if (!entities.get(getter).contains(value)) {
throw new OvalException(JOVALMsg.getMessage(JOVALMsg.ERROR_OBJECT_PERMUTATION, getter, value.toString()));
} else if (size == 0) {
@SuppressWarnings("unchecked")
Collection<ObjectType> empty = (Collection<ObjectType>)Collections.EMPTY_LIST;
}
int numPermutations = size / entities.get(getter).size();
ArrayList<Hashtable<String, Object>> valList = new ArrayList<Hashtable<String, Object>>(numPermutations);
for (int i=0; i < numPermutations; i++) {
Hashtable<String, Object> values = new Hashtable<String, Object>();
values.put(getter, value);
valList.add(values);
}
for (String key : entities.keySet()) {
if (!getter.equals(key)) {
List<Object> list = entities.get(key);
int numRepeats = numPermutations / list.size();
int index = 0;
for (Object val : list) {
for (int i=0; i < numRepeats; i++) {
valList.get(index++).put(key, val);
}
}
}
}
ArrayList<ObjectType> objects = new ArrayList<ObjectType>();
try {
for (Hashtable<String, Object> values : valList) {
objects.add(newObject(values));
}
} catch (InstantiationException e) {
logger.warn(JOVALMsg.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
throw new OvalException(JOVALMsg.getMessage(JOVALMsg.ERROR_REFLECTION, e.getMessage(), id));
} catch (NoSuchMethodException e) {
logger.warn(JOVALMsg.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
throw new OvalException(JOVALMsg.getMessage(JOVALMsg.ERROR_REFLECTION, e.getMessage(), id));
} catch (IllegalAccessException e) {
logger.warn(JOVALMsg.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
throw new OvalException(JOVALMsg.getMessage(JOVALMsg.ERROR_REFLECTION, e.getMessage(), id));
} catch (InvocationTargetException e) {
logger.warn(JOVALMsg.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
throw new OvalException(JOVALMsg.getMessage(JOVALMsg.ERROR_REFLECTION, e.getMessage(), id));
}
return objects;
}
/**
* Make a new instance of an ObjectType, with the specified group of entity values.
*/
private ObjectType newObject(Hashtable<String, Object> values)
throws InstantiationException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
ObjectType obj = (ObjectType)create.invoke(factory);
obj.setId(id);
if (behaviors != null) {
Method setBehaviors = clazz.getMethod("setBehaviors", behaviors.getClass());
setBehaviors.invoke(obj, behaviors);
}
for (String getter : values.keySet()) {
Object entity = values.get(getter);
String setter = new StringBuffer("s").append(getter.substring(1)).toString();
@SuppressWarnings("unchecked")
Method setObj = clazz.getMethod(setter, entity.getClass());
setObj.invoke(obj, entity);
}
return obj;
}
}
class Variant {
private String name;
private CheckEnumeration check;
Variant(String name, CheckEnumeration check) {
this.name = name;
this.check = check;
}
String getName() {
return name;
}
CheckEnumeration getCheck() {
return check;
}
}
/**
* Implementation of IProvider.IRequestContext.
*/
class RequestContext implements IRequestContext {
private Stack<Level> levels;
private Map<Variant, RequestContext> variants;
private Variant variant = null;
RequestContext(ObjectType object) {
levels = new Stack<Level>();
levels.push(new Level(object));
}
Collection<VariableValueType> getVars() {
return getVars(levels.peek().vars);
}
Collection<MessageType> getMessages() {
return levels.peek().messages;
}
void addVar(VariableValueType var) {
String id = var.getVariableId();
String value = (String)var.getValue();
Hashtable<String, HashSet<String>> vars = levels.peek().vars;
if (vars.containsKey(id)) {
vars.get(id).add(value);
} else {
HashSet<String> vals = new HashSet<String>();
vals.add(value);
vars.put(id, vals);
}
}
ObjectType getObject() {
return levels.peek().object;
}
void pushObject(ObjectType obj) throws OvalException {
for (Level level : levels) {
if (level.object.equals(obj)) {
throw new OvalException(JOVALMsg.getMessage(JOVALMsg.ERROR_OVAL_LOOP, obj.getId()));
}
}
levels.push(new Level(obj));
}
ObjectType popObject() {
Level level = levels.pop();
for (VariableValueType var : getVars(level.vars)) {
addVar(var);
}
levels.peek().messages.addAll(level.messages);
return level.object;
}
RequestContext variant(String name, CheckEnumeration varCheck) {
if (variants == null) {
variants = new HashMap<Variant, RequestContext>();
}
Variant v = new Variant(name, varCheck);
RequestContext ctx = new RequestContext(levels.peek(), v);
variants.put(v, ctx);
return ctx;
}
Variant getVariant() {
return variant;
}
Collection<Map.Entry<Variant, RequestContext>> variants() {
if (variants == null) {
return null;
} else {
return variants.entrySet();
}
}
// Implement IRequestContext
public void addMessage(MessageType msg) {
levels.peek().messages.add(msg);
}
// Private
private RequestContext(Level level, Variant variant) {
levels = new Stack<Level>();
levels.push(level);
this.variant = variant;
}
private Collection<VariableValueType> getVars(Hashtable<String, HashSet<String>> vars) {
Collection<VariableValueType> result = new ArrayList<VariableValueType>();
for (String id : vars.keySet()) {
for (String value : vars.get(id)) {
VariableValueType variableValueType = Factories.sc.core.createVariableValueType();
variableValueType.setVariableId(id);
variableValueType.setValue(value);
result.add(variableValueType);
}
}
return result;
}
private class Level {
ObjectType object;
Hashtable<String, HashSet<String>> vars;
Collection<MessageType> messages;
Level(ObjectType object) {
this.object = object;
this.vars = new Hashtable<String, HashSet<String>>();
this.messages = new ArrayList<MessageType>();
}
}
}
/**
* A container class for communicating discovered variable reference information from the resolveUnknownEntity method.
*/
private class VarData {
boolean isVar;
CheckEnumeration check;
VarData() {
isVar = false;
}
boolean isRef() {
return isVar;
}
void setCheck(CheckEnumeration check) {
isVar = true;
if (check == null) {
this.check = CheckEnumeration.ALL;
} else {
this.check = check;
}
}
CheckEnumeration getCheck() {
return check;
}
}
private class AbortException extends RuntimeException {
AbortException(String message) {
super(message);
}
}
private OperationEnumeration invert(OperationEnumeration op) throws IllegalArgumentException {
switch(op) {
case EQUALS:
return OperationEnumeration.NOT_EQUAL;
case GREATER_THAN:
return OperationEnumeration.LESS_THAN_OR_EQUAL;
case GREATER_THAN_OR_EQUAL:
return OperationEnumeration.LESS_THAN;
case LESS_THAN:
return OperationEnumeration.GREATER_THAN_OR_EQUAL;
case LESS_THAN_OR_EQUAL:
return OperationEnumeration.GREATER_THAN;
case NOT_EQUAL:
return OperationEnumeration.EQUALS;
case CASE_INSENSITIVE_EQUALS:
return OperationEnumeration.CASE_INSENSITIVE_NOT_EQUAL;
case CASE_INSENSITIVE_NOT_EQUAL:
return OperationEnumeration.CASE_INSENSITIVE_EQUALS;
case SUBSET_OF:
case SUPERSET_OF:
case BITWISE_AND:
case BITWISE_OR:
case PATTERN_MATCH:
default:
throw new IllegalArgumentException(op.value());
}
}
private Object invertEntity(ObjectType obj, String methodName, Object entity) throws IllegalArgumentException,
OvalException, ResolveException, InstantiationException, ClassNotFoundException,
NoSuchMethodException, IllegalAccessException, InvocationTargetException {
if (entity instanceof JAXBElement) {
String pkgName = obj.getClass().getPackage().getName();
Class<?> factoryClass = Class.forName(pkgName + ".ObjectFactory");
Object factory = factoryClass.newInstance();
String unqualClassName = obj.getClass().getName().substring(pkgName.length() + 1);
String entityName = methodName.substring(3);
if (((JAXBElement)entity).getValue() == null) {
throw new IllegalArgumentException(((JAXBElement)entity).getName().toString());
} else {
Class targetClass = ((JAXBElement)entity).getValue().getClass();
Method method = factoryClass.getMethod("create" + unqualClassName + entityName, targetClass);
return method.invoke(factory, invertEntity(obj, methodName, ((JAXBElement)entity).getValue()));
}
} else if (entity instanceof EntitySimpleBaseType) {
EntitySimpleBaseType base = (EntitySimpleBaseType)entity;
base.setOperation(invert(base.getOperation()));
return base;
} else if (entity instanceof EntityObjectRecordType) {
EntityObjectRecordType record = (EntityObjectRecordType)entity;
record.setOperation(invert(record.getOperation()));
return record;
} else {
String id = obj.getId();
String message = JOVALMsg.getMessage(JOVALMsg.ERROR_UNSUPPORTED_ENTITY, entity.getClass().getName(), id);
throw new OvalException(message);
}
}
/**
* Take an entity that may be a var_ref, and return a list of all resulting concrete entities (i.e., isSetValue == true).
* The result may be a JAXBElement list, or EntitySimpleBaseType list or an EntityObjectRecordType list.
*/
private List<Object> resolveUnknownEntity(String methodName, Object entity, RequestContext rc, VarData vd)
throws OvalException, ResolveException, InstantiationException, ClassNotFoundException,
NoSuchMethodException, IllegalAccessException, InvocationTargetException {
List<Object> result = new ArrayList<Object>();
//
// JAXBElement-wrapped entities are unwrapped, resolved, and re-wrapped using introspection.
//
if (entity instanceof JAXBElement) {
String pkgName = rc.getObject().getClass().getPackage().getName();
Class<?> factoryClass = Class.forName(pkgName + ".ObjectFactory");
Object factory = factoryClass.newInstance();
String unqualClassName = rc.getObject().getClass().getName().substring(pkgName.length() + 1);
String entityName = methodName.substring(3);
if (((JAXBElement)entity).getValue() == null) {
result.add(entity);
} else {
Class targetClass = ((JAXBElement)entity).getValue().getClass();
Method method = factoryClass.getMethod("create" + unqualClassName + entityName, targetClass);
for (Object resolved : resolveUnknownEntity(methodName, ((JAXBElement)entity).getValue(), rc, vd)) {
result.add(method.invoke(factory, resolved));
}
}
//
// All the simple types are handled here using introspection.
//
} else if (entity instanceof EntitySimpleBaseType) {
EntitySimpleBaseType simple = (EntitySimpleBaseType)entity;
if (simple.isSetVarRef()) {
vd.setCheck((CheckEnumeration)safeInvokeMethod(simple, "getVarCheck"));
try {
IType.Type t = TypeFactory.convertType(TypeFactory.getSimpleDatatype(simple.getDatatype()));
Class objClass = entity.getClass();
String pkgName = objClass.getPackage().getName();
Class<?> factoryClass = Class.forName(pkgName + ".ObjectFactory");
Object factory = factoryClass.newInstance();
String unqualClassName = objClass.getName().substring(pkgName.length() + 1);
Method method = factoryClass.getMethod("create" + unqualClassName);
for (IType type : resolveVariable(simple.getVarRef(), rc)) {
EntitySimpleBaseType instance = (EntitySimpleBaseType)method.invoke(factory);
instance.setDatatype(simple.getDatatype());
instance.setValue(type.cast(t).getString());
instance.setOperation(simple.getOperation());
result.add(instance);
}
} catch (TypeConversionException e) {
MessageType message = Factories.common.createMessageType();
message.setLevel(MessageLevelEnumeration.ERROR);
message.setValue(JOVALMsg.getMessage(JOVALMsg.ERROR_TYPE_CONVERSION, e.getMessage()));
rc.addMessage(message);
}
} else {
result.add(entity);
}
//
// In the future, it may be necessary to support additional complex types, but right now the only complex type
// is the RECORD.
//
} else if (entity instanceof EntityObjectRecordType) {
EntityObjectRecordType record = (EntityObjectRecordType)entity;
if (record.isSetVarRef()) {
vd.setCheck((CheckEnumeration)safeInvokeMethod(record, "getVarCheck"));
for (IType type : resolveVariable(record.getVarRef(), rc)) {
switch(type.getType()) {
case RECORD: {
EntityObjectRecordType instance = Factories.definitions.core.createEntityObjectRecordType();
instance.setDatatype(ComplexDatatypeEnumeration.RECORD.value());
RecordType rt = (RecordType)type;
for (String fieldName : rt.fields()) {
IType fieldType = rt.getField(fieldName);
try {
EntityObjectFieldType fieldEntity = Factories.definitions.core.createEntityObjectFieldType();
fieldEntity.setName(fieldName);
fieldEntity.setDatatype(type.getType().getSimple().value());
fieldEntity.setValue(type.getString());
//
// A resolved entity field cannot have any check information, so use the default ALL.
//
fieldEntity.setEntityCheck(CheckEnumeration.ALL);
instance.getField().add(fieldEntity);
} catch (UnsupportedOperationException e) {
MessageType message = Factories.common.createMessageType();
message.setLevel(MessageLevelEnumeration.ERROR);
message.setValue(e.getMessage());
rc.addMessage(message);
}
}
result.add(instance);
break;
}
default:
MessageType message = Factories.common.createMessageType();
message.setLevel(MessageLevelEnumeration.ERROR);
String s = JOVALMsg.getMessage(JOVALMsg.ERROR_TYPE_CONVERSION, type.getType(), IType.Type.RECORD);
message.setValue(s);
rc.addMessage(message);
break;
}
}
} else {
//
// Resolve any var_refs in the fields, and return a permutation list of the resulting record types.
//
int numPermutations = 1;
List<List<EntityObjectFieldType>> lists = new ArrayList<List<EntityObjectFieldType>>();
for (EntityObjectFieldType field : record.getField()) {
List<EntityObjectFieldType> resolved = resolveField(field, rc);
if (resolved.size() == 0) {
//
// This condition means that the field was a variable reference with no value. The
// OVAL specification implies that this should mean the record does not exist. Returning
// an empty entity list makes this assertion.
//
// http://oval.mitre.org/language/version5.10.1/ovaldefinition/documentation/oval-definitions-schema.html#EntityAttributeGroup
//
numPermutations = 0;
MessageType message = Factories.common.createMessageType();
message.setLevel(MessageLevelEnumeration.INFO);
String entityName = methodName.substring(3).toLowerCase();
String s = JOVALMsg.getMessage(JOVALMsg.STATUS_EMPTY_RECORD, entityName, field.getName());
message.setValue(s);
rc.addMessage(message);
} else if (resolved.size() > 0) {
numPermutations = numPermutations * resolved.size();
lists.add(resolved);
}
}
if (numPermutations > 0) {
List<EntityObjectRecordType> records = new ArrayList<EntityObjectRecordType>();
for (int i=0; i < numPermutations; i++) {
EntityObjectRecordType base = Factories.definitions.core.createEntityObjectRecordType();
base.setDatatype(ComplexDatatypeEnumeration.RECORD.value());
base.setMask(record.getMask());
base.setOperation(record.getOperation());
records.add(base);
}
for (List<EntityObjectFieldType> list : lists) {
int divisor = list.size();
int groupSize = records.size() / divisor;
int index = 0;
for (int i=0; i < list.size(); i++) {
for (int j=0; j < groupSize; j++) {
records.get(index++).getField().add(list.get(i));
}
}
}
result.addAll(records);
}
}
} else {
String id = rc.getObject().getId();
String message = JOVALMsg.getMessage(JOVALMsg.ERROR_UNSUPPORTED_ENTITY, entity.getClass().getName(), id);
throw new OvalException(message);
}
return result;
}
/**
* Take a field that may contain a var_ref, and return the resolved list of fields (i.e., isSetVarRef() == false).
*/
private List<EntityObjectFieldType> resolveField(EntityObjectFieldType field, RequestContext rc)
throws ResolveException, OvalException {
List<EntityObjectFieldType> result = new ArrayList<EntityObjectFieldType>();
if (field.isSetVarRef()) {
try {
IType.Type t = TypeFactory.convertType(TypeFactory.getSimpleDatatype(field.getDatatype()));
for (IType type : resolveVariable(field.getVarRef(), rc)) {
EntityObjectFieldType fieldEntity = Factories.definitions.core.createEntityObjectFieldType();
fieldEntity.setName(field.getName());
fieldEntity.setDatatype(field.getDatatype());
fieldEntity.setValue(type.cast(t).getString());
fieldEntity.setEntityCheck(field.getEntityCheck());
result.add(fieldEntity);
}
} catch (TypeConversionException e) {
MessageType message = Factories.common.createMessageType();
message.setLevel(MessageLevelEnumeration.ERROR);
message.setValue(JOVALMsg.getMessage(JOVALMsg.ERROR_TYPE_CONVERSION, e.getMessage()));
rc.addMessage(message);
}
} else {
result.add(field);
}
return result;
}
/**
* If getSet() were a method of ObjectType (instead of only some of its subclasses), this is what it would return.
*/
private Set getObjectSet(ObjectType obj) {
Set objectSet = null;
try {
Method isSetSet = obj.getClass().getMethod("isSetSet");
if (((Boolean)isSetSet.invoke(obj)).booleanValue()) {
Method getSet = obj.getClass().getMethod("getSet");
objectSet = (Set)getSet.invoke(obj);
}
} catch (NoSuchMethodException e) {
// Object doesn't support Sets; no big deal.
} catch (IllegalAccessException e) {
logger.warn(JOVALMsg.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
} catch (InvocationTargetException e) {
logger.warn(JOVALMsg.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
}
return objectSet;
}
/**
* If getFilter() were a method of ObjectType (instead of only some of its subclasses), this is what it would return.
*/
private List<Filter> getObjectFilters(ObjectType obj) {
List<Filter> filters = new ArrayList<Filter>();
Object oFilters = safeInvokeMethod(obj, "getFilter");
if (oFilters != null && oFilters instanceof List) {
for (Object oFilter : (List)oFilters) {
if (oFilter instanceof Filter) {
filters.add((Filter)oFilter);
}
}
}
return filters;
}
/**
* Given Collections of items and filters, returns the appropriately filtered collection.
*/
private Collection<ItemType> filterItems(List<Filter> filters, Collection<ItemType> items, RequestContext rc)
throws NoSuchElementException, OvalException {
Collection<ItemType> filtered = new HashSet<ItemType>();
filtered.addAll(items);
if (filters.size() == 0) {
return filtered;
}
for (Filter filter : filters) {
StateType state = definitions.getState(filter.getValue()).getValue();
Iterator<ItemType> iter = filtered.iterator();
while (iter.hasNext()) {
ItemType item = iter.next();
try {
ResultEnumeration result = compare(state, item, rc);
switch(filter.getAction()) {
case INCLUDE:
if (result == ResultEnumeration.TRUE) {
logger.debug(JOVALMsg.STATUS_FILTER, filter.getAction().value(),
item.getId() == null ? "(unassigned)" : item.getId(), rc.getObject().getId());
} else {
iter.remove();
}
break;
case EXCLUDE:
if (result == ResultEnumeration.TRUE) {
iter.remove();
logger.debug(JOVALMsg.STATUS_FILTER, filter.getAction().value(),
item.getId() == null ? "(unassigned)" : item.getId(), rc.getObject().getId());
}
break;
}
} catch (TestException e) {
logger.debug(JOVALMsg.ERROR_COMPONENT_FILTER, e.getMessage());
logger.trace(JOVALMsg.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
}
}
}
return filtered;
}
/**
* Get a list of items belonging to a Set.
*/
private Collection<ItemType> getSetItems(Set s, RequestContext rc) throws NoSuchElementException, OvalException {
//
// First, retrieve the filtered list of items in the Set, recursively.
//
Collection<Collection<ItemType>> lists = new ArrayList<Collection<ItemType>>();
if (s.isSetSet()) {
for (Set set : s.getSet()) {
lists.add(getSetItems(set, rc));
}
} else {
for (String objectId : s.getObjectReference()) {
Collection<ItemType> items = new ArrayList<ItemType>();
try {
for (JAXBElement<? extends ItemType> elt : sc.getItemsByObjectId(objectId)) {
items.add(elt.getValue());
}
} catch (NoSuchElementException e) {
rc.pushObject(definitions.getObject(objectId).getValue());
items = scanObject(rc);
rc.popObject();
}
lists.add(filterItems(s.getFilter(), items, rc));
}
}
switch(s.getSetOperator()) {
case INTERSECTION: {
ItemSet<ItemType> intersection = null;
for (Collection<ItemType> items : lists) {
if (intersection == null) {
intersection = new ItemSet<ItemType>(items);
} else {
intersection = intersection.intersection(new ItemSet<ItemType>(items));
}
}
return intersection == null ? new ArrayList<ItemType>() : intersection.toList();
}
case COMPLEMENT: {
switch(lists.size()) {
case 0:
return new ArrayList<ItemType>();
case 1:
return lists.iterator().next();
case 2:
Iterator<Collection<ItemType>> iter = lists.iterator();
Collection<ItemType> set1 = iter.next();
Collection<ItemType> set2 = iter.next();
return new ItemSet<ItemType>(set1).complement(new ItemSet<ItemType>(set2)).toList();
default:
throw new OvalException(JOVALMsg.getMessage(JOVALMsg.ERROR_SET_COMPLEMENT, new Integer(lists.size())));
}
}
case UNION:
default: {
ItemSet<ItemType> union = new ItemSet<ItemType>();
for (Collection<ItemType> items : lists) {
union = union.union(new ItemSet<ItemType>(items));
}
return union.toList();
}
}
}
/**
* Evaluate a DefinitionType.
*/
private scap.oval.results.DefinitionType evaluateDefinition(DefinitionType definition) throws OvalException {
String id = definition.getId();
try {
return results.getDefinition(id);
} catch (NoSuchElementException e) {
}
scap.oval.results.DefinitionType definitionResult = Factories.results.createDefinitionType();
logger.debug(JOVALMsg.STATUS_DEFINITION, id);
producer.sendNotify(Message.DEFINITION, id);
definitionResult.setDefinitionId(id);
definitionResult.setVersion(definition.getVersion());
definitionResult.setClazz(definition.getClazz());
try {
ResultEnumeration criteriaResult = ResultEnumeration.NOT_EVALUATED;
if (definition.isSetCriteria()) {
scap.oval.results.CriteriaType criteria = evaluateCriteria(definition.getCriteria());
definitionResult.setCriteria(criteria);
criteriaResult = criteria.getResult();
}
definitionResult.setResult(criteriaResult);
} catch (NoSuchElementException e) {
definitionResult.setResult(ResultEnumeration.ERROR);
MessageType message = Factories.common.createMessageType();
message.setLevel(MessageLevelEnumeration.ERROR);
message.setValue(e.getMessage());
definitionResult.getMessage().add(message);
}
results.storeDefinitionResult(definitionResult);
return definitionResult;
}
private scap.oval.results.CriteriaType evaluateCriteria(CriteriaType criteriaDefinition)
throws NoSuchElementException, OvalException {
scap.oval.results.CriteriaType criteriaResult = Factories.results.createCriteriaType();
criteriaResult.setOperator(criteriaDefinition.getOperator());
criteriaResult.setNegate(criteriaDefinition.getNegate());
OperatorData operator = new OperatorData(criteriaDefinition.getNegate());
for (Object child : criteriaDefinition.getCriteriaOrCriterionOrExtendDefinition()) {
Object resultObject = null;
if (child instanceof CriteriaType) {
CriteriaType ctDefinition = (CriteriaType)child;
scap.oval.results.CriteriaType ctResult = evaluateCriteria(ctDefinition);
operator.addResult(ctResult.getResult());
resultObject = ctResult;
} else if (child instanceof CriterionType) {
CriterionType ctDefinition = (CriterionType)child;
scap.oval.results.CriterionType ctResult = evaluateCriterion(ctDefinition);
operator.addResult(ctResult.getResult());
resultObject = ctResult;
} else if (child instanceof ExtendDefinitionType) {
ExtendDefinitionType edtDefinition = (ExtendDefinitionType)child;
String defId = edtDefinition.getDefinitionRef();
DefinitionType defDefinition = definitions.getDefinition(defId);
scap.oval.results.DefinitionType defResult = evaluateDefinition(defDefinition);
scap.oval.results.ExtendDefinitionType edtResult;
edtResult = Factories.results.createExtendDefinitionType();
edtResult.setDefinitionRef(defId);
edtResult.setVersion(defDefinition.getVersion());
edtResult.setNegate(edtDefinition.getNegate());
OperatorData od = new OperatorData(edtDefinition.getNegate());
od.addResult(defResult.getResult());
edtResult.setResult(od.getResult(OperatorEnumeration.AND));
if (edtDefinition.isSetApplicabilityCheck() && edtDefinition.getApplicabilityCheck()) {
switch(edtResult.getResult()) {
case FALSE:
edtResult.setResult(ResultEnumeration.NOT_APPLICABLE);
break;
}
}
operator.addResult(edtResult.getResult());
resultObject = edtResult;
} else {
throw new OvalException(JOVALMsg.getMessage(JOVALMsg.ERROR_BAD_COMPONENT, child.getClass().getName()));
}
criteriaResult.getCriteriaOrCriterionOrExtendDefinition().add(resultObject);
}
ResultEnumeration result = operator.getResult(criteriaDefinition.getOperator());
if (criteriaDefinition.isSetApplicabilityCheck() && criteriaDefinition.getApplicabilityCheck()) {
switch(result) {
case FALSE:
result = ResultEnumeration.NOT_APPLICABLE;
break;
}
}
criteriaResult.setResult(result);
return criteriaResult;
}
private scap.oval.results.CriterionType evaluateCriterion(CriterionType criterionDefinition)
throws NoSuchElementException, OvalException {
String testId = criterionDefinition.getTestRef();
TestType testResult = results.getTest(testId);
if (testResult == null) {
scap.oval.definitions.core.TestType testDefinition = definitions.getTest(testId).getValue();
testResult = Factories.results.createTestType();
testResult.setTestId(testDefinition.getId());
testResult.setCheck(testDefinition.getCheck());
testResult.setCheckExistence(testDefinition.getCheckExistence());
testResult.setStateOperator(testDefinition.getStateOperator());
if (evalEnabled) {
if (testDefinition instanceof UnknownTest) {
testResult.setResult(ResultEnumeration.UNKNOWN);
} else {
evaluateTest(testResult);
}
} else {
testResult.setResult(ResultEnumeration.NOT_EVALUATED);
}
results.storeTestResult(testResult);
}
scap.oval.results.CriterionType criterionResult = Factories.results.createCriterionType();
criterionResult.setTestRef(testId);
criterionResult.setNegate(criterionDefinition.getNegate());
OperatorData od = new OperatorData(criterionDefinition.getNegate());
od.addResult(testResult.getResult());
criterionResult.setResult(od.getResult(OperatorEnumeration.AND));
if (criterionDefinition.isSetApplicabilityCheck() && criterionDefinition.getApplicabilityCheck()) {
switch(criterionResult.getResult()) {
case FALSE:
criterionResult.setResult(ResultEnumeration.NOT_APPLICABLE);
break;
}
}
return criterionResult;
}
private void evaluateTest(TestType testResult) throws NoSuchElementException, OvalException {
String testId = testResult.getTestId();
logger.debug(JOVALMsg.STATUS_TEST, testId);
scap.oval.definitions.core.TestType testDefinition = definitions.getTest(testId).getValue();
String objectId = getObjectRef(testDefinition);
List<String> stateIds = getStateRef(testDefinition);
//
// Create all the structures we'll need to store information about the evaluation of the test.
//
RequestContext rc = new RequestContext(definitions.getObject(objectId).getValue());
ExistenceData existence = new ExistenceData();
CheckData check = new CheckData();
switch(sc.getObjectFlag(objectId)) {
//
// If the object is flagged as incomplete, then at least one item will not have been checked against the
// state. So, we record the fact that we don't know how it would evaluate against the state.
//
case INCOMPLETE:
check.addResult(ResultEnumeration.UNKNOWN);
// fall-thru
//
// Note: If the object is flagged as complete but there are no items, existenceResult will remain at its
// default value of DOES_NOT_EXIST (which is, of course, exactly what we want to happen).
//
case COMPLETE:
for (JAXBElement<? extends ItemType> elt : sc.getItemsByObjectId(objectId)) {
ItemType item = elt.getValue();
existence.addStatus(item.getStatus());
TestedItemType testedItem = Factories.results.createTestedItemType();
testedItem.setItemId(item.getId());
testedItem.setResult(ResultEnumeration.NOT_EVALUATED);
//
// Note: items with a status of DOES_NOT_EXIST have no impact on the result.
//
switch(item.getStatus()) {
case EXISTS:
if (stateIds.size() > 0) {
OperatorData result = new OperatorData(false);
for (String stateId : stateIds) {
StateType state = definitions.getState(stateId).getValue();
try {
result.addResult(compare(state, item, rc));
} catch (TestException e) {
logger.warn(JOVALMsg.ERROR_TESTEXCEPTION, testId, e.getMessage());
logger.debug(JOVALMsg.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
MessageType message = Factories.common.createMessageType();
message.setLevel(MessageLevelEnumeration.ERROR);
message.setValue(e.getMessage());
testedItem.getMessage().add(message);
result.addResult(ResultEnumeration.ERROR);
}
}
testedItem.setResult(result.getResult(testDefinition.getStateOperator()));
check.addResult(testedItem.getResult());
}
break;
case ERROR:
check.addResult(ResultEnumeration.ERROR);
break;
//
// This should not be possible.
//
case NOT_COLLECTED:
String msg = JOVALMsg.getMessage(JOVALMsg.ERROR_OVAL_STATES, objectId, "COMPLETE", "NOT_COLLECTED");
throw new OvalException(msg);
}
testResult.getTestedItem().add(testedItem);
}
break;
case DOES_NOT_EXIST:
existence.addStatus(StatusEnumeration.DOES_NOT_EXIST);
break;
case ERROR:
existence.addStatus(StatusEnumeration.ERROR);
break;
case NOT_APPLICABLE:
// No impact on existence check
break;
case NOT_COLLECTED:
existence.addStatus(StatusEnumeration.NOT_COLLECTED);
break;
}
//
// Add all the tested variables that were resolved for the object and state (stored in the RequestContext).
//
for (VariableValueType var : rc.getVars()) {
TestedVariableType testedVariable = Factories.results.createTestedVariableType();
testedVariable.setVariableId(var.getVariableId());
testedVariable.setValue(var.getValue());
testResult.getTestedVariable().add(testedVariable);
}
//
// DAS: Note that the NONE_EXIST check is deprecated as of 5.3, and will be eliminated in 6.0.
// Per D. Haynes, in this case, any state and/or check should be ignored.
//
if (testDefinition.getCheck() == CheckEnumeration.NONE_EXIST) {
logger.warn(JOVALMsg.STATUS_CHECK_NONE_EXIST, testDefinition.getCheckExistence(), testId);
testResult.setResult(existence.getResult(ExistenceEnumeration.NONE_EXIST));
//
// If the object is not applicable, then the result is NOT_APPLICABLE.
//
} else if (sc.getObjectFlag(objectId) == FlagEnumeration.NOT_APPLICABLE) {
testResult.setResult(ResultEnumeration.NOT_APPLICABLE);
//
// If there are no items, or there is no state, then the result of the test is simply the result of the existence
// check.
//
} else if (sc.getItemsByObjectId(objectId).size() == 0 || stateIds.size() == 0) {
testResult.setResult(existence.getResult(testDefinition.getCheckExistence()));
//
// If there are items matching the object, then check the existence check, then (if successful) the check.
//
} else {
ResultEnumeration existenceResult = existence.getResult(testDefinition.getCheckExistence());
switch(existenceResult) {
case TRUE:
testResult.setResult(check.getResult(testDefinition.getCheck()));
break;
default:
testResult.setResult(existenceResult);
break;
}
}
}
/**
* If getObject() were a method of TestType (instead of only some of its subclasses), this is what it would return.
*/
private String getObjectRef(scap.oval.definitions.core.TestType test) throws OvalException {
try {
Method getObject = test.getClass().getMethod("getObject");
ObjectRefType objectRef = (ObjectRefType)getObject.invoke(test);
if (objectRef != null) {
String ref = objectRef.getObjectRef();
if (ref != null) {
return objectRef.getObjectRef();
}
}
} catch (NoSuchMethodException e) {
logger.warn(JOVALMsg.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
} catch (IllegalAccessException e) {
logger.warn(JOVALMsg.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
} catch (InvocationTargetException e) {
logger.warn(JOVALMsg.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
}
throw new OvalException(JOVALMsg.getMessage(JOVALMsg.ERROR_TEST_NOOBJREF, test.getId()));
}
/**
* If getState() were a method of TestType (instead of only some of its subclasses), this is what it would return.
*/
private List<String> getStateRef(scap.oval.definitions.core.TestType test) {
List<String> refs = new ArrayList<String>();
try {
Method getObject = test.getClass().getMethod("getState");
Object o = getObject.invoke(test);
if (o instanceof List && ((List)o).size() > 0) {
for (Object stateRefObj : (List)o) {
refs.add(((StateRefType)stateRefObj).getStateRef());
}
} else if (o instanceof StateRefType) {
refs.add(((StateRefType)o).getStateRef());
}
} catch (NoSuchMethodException e) {
logger.warn(JOVALMsg.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
} catch (IllegalAccessException e) {
logger.warn(JOVALMsg.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
} catch (InvocationTargetException e) {
logger.warn(JOVALMsg.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
}
return refs;
}
/**
* Determine whether or not the specified item matches the specified object.
*/
private ResultEnumeration compare(ObjectType object, ItemType item, RequestContext rc) throws OvalException, TestException {
if (!OBJECT_ITEM_MAP.get(object.getClass()).equals(item.getClass())) {
return ResultEnumeration.FALSE;
}
try {
OperatorData result = new OperatorData(false);
int facets = 0;
for (Method method : getMethods(object.getClass()).values()) {
String methodName = method.getName();
if (methodName.startsWith("get") && !OBJECT_METHOD_NAMES.contains(methodName)) {
facets++;
Object objectEntityObj = method.invoke(object);
if (objectEntityObj instanceof JAXBElement) {
if (XSITools.isNil((JAXBElement)objectEntityObj)) {
Object itemEntityObj = getMethod(item.getClass(), methodName).invoke(item);
if (itemEntityObj == null) {
result.addResult(ResultEnumeration.TRUE);
} else if (itemEntityObj instanceof JAXBElement) {
if (XSITools.isNil((JAXBElement)itemEntityObj)) {
result.addResult(ResultEnumeration.TRUE);
} else {
result.addResult(ResultEnumeration.FALSE);
}
} else {
result.addResult(ResultEnumeration.FALSE);
}
continue; // move on
} else {
objectEntityObj = ((JAXBElement)objectEntityObj).getValue(); // keep processing
}
}
if (objectEntityObj == null) {
// continue
} else if (objectEntityObj instanceof EntitySimpleBaseType) {
EntitySimpleBaseType objectEntity = (EntitySimpleBaseType)objectEntityObj;
Object itemEntityObj = getMethod(item.getClass(), methodName).invoke(item);
if (itemEntityObj instanceof JAXBElement) {
itemEntityObj = ((JAXBElement)itemEntityObj).getValue();
}
if (itemEntityObj instanceof EntityItemSimpleBaseType || itemEntityObj == null) {
result.addResult(compare(objectEntity, (EntityItemSimpleBaseType)itemEntityObj, rc));
} else {
String message = JOVALMsg.getMessage(JOVALMsg.ERROR_UNSUPPORTED_ENTITY,
itemEntityObj.getClass().getName(), item.getId());
throw new OvalException(message);
}
} else if (objectEntityObj instanceof EntityObjectRecordType) {
EntityObjectRecordType objectEntity = (EntityObjectRecordType)objectEntityObj;
Object itemEntityObj = getMethod(item.getClass(), methodName).invoke(item);
if (itemEntityObj instanceof JAXBElement) {
itemEntityObj = ((JAXBElement)itemEntityObj).getValue();
}
if (itemEntityObj instanceof EntityItemRecordType) {
result.addResult(compare(objectEntity, (EntityItemRecordType)itemEntityObj, rc));
} else {
String message = JOVALMsg.getMessage(JOVALMsg.ERROR_UNSUPPORTED_ENTITY,
itemEntityObj.getClass().getName(), item.getId());
throw new OvalException(message);
}
} else {
String message = JOVALMsg.getMessage(JOVALMsg.ERROR_UNSUPPORTED_ENTITY,
objectEntityObj.getClass().getName(), object.getId());
throw new OvalException(message);
}
}
}
if (facets > 0) {
return result.getResult(OperatorEnumeration.AND);
} else {
// Singleton object type
return ResultEnumeration.TRUE;
}
} catch (NoSuchMethodException e) {
logger.warn(JOVALMsg.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
throw new OvalException(JOVALMsg.getMessage(JOVALMsg.ERROR_REFLECTION, e.getMessage(), object.getId()));
} catch (IllegalAccessException e) {
logger.warn(JOVALMsg.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
throw new OvalException(JOVALMsg.getMessage(JOVALMsg.ERROR_REFLECTION, e.getMessage(), object.getId()));
} catch (InvocationTargetException e) {
logger.warn(JOVALMsg.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
throw new OvalException(JOVALMsg.getMessage(JOVALMsg.ERROR_REFLECTION, e.getMessage(), object.getId()));
}
}
/**
* Determine whether or not the specified item matches the specified state.
*/
private ResultEnumeration compare(StateType state, ItemType item, RequestContext rc) throws OvalException, TestException {
try {
OperatorData result = new OperatorData(false);
for (Method method : getMethods(state.getClass()).values()) {
String methodName = method.getName();
if (methodName.startsWith("get") && !STATE_METHOD_NAMES.contains(methodName)) {
Object stateEntityObj = method.invoke(state);
if (stateEntityObj == null) {
// continue
} else if (stateEntityObj instanceof EntityStateSimpleBaseType) {
EntityStateSimpleBaseType stateEntity = (EntityStateSimpleBaseType)stateEntityObj;
Object itemEntityObj = getMethod(item.getClass(), methodName).invoke(item);
if (itemEntityObj instanceof JAXBElement) {
itemEntityObj = ((JAXBElement)itemEntityObj).getValue();
}
if (itemEntityObj instanceof EntityItemSimpleBaseType || itemEntityObj == null) {
result.addResult(compare(stateEntity, (EntityItemSimpleBaseType)itemEntityObj, rc));
} else if (itemEntityObj instanceof Collection) {
CheckData cd = new CheckData();
Collection entityObjs = (Collection)itemEntityObj;
if (entityObjs.size() == 0) {
cd.addResult(ResultEnumeration.FALSE);
} else {
for (Object entityObj : entityObjs) {
EntityItemSimpleBaseType itemEntity = (EntityItemSimpleBaseType)entityObj;
cd.addResult(compare(stateEntity, itemEntity, rc));
}
}
result.addResult(cd.getResult(stateEntity.getEntityCheck()));
} else {
String message = JOVALMsg.getMessage(JOVALMsg.ERROR_UNSUPPORTED_ENTITY,
itemEntityObj.getClass().getName(), item.getId());
throw new OvalException(message);
}
} else if (stateEntityObj instanceof EntityStateRecordType) {
EntityStateRecordType stateEntity = (EntityStateRecordType)stateEntityObj;
Object itemEntityObj = getMethod(item.getClass(), methodName).invoke(item);
if (itemEntityObj instanceof JAXBElement) {
itemEntityObj = ((JAXBElement)itemEntityObj).getValue();
}
if (itemEntityObj instanceof EntityItemRecordType) {
result.addResult(compare(stateEntity, (EntityItemRecordType)itemEntityObj, rc));
} else if (itemEntityObj instanceof Collection) {
CheckData cd = new CheckData();
Collection entityObjs = (Collection)itemEntityObj;
if (entityObjs.size() == 0) {
cd.addResult(ResultEnumeration.FALSE);
} else {
for (Object entityObj : entityObjs) {
if (entityObj instanceof EntityItemRecordType) {
cd.addResult(compare(stateEntity, (EntityItemRecordType)entityObj, rc));
} else {
String msg = JOVALMsg.getMessage(JOVALMsg.ERROR_UNSUPPORTED_ENTITY,
entityObj.getClass().getName(), item.getId());
throw new OvalException(msg);
}
}
}
result.addResult(cd.getResult(stateEntity.getEntityCheck()));
} else {
String message = JOVALMsg.getMessage(JOVALMsg.ERROR_UNSUPPORTED_ENTITY,
itemEntityObj.getClass().getName(), item.getId());
throw new OvalException(message);
}
} else {
String message = JOVALMsg.getMessage(JOVALMsg.ERROR_UNSUPPORTED_ENTITY,
stateEntityObj.getClass().getName(), state.getId());
throw new OvalException(message);
}
}
}
return result.getResult(state.getOperator());
} catch (NoSuchMethodException e) {
logger.warn(JOVALMsg.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
throw new OvalException(JOVALMsg.getMessage(JOVALMsg.ERROR_REFLECTION, e.getMessage(), state.getId()));
} catch (IllegalAccessException e) {
logger.warn(JOVALMsg.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
throw new OvalException(JOVALMsg.getMessage(JOVALMsg.ERROR_REFLECTION, e.getMessage(), state.getId()));
} catch (InvocationTargetException e) {
logger.warn(JOVALMsg.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
throw new OvalException(JOVALMsg.getMessage(JOVALMsg.ERROR_REFLECTION, e.getMessage(), state.getId()));
}
}
/**
* Compare an object record and item record. All the object record's fields must match for a TRUE result (i.e.,
* the item may have additional fields).
*/
private ResultEnumeration compare(EntityObjectRecordType objectRecord, EntityItemRecordType itemRecord, RequestContext rc)
throws TestException, OvalException {
Map<String, EntityObjectFieldType> objectFields = new HashMap<String, EntityObjectFieldType>();
for (EntityObjectFieldType objectField : objectRecord.getField()) {
objectFields.put(objectField.getName(), objectField);
}
Map<String, Collection<EntityItemFieldType>> itemFields = new HashMap<String, Collection<EntityItemFieldType>>();
for (EntityItemFieldType itemField : itemRecord.getField()) {
String name = itemField.getName();
if (!itemFields.containsKey(name)) {
itemFields.put(name, new ArrayList<EntityItemFieldType>());
}
itemFields.get(name).add(itemField);
}
OperatorData od = new OperatorData(false);
for (Map.Entry<String, EntityObjectFieldType> entry : objectFields.entrySet()) {
String name = entry.getKey();
EntityObjectFieldType objectField = entry.getValue();
if (itemFields.containsKey(name)) {
EntitySimpleBaseType object = new ObjectFieldBridge(objectField);
CheckData cd = new CheckData();
for (EntityItemFieldType itemField : itemFields.get(name)) {
cd.addResult(compare(object, new ItemFieldBridge(itemField), rc));
}
od.addResult(cd.getResult(objectField.getEntityCheck()));
} else {
od.addResult(ResultEnumeration.FALSE);
}
}
return od.getResult(OperatorEnumeration.AND);
}
/**
* Compare a state record and item record. All the state record's fields must match for a TRUE result (i.e.,
* the item may have additional fields).
*/
private ResultEnumeration compare(EntityStateRecordType stateRecord, EntityItemRecordType itemRecord, RequestContext rc)
throws TestException, OvalException {
Map<String, EntityStateFieldType> stateFields = new HashMap<String, EntityStateFieldType>();
for (EntityStateFieldType stateField : stateRecord.getField()) {
stateFields.put(stateField.getName(), stateField);
}
Map<String, Collection<EntityItemFieldType>> itemFields = new HashMap<String, Collection<EntityItemFieldType>>();
for (EntityItemFieldType itemField : itemRecord.getField()) {
String name = itemField.getName();
if (!itemFields.containsKey(name)) {
itemFields.put(name, new ArrayList<EntityItemFieldType>());
}
itemFields.get(name).add(itemField);
}
OperatorData od = new OperatorData(false);
for (Map.Entry<String, EntityStateFieldType> entry : stateFields.entrySet()) {
String name = entry.getKey();
EntityStateFieldType stateField = entry.getValue();
if (itemFields.containsKey(name)) {
EntityStateSimpleBaseType state = new StateFieldBridge(stateField);
CheckData cd = new CheckData();
for (EntityItemFieldType itemField : itemFields.get(name)) {
cd.addResult(compare(state, new ItemFieldBridge(itemField), rc));
}
od.addResult(cd.getResult(stateField.getEntityCheck()));
} else {
od.addResult(ResultEnumeration.FALSE);
}
}
return od.getResult(OperatorEnumeration.AND);
}
/**
* Compare a state or object SimpleBaseType to an item SimpleBaseType. If the item is null, this method returns false.
*/
private ResultEnumeration compare(EntitySimpleBaseType base, EntityItemSimpleBaseType item, RequestContext rc)
throws TestException, OvalException {
if (item == null) {
// Absence of the item translates to UNKNOWN per D. Haynes
return ResultEnumeration.UNKNOWN;
} else {
switch(item.getStatus()) {
case NOT_COLLECTED:
return ResultEnumeration.NOT_EVALUATED;
case ERROR:
return ResultEnumeration.ERROR;
case DOES_NOT_EXIST:
return ResultEnumeration.FALSE;
}
}
//
// Handle the variable_ref case
//
if (base.isSetVarRef()) {
CheckData cd = new CheckData();
EntitySimpleBaseType varInstance = Factories.definitions.core.createEntityObjectAnySimpleType();
varInstance.setDatatype(base.getDatatype());
varInstance.setOperation(base.getOperation());
varInstance.setMask(base.getMask());
String ref = base.getVarRef();
try {
Collection<IType> values = resolveVariable(ref, rc);
if (values.size() == 0) {
//
// According to the specification, the test must result in an error condition in this case. See:
// http://oval.mitre.org/language/version5.10.1/ovaldefinition/documentation/oval-definitions-schema.html#EntityAttributeGroup
//
String reason = JOVALMsg.getMessage(JOVALMsg.ERROR_VARIABLE_NO_VALUES);
throw new TestException(JOVALMsg.getMessage(JOVALMsg.ERROR_RESOLVE_VAR, ref, reason));
} else {
for (IType value : values) {
value = value.cast(TypeFactory.getSimpleDatatype(base.getDatatype()));
varInstance.setValue(value.getString());
cd.addResult(testImpl(varInstance, item));
}
}
} catch (TypeConversionException e) {
String reason = JOVALMsg.getMessage(JOVALMsg.ERROR_TYPE_CONVERSION, e.getMessage());
throw new TestException(JOVALMsg.getMessage(JOVALMsg.ERROR_RESOLVE_VAR, ref, reason));
} catch (NoSuchElementException e) {
String reason = JOVALMsg.getMessage(JOVALMsg.ERROR_VARIABLE_MISSING);
throw new TestException(JOVALMsg.getMessage(JOVALMsg.ERROR_RESOLVE_VAR, ref, reason));
} catch (ResolveException e) {
throw new TestException(JOVALMsg.getMessage(JOVALMsg.ERROR_RESOLVE_VAR, ref, e.getMessage()));
}
return cd.getResult(base.getVarCheck());
} else {
return testImpl(base, item);
}
}
/**
* Perform the the OVAL test by comparing the state/object (AKA base) and item.
*/
private ResultEnumeration testImpl(EntitySimpleBaseType base, EntityItemSimpleBaseType item) throws TestException {
//
// This is a good place to check if the engine is being destroyed
//
if (abort) {
throw new AbortException(JOVALMsg.getMessage(JOVALMsg.ERROR_ENGINE_ABORT));
}
if (!item.isSetValue() || !base.isSetValue()) {
String msg = JOVALMsg.getMessage(JOVALMsg.ERROR_TEST_INCOMPARABLE, item.getValue(), base.getValue());
throw new TestException(msg);
}
//
// Let the base dictate the datatype
//
IType baseValue=null, itemValue=null;
try {
baseValue = TypeFactory.createType(base);
itemValue = TypeFactory.createType(item).cast(baseValue.getType());
} catch (IllegalArgumentException e) {
throw new TestException(e);
} catch (TypeConversionException e) {
throw new TestException(e);
}
//
// Validate the operation by datatype, then execute it. See section 5.3.6.3.1 of the specification:
// http://oval.mitre.org/language/version5.10.1/OVAL_Language_Specification_01-20-2012.pdf
//
OperationEnumeration op = base.getOperation();
switch(baseValue.getType()) {
case BINARY:
case BOOLEAN:
case RECORD:
return trivialComparison(baseValue, itemValue, op);
case EVR_STRING:
case FLOAT:
case FILESET_REVISION:
case IOS_VERSION:
case VERSION:
return basicComparison(baseValue, itemValue, op);
case INT: {
int sInt = ((IntType)baseValue).getData().intValue();
int iInt = ((IntType)itemValue).getData().intValue();
switch(op) {
case BITWISE_AND:
if (sInt == (iInt & sInt)) {
return ResultEnumeration.TRUE;
} else {
return ResultEnumeration.FALSE;
}
case BITWISE_OR:
if (sInt == (iInt | sInt)) {
return ResultEnumeration.TRUE;
} else {
return ResultEnumeration.FALSE;
}
default:
return basicComparison(baseValue, itemValue, op);
}
}
case IPV_4_ADDRESS: {
Ip4AddressType sIp = (Ip4AddressType)baseValue;
Ip4AddressType iIp = (Ip4AddressType)itemValue;
switch(op) {
case SUBSET_OF:
if (iIp.contains(sIp)) {
return ResultEnumeration.TRUE;
} else {
return ResultEnumeration.FALSE;
}
case SUPERSET_OF:
if (sIp.contains(iIp)) {
return ResultEnumeration.TRUE;
} else {
return ResultEnumeration.FALSE;
}
default:
return basicComparison(baseValue, itemValue, op);
}
}
case IPV_6_ADDRESS: {
Ip6AddressType sIp = (Ip6AddressType)baseValue;
Ip6AddressType iIp = (Ip6AddressType)itemValue;
switch(op) {
case SUBSET_OF:
if (iIp.contains(sIp)) {
return ResultEnumeration.TRUE;
} else {
return ResultEnumeration.FALSE;
}
case SUPERSET_OF:
if (iIp.contains(sIp)) {
return ResultEnumeration.FALSE;
} else {
return ResultEnumeration.TRUE;
}
default:
return basicComparison(baseValue, itemValue, op);
}
}
case STRING: {
String sStr = ((StringType)baseValue).getData();
String iStr = ((StringType)itemValue).getData();
switch(op) {
case CASE_INSENSITIVE_EQUALS:
if (iStr.equalsIgnoreCase(sStr)) {
return ResultEnumeration.TRUE;
} else {
return ResultEnumeration.FALSE;
}
case CASE_INSENSITIVE_NOT_EQUAL:
if (iStr.equalsIgnoreCase(sStr)) {
return ResultEnumeration.FALSE;
} else {
return ResultEnumeration.TRUE;
}
case PATTERN_MATCH:
try {
if (StringTools.pattern(sStr).matcher(iStr).find()) {
return ResultEnumeration.TRUE;
} else {
return ResultEnumeration.FALSE;
}
} catch (PatternSyntaxException e) {
throw new TestException(e);
}
default:
return trivialComparison(baseValue, itemValue, op);
}
}
}
throw new TestException(JOVALMsg.getMessage(JOVALMsg.ERROR_UNSUPPORTED_OPERATION, op));
}
/**
* =, !=, or throws a TestException
*/
private ResultEnumeration trivialComparison(IType base, IType item, OperationEnumeration op) throws TestException {
switch(op) {
case EQUALS:
if (item.equals(base)) {
return ResultEnumeration.TRUE;
} else {
return ResultEnumeration.FALSE;
}
case NOT_EQUAL:
if (item.equals(base)) {
return ResultEnumeration.FALSE;
} else {
return ResultEnumeration.TRUE;
}
}
throw new TestException(JOVALMsg.getMessage(JOVALMsg.ERROR_UNSUPPORTED_OPERATION, op));
}
/**
* =, !=, <, <=, >, >=, or throws a TestException
*/
private ResultEnumeration basicComparison(IType base, IType item, OperationEnumeration op) throws TestException {
switch(op) {
case GREATER_THAN:
if (item.compareTo(base) > 0) {
return ResultEnumeration.TRUE;
} else {
return ResultEnumeration.FALSE;
}
case GREATER_THAN_OR_EQUAL:
if (item.compareTo(base) >= 0) {
return ResultEnumeration.TRUE;
} else {
return ResultEnumeration.FALSE;
}
case LESS_THAN:
if (item.compareTo(base) < 0) {
return ResultEnumeration.TRUE;
} else {
return ResultEnumeration.FALSE;
}
case LESS_THAN_OR_EQUAL:
if (item.compareTo(base) <= 0) {
return ResultEnumeration.TRUE;
} else {
return ResultEnumeration.FALSE;
}
default:
return trivialComparison(base, item, op);
}
}
/**
* Return the value of the Variable with the specified ID, and also add any chained variables to the provided list.
*/
private Collection<IType> resolveVariable(String variableId, RequestContext rc)
throws NoSuchElementException, ResolveException, OvalException {
Collection<IType> result = variableMap.get(variableId);
if (result == null) {
logger.trace(JOVALMsg.STATUS_VARIABLE_CREATE, variableId);
try {
result = resolveComponent(definitions.getVariable(variableId), rc);
} catch (IllegalArgumentException e) {
throw new ResolveException(e);
} catch (UnsupportedOperationException e) {
throw new ResolveException(e);
}
variableMap.put(variableId, result);
} else {
for (IType value : result) {
VariableValueType variableValueType = Factories.sc.core.createVariableValueType();
variableValueType.setVariableId(variableId);
variableValueType.setValue(value.getString());
rc.addVar(variableValueType);
}
logger.trace(JOVALMsg.STATUS_VARIABLE_RECYCLE, variableId);
}
return result;
}
/**
* Recursively resolve a component. Since there is no base class for component types, this method accepts an Object.
*
* @see http://oval.mitre.org/language/version5.10/ovaldefinition/documentation/oval-definitions-schema.html#FunctionGroup
*/
private Collection<IType> resolveComponent(Object object, RequestContext rc) throws NoSuchElementException,
UnsupportedOperationException, IllegalArgumentException, ResolveException, OvalException {
//
// This is a good place to check if the engine is being destroyed
//
if (abort) {
throw new AbortException(JOVALMsg.getMessage(JOVALMsg.ERROR_ENGINE_ABORT));
}
//
// Why do variables point to variables? Because sometimes they are nested.
//
if (object instanceof LocalVariable) {
LocalVariable localVariable = (LocalVariable)object;
Collection<IType> values = resolveComponent(getComponent(localVariable), rc);
if (values.size() == 0) {
VariableValueType variableValueType = Factories.sc.core.createVariableValueType();
variableValueType.setVariableId(localVariable.getId());
rc.addVar(variableValueType);
} else {
Collection<IType> convertedValues = new ArrayList<IType>();
for (IType value : values) {
try {
//
// Convert values from the originating type to the variable's defined datatype
//
convertedValues.add(value.cast(localVariable.getDatatype()));
VariableValueType variableValueType = Factories.sc.core.createVariableValueType();
variableValueType.setVariableId(localVariable.getId());
variableValueType.setValue(value.getString());
rc.addVar(variableValueType);
} catch (TypeConversionException e) {
MessageType message = Factories.common.createMessageType();
message.setLevel(MessageLevelEnumeration.ERROR);
message.setValue(JOVALMsg.getMessage(JOVALMsg.ERROR_TYPE_CONVERSION, e.getMessage()));
rc.addMessage(message);
}
}
values = convertedValues;
}
return values;
//
// Add an externally-defined variable.
//
} else if (object instanceof ExternalVariable) {
ExternalVariable externalVariable = (ExternalVariable)object;
String id = externalVariable.getId();
if (externalVariables == null) {
throw new ResolveException(JOVALMsg.getMessage(JOVALMsg.ERROR_EXTERNAL_VARIABLE_SOURCE, id));
} else {
Collection<IType> values = new ArrayList<IType>();
try {
for (IType value : externalVariables.getValue(id)) {
try {
values.add(value.cast(externalVariable.getDatatype()));
} catch (TypeConversionException e) {
MessageType message = Factories.common.createMessageType();
message.setLevel(MessageLevelEnumeration.ERROR);
message.setValue(JOVALMsg.getMessage(JOVALMsg.ERROR_TYPE_CONVERSION, e.getMessage()));
rc.addMessage(message);
}
}
} catch (NoSuchElementException e) {
- MessageType message = Factories.common.createMessageType();
- message.setLevel(MessageLevelEnumeration.ERROR);
- message.setValue(JOVALMsg.getMessage(JOVALMsg.ERROR_EXTERNAL_VARIABLE, e.getMessage()));
- rc.addMessage(message);
+ throw new ResolveException(JOVALMsg.getMessage(JOVALMsg.ERROR_EXTERNAL_VARIABLE, e.getMessage()));
}
if (values.size() == 0) {
VariableValueType variableValueType = Factories.sc.core.createVariableValueType();
variableValueType.setVariableId(externalVariable.getId());
rc.addVar(variableValueType);
} else {
for (IType value : values) {
VariableValueType variableValueType = Factories.sc.core.createVariableValueType();
variableValueType.setVariableId(externalVariable.getId());
variableValueType.setValue(value.getString());
rc.addVar(variableValueType);
}
}
return values;
}
//
// Add a constant variable.
//
} else if (object instanceof ConstantVariable) {
ConstantVariable constantVariable = (ConstantVariable)object;
String id = constantVariable.getId();
Collection<IType> values = new ArrayList<IType>();
List<ValueType> valueTypes = constantVariable.getValue();
if (valueTypes.size() == 0) {
VariableValueType variableValueType = Factories.sc.core.createVariableValueType();
variableValueType.setVariableId(constantVariable.getId());
rc.addVar(variableValueType);
} else {
for (ValueType value : valueTypes) {
VariableValueType variableValueType = Factories.sc.core.createVariableValueType();
variableValueType.setVariableId(id);
String s = (String)value.getValue();
variableValueType.setValue(s);
rc.addVar(variableValueType);
values.add(TypeFactory.createType(constantVariable.getDatatype(), s));
}
}
return values;
//
// Add a static (literal) value.
//
} else if (object instanceof LiteralComponentType) {
LiteralComponentType literal = (LiteralComponentType)object;
Collection<IType> values = new ArrayList<IType>();
values.add(TypeFactory.createType(literal.getDatatype(), (String)literal.getValue()));
return values;
//
// Retrieve from an ItemType (which possibly has to be fetched from an adapter)
//
} else if (object instanceof ObjectComponentType) {
ObjectComponentType oc = (ObjectComponentType)object;
String objectId = oc.getObjectRef();
Collection<ItemType> items = new ArrayList<ItemType>();
try {
//
// First, we scan the SystemCharacteristics for items related to the object.
//
for (JAXBElement<? extends ItemType> elt : sc.getItemsByObjectId(objectId)) {
items.add(elt.getValue());
}
} catch (NoSuchElementException e) {
//
// If the object has not yet been scanned, then it must be retrieved live from the adapter
//
rc.pushObject(definitions.getObject(objectId).getValue());
items = scanObject(rc);
rc.popObject();
}
return extractItemData(objectId, oc, items);
//
// Resolve and return.
//
} else if (object instanceof VariableComponentType) {
return resolveComponent(definitions.getVariable(((VariableComponentType)object).getVarRef()), rc);
//
// Resolve and concatenate child components.
//
} else if (object instanceof ConcatFunctionType) {
Collection<IType> values = new ArrayList<IType>();
ConcatFunctionType concat = (ConcatFunctionType)object;
for (Object child : concat.getObjectComponentOrVariableComponentOrLiteralComponent()) {
Collection<IType> next = resolveComponent(child, rc);
if (next.size() == 0) {
@SuppressWarnings("unchecked")
Collection<IType> empty = (Collection<IType>)Collections.EMPTY_LIST;
return empty;
} else if (values.size() == 0) {
values.addAll(next);
} else {
Collection<IType> newValues = new ArrayList<IType>();
for (IType base : values) {
for (IType val : next) {
newValues.add(TypeFactory.createType(IType.Type.STRING, base.getString() + val.getString()));
}
}
values = newValues;
}
}
return values;
//
// Escape anything that could be pattern-matched.
//
} else if (object instanceof EscapeRegexFunctionType) {
Collection<IType> values = new ArrayList<IType>();
for (IType value : resolveComponent(getComponent((EscapeRegexFunctionType)object), rc)) {
values.add(TypeFactory.createType(IType.Type.STRING, StringTools.escapeRegex(value.getString())));
}
return values;
//
// Process a Split, which contains a component and a delimiter with which to split it up.
//
} else if (object instanceof SplitFunctionType) {
SplitFunctionType split = (SplitFunctionType)object;
Collection<IType> values = new ArrayList<IType>();
for (IType value : resolveComponent(getComponent(split), rc)) {
for (String s : StringTools.toList(StringTools.tokenize(value.getString(), split.getDelimiter(), false))) {
values.add(TypeFactory.createType(IType.Type.STRING, s));
}
}
return values;
//
// Process a RegexCapture, which returns the regions of a component resolved as a String that match the first
// subexpression in the given pattern.
//
} else if (object instanceof RegexCaptureFunctionType) {
RegexCaptureFunctionType regexCapture = (RegexCaptureFunctionType)object;
Pattern p = StringTools.pattern(regexCapture.getPattern());
Collection<IType> values = new ArrayList<IType>();
for (IType value : resolveComponent(getComponent(regexCapture), rc)) {
Matcher m = p.matcher(value.getString());
if (m.groupCount() >= 1) {
if (m.find()) {
values.add(TypeFactory.createType(IType.Type.STRING, m.group(1)));
} else {
values.add(StringType.EMPTY);
}
} else {
values.add(StringType.EMPTY);
MessageType message = Factories.common.createMessageType();
message.setLevel(MessageLevelEnumeration.WARNING);
message.setValue(JOVALMsg.getMessage(JOVALMsg.WARNING_REGEX_GROUP, p.pattern()));
rc.addMessage(message);
}
}
return values;
//
// Process a Substring
//
} else if (object instanceof SubstringFunctionType) {
SubstringFunctionType st = (SubstringFunctionType)object;
int start = st.getSubstringStart();
start = Math.max(1, start); // a start index < 1 means start at 1
start--; // OVAL counter begins at 1 instead of 0
int len = st.getSubstringLength();
Collection<IType> values = new ArrayList<IType>();
for (IType value : resolveComponent(getComponent(st), rc)) {
String str = value.getString();
//
// If the substring_start attribute has value greater than the length of the original string
// an error should be reported.
//
if (start > str.length()) {
throw new ResolveException(JOVALMsg.getMessage(JOVALMsg.ERROR_SUBSTRING, str, new Integer(start)));
//
// A substring_length value greater than the actual length of the string, or a negative value,
// means to include all of the characters after the starting character.
//
} else if (len < 0 || str.length() <= (start+len)) {
values.add(TypeFactory.createType(IType.Type.STRING, str.substring(start)));
} else {
values.add(TypeFactory.createType(IType.Type.STRING, str.substring(start, start+len)));
}
}
return values;
//
// Process a Begin
//
} else if (object instanceof BeginFunctionType) {
BeginFunctionType bt = (BeginFunctionType)object;
String s = bt.getCharacter();
Collection<IType> values = new ArrayList<IType>();
for (IType value : resolveComponent(getComponent(bt), rc)) {
String str = value.getString();
if (str.startsWith(s)) {
values.add(value);
} else {
values.add(TypeFactory.createType(IType.Type.STRING, s + str));
}
}
return values;
//
// Process an End
//
} else if (object instanceof EndFunctionType) {
EndFunctionType et = (EndFunctionType)object;
String s = et.getCharacter();
Collection<IType> values = new ArrayList<IType>();
for (IType value : resolveComponent(getComponent(et), rc)) {
String str = value.getString();
if (str.endsWith(s)) {
values.add(value);
} else {
values.add(TypeFactory.createType(IType.Type.STRING, str + s));
}
}
return values;
//
// Process a TimeDifference
//
} else if (object instanceof TimeDifferenceFunctionType) {
TimeDifferenceFunctionType tt = (TimeDifferenceFunctionType)object;
Collection<IType> values = new ArrayList<IType>();
List<Object> children = tt.getObjectComponentOrVariableComponentOrLiteralComponent();
Collection<IType> ts1;
Collection<IType> ts2;
if (children.size() == 1) {
tt.setFormat1(DateTimeFormatEnumeration.SECONDS_SINCE_EPOCH);
ts1 = new ArrayList<IType>();
try {
String val = Long.toString(plugin.getSession().getTime() / 1000L);
ts1.add(TypeFactory.createType(IType.Type.INT, val));
} catch (Exception e) {
throw new ResolveException(e);
}
ts2 = resolveComponent(children.get(0), rc);
} else if (children.size() == 2) {
ts1 = resolveComponent(children.get(0), rc);
ts2 = resolveComponent(children.get(1), rc);
} else {
String msg = JOVALMsg.getMessage(JOVALMsg.ERROR_BAD_TIMEDIFFERENCE, Integer.toString(children.size()));
throw new ResolveException(msg);
}
for (IType time1 : ts1) {
try {
long tm1 = DateTime.getTime(time1.getString(), tt.getFormat1());
for (IType time2 : ts2) {
long tm2 = DateTime.getTime(time2.getString(), tt.getFormat2());
long diff = (tm1 - tm2)/1000L; // convert diff to seconds
values.add(TypeFactory.createType(IType.Type.INT, Long.toString(diff)));
}
} catch (IllegalArgumentException e) {
throw new ResolveException(e.getMessage());
} catch (ParseException e) {
throw new ResolveException(e.getMessage());
}
}
return values;
//
// Process Arithmetic
//
} else if (object instanceof ArithmeticFunctionType) {
ArithmeticFunctionType at = (ArithmeticFunctionType)object;
Stack<Collection<IType>> rows = new Stack<Collection<IType>>();
ArithmeticEnumeration op = at.getArithmeticOperation();
for (Object child : at.getObjectComponentOrVariableComponentOrLiteralComponent()) {
Collection<IType> row = new ArrayList<IType>();
for (IType cell : resolveComponent(child, rc)) {
row.add(cell);
}
rows.add(row);
}
return computeProduct(op, rows);
//
// Process Count
//
} else if (object instanceof CountFunctionType) {
CountFunctionType ct = (CountFunctionType)object;
Collection<IType> children = new ArrayList<IType>();
for (Object child : ct.getObjectComponentOrVariableComponentOrLiteralComponent()) {
children.addAll(resolveComponent(child, rc));
}
Collection<IType> values = new ArrayList<IType>();
values.add(TypeFactory.createType(IType.Type.INT, Integer.toString(children.size())));
return values;
//
// Process Unique
//
} else if (object instanceof UniqueFunctionType) {
UniqueFunctionType ut = (UniqueFunctionType)object;
HashSet<IType> values = new HashSet<IType>();
for (Object child : ut.getObjectComponentOrVariableComponentOrLiteralComponent()) {
values.addAll(resolveComponent(child, rc));
}
return values;
} else {
throw new OvalException(JOVALMsg.getMessage(JOVALMsg.ERROR_UNSUPPORTED_COMPONENT, object.getClass().getName()));
}
}
/**
* Perform the Arithmetic operation on permutations of the Stack, and return the resulting permutations.
*/
private List<IType> computeProduct(ArithmeticEnumeration op, Stack<Collection<IType>> rows)
throws IllegalArgumentException {
List<IType> results = new ArrayList<IType>();
if (rows.empty()) {
switch(op) {
case ADD:
results.add(TypeFactory.createType(IType.Type.INT, "0"));
break;
case MULTIPLY:
results.add(TypeFactory.createType(IType.Type.INT, "1"));
break;
}
} else {
for (IType type : rows.pop()) {
String value = type.getString();
Stack<Collection<IType>> copy = new Stack<Collection<IType>>();
copy.addAll(rows);
for (IType otherType : computeProduct(op, copy)) {
String otherValue = otherType.getString();
switch(op) {
case ADD:
if (value.indexOf(".") == -1 && otherValue.indexOf(".") == -1) {
String sum = new BigInteger(value).add(new BigInteger(otherValue)).toString();
results.add(TypeFactory.createType(IType.Type.INT, sum));
} else {
String sum = new BigDecimal(value).add(new BigDecimal(otherValue)).toString();
results.add(TypeFactory.createType(IType.Type.FLOAT, sum));
}
break;
case MULTIPLY:
if (value.indexOf(".") == -1 && otherValue.indexOf(".") == -1) {
String product = new BigInteger(value).multiply(new BigInteger(otherValue)).toString();
results.add(TypeFactory.createType(IType.Type.INT, product));
} else {
String product = new BigDecimal(value).multiply(new BigDecimal(otherValue)).toString();
results.add(TypeFactory.createType(IType.Type.FLOAT, product));
}
break;
}
}
}
}
return results;
}
/**
* The final step in resolving an object reference variable's value is extracting the item field or record from the items
* associated with that ObjectType, which is the function of this method.
*/
private List<IType> extractItemData(String objectId, ObjectComponentType oc, Collection list)
throws OvalException, ResolveException, NoSuchElementException, IllegalArgumentException {
List<IType> values = new ArrayList<IType>();
for (Object o : list) {
if (o instanceof ItemType) {
String fieldName = oc.getItemField();
try {
ItemType item = (ItemType)o;
String methodName = getAccessorMethodName(fieldName);
Method method = item.getClass().getMethod(methodName);
o = method.invoke(item);
} catch (NoSuchMethodException e) {
//
// The specification indicates that an object_component must have an error flag in this case.
//
String msg = JOVALMsg.getMessage(JOVALMsg.ERROR_RESOLVE_ITEM_FIELD, fieldName, o.getClass().getName());
throw new ResolveException(msg);
} catch (IllegalAccessException e) {
logger.warn(JOVALMsg.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
return null;
} catch (InvocationTargetException e) {
logger.warn(JOVALMsg.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
return null;
}
}
if (o instanceof JAXBElement) {
o = ((JAXBElement)o).getValue();
}
if (o == null) {
// skip nulls
} else if (o instanceof EntityItemSimpleBaseType) {
try {
EntityItemSimpleBaseType base = (EntityItemSimpleBaseType)o;
SimpleDatatypeEnumeration type = TypeFactory.getSimpleDatatype(base.getDatatype());
values.add(TypeFactory.createType(type, (String)base.getValue()));
} catch (IllegalArgumentException e) {
throw new ResolveException(e);
}
} else if (o instanceof List) {
values.addAll(extractItemData(objectId, null, (List)o));
} else if (o instanceof EntityItemRecordType) {
EntityItemRecordType record = (EntityItemRecordType)o;
if (oc.isSetRecordField()) {
String fieldName = oc.getRecordField();
for (EntityItemFieldType field : record.getField()) {
switch(field.getStatus()) {
case EXISTS:
try {
SimpleDatatypeEnumeration type = TypeFactory.getSimpleDatatype(field.getDatatype());
values.add(TypeFactory.createType(type, (String)field.getValue()));
} catch (IllegalArgumentException e) {
throw new ResolveException(e);
}
break;
default:
logger.warn(JOVALMsg.WARNING_FIELD_STATUS, field.getName(), field.getStatus(), objectId);
break;
}
}
} else {
try {
values.add(new RecordType(record));
} catch (IllegalArgumentException e) {
throw new ResolveException(e);
}
}
} else {
throw new OvalException(JOVALMsg.getMessage(JOVALMsg.ERROR_REFLECTION, o.getClass().getName(), objectId));
}
}
return values;
}
/**
* Recursively determine all the Object IDs referred to by the specified definition, extend_definition, criteria,
* criterion, test, object, state, filter, set, variable or component.
*
* @param obj the object whose object references are to be recursively resolved
* @param indirect specifies whether or not indirect references should be followed (i.e., variables, filters and sets).
*/
private Collection<String> getObjectReferences(Object obj, boolean indirect) throws OvalException {
Collection<String> results = new HashSet<String>();
String reflectionId = null;
try {
if (obj instanceof DefinitionType) {
DefinitionType def = (DefinitionType)obj;
if (def.isSetCriteria()) {
for (Object sub : def.getCriteria().getCriteriaOrCriterionOrExtendDefinition()) {
results.addAll(getObjectReferences(sub, indirect));
}
}
} else if (obj instanceof CriteriaType) {
for (Object sub : ((CriteriaType)obj).getCriteriaOrCriterionOrExtendDefinition()) {
results.addAll(getObjectReferences(sub, indirect));
}
} else if (obj instanceof ExtendDefinitionType) {
Object next = definitions.getDefinition(((ExtendDefinitionType)obj).getDefinitionRef());
results = getObjectReferences(next, indirect);
} else if (obj instanceof CriterionType) {
results = getObjectReferences(definitions.getTest(((CriterionType)obj).getTestRef()).getValue(), indirect);
} else if (obj instanceof scap.oval.definitions.core.TestType) {
ObjectRefType oRef = (ObjectRefType)safeInvokeMethod(obj, "getObject");
if (oRef != null) {
results.addAll(getObjectReferences(definitions.getObject(oRef.getObjectRef()).getValue(), indirect));
}
Object oRefs = safeInvokeMethod(obj, "getState");
@SuppressWarnings("unchecked")
List<StateRefType> sRefs = (List<StateRefType>)oRefs;
if (sRefs != null) {
for (StateRefType sRef : sRefs) {
results.addAll(getObjectReferences(definitions.getState(sRef.getStateRef()).getValue(), indirect));
}
}
} else if (obj instanceof ObjectType) {
ObjectType ot = (ObjectType)obj;
reflectionId = ot.getId();
results.add(ot.getId());
results.addAll(getObjectReferences(getObjectFilters(ot), indirect));
results.addAll(getObjectReferences(getObjectSet(ot), indirect));
if (ot instanceof VariableObject) {
VariableObject vo = (VariableObject)ot;
if (vo.isSetVarRef()) {
Object next = definitions.getVariable((String)vo.getVarRef().getValue());
results.addAll(getObjectReferences(next, indirect));
}
} else {
for (Method method : getMethods(ot.getClass()).values()) {
String methodName = method.getName();
if (methodName.startsWith("get") && !OBJECT_METHOD_NAMES.contains(methodName)) {
results.addAll(getObjectReferences(method.invoke(ot), indirect));
}
}
}
} else if (obj instanceof StateType) {
StateType st = (StateType)obj;
reflectionId = st.getId();
for (Method method : getMethods(obj.getClass()).values()) {
String methodName = method.getName();
if (methodName.startsWith("get") && !STATE_METHOD_NAMES.contains(methodName)) {
results.addAll(getObjectReferences(method.invoke(st), indirect));
}
}
} else if (obj instanceof Filter) {
if (indirect) {
results = getObjectReferences(definitions.getState(((Filter)obj).getValue()), indirect);
}
} else if (obj instanceof Set) {
if (indirect) {
Set set = (Set)obj;
if (set.isSetObjectReference()) {
for (String id : set.getObjectReference()) {
results.addAll(getObjectReferences(definitions.getObject(id).getValue(), indirect));
}
results.addAll(getObjectReferences(set.getFilter(), indirect));
} else {
results = getObjectReferences(set.getSet(), indirect);
}
}
} else if (obj instanceof JAXBElement) {
results = getObjectReferences(((JAXBElement)obj).getValue(), indirect);
} else if (obj instanceof EntitySimpleBaseType) {
EntitySimpleBaseType simple = (EntitySimpleBaseType)obj;
if (indirect && simple.isSetVarRef()) {
results = getObjectReferences(definitions.getVariable(simple.getVarRef()), indirect);
}
} else if (obj instanceof EntityComplexBaseType) {
EntityComplexBaseType complex = (EntityComplexBaseType)obj;
if (indirect && complex.isSetVarRef()) {
results = getObjectReferences(definitions.getVariable(complex.getVarRef()), indirect);
}
} else if (obj instanceof List) {
for (Object elt : (List)obj) {
results.addAll(getObjectReferences(elt, indirect));
}
} else if (obj instanceof ObjectComponentType) {
Object next = definitions.getObject(((ObjectComponentType)obj).getObjectRef()).getValue();
results = getObjectReferences(next, indirect);
} else if (obj instanceof VariableComponentType) {
VariableType var = definitions.getVariable(((VariableComponentType)obj).getVarRef());
if (var instanceof LocalVariable) {
results = getObjectReferences(var, indirect);
}
} else if (obj != null) {
try {
results = getObjectReferences(getComponent(obj), indirect);
} catch (OvalException e) {
// not a component
}
}
} catch (NoSuchElementException e) {
// this will lead to an error evaluating the definition later on
} catch (ClassCastException e) {
logger.warn(JOVALMsg.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
throw new OvalException(JOVALMsg.getMessage(JOVALMsg.ERROR_REFLECTION, e.getMessage(), reflectionId));
} catch (IllegalAccessException e) {
logger.warn(JOVALMsg.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
throw new OvalException(JOVALMsg.getMessage(JOVALMsg.ERROR_REFLECTION, e.getMessage(), reflectionId));
} catch (InvocationTargetException e) {
logger.warn(JOVALMsg.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
throw new OvalException(JOVALMsg.getMessage(JOVALMsg.ERROR_REFLECTION, e.getMessage(), reflectionId));
}
return results;
}
/**
* Use reflection to get the child component of a function type. Since there is no base class for all the OVAL function
* types, this method accepts any Object.
*/
private Object getComponent(Object unknown) throws OvalException {
Object obj = safeInvokeMethod(unknown, "getArithmetic");
if (obj != null) {
return obj;
}
obj = safeInvokeMethod(unknown, "getBegin");
if (obj != null) {
return obj;
}
obj = safeInvokeMethod(unknown, "getCount");
if (obj != null) {
return obj;
}
obj = safeInvokeMethod(unknown, "getConcat");
if (obj != null) {
return obj;
}
obj = safeInvokeMethod(unknown, "getEnd");
if (obj != null) {
return obj;
}
obj = safeInvokeMethod(unknown, "getEscapeRegex");
if (obj != null) {
return obj;
}
obj = safeInvokeMethod(unknown, "getLiteralComponent");
if (obj != null) {
return obj;
}
obj = safeInvokeMethod(unknown, "getObjectComponent");
if (obj != null) {
return obj;
}
obj = safeInvokeMethod(unknown, "getRegexCapture");
if (obj != null) {
return obj;
}
obj = safeInvokeMethod(unknown, "getSplit");
if (obj != null) {
return obj;
}
obj = safeInvokeMethod(unknown, "getSubstring");
if (obj != null) {
return obj;
}
obj = safeInvokeMethod(unknown, "getTimeDifference");
if (obj != null) {
return obj;
}
obj = safeInvokeMethod(unknown, "getUnique");
if (obj != null) {
return obj;
}
obj = safeInvokeMethod(unknown, "getVariableComponent");
if (obj != null) {
return obj;
}
obj = safeInvokeMethod(unknown, "getObjectComponentOrVariableComponentOrLiteralComponent");
if (obj != null) {
return obj;
}
throw new OvalException(JOVALMsg.getMessage(JOVALMsg.ERROR_UNSUPPORTED_COMPONENT, unknown.getClass().getName()));
}
private static Map<String, Map<String, Method>> METHOD_REGISTRY;
private static java.util.Set<String> OBJECT_METHOD_NAMES;
static {
METHOD_REGISTRY = new HashMap<String, Map<String, Method>>();
OBJECT_METHOD_NAMES = getNames(getMethods(ObjectType.class).values());
OBJECT_METHOD_NAMES.add("getBehaviors");
OBJECT_METHOD_NAMES.add("getFilter");
OBJECT_METHOD_NAMES.add("getSet");
}
private static java.util.Set<String> STATE_METHOD_NAMES = getNames(getMethods(StateType.class).values());
/**
* List the unique names of all the no-argument methods. This is not necessarily a fast method.
*/
private static java.util.Set<String> getNames(Collection<Method> methods) {
java.util.Set<String> names = new HashSet<String>();
for (Method m : methods) {
names.add(m.getName());
}
return names;
}
/**
* Use introspection to list all the no-argument methods of the specified Class, organized by name.
*/
private static Map<String, Method> getMethods(Class clazz) {
String className = clazz.getName();
if (METHOD_REGISTRY.containsKey(className)) {
return METHOD_REGISTRY.get(className);
} else {
Map<String, Method> methods = new HashMap<String, Method>();
Method[] m = clazz.getMethods();
for (int i=0; i < m.length; i++) {
methods.put(m[i].getName(), m[i]);
}
METHOD_REGISTRY.put(className, methods);
return methods;
}
}
/**
* Use introspection to get the no-argument method of the specified Class, with the specified name.
*/
private static Method getMethod(Class clazz, String name) throws NoSuchMethodException {
Map<String, Method> methods = getMethods(clazz);
if (methods.containsKey(name)) {
return methods.get(name);
} else {
throw new NoSuchMethodException(clazz.getName() + "." + name + "()");
}
}
/**
* Given the name of an XML node, guess the name of the accessor field that JAXB would generate.
* For example, field_name -> getFieldName.
*/
private String getAccessorMethodName(String fieldName) {
StringTokenizer tok = new StringTokenizer(fieldName, "_");
StringBuffer sb = new StringBuffer("get");
while(tok.hasMoreTokens()) {
byte[] ba = tok.nextToken().toLowerCase().getBytes(StringTools.ASCII);
if (97 <= ba[0] && ba[0] <= 122) {
ba[0] -= 32; // Capitalize the first letter.
}
sb.append(new String(ba, StringTools.ASCII));
}
return sb.toString();
}
/**
* Safely invoke a method that takes no arguments and returns an Object.
*
* @returns null if the method is not implemented, if there was an error, or if the method returned null.
*/
private Object safeInvokeMethod(Object obj, String name) {
Object result = null;
try {
Method m = obj.getClass().getMethod(name);
result = m.invoke(obj);
} catch (NoSuchMethodException e) {
// Object doesn't implement the method; no big deal.
} catch (IllegalAccessException e) {
logger.warn(JOVALMsg.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
} catch (InvocationTargetException e) {
logger.warn(JOVALMsg.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
}
return result;
}
/**
* An EntityObjectSimpleBaseType wrapper for an EntityStateFieldType.
*/
private class ObjectFieldBridge extends EntitySimpleBaseType {
ObjectFieldBridge(EntityObjectFieldType field) {
datatype = field.getDatatype();
mask = field.getMask();
operation = field.getOperation();
value = field.getValue();
varCheck = field.getVarCheck();
varRef = field.getVarRef();
}
}
/**
* An EntityStateSimpleBaseType wrapper for an EntityStateFieldType.
*/
private class StateFieldBridge extends EntityStateSimpleBaseType {
StateFieldBridge(EntityStateFieldType field) {
datatype = field.getDatatype();
mask = field.getMask();
operation = field.getOperation();
value = field.getValue();
varCheck = field.getVarCheck();
varRef = field.getVarRef();
entityCheck = field.getEntityCheck();
}
}
/**
* An EntityItemSimpleBaseType wrapper for an EntityItemFieldType.
*/
private class ItemFieldBridge extends EntityItemSimpleBaseType {
ItemFieldBridge(EntityItemFieldType field) {
datatype = field.getDatatype();
mask = field.getMask();
value = field.getValue();
}
}
}
| true | true | private Collection<IType> resolveComponent(Object object, RequestContext rc) throws NoSuchElementException,
UnsupportedOperationException, IllegalArgumentException, ResolveException, OvalException {
//
// This is a good place to check if the engine is being destroyed
//
if (abort) {
throw new AbortException(JOVALMsg.getMessage(JOVALMsg.ERROR_ENGINE_ABORT));
}
//
// Why do variables point to variables? Because sometimes they are nested.
//
if (object instanceof LocalVariable) {
LocalVariable localVariable = (LocalVariable)object;
Collection<IType> values = resolveComponent(getComponent(localVariable), rc);
if (values.size() == 0) {
VariableValueType variableValueType = Factories.sc.core.createVariableValueType();
variableValueType.setVariableId(localVariable.getId());
rc.addVar(variableValueType);
} else {
Collection<IType> convertedValues = new ArrayList<IType>();
for (IType value : values) {
try {
//
// Convert values from the originating type to the variable's defined datatype
//
convertedValues.add(value.cast(localVariable.getDatatype()));
VariableValueType variableValueType = Factories.sc.core.createVariableValueType();
variableValueType.setVariableId(localVariable.getId());
variableValueType.setValue(value.getString());
rc.addVar(variableValueType);
} catch (TypeConversionException e) {
MessageType message = Factories.common.createMessageType();
message.setLevel(MessageLevelEnumeration.ERROR);
message.setValue(JOVALMsg.getMessage(JOVALMsg.ERROR_TYPE_CONVERSION, e.getMessage()));
rc.addMessage(message);
}
}
values = convertedValues;
}
return values;
//
// Add an externally-defined variable.
//
} else if (object instanceof ExternalVariable) {
ExternalVariable externalVariable = (ExternalVariable)object;
String id = externalVariable.getId();
if (externalVariables == null) {
throw new ResolveException(JOVALMsg.getMessage(JOVALMsg.ERROR_EXTERNAL_VARIABLE_SOURCE, id));
} else {
Collection<IType> values = new ArrayList<IType>();
try {
for (IType value : externalVariables.getValue(id)) {
try {
values.add(value.cast(externalVariable.getDatatype()));
} catch (TypeConversionException e) {
MessageType message = Factories.common.createMessageType();
message.setLevel(MessageLevelEnumeration.ERROR);
message.setValue(JOVALMsg.getMessage(JOVALMsg.ERROR_TYPE_CONVERSION, e.getMessage()));
rc.addMessage(message);
}
}
} catch (NoSuchElementException e) {
MessageType message = Factories.common.createMessageType();
message.setLevel(MessageLevelEnumeration.ERROR);
message.setValue(JOVALMsg.getMessage(JOVALMsg.ERROR_EXTERNAL_VARIABLE, e.getMessage()));
rc.addMessage(message);
}
if (values.size() == 0) {
VariableValueType variableValueType = Factories.sc.core.createVariableValueType();
variableValueType.setVariableId(externalVariable.getId());
rc.addVar(variableValueType);
} else {
for (IType value : values) {
VariableValueType variableValueType = Factories.sc.core.createVariableValueType();
variableValueType.setVariableId(externalVariable.getId());
variableValueType.setValue(value.getString());
rc.addVar(variableValueType);
}
}
return values;
}
//
// Add a constant variable.
//
} else if (object instanceof ConstantVariable) {
ConstantVariable constantVariable = (ConstantVariable)object;
String id = constantVariable.getId();
Collection<IType> values = new ArrayList<IType>();
List<ValueType> valueTypes = constantVariable.getValue();
if (valueTypes.size() == 0) {
VariableValueType variableValueType = Factories.sc.core.createVariableValueType();
variableValueType.setVariableId(constantVariable.getId());
rc.addVar(variableValueType);
} else {
for (ValueType value : valueTypes) {
VariableValueType variableValueType = Factories.sc.core.createVariableValueType();
variableValueType.setVariableId(id);
String s = (String)value.getValue();
variableValueType.setValue(s);
rc.addVar(variableValueType);
values.add(TypeFactory.createType(constantVariable.getDatatype(), s));
}
}
return values;
//
// Add a static (literal) value.
//
} else if (object instanceof LiteralComponentType) {
LiteralComponentType literal = (LiteralComponentType)object;
Collection<IType> values = new ArrayList<IType>();
values.add(TypeFactory.createType(literal.getDatatype(), (String)literal.getValue()));
return values;
//
// Retrieve from an ItemType (which possibly has to be fetched from an adapter)
//
} else if (object instanceof ObjectComponentType) {
ObjectComponentType oc = (ObjectComponentType)object;
String objectId = oc.getObjectRef();
Collection<ItemType> items = new ArrayList<ItemType>();
try {
//
// First, we scan the SystemCharacteristics for items related to the object.
//
for (JAXBElement<? extends ItemType> elt : sc.getItemsByObjectId(objectId)) {
items.add(elt.getValue());
}
} catch (NoSuchElementException e) {
//
// If the object has not yet been scanned, then it must be retrieved live from the adapter
//
rc.pushObject(definitions.getObject(objectId).getValue());
items = scanObject(rc);
rc.popObject();
}
return extractItemData(objectId, oc, items);
//
// Resolve and return.
//
} else if (object instanceof VariableComponentType) {
return resolveComponent(definitions.getVariable(((VariableComponentType)object).getVarRef()), rc);
//
// Resolve and concatenate child components.
//
} else if (object instanceof ConcatFunctionType) {
Collection<IType> values = new ArrayList<IType>();
ConcatFunctionType concat = (ConcatFunctionType)object;
for (Object child : concat.getObjectComponentOrVariableComponentOrLiteralComponent()) {
Collection<IType> next = resolveComponent(child, rc);
if (next.size() == 0) {
@SuppressWarnings("unchecked")
Collection<IType> empty = (Collection<IType>)Collections.EMPTY_LIST;
return empty;
} else if (values.size() == 0) {
values.addAll(next);
} else {
Collection<IType> newValues = new ArrayList<IType>();
for (IType base : values) {
for (IType val : next) {
newValues.add(TypeFactory.createType(IType.Type.STRING, base.getString() + val.getString()));
}
}
values = newValues;
}
}
return values;
//
// Escape anything that could be pattern-matched.
//
} else if (object instanceof EscapeRegexFunctionType) {
Collection<IType> values = new ArrayList<IType>();
for (IType value : resolveComponent(getComponent((EscapeRegexFunctionType)object), rc)) {
values.add(TypeFactory.createType(IType.Type.STRING, StringTools.escapeRegex(value.getString())));
}
return values;
//
// Process a Split, which contains a component and a delimiter with which to split it up.
//
} else if (object instanceof SplitFunctionType) {
SplitFunctionType split = (SplitFunctionType)object;
Collection<IType> values = new ArrayList<IType>();
for (IType value : resolveComponent(getComponent(split), rc)) {
for (String s : StringTools.toList(StringTools.tokenize(value.getString(), split.getDelimiter(), false))) {
values.add(TypeFactory.createType(IType.Type.STRING, s));
}
}
return values;
//
// Process a RegexCapture, which returns the regions of a component resolved as a String that match the first
// subexpression in the given pattern.
//
} else if (object instanceof RegexCaptureFunctionType) {
RegexCaptureFunctionType regexCapture = (RegexCaptureFunctionType)object;
Pattern p = StringTools.pattern(regexCapture.getPattern());
Collection<IType> values = new ArrayList<IType>();
for (IType value : resolveComponent(getComponent(regexCapture), rc)) {
Matcher m = p.matcher(value.getString());
if (m.groupCount() >= 1) {
if (m.find()) {
values.add(TypeFactory.createType(IType.Type.STRING, m.group(1)));
} else {
values.add(StringType.EMPTY);
}
} else {
values.add(StringType.EMPTY);
MessageType message = Factories.common.createMessageType();
message.setLevel(MessageLevelEnumeration.WARNING);
message.setValue(JOVALMsg.getMessage(JOVALMsg.WARNING_REGEX_GROUP, p.pattern()));
rc.addMessage(message);
}
}
return values;
//
// Process a Substring
//
} else if (object instanceof SubstringFunctionType) {
SubstringFunctionType st = (SubstringFunctionType)object;
int start = st.getSubstringStart();
start = Math.max(1, start); // a start index < 1 means start at 1
start--; // OVAL counter begins at 1 instead of 0
int len = st.getSubstringLength();
Collection<IType> values = new ArrayList<IType>();
for (IType value : resolveComponent(getComponent(st), rc)) {
String str = value.getString();
//
// If the substring_start attribute has value greater than the length of the original string
// an error should be reported.
//
if (start > str.length()) {
throw new ResolveException(JOVALMsg.getMessage(JOVALMsg.ERROR_SUBSTRING, str, new Integer(start)));
//
// A substring_length value greater than the actual length of the string, or a negative value,
// means to include all of the characters after the starting character.
//
} else if (len < 0 || str.length() <= (start+len)) {
values.add(TypeFactory.createType(IType.Type.STRING, str.substring(start)));
} else {
values.add(TypeFactory.createType(IType.Type.STRING, str.substring(start, start+len)));
}
}
return values;
//
// Process a Begin
//
} else if (object instanceof BeginFunctionType) {
BeginFunctionType bt = (BeginFunctionType)object;
String s = bt.getCharacter();
Collection<IType> values = new ArrayList<IType>();
for (IType value : resolveComponent(getComponent(bt), rc)) {
String str = value.getString();
if (str.startsWith(s)) {
values.add(value);
} else {
values.add(TypeFactory.createType(IType.Type.STRING, s + str));
}
}
return values;
//
// Process an End
//
} else if (object instanceof EndFunctionType) {
EndFunctionType et = (EndFunctionType)object;
String s = et.getCharacter();
Collection<IType> values = new ArrayList<IType>();
for (IType value : resolveComponent(getComponent(et), rc)) {
String str = value.getString();
if (str.endsWith(s)) {
values.add(value);
} else {
values.add(TypeFactory.createType(IType.Type.STRING, str + s));
}
}
return values;
//
// Process a TimeDifference
//
} else if (object instanceof TimeDifferenceFunctionType) {
TimeDifferenceFunctionType tt = (TimeDifferenceFunctionType)object;
Collection<IType> values = new ArrayList<IType>();
List<Object> children = tt.getObjectComponentOrVariableComponentOrLiteralComponent();
Collection<IType> ts1;
Collection<IType> ts2;
if (children.size() == 1) {
tt.setFormat1(DateTimeFormatEnumeration.SECONDS_SINCE_EPOCH);
ts1 = new ArrayList<IType>();
try {
String val = Long.toString(plugin.getSession().getTime() / 1000L);
ts1.add(TypeFactory.createType(IType.Type.INT, val));
} catch (Exception e) {
throw new ResolveException(e);
}
ts2 = resolveComponent(children.get(0), rc);
} else if (children.size() == 2) {
ts1 = resolveComponent(children.get(0), rc);
ts2 = resolveComponent(children.get(1), rc);
} else {
String msg = JOVALMsg.getMessage(JOVALMsg.ERROR_BAD_TIMEDIFFERENCE, Integer.toString(children.size()));
throw new ResolveException(msg);
}
for (IType time1 : ts1) {
try {
long tm1 = DateTime.getTime(time1.getString(), tt.getFormat1());
for (IType time2 : ts2) {
long tm2 = DateTime.getTime(time2.getString(), tt.getFormat2());
long diff = (tm1 - tm2)/1000L; // convert diff to seconds
values.add(TypeFactory.createType(IType.Type.INT, Long.toString(diff)));
}
} catch (IllegalArgumentException e) {
throw new ResolveException(e.getMessage());
} catch (ParseException e) {
throw new ResolveException(e.getMessage());
}
}
return values;
//
// Process Arithmetic
//
} else if (object instanceof ArithmeticFunctionType) {
ArithmeticFunctionType at = (ArithmeticFunctionType)object;
Stack<Collection<IType>> rows = new Stack<Collection<IType>>();
ArithmeticEnumeration op = at.getArithmeticOperation();
for (Object child : at.getObjectComponentOrVariableComponentOrLiteralComponent()) {
Collection<IType> row = new ArrayList<IType>();
for (IType cell : resolveComponent(child, rc)) {
row.add(cell);
}
rows.add(row);
}
return computeProduct(op, rows);
//
// Process Count
//
} else if (object instanceof CountFunctionType) {
CountFunctionType ct = (CountFunctionType)object;
Collection<IType> children = new ArrayList<IType>();
for (Object child : ct.getObjectComponentOrVariableComponentOrLiteralComponent()) {
children.addAll(resolveComponent(child, rc));
}
Collection<IType> values = new ArrayList<IType>();
values.add(TypeFactory.createType(IType.Type.INT, Integer.toString(children.size())));
return values;
//
// Process Unique
//
} else if (object instanceof UniqueFunctionType) {
UniqueFunctionType ut = (UniqueFunctionType)object;
HashSet<IType> values = new HashSet<IType>();
for (Object child : ut.getObjectComponentOrVariableComponentOrLiteralComponent()) {
values.addAll(resolveComponent(child, rc));
}
return values;
} else {
throw new OvalException(JOVALMsg.getMessage(JOVALMsg.ERROR_UNSUPPORTED_COMPONENT, object.getClass().getName()));
}
}
| private Collection<IType> resolveComponent(Object object, RequestContext rc) throws NoSuchElementException,
UnsupportedOperationException, IllegalArgumentException, ResolveException, OvalException {
//
// This is a good place to check if the engine is being destroyed
//
if (abort) {
throw new AbortException(JOVALMsg.getMessage(JOVALMsg.ERROR_ENGINE_ABORT));
}
//
// Why do variables point to variables? Because sometimes they are nested.
//
if (object instanceof LocalVariable) {
LocalVariable localVariable = (LocalVariable)object;
Collection<IType> values = resolveComponent(getComponent(localVariable), rc);
if (values.size() == 0) {
VariableValueType variableValueType = Factories.sc.core.createVariableValueType();
variableValueType.setVariableId(localVariable.getId());
rc.addVar(variableValueType);
} else {
Collection<IType> convertedValues = new ArrayList<IType>();
for (IType value : values) {
try {
//
// Convert values from the originating type to the variable's defined datatype
//
convertedValues.add(value.cast(localVariable.getDatatype()));
VariableValueType variableValueType = Factories.sc.core.createVariableValueType();
variableValueType.setVariableId(localVariable.getId());
variableValueType.setValue(value.getString());
rc.addVar(variableValueType);
} catch (TypeConversionException e) {
MessageType message = Factories.common.createMessageType();
message.setLevel(MessageLevelEnumeration.ERROR);
message.setValue(JOVALMsg.getMessage(JOVALMsg.ERROR_TYPE_CONVERSION, e.getMessage()));
rc.addMessage(message);
}
}
values = convertedValues;
}
return values;
//
// Add an externally-defined variable.
//
} else if (object instanceof ExternalVariable) {
ExternalVariable externalVariable = (ExternalVariable)object;
String id = externalVariable.getId();
if (externalVariables == null) {
throw new ResolveException(JOVALMsg.getMessage(JOVALMsg.ERROR_EXTERNAL_VARIABLE_SOURCE, id));
} else {
Collection<IType> values = new ArrayList<IType>();
try {
for (IType value : externalVariables.getValue(id)) {
try {
values.add(value.cast(externalVariable.getDatatype()));
} catch (TypeConversionException e) {
MessageType message = Factories.common.createMessageType();
message.setLevel(MessageLevelEnumeration.ERROR);
message.setValue(JOVALMsg.getMessage(JOVALMsg.ERROR_TYPE_CONVERSION, e.getMessage()));
rc.addMessage(message);
}
}
} catch (NoSuchElementException e) {
throw new ResolveException(JOVALMsg.getMessage(JOVALMsg.ERROR_EXTERNAL_VARIABLE, e.getMessage()));
}
if (values.size() == 0) {
VariableValueType variableValueType = Factories.sc.core.createVariableValueType();
variableValueType.setVariableId(externalVariable.getId());
rc.addVar(variableValueType);
} else {
for (IType value : values) {
VariableValueType variableValueType = Factories.sc.core.createVariableValueType();
variableValueType.setVariableId(externalVariable.getId());
variableValueType.setValue(value.getString());
rc.addVar(variableValueType);
}
}
return values;
}
//
// Add a constant variable.
//
} else if (object instanceof ConstantVariable) {
ConstantVariable constantVariable = (ConstantVariable)object;
String id = constantVariable.getId();
Collection<IType> values = new ArrayList<IType>();
List<ValueType> valueTypes = constantVariable.getValue();
if (valueTypes.size() == 0) {
VariableValueType variableValueType = Factories.sc.core.createVariableValueType();
variableValueType.setVariableId(constantVariable.getId());
rc.addVar(variableValueType);
} else {
for (ValueType value : valueTypes) {
VariableValueType variableValueType = Factories.sc.core.createVariableValueType();
variableValueType.setVariableId(id);
String s = (String)value.getValue();
variableValueType.setValue(s);
rc.addVar(variableValueType);
values.add(TypeFactory.createType(constantVariable.getDatatype(), s));
}
}
return values;
//
// Add a static (literal) value.
//
} else if (object instanceof LiteralComponentType) {
LiteralComponentType literal = (LiteralComponentType)object;
Collection<IType> values = new ArrayList<IType>();
values.add(TypeFactory.createType(literal.getDatatype(), (String)literal.getValue()));
return values;
//
// Retrieve from an ItemType (which possibly has to be fetched from an adapter)
//
} else if (object instanceof ObjectComponentType) {
ObjectComponentType oc = (ObjectComponentType)object;
String objectId = oc.getObjectRef();
Collection<ItemType> items = new ArrayList<ItemType>();
try {
//
// First, we scan the SystemCharacteristics for items related to the object.
//
for (JAXBElement<? extends ItemType> elt : sc.getItemsByObjectId(objectId)) {
items.add(elt.getValue());
}
} catch (NoSuchElementException e) {
//
// If the object has not yet been scanned, then it must be retrieved live from the adapter
//
rc.pushObject(definitions.getObject(objectId).getValue());
items = scanObject(rc);
rc.popObject();
}
return extractItemData(objectId, oc, items);
//
// Resolve and return.
//
} else if (object instanceof VariableComponentType) {
return resolveComponent(definitions.getVariable(((VariableComponentType)object).getVarRef()), rc);
//
// Resolve and concatenate child components.
//
} else if (object instanceof ConcatFunctionType) {
Collection<IType> values = new ArrayList<IType>();
ConcatFunctionType concat = (ConcatFunctionType)object;
for (Object child : concat.getObjectComponentOrVariableComponentOrLiteralComponent()) {
Collection<IType> next = resolveComponent(child, rc);
if (next.size() == 0) {
@SuppressWarnings("unchecked")
Collection<IType> empty = (Collection<IType>)Collections.EMPTY_LIST;
return empty;
} else if (values.size() == 0) {
values.addAll(next);
} else {
Collection<IType> newValues = new ArrayList<IType>();
for (IType base : values) {
for (IType val : next) {
newValues.add(TypeFactory.createType(IType.Type.STRING, base.getString() + val.getString()));
}
}
values = newValues;
}
}
return values;
//
// Escape anything that could be pattern-matched.
//
} else if (object instanceof EscapeRegexFunctionType) {
Collection<IType> values = new ArrayList<IType>();
for (IType value : resolveComponent(getComponent((EscapeRegexFunctionType)object), rc)) {
values.add(TypeFactory.createType(IType.Type.STRING, StringTools.escapeRegex(value.getString())));
}
return values;
//
// Process a Split, which contains a component and a delimiter with which to split it up.
//
} else if (object instanceof SplitFunctionType) {
SplitFunctionType split = (SplitFunctionType)object;
Collection<IType> values = new ArrayList<IType>();
for (IType value : resolveComponent(getComponent(split), rc)) {
for (String s : StringTools.toList(StringTools.tokenize(value.getString(), split.getDelimiter(), false))) {
values.add(TypeFactory.createType(IType.Type.STRING, s));
}
}
return values;
//
// Process a RegexCapture, which returns the regions of a component resolved as a String that match the first
// subexpression in the given pattern.
//
} else if (object instanceof RegexCaptureFunctionType) {
RegexCaptureFunctionType regexCapture = (RegexCaptureFunctionType)object;
Pattern p = StringTools.pattern(regexCapture.getPattern());
Collection<IType> values = new ArrayList<IType>();
for (IType value : resolveComponent(getComponent(regexCapture), rc)) {
Matcher m = p.matcher(value.getString());
if (m.groupCount() >= 1) {
if (m.find()) {
values.add(TypeFactory.createType(IType.Type.STRING, m.group(1)));
} else {
values.add(StringType.EMPTY);
}
} else {
values.add(StringType.EMPTY);
MessageType message = Factories.common.createMessageType();
message.setLevel(MessageLevelEnumeration.WARNING);
message.setValue(JOVALMsg.getMessage(JOVALMsg.WARNING_REGEX_GROUP, p.pattern()));
rc.addMessage(message);
}
}
return values;
//
// Process a Substring
//
} else if (object instanceof SubstringFunctionType) {
SubstringFunctionType st = (SubstringFunctionType)object;
int start = st.getSubstringStart();
start = Math.max(1, start); // a start index < 1 means start at 1
start--; // OVAL counter begins at 1 instead of 0
int len = st.getSubstringLength();
Collection<IType> values = new ArrayList<IType>();
for (IType value : resolveComponent(getComponent(st), rc)) {
String str = value.getString();
//
// If the substring_start attribute has value greater than the length of the original string
// an error should be reported.
//
if (start > str.length()) {
throw new ResolveException(JOVALMsg.getMessage(JOVALMsg.ERROR_SUBSTRING, str, new Integer(start)));
//
// A substring_length value greater than the actual length of the string, or a negative value,
// means to include all of the characters after the starting character.
//
} else if (len < 0 || str.length() <= (start+len)) {
values.add(TypeFactory.createType(IType.Type.STRING, str.substring(start)));
} else {
values.add(TypeFactory.createType(IType.Type.STRING, str.substring(start, start+len)));
}
}
return values;
//
// Process a Begin
//
} else if (object instanceof BeginFunctionType) {
BeginFunctionType bt = (BeginFunctionType)object;
String s = bt.getCharacter();
Collection<IType> values = new ArrayList<IType>();
for (IType value : resolveComponent(getComponent(bt), rc)) {
String str = value.getString();
if (str.startsWith(s)) {
values.add(value);
} else {
values.add(TypeFactory.createType(IType.Type.STRING, s + str));
}
}
return values;
//
// Process an End
//
} else if (object instanceof EndFunctionType) {
EndFunctionType et = (EndFunctionType)object;
String s = et.getCharacter();
Collection<IType> values = new ArrayList<IType>();
for (IType value : resolveComponent(getComponent(et), rc)) {
String str = value.getString();
if (str.endsWith(s)) {
values.add(value);
} else {
values.add(TypeFactory.createType(IType.Type.STRING, str + s));
}
}
return values;
//
// Process a TimeDifference
//
} else if (object instanceof TimeDifferenceFunctionType) {
TimeDifferenceFunctionType tt = (TimeDifferenceFunctionType)object;
Collection<IType> values = new ArrayList<IType>();
List<Object> children = tt.getObjectComponentOrVariableComponentOrLiteralComponent();
Collection<IType> ts1;
Collection<IType> ts2;
if (children.size() == 1) {
tt.setFormat1(DateTimeFormatEnumeration.SECONDS_SINCE_EPOCH);
ts1 = new ArrayList<IType>();
try {
String val = Long.toString(plugin.getSession().getTime() / 1000L);
ts1.add(TypeFactory.createType(IType.Type.INT, val));
} catch (Exception e) {
throw new ResolveException(e);
}
ts2 = resolveComponent(children.get(0), rc);
} else if (children.size() == 2) {
ts1 = resolveComponent(children.get(0), rc);
ts2 = resolveComponent(children.get(1), rc);
} else {
String msg = JOVALMsg.getMessage(JOVALMsg.ERROR_BAD_TIMEDIFFERENCE, Integer.toString(children.size()));
throw new ResolveException(msg);
}
for (IType time1 : ts1) {
try {
long tm1 = DateTime.getTime(time1.getString(), tt.getFormat1());
for (IType time2 : ts2) {
long tm2 = DateTime.getTime(time2.getString(), tt.getFormat2());
long diff = (tm1 - tm2)/1000L; // convert diff to seconds
values.add(TypeFactory.createType(IType.Type.INT, Long.toString(diff)));
}
} catch (IllegalArgumentException e) {
throw new ResolveException(e.getMessage());
} catch (ParseException e) {
throw new ResolveException(e.getMessage());
}
}
return values;
//
// Process Arithmetic
//
} else if (object instanceof ArithmeticFunctionType) {
ArithmeticFunctionType at = (ArithmeticFunctionType)object;
Stack<Collection<IType>> rows = new Stack<Collection<IType>>();
ArithmeticEnumeration op = at.getArithmeticOperation();
for (Object child : at.getObjectComponentOrVariableComponentOrLiteralComponent()) {
Collection<IType> row = new ArrayList<IType>();
for (IType cell : resolveComponent(child, rc)) {
row.add(cell);
}
rows.add(row);
}
return computeProduct(op, rows);
//
// Process Count
//
} else if (object instanceof CountFunctionType) {
CountFunctionType ct = (CountFunctionType)object;
Collection<IType> children = new ArrayList<IType>();
for (Object child : ct.getObjectComponentOrVariableComponentOrLiteralComponent()) {
children.addAll(resolveComponent(child, rc));
}
Collection<IType> values = new ArrayList<IType>();
values.add(TypeFactory.createType(IType.Type.INT, Integer.toString(children.size())));
return values;
//
// Process Unique
//
} else if (object instanceof UniqueFunctionType) {
UniqueFunctionType ut = (UniqueFunctionType)object;
HashSet<IType> values = new HashSet<IType>();
for (Object child : ut.getObjectComponentOrVariableComponentOrLiteralComponent()) {
values.addAll(resolveComponent(child, rc));
}
return values;
} else {
throw new OvalException(JOVALMsg.getMessage(JOVALMsg.ERROR_UNSUPPORTED_COMPONENT, object.getClass().getName()));
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.