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/sql-builder-api/src/main/java/cx/ath/jbzdak/sqlbuilder/dialect/peer/ParameterLiteralPeer.java b/sql-builder-api/src/main/java/cx/ath/jbzdak/sqlbuilder/dialect/peer/ParameterLiteralPeer.java
index 0852f94..2c67384 100644
--- a/sql-builder-api/src/main/java/cx/ath/jbzdak/sqlbuilder/dialect/peer/ParameterLiteralPeer.java
+++ b/sql-builder-api/src/main/java/cx/ath/jbzdak/sqlbuilder/dialect/peer/ParameterLiteralPeer.java
@@ -1,37 +1,37 @@
/*
* Copyright (c) 2011 for Jacek Bzdak
*
* This file is part of query builder.
*
* Query builder 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.
*
* Query builder 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 Query builder. If not, see <http://www.gnu.org/licenses/>.
*/
package cx.ath.jbzdak.sqlbuilder.dialect.peer;
import cx.ath.jbzdak.sqlbuilder.RenderingContext;
import cx.ath.jbzdak.sqlbuilder.literal.ParameterLiteral;
import cx.ath.jbzdak.sqlbuilder.parameter.Parameter;
/**
* Created by: Jacek Bzdak
*/
public class ParameterLiteralPeer extends AbstractPeer<ParameterLiteral>{
@Override
protected void appendToInternal(RenderingContext renderingContext, StringBuilder stringBuilder) {
- stringBuilder.append(":");
+ stringBuilder.append(" :");
stringBuilder.append(parent.getLiteralValue().getName());
stringBuilder.append(" ");
}
}
| true | true | protected void appendToInternal(RenderingContext renderingContext, StringBuilder stringBuilder) {
stringBuilder.append(":");
stringBuilder.append(parent.getLiteralValue().getName());
stringBuilder.append(" ");
}
| protected void appendToInternal(RenderingContext renderingContext, StringBuilder stringBuilder) {
stringBuilder.append(" :");
stringBuilder.append(parent.getLiteralValue().getName());
stringBuilder.append(" ");
}
|
diff --git a/source/oms/src/main/java/org/marketcetera/oms/OutgoingMessageHandler.java b/source/oms/src/main/java/org/marketcetera/oms/OutgoingMessageHandler.java
index 0c9c5131c..2b7e227a7 100644
--- a/source/oms/src/main/java/org/marketcetera/oms/OutgoingMessageHandler.java
+++ b/source/oms/src/main/java/org/marketcetera/oms/OutgoingMessageHandler.java
@@ -1,312 +1,311 @@
package org.marketcetera.oms;
import org.marketcetera.core.*;
import org.marketcetera.quickfix.*;
import quickfix.*;
import quickfix.field.*;
import java.math.BigDecimal;
import java.util.LinkedList;
import java.util.List;
/**
* OutgoingMessageHandler is the "middle" stage that recieves an incoming order request
* from JMS, does some operations on it in and sends it on to the FIX sender
*
* This is essentially the "OrderManager" stage: we send an immediate "ack" to an
* incoming NewOrder, apply order modifiers and send it on.
*
* @author gmiller
* $Id$
*/
@ClassVersion("$Id$")
public class OutgoingMessageHandler {
private List<MessageModifier> messageModifiers;
private MessageRouteManager routeMgr;
private SessionID defaultSessionID; // used to store the SessionID so that FIX sender can find it
private IQuickFIXSender quickFIXSender = new QuickFIXSender();
private IDFactory idFactory;
private FIXMessageFactory msgFactory;
private OrderLimits orderLimits;
// this is temporary, until we have much better JMX visibility
protected QuickFIXApplication qfApp;
public OutgoingMessageHandler(SessionSettings settings, FIXMessageFactory inFactory, OrderLimits inLimits,
QuickFIXApplication inQFApp)
throws ConfigError, FieldConvertError, MarketceteraException {
setMessageModifiers(new LinkedList<MessageModifier>());
setOrderRouteManager(new MessageRouteManager());
msgFactory = inFactory;
idFactory = createDatabaseIDFactory(settings);
orderLimits = inLimits;
qfApp = inQFApp;
try {
idFactory.init();
} catch (Exception ex) {
if(LoggerAdapter.isDebugEnabled(this)) { LoggerAdapter.debug("Error initializing the ID factory", ex, this); }
// ignore the exception - should get the in-memory id factory instead
}
}
public void setOrderRouteManager(MessageRouteManager inMgr)
{
routeMgr = inMgr;
}
public void setMessageModifiers(List<MessageModifier> mods){
messageModifiers = new LinkedList<MessageModifier>();
for (MessageModifier mod : mods) {
messageModifiers.add(mod);
}
messageModifiers.add(new TransactionTimeInsertMessageModifier());
}
/** Only supports NewOrderSingle, OrderCancelReplace and OrderCancel orders at this point
* Rejects orders that are of the wrong FIX version, or if the OMS is not logged on to a FIX destination.
* Runs the incoming orders through message modifiers, and forwards them on to a FIX destination.
* @param message Incoming message
* @return ExecutionReport for this message
* @throws MarketceteraException
*/
@SuppressWarnings({"ThrowableInstanceNeverThrown"})
public Message handleMessage(Message message) throws MarketceteraException {
if(message == null) {
LoggerAdapter.error(OMSMessageKey.ERROR_INCOMING_MSG_NULL.getLocalizedMessage(), this);
return null;
}
if(!qfApp.isLoggedOn()) {
return createRejectionMessage(new MarketceteraException(OMSMessageKey.ERROR_NO_DESTINATION_CONNECTION.getLocalizedMessage()),
message);
}
try {
String version = message.getHeader().getField(new BeginString()).getValue();
if(!msgFactory.getBeginString().equals(version)) {
return createRejectionMessage(new MarketceteraException(OMSMessageKey.ERROR_MISMATCHED_FIX_VERSION.getLocalizedMessage(
msgFactory.getBeginString(), version)), message);
}
} catch (FieldNotFound fieldNotFound) {
return createRejectionMessage(new MarketceteraException(OMSMessageKey.ERROR_MALFORMED_MESSAGE_NO_FIX_VERSION.getLocalizedMessage()),
message);
}
- Message returnVal = null;
+ Message returnExecReport = null;
try {
if(!(FIXMessageUtil.isOrderSingle(message) || FIXMessageUtil.isCancelRequest(message)
|| FIXMessageUtil.isCancelReplaceRequest(message))) {
throw new UnsupportedMessageType();
}
modifyOrder(message);
orderLimits.verifyOrderLimits(message);
routeMgr.modifyMessage(message, msgFactory.getMsgAugmentor());
// if single, pre-create an executionReport and send it back
if (FIXMessageUtil.isOrderSingle(message))
{
- Message outReport = executionReportFromNewOrder(message);
- if(LoggerAdapter.isDebugEnabled(this)) {
- LoggerAdapter.debug("Sending immediate execReport: "+outReport, this);
- }
- returnVal = outReport;
+ returnExecReport = executionReportFromNewOrder(message);
}
sendMessage(message);
+ if(returnExecReport != null && LoggerAdapter.isDebugEnabled(this)) {
+ LoggerAdapter.debug("Sending immediate execReport: "+returnExecReport, this);
+ }
} catch (FieldNotFound fnfEx) {
MarketceteraFIXException mfix = MarketceteraFIXException.createFieldNotFoundException(fnfEx);
- returnVal = createRejectionMessage(mfix, message);
+ returnExecReport = createRejectionMessage(mfix, message);
} catch(SessionNotFound snf) {
MarketceteraException ex = new MarketceteraException(MessageKey.SESSION_NOT_FOUND.getLocalizedMessage(defaultSessionID), snf);
- returnVal = createRejectionMessage(ex, message);
+ returnExecReport = createRejectionMessage(ex, message);
} catch(UnsupportedMessageType umt) {
try {
String msgType = message.getHeader().getString(MsgType.FIELD);
- returnVal = createBusinessMessageReject(msgType,
+ returnExecReport = createBusinessMessageReject(msgType,
OMSMessageKey.ERROR_UNSUPPORTED_ORDER_TYPE.getLocalizedMessage(
FIXDataDictionaryManager.getCurrentFIXDataDictionary().getHumanFieldValue(MsgType.FIELD, msgType)));
} catch (FieldNotFound fieldNotFound) {
- returnVal = createBusinessMessageReject("UNKNOWN", OMSMessageKey.ERROR_UNSUPPORTED_ORDER_TYPE.getLocalizedMessage("UNKNOWN"));
+ returnExecReport = createBusinessMessageReject("UNKNOWN", OMSMessageKey.ERROR_UNSUPPORTED_ORDER_TYPE.getLocalizedMessage("UNKNOWN"));
}
} catch (MarketceteraException e) {
- returnVal = createRejectionMessage(e, message);
+ returnExecReport = createRejectionMessage(e, message);
} catch(Exception ex) {
- returnVal = createRejectionMessage(ex, message);
+ returnExecReport = createRejectionMessage(ex, message);
}
- return returnVal;
+ return returnExecReport;
}
/** Sends the message to the destination
* @param message Message to send
* @throws SessionNotFound
*/
private void sendMessage(Message message) throws SessionNotFound {
if (defaultSessionID != null) {
quickFIXSender.sendToTarget(message, defaultSessionID);
} else {
quickFIXSender.sendToTarget(message);
}
}
/** Creates a rejection message
* If we are using a FIX4.2 or higher, we return a BusinessMessageReject,
* otherwise it's a session-level reject.
* @param msgType {@link MsgType} of the offending message
* @param rejReason Text string explaining the reason for rejection.
* @return rejection message
*/
protected Message createBusinessMessageReject(String msgType, String rejReason) {
Message reject;
if(FIXVersion.FIX40.toString().equals(msgFactory.getBeginString()) ||
FIXVersion.FIX41.toString().equals(msgFactory.getBeginString())) {
reject = msgFactory.createMessage(MsgType.REJECT);
reject.setField(new Text(rejReason));
} else {
reject = msgFactory.newBusinessMessageReject(msgType,
BusinessRejectReason.UNSUPPORTED_MESSAGE_TYPE, rejReason);
}
return reject;
}
/** Creates a rejection message based on the message that causes the rejection
* Currently, if it's an orderCancel then we send back an OrderCancelReject,
* otherwise we always send back the ExecutionReport.
* @param existingOrder
* @return Corresponding rejection Message
*/
protected Message createRejectionMessage(Exception causeEx, Message existingOrder)
{
Message rejection = null;
if(FIXMessageUtil.isCancelReplaceRequest(existingOrder) ||
FIXMessageUtil.isCancelRequest(existingOrder) )
{
rejection = msgFactory.newOrderCancelReject();
} else {
rejection = msgFactory.createMessage(MsgType.EXECUTION_REPORT);
rejection.setField(getNextExecId());
rejection.setField(new AvgPx(0));
rejection.setField(new CumQty(0));
rejection.setField(new LastShares(0));
rejection.setField(new LastPx(0));
rejection.setField(new ExecTransType(ExecTransType.STATUS));
}
rejection.setField(new OrdStatus(OrdStatus.REJECTED));
FIXMessageUtil.fillFieldsFromExistingMessage(rejection, existingOrder);
String msg = (causeEx.getMessage() == null) ? causeEx.toString() : causeEx.getMessage();
LoggerAdapter.error(OMSMessageKey.MESSAGE_EXCEPTION.getLocalizedMessage(msg, existingOrder), this);
if(LoggerAdapter.isDebugEnabled(this)) { LoggerAdapter.debug("Reason for above rejection: "+msg, causeEx, this); }
rejection.setString(Text.FIELD, msg);
// manually set the ClOrdID since it's not required in the dictionary but is for electronic orders
try {
rejection.setField(new ClOrdID(existingOrder.getString(ClOrdID.FIELD)));
} catch(FieldNotFound ignored) {
// don't set it if it's not there
}
try {
msgFactory.getMsgAugmentor().executionReportAugment(rejection);
} catch (FieldNotFound fieldNotFound) {
MarketceteraFIXException mfix = MarketceteraFIXException.createFieldNotFoundException(fieldNotFound);
if(LoggerAdapter.isDebugEnabled(this)) { LoggerAdapter.debug(mfix.getLocalizedMessage(), fieldNotFound, this); }
// ignore the exception since we are already sending a reject
}
rejection.getHeader().setField(new SendingTime());
return rejection;
}
protected Message executionReportFromNewOrder(Message newOrder) throws FieldNotFound {
if (FIXMessageUtil.isOrderSingle(newOrder)){
String clOrdId = newOrder.getString(ClOrdID.FIELD);
char side = newOrder.getChar(Side.FIELD);
String symbol = newOrder.getString(Symbol.FIELD);
BigDecimal orderQty = new BigDecimal(newOrder.getString(OrderQty.FIELD));
BigDecimal orderPrice = null;
try {
String strPrice = newOrder.getString(Price.FIELD);
orderPrice = new BigDecimal(strPrice);
} catch(FieldNotFound ex) {
// leave as null
}
String inAccount = null;
try {
inAccount = newOrder.getString(Account.FIELD);
} catch (FieldNotFound ex) {
// only set the Account field if it's there
}
Message execReport = msgFactory.newExecutionReport(
null,
clOrdId,
getNextExecId().getValue(),
OrdStatus.NEW,
side,
orderQty,
orderPrice,
BigDecimal.ZERO,
BigDecimal.ZERO,
BigDecimal.ZERO,
BigDecimal.ZERO,
new MSymbol(symbol),
inAccount);
execReport.getHeader().setField(new SendingTime());
FIXMessageUtil.fillFieldsFromExistingMessage(execReport, newOrder, false);
return execReport;
} else {
return null;
}
}
/** Apply all the order modifiers to this message */
protected void modifyOrder(Message inOrder) throws MarketceteraException
{
for (MessageModifier oneModifier : messageModifiers) {
oneModifier.modifyMessage(inOrder, msgFactory.getMsgAugmentor());
}
}
/** Sets the default session */
public void setDefaultSessionID(SessionID inSessionID)
{
defaultSessionID = inSessionID;
}
public SessionID getDefaultSessionID() {
return defaultSessionID;
}
public IQuickFIXSender getQuickFIXSender() {
return quickFIXSender;
}
public void setQuickFIXSender(IQuickFIXSender quickFIXSender) {
this.quickFIXSender = quickFIXSender;
}
protected IDFactory createDatabaseIDFactory(SessionSettings settings) throws ConfigError, FieldConvertError {
return new DatabaseIDFactory(settings.getString(JdbcSetting.SETTING_JDBC_CONNECTION_URL),
settings.getString(JdbcSetting.SETTING_JDBC_DRIVER), settings.getString(JdbcSetting.SETTING_JDBC_USER),
settings.getString(JdbcSetting.SETTING_JDBC_PASSWORD), DatabaseIDFactory.TABLE_NAME, DatabaseIDFactory.COL_NAME,
DatabaseIDFactory.NUM_IDS_GRABBED);
}
/** Returns the next ExecID from the factory, or a hardcoded ZZ-internal if we have
* problems creating an execID
* @return
*/
private ExecID getNextExecId() {
try {
return new ExecID(idFactory.getNext());
} catch(NoMoreIDsException ex) {
LoggerAdapter.error(OMSMessageKey.ERROR_GENERATING_EXEC_ID.getLocalizedMessage(ex.getMessage()), this);
return new ExecID("ZZ-INTERNAL");
}
}
}
| false | true | public Message handleMessage(Message message) throws MarketceteraException {
if(message == null) {
LoggerAdapter.error(OMSMessageKey.ERROR_INCOMING_MSG_NULL.getLocalizedMessage(), this);
return null;
}
if(!qfApp.isLoggedOn()) {
return createRejectionMessage(new MarketceteraException(OMSMessageKey.ERROR_NO_DESTINATION_CONNECTION.getLocalizedMessage()),
message);
}
try {
String version = message.getHeader().getField(new BeginString()).getValue();
if(!msgFactory.getBeginString().equals(version)) {
return createRejectionMessage(new MarketceteraException(OMSMessageKey.ERROR_MISMATCHED_FIX_VERSION.getLocalizedMessage(
msgFactory.getBeginString(), version)), message);
}
} catch (FieldNotFound fieldNotFound) {
return createRejectionMessage(new MarketceteraException(OMSMessageKey.ERROR_MALFORMED_MESSAGE_NO_FIX_VERSION.getLocalizedMessage()),
message);
}
Message returnVal = null;
try {
if(!(FIXMessageUtil.isOrderSingle(message) || FIXMessageUtil.isCancelRequest(message)
|| FIXMessageUtil.isCancelReplaceRequest(message))) {
throw new UnsupportedMessageType();
}
modifyOrder(message);
orderLimits.verifyOrderLimits(message);
routeMgr.modifyMessage(message, msgFactory.getMsgAugmentor());
// if single, pre-create an executionReport and send it back
if (FIXMessageUtil.isOrderSingle(message))
{
Message outReport = executionReportFromNewOrder(message);
if(LoggerAdapter.isDebugEnabled(this)) {
LoggerAdapter.debug("Sending immediate execReport: "+outReport, this);
}
returnVal = outReport;
}
sendMessage(message);
} catch (FieldNotFound fnfEx) {
MarketceteraFIXException mfix = MarketceteraFIXException.createFieldNotFoundException(fnfEx);
returnVal = createRejectionMessage(mfix, message);
} catch(SessionNotFound snf) {
MarketceteraException ex = new MarketceteraException(MessageKey.SESSION_NOT_FOUND.getLocalizedMessage(defaultSessionID), snf);
returnVal = createRejectionMessage(ex, message);
} catch(UnsupportedMessageType umt) {
try {
String msgType = message.getHeader().getString(MsgType.FIELD);
returnVal = createBusinessMessageReject(msgType,
OMSMessageKey.ERROR_UNSUPPORTED_ORDER_TYPE.getLocalizedMessage(
FIXDataDictionaryManager.getCurrentFIXDataDictionary().getHumanFieldValue(MsgType.FIELD, msgType)));
} catch (FieldNotFound fieldNotFound) {
returnVal = createBusinessMessageReject("UNKNOWN", OMSMessageKey.ERROR_UNSUPPORTED_ORDER_TYPE.getLocalizedMessage("UNKNOWN"));
}
} catch (MarketceteraException e) {
returnVal = createRejectionMessage(e, message);
} catch(Exception ex) {
returnVal = createRejectionMessage(ex, message);
}
return returnVal;
}
| public Message handleMessage(Message message) throws MarketceteraException {
if(message == null) {
LoggerAdapter.error(OMSMessageKey.ERROR_INCOMING_MSG_NULL.getLocalizedMessage(), this);
return null;
}
if(!qfApp.isLoggedOn()) {
return createRejectionMessage(new MarketceteraException(OMSMessageKey.ERROR_NO_DESTINATION_CONNECTION.getLocalizedMessage()),
message);
}
try {
String version = message.getHeader().getField(new BeginString()).getValue();
if(!msgFactory.getBeginString().equals(version)) {
return createRejectionMessage(new MarketceteraException(OMSMessageKey.ERROR_MISMATCHED_FIX_VERSION.getLocalizedMessage(
msgFactory.getBeginString(), version)), message);
}
} catch (FieldNotFound fieldNotFound) {
return createRejectionMessage(new MarketceteraException(OMSMessageKey.ERROR_MALFORMED_MESSAGE_NO_FIX_VERSION.getLocalizedMessage()),
message);
}
Message returnExecReport = null;
try {
if(!(FIXMessageUtil.isOrderSingle(message) || FIXMessageUtil.isCancelRequest(message)
|| FIXMessageUtil.isCancelReplaceRequest(message))) {
throw new UnsupportedMessageType();
}
modifyOrder(message);
orderLimits.verifyOrderLimits(message);
routeMgr.modifyMessage(message, msgFactory.getMsgAugmentor());
// if single, pre-create an executionReport and send it back
if (FIXMessageUtil.isOrderSingle(message))
{
returnExecReport = executionReportFromNewOrder(message);
}
sendMessage(message);
if(returnExecReport != null && LoggerAdapter.isDebugEnabled(this)) {
LoggerAdapter.debug("Sending immediate execReport: "+returnExecReport, this);
}
} catch (FieldNotFound fnfEx) {
MarketceteraFIXException mfix = MarketceteraFIXException.createFieldNotFoundException(fnfEx);
returnExecReport = createRejectionMessage(mfix, message);
} catch(SessionNotFound snf) {
MarketceteraException ex = new MarketceteraException(MessageKey.SESSION_NOT_FOUND.getLocalizedMessage(defaultSessionID), snf);
returnExecReport = createRejectionMessage(ex, message);
} catch(UnsupportedMessageType umt) {
try {
String msgType = message.getHeader().getString(MsgType.FIELD);
returnExecReport = createBusinessMessageReject(msgType,
OMSMessageKey.ERROR_UNSUPPORTED_ORDER_TYPE.getLocalizedMessage(
FIXDataDictionaryManager.getCurrentFIXDataDictionary().getHumanFieldValue(MsgType.FIELD, msgType)));
} catch (FieldNotFound fieldNotFound) {
returnExecReport = createBusinessMessageReject("UNKNOWN", OMSMessageKey.ERROR_UNSUPPORTED_ORDER_TYPE.getLocalizedMessage("UNKNOWN"));
}
} catch (MarketceteraException e) {
returnExecReport = createRejectionMessage(e, message);
} catch(Exception ex) {
returnExecReport = createRejectionMessage(ex, message);
}
return returnExecReport;
}
|
diff --git a/spring/src/main/java/com/techempower/spring/web/HelloController.java b/spring/src/main/java/com/techempower/spring/web/HelloController.java
index 7b1d8acae..80e59a8c7 100644
--- a/spring/src/main/java/com/techempower/spring/web/HelloController.java
+++ b/spring/src/main/java/com/techempower/spring/web/HelloController.java
@@ -1,33 +1,33 @@
package com.techempower.spring.web;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
final class HelloController {
@RequestMapping(value = "/json", produces = "application/json")
Message json() {
- return new Message("Hello, world");
+ return new Message("Hello, World!");
}
@RequestMapping(value = "/plaintext", produces = "text/plain")
String plaintext() {
return "Hello, World!";
}
public static final class Message {
private final String message;
private Message(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
}
}
| true | true | Message json() {
return new Message("Hello, world");
}
| Message json() {
return new Message("Hello, World!");
}
|
diff --git a/src/main/java/com/oschrenk/humangeo/calc/AlongTrackOrthodromeDistance.java b/src/main/java/com/oschrenk/humangeo/calc/AlongTrackOrthodromeDistance.java
index 4bfb206..0a50708 100644
--- a/src/main/java/com/oschrenk/humangeo/calc/AlongTrackOrthodromeDistance.java
+++ b/src/main/java/com/oschrenk/humangeo/calc/AlongTrackOrthodromeDistance.java
@@ -1,60 +1,60 @@
/*
* Adapted from <a
* href="http://www.movable-type.co.uk/scripts/latlong.html">JavaScript
* version</a> created by <a href="http://www.movable-type.co.uk/">Chris
* Veness<a/> under the <a
* href="http://creativecommons.org/licenses/by/3.0/">Create Commons Attribution
* 3.0</a> licencse.
*/
package com.oschrenk.humangeo.calc;
import com.oschrenk.humangeo.api.Distance;
import com.oschrenk.humangeo.core.Segment;
import com.oschrenk.humangeo.core.Sphere;
import com.oschrenk.humangeo.cs.Geographic2dCoordinate;
/**
* The along-track distance, is the distance from the start point to the closest
* point on the path to the third point along a great-circle path.
*
* @author Oliver Schrenk <[email protected]>
*/
public class AlongTrackOrthodromeDistance implements
Distance<Geographic2dCoordinate, Segment<Geographic2dCoordinate>> {
private final Sphere sphere;
public AlongTrackOrthodromeDistance(final Sphere sphere) {
super();
this.sphere = sphere;
}
/*
* @see com.oschrenk.humangeo.api.Distance#distance(java.lang.Object,
* java.lang.Object)
*/
@Override
public double distance(final Geographic2dCoordinate point,
final Segment<Geographic2dCoordinate> segment) {
// dAt = Math.acos(Math.cos(d13/r)/Math.cos(dXt/r)) * r;
final double r = sphere.getRadius();
final double d13 = new HaversineDistance(sphere).distance(
segment.getFrom(), point);
final double dXt = new CrossTrackOrthodromeDistance(sphere).distance(
point, segment);
// @formatter:off
final double dAt = //
Math.acos( //
- Math.cos(Math.toRadians(d13 / r)) //
+ Math.cos(d13 / r) //
/ //
- Math.cos(Math.toRadians(dXt) / r) //
+ Math.cos(dXt / r) //
) //
* r;
// @formatter:on
return dAt;
}
}
| false | true | public double distance(final Geographic2dCoordinate point,
final Segment<Geographic2dCoordinate> segment) {
// dAt = Math.acos(Math.cos(d13/r)/Math.cos(dXt/r)) * r;
final double r = sphere.getRadius();
final double d13 = new HaversineDistance(sphere).distance(
segment.getFrom(), point);
final double dXt = new CrossTrackOrthodromeDistance(sphere).distance(
point, segment);
// @formatter:off
final double dAt = //
Math.acos( //
Math.cos(Math.toRadians(d13 / r)) //
/ //
Math.cos(Math.toRadians(dXt) / r) //
) //
* r;
// @formatter:on
return dAt;
}
| public double distance(final Geographic2dCoordinate point,
final Segment<Geographic2dCoordinate> segment) {
// dAt = Math.acos(Math.cos(d13/r)/Math.cos(dXt/r)) * r;
final double r = sphere.getRadius();
final double d13 = new HaversineDistance(sphere).distance(
segment.getFrom(), point);
final double dXt = new CrossTrackOrthodromeDistance(sphere).distance(
point, segment);
// @formatter:off
final double dAt = //
Math.acos( //
Math.cos(d13 / r) //
/ //
Math.cos(dXt / r) //
) //
* r;
// @formatter:on
return dAt;
}
|
diff --git a/src/FE_SRC_COMMON/com/ForgeEssentials/core/compat/SanityChecker.java b/src/FE_SRC_COMMON/com/ForgeEssentials/core/compat/SanityChecker.java
index c287158df..cc4868aa9 100644
--- a/src/FE_SRC_COMMON/com/ForgeEssentials/core/compat/SanityChecker.java
+++ b/src/FE_SRC_COMMON/com/ForgeEssentials/core/compat/SanityChecker.java
@@ -1,48 +1,48 @@
package com.ForgeEssentials.core.compat;
import com.ForgeEssentials.core.ForgeEssentials;
import com.ForgeEssentials.util.OutputHandler;
import cpw.mods.fml.common.Loader;
public class SanityChecker
{
public void run()
{
- if (ForgeEssentials.sanitycheck = false)
+ if (!ForgeEssentials.sanitycheck)
{
OutputHandler.severe("Sanity checking has been disabled. Do not bug the FE team with issues running FE on a bukkit server, or with any other server mod.");
return;
}
// Check for BukkitForge
if (Loader.isModLoaded("BukkitForge"))
{
OutputHandler.severe("Sanity check failed: Detected BukkitForge, bad things may happen, proceed at your own risk.");
}
// Check for Fihgu's mods
else if (Loader.isModLoaded("fihgu's Core Mod"))
{
OutputHandler.severe("Sanity check failed: Detected Fihgu's mods, stopping server for your safety.");
//throw new RuntimeException("ForgeEssentials: Please DO NOT use FE with Fihgu's mods, bad things WILL happen. Trust us. You were warned,");
}
else
{
// Check for MCPC+ or LavaBukkit
try
{
Class.forName("org.bukkit.craftbukkit.Main", false, getClass().getClassLoader());
OutputHandler.severe("Sanity check failed: Detected a ForgeBukkit server implementation, bad things may happen, proceed at your own risk.");
}
catch (ClassNotFoundException e)
{
// Safe!
}
}
OutputHandler.fine("Sanity check passed, it's all good to go!");
}
}
| true | true | public void run()
{
if (ForgeEssentials.sanitycheck = false)
{
OutputHandler.severe("Sanity checking has been disabled. Do not bug the FE team with issues running FE on a bukkit server, or with any other server mod.");
return;
}
// Check for BukkitForge
if (Loader.isModLoaded("BukkitForge"))
{
OutputHandler.severe("Sanity check failed: Detected BukkitForge, bad things may happen, proceed at your own risk.");
}
// Check for Fihgu's mods
else if (Loader.isModLoaded("fihgu's Core Mod"))
{
OutputHandler.severe("Sanity check failed: Detected Fihgu's mods, stopping server for your safety.");
//throw new RuntimeException("ForgeEssentials: Please DO NOT use FE with Fihgu's mods, bad things WILL happen. Trust us. You were warned,");
}
else
{
// Check for MCPC+ or LavaBukkit
try
{
Class.forName("org.bukkit.craftbukkit.Main", false, getClass().getClassLoader());
OutputHandler.severe("Sanity check failed: Detected a ForgeBukkit server implementation, bad things may happen, proceed at your own risk.");
}
catch (ClassNotFoundException e)
{
// Safe!
}
}
OutputHandler.fine("Sanity check passed, it's all good to go!");
}
| public void run()
{
if (!ForgeEssentials.sanitycheck)
{
OutputHandler.severe("Sanity checking has been disabled. Do not bug the FE team with issues running FE on a bukkit server, or with any other server mod.");
return;
}
// Check for BukkitForge
if (Loader.isModLoaded("BukkitForge"))
{
OutputHandler.severe("Sanity check failed: Detected BukkitForge, bad things may happen, proceed at your own risk.");
}
// Check for Fihgu's mods
else if (Loader.isModLoaded("fihgu's Core Mod"))
{
OutputHandler.severe("Sanity check failed: Detected Fihgu's mods, stopping server for your safety.");
//throw new RuntimeException("ForgeEssentials: Please DO NOT use FE with Fihgu's mods, bad things WILL happen. Trust us. You were warned,");
}
else
{
// Check for MCPC+ or LavaBukkit
try
{
Class.forName("org.bukkit.craftbukkit.Main", false, getClass().getClassLoader());
OutputHandler.severe("Sanity check failed: Detected a ForgeBukkit server implementation, bad things may happen, proceed at your own risk.");
}
catch (ClassNotFoundException e)
{
// Safe!
}
}
OutputHandler.fine("Sanity check passed, it's all good to go!");
}
|
diff --git a/h2/src/main/org/h2/bnf/context/DbColumn.java b/h2/src/main/org/h2/bnf/context/DbColumn.java
index 63f67a944..91242e551 100644
--- a/h2/src/main/org/h2/bnf/context/DbColumn.java
+++ b/h2/src/main/org/h2/bnf/context/DbColumn.java
@@ -1,85 +1,85 @@
/*
* Copyright 2004-2013 H2 Group. Multiple-Licensed under the H2 License,
* Version 1.0, and under the Eclipse Public License, Version 1.0
* (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.bnf.context;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* Keeps the meta data information of a column.
* This class is used by the H2 Console.
*/
public class DbColumn {
private final String name;
private final String quotedName;
private final String dataType;
private int position;
- public DbColumn(DbContents contents, ResultSet rs, boolean prodecureColumn) throws SQLException {
+ public DbColumn(DbContents contents, ResultSet rs, boolean procedureColumn) throws SQLException {
name = rs.getString("COLUMN_NAME");
quotedName = contents.quoteIdentifier(name);
String type = rs.getString("TYPE_NAME");
// a procedures column size is identified by PRECISION, for table this
// is COLUMN_SIZE
String columnSizeName;
- if (prodecureColumn) {
+ if (procedureColumn) {
columnSizeName = "PRECISION";
} else {
columnSizeName = "COLUMN_SIZE";
}
int size = rs.getInt(columnSizeName);
position = rs.getInt("ORDINAL_POSITION");
boolean isSQLite = contents.isSQLite();
if (size > 0 && !isSQLite) {
type += "(" + size;
int prec = rs.getInt("DECIMAL_DIGITS");
if (prec > 0) {
type += ", " + prec;
}
type += ")";
}
if (rs.getInt("NULLABLE") == DatabaseMetaData.columnNoNulls) {
type += " NOT NULL";
}
dataType = type;
}
/**
* @return The data type name (including precision and the NOT NULL flag if
* applicable).
*/
public String getDataType() {
return dataType;
}
/**
* @return The column name.
*/
public String getName() {
return name;
}
/**
* @return The quoted table name.
*/
public String getQuotedName() {
return quotedName;
}
/**
* @return Column index
*/
public int getPosition() {
return position;
}
}
| false | true | public DbColumn(DbContents contents, ResultSet rs, boolean prodecureColumn) throws SQLException {
name = rs.getString("COLUMN_NAME");
quotedName = contents.quoteIdentifier(name);
String type = rs.getString("TYPE_NAME");
// a procedures column size is identified by PRECISION, for table this
// is COLUMN_SIZE
String columnSizeName;
if (prodecureColumn) {
columnSizeName = "PRECISION";
} else {
columnSizeName = "COLUMN_SIZE";
}
int size = rs.getInt(columnSizeName);
position = rs.getInt("ORDINAL_POSITION");
boolean isSQLite = contents.isSQLite();
if (size > 0 && !isSQLite) {
type += "(" + size;
int prec = rs.getInt("DECIMAL_DIGITS");
if (prec > 0) {
type += ", " + prec;
}
type += ")";
}
if (rs.getInt("NULLABLE") == DatabaseMetaData.columnNoNulls) {
type += " NOT NULL";
}
dataType = type;
}
| public DbColumn(DbContents contents, ResultSet rs, boolean procedureColumn) throws SQLException {
name = rs.getString("COLUMN_NAME");
quotedName = contents.quoteIdentifier(name);
String type = rs.getString("TYPE_NAME");
// a procedures column size is identified by PRECISION, for table this
// is COLUMN_SIZE
String columnSizeName;
if (procedureColumn) {
columnSizeName = "PRECISION";
} else {
columnSizeName = "COLUMN_SIZE";
}
int size = rs.getInt(columnSizeName);
position = rs.getInt("ORDINAL_POSITION");
boolean isSQLite = contents.isSQLite();
if (size > 0 && !isSQLite) {
type += "(" + size;
int prec = rs.getInt("DECIMAL_DIGITS");
if (prec > 0) {
type += ", " + prec;
}
type += ")";
}
if (rs.getInt("NULLABLE") == DatabaseMetaData.columnNoNulls) {
type += " NOT NULL";
}
dataType = type;
}
|
diff --git a/demos/helloworld/gdx-helloworld-android/src/com/badlogic/gdx/GDXHelloWorld.java b/demos/helloworld/gdx-helloworld-android/src/com/badlogic/gdx/GDXHelloWorld.java
index a8585fce9..22db35586 100644
--- a/demos/helloworld/gdx-helloworld-android/src/com/badlogic/gdx/GDXHelloWorld.java
+++ b/demos/helloworld/gdx-helloworld-android/src/com/badlogic/gdx/GDXHelloWorld.java
@@ -1,27 +1,26 @@
/*******************************************************************************
* Copyright 2010 Mario Zechner ([email protected])
*
* 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;
import android.os.Bundle;
import com.badlogic.gdx.backends.android.AndroidApplication;
import com.badlogic.gdx.helloworld.HelloWorld;
public class GDXHelloWorld extends AndroidApplication {
@Override public void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
- initialize(false);
- getGraphics().setRenderListener(new HelloWorld());
+ initialize(new HelloWorld(), false);
}
}
| true | true | @Override public void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initialize(false);
getGraphics().setRenderListener(new HelloWorld());
}
| @Override public void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initialize(new HelloWorld(), false);
}
|
diff --git a/web/src/main/java/org/eurekastreams/web/client/model/requests/PersonPagePropertiesDTOToPersonTransformer.java b/web/src/main/java/org/eurekastreams/web/client/model/requests/PersonPagePropertiesDTOToPersonTransformer.java
index 2ec1c4930..fa6aa85a5 100644
--- a/web/src/main/java/org/eurekastreams/web/client/model/requests/PersonPagePropertiesDTOToPersonTransformer.java
+++ b/web/src/main/java/org/eurekastreams/web/client/model/requests/PersonPagePropertiesDTOToPersonTransformer.java
@@ -1,76 +1,83 @@
/*
* Copyright (c) 2010 Lockheed Martin Corporation
*
* 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.eurekastreams.web.client.model.requests;
import java.util.ArrayList;
import java.util.List;
import org.eurekastreams.server.domain.Gadget;
import org.eurekastreams.server.domain.GadgetDefinition;
import org.eurekastreams.server.domain.Person;
import org.eurekastreams.server.domain.Tab;
import org.eurekastreams.server.domain.TabGroup;
import org.eurekastreams.server.domain.Theme;
import org.eurekastreams.server.search.modelview.GadgetDTO;
import org.eurekastreams.server.search.modelview.PersonPagePropertiesDTO;
import org.eurekastreams.server.search.modelview.TabDTO;
/**
* DTO to Person transformer. Temporary solution until we refactor.
*
*/
public class PersonPagePropertiesDTOToPersonTransformer
{
/**
* Transform a PersonPagePropertiesDTO to a Person object.
*
* @param dto
* the dto.
* @return the person.
*/
public Person transform(final PersonPagePropertiesDTO dto)
{
Person person = new Person();
- person.setTheme(new Theme("", "", "", dto.getThemeCssFile(), "", "", "", ""));
+ if (dto.getThemeCssFile() == null)
+ {
+ person.setTheme(null);
+ }
+ else
+ {
+ person.setTheme(new Theme("", "", "", dto.getThemeCssFile(), "", "", "", ""));
+ }
TabGroup startTabGroup = new TabGroup();
for (TabDTO tabDTO : dto.getTabDTOs())
{
Tab tab = new Tab(tabDTO.getTabName(), tabDTO.getTabLayout(), tabDTO.getId());
tab.setTabIndex(tabDTO.getTabIndex());
List<Gadget> gadgets = new ArrayList<Gadget>();
for (GadgetDTO gadgetDTO : tabDTO.getGadgets())
{
GadgetDefinition gadgetDef = new GadgetDefinition(gadgetDTO.getGadgetDefinition().getUrl(), gadgetDTO
.getGadgetDefinition().getUuid());
gadgetDef.setId(gadgetDTO.getGadgetDefinition().getId());
Gadget gadget = new Gadget(gadgetDef, gadgetDTO.getZoneNumber(), gadgetDTO.getZoneIndex(), null,
gadgetDTO.getGadgetUserPref());
gadget.setId(gadgetDTO.getId());
gadgets.add(gadget);
}
tab.setGadgets(gadgets);
startTabGroup.addTab(tab);
}
person.setStartTabGroup(startTabGroup);
return person;
}
}
| true | true | public Person transform(final PersonPagePropertiesDTO dto)
{
Person person = new Person();
person.setTheme(new Theme("", "", "", dto.getThemeCssFile(), "", "", "", ""));
TabGroup startTabGroup = new TabGroup();
for (TabDTO tabDTO : dto.getTabDTOs())
{
Tab tab = new Tab(tabDTO.getTabName(), tabDTO.getTabLayout(), tabDTO.getId());
tab.setTabIndex(tabDTO.getTabIndex());
List<Gadget> gadgets = new ArrayList<Gadget>();
for (GadgetDTO gadgetDTO : tabDTO.getGadgets())
{
GadgetDefinition gadgetDef = new GadgetDefinition(gadgetDTO.getGadgetDefinition().getUrl(), gadgetDTO
.getGadgetDefinition().getUuid());
gadgetDef.setId(gadgetDTO.getGadgetDefinition().getId());
Gadget gadget = new Gadget(gadgetDef, gadgetDTO.getZoneNumber(), gadgetDTO.getZoneIndex(), null,
gadgetDTO.getGadgetUserPref());
gadget.setId(gadgetDTO.getId());
gadgets.add(gadget);
}
tab.setGadgets(gadgets);
startTabGroup.addTab(tab);
}
person.setStartTabGroup(startTabGroup);
return person;
}
| public Person transform(final PersonPagePropertiesDTO dto)
{
Person person = new Person();
if (dto.getThemeCssFile() == null)
{
person.setTheme(null);
}
else
{
person.setTheme(new Theme("", "", "", dto.getThemeCssFile(), "", "", "", ""));
}
TabGroup startTabGroup = new TabGroup();
for (TabDTO tabDTO : dto.getTabDTOs())
{
Tab tab = new Tab(tabDTO.getTabName(), tabDTO.getTabLayout(), tabDTO.getId());
tab.setTabIndex(tabDTO.getTabIndex());
List<Gadget> gadgets = new ArrayList<Gadget>();
for (GadgetDTO gadgetDTO : tabDTO.getGadgets())
{
GadgetDefinition gadgetDef = new GadgetDefinition(gadgetDTO.getGadgetDefinition().getUrl(), gadgetDTO
.getGadgetDefinition().getUuid());
gadgetDef.setId(gadgetDTO.getGadgetDefinition().getId());
Gadget gadget = new Gadget(gadgetDef, gadgetDTO.getZoneNumber(), gadgetDTO.getZoneIndex(), null,
gadgetDTO.getGadgetUserPref());
gadget.setId(gadgetDTO.getId());
gadgets.add(gadget);
}
tab.setGadgets(gadgets);
startTabGroup.addTab(tab);
}
person.setStartTabGroup(startTabGroup);
return person;
}
|
diff --git a/src/com/massivecraft/mcore/ps/PSFormatAbstract.java b/src/com/massivecraft/mcore/ps/PSFormatAbstract.java
index 2ed855a8..66e477a1 100644
--- a/src/com/massivecraft/mcore/ps/PSFormatAbstract.java
+++ b/src/com/massivecraft/mcore/ps/PSFormatAbstract.java
@@ -1,152 +1,148 @@
package com.massivecraft.mcore.ps;
import java.util.ArrayList;
import java.util.List;
import com.massivecraft.mcore.mixin.Mixin;
import com.massivecraft.mcore.util.Txt;
public class PSFormatAbstract implements PSFormat
{
// -------------------------------------------- //
// FIELDS
// -------------------------------------------- //
private final String strNull;
private final String strStart;
private final boolean useWorldDisplayname;
private final boolean useWorldAlias;
private final String formatWorld;
private final String formatBlockX;
private final String formatBlockY;
private final String formatBlockZ;
private final String formatLocationX;
private final String formatLocationY;
private final String formatLocationZ;
private final String formatChunkX;
private final String formatChunkZ;
private final String formatPitch;
private final String formatYaw;
private final String formatVelocityX;
private final String formatVelocityY;
private final String formatVelocityZ;
private final String strGlue;
private final String strStop;
// -------------------------------------------- //
// CONSTRUCT
// -------------------------------------------- //
public PSFormatAbstract(String strNull, String strStart, boolean useWorldDisplayname, boolean useWorldAlias, String formatWorld, String formatBlockX, String formatBlockY, String formatBlockZ, String formatLocationX, String formatLocationY, String formatLocationZ, String formatChunkX, String formatChunkZ, String formatPitch, String formatYaw, String formatVelocityX, String formatVelocityY, String formatVelocityZ, String strGlue, String strStop)
{
this.strNull = strNull;
this.strStart = strStart;
this.useWorldDisplayname = useWorldDisplayname;
this.useWorldAlias = useWorldAlias;
this.formatWorld = formatWorld;
this.formatBlockX = formatBlockX;
this.formatBlockY = formatBlockY;
this.formatBlockZ = formatBlockZ;
this.formatLocationX = formatLocationX;
this.formatLocationY = formatLocationY;
this.formatLocationZ = formatLocationZ;
this.formatChunkX = formatChunkX;
this.formatChunkZ = formatChunkZ;
this.formatPitch = formatPitch;
this.formatYaw = formatYaw;
this.formatVelocityX = formatVelocityX;
this.formatVelocityY = formatVelocityY;
this.formatVelocityZ = formatVelocityZ;
this.strGlue = strGlue;
this.strStop = strStop;
}
// -------------------------------------------- //
// OVERRIDE
// -------------------------------------------- //
@Override
public String format(PS ps)
{
if (ps == null) return this.strNull;
List<String> entries = this.formatEntries(ps);
return this.strStart + Txt.implode(entries, this.strGlue) + this.strStop;
}
// -------------------------------------------- //
// UTIL
// -------------------------------------------- //
public List<String> formatEntries(PS ps)
{
List<String> ret = new ArrayList<String>();
Object val = null;
- if (this.useWorldDisplayname)
+ val = ps.getWorld();
+ if (val != null)
{
- val = ps.getWorld();
- val = Mixin.getWorldDisplayName(val.toString());
- if (val != null) ret.add(String.format(this.formatWorld, val));
- }
- else if (this.useWorldAlias)
- {
- val = ps.getWorld();
- val = Mixin.getWorldAliasOrId(val.toString());
- if (val != null) ret.add(String.format(this.formatWorld, val));
- }
- else
- {
- val = ps.getWorld();
- if (val != null) ret.add(String.format(this.formatWorld, val));
+ if (this.useWorldDisplayname)
+ {
+ val = Mixin.getWorldDisplayName(val.toString());
+ }
+ else if (this.useWorldAlias)
+ {
+ val = Mixin.getWorldAliasOrId(val.toString());
+ }
+ ret.add(String.format(this.formatWorld, val));
}
val = ps.getBlockX();
if (val != null) ret.add(String.format(this.formatBlockX, val));
val = ps.getBlockY();
if (val != null) ret.add(String.format(this.formatBlockY, val));
val = ps.getBlockZ();
if (val != null) ret.add(String.format(this.formatBlockZ, val));
val = ps.getLocationX();
if (val != null) ret.add(String.format(this.formatLocationX, val));
val = ps.getLocationY();
if (val != null) ret.add(String.format(this.formatLocationY, val));
val = ps.getLocationZ();
if (val != null) ret.add(String.format(this.formatLocationZ, val));
val = ps.getChunkX();
if (val != null) ret.add(String.format(this.formatChunkX, val));
val = ps.getChunkZ();
if (val != null) ret.add(String.format(this.formatChunkZ, val));
val = ps.getPitch();
if (val != null) ret.add(String.format(this.formatPitch, val));
val = ps.getYaw();
if (val != null) ret.add(String.format(this.formatYaw, val));
val = ps.getVelocityX();
if (val != null) ret.add(String.format(this.formatVelocityX, val));
val = ps.getVelocityY();
if (val != null) ret.add(String.format(this.formatVelocityY, val));
val = ps.getVelocityZ();
if (val != null) ret.add(String.format(this.formatVelocityZ, val));
return ret;
}
}
| false | true | public List<String> formatEntries(PS ps)
{
List<String> ret = new ArrayList<String>();
Object val = null;
if (this.useWorldDisplayname)
{
val = ps.getWorld();
val = Mixin.getWorldDisplayName(val.toString());
if (val != null) ret.add(String.format(this.formatWorld, val));
}
else if (this.useWorldAlias)
{
val = ps.getWorld();
val = Mixin.getWorldAliasOrId(val.toString());
if (val != null) ret.add(String.format(this.formatWorld, val));
}
else
{
val = ps.getWorld();
if (val != null) ret.add(String.format(this.formatWorld, val));
}
val = ps.getBlockX();
if (val != null) ret.add(String.format(this.formatBlockX, val));
val = ps.getBlockY();
if (val != null) ret.add(String.format(this.formatBlockY, val));
val = ps.getBlockZ();
if (val != null) ret.add(String.format(this.formatBlockZ, val));
val = ps.getLocationX();
if (val != null) ret.add(String.format(this.formatLocationX, val));
val = ps.getLocationY();
if (val != null) ret.add(String.format(this.formatLocationY, val));
val = ps.getLocationZ();
if (val != null) ret.add(String.format(this.formatLocationZ, val));
val = ps.getChunkX();
if (val != null) ret.add(String.format(this.formatChunkX, val));
val = ps.getChunkZ();
if (val != null) ret.add(String.format(this.formatChunkZ, val));
val = ps.getPitch();
if (val != null) ret.add(String.format(this.formatPitch, val));
val = ps.getYaw();
if (val != null) ret.add(String.format(this.formatYaw, val));
val = ps.getVelocityX();
if (val != null) ret.add(String.format(this.formatVelocityX, val));
val = ps.getVelocityY();
if (val != null) ret.add(String.format(this.formatVelocityY, val));
val = ps.getVelocityZ();
if (val != null) ret.add(String.format(this.formatVelocityZ, val));
return ret;
}
| public List<String> formatEntries(PS ps)
{
List<String> ret = new ArrayList<String>();
Object val = null;
val = ps.getWorld();
if (val != null)
{
if (this.useWorldDisplayname)
{
val = Mixin.getWorldDisplayName(val.toString());
}
else if (this.useWorldAlias)
{
val = Mixin.getWorldAliasOrId(val.toString());
}
ret.add(String.format(this.formatWorld, val));
}
val = ps.getBlockX();
if (val != null) ret.add(String.format(this.formatBlockX, val));
val = ps.getBlockY();
if (val != null) ret.add(String.format(this.formatBlockY, val));
val = ps.getBlockZ();
if (val != null) ret.add(String.format(this.formatBlockZ, val));
val = ps.getLocationX();
if (val != null) ret.add(String.format(this.formatLocationX, val));
val = ps.getLocationY();
if (val != null) ret.add(String.format(this.formatLocationY, val));
val = ps.getLocationZ();
if (val != null) ret.add(String.format(this.formatLocationZ, val));
val = ps.getChunkX();
if (val != null) ret.add(String.format(this.formatChunkX, val));
val = ps.getChunkZ();
if (val != null) ret.add(String.format(this.formatChunkZ, val));
val = ps.getPitch();
if (val != null) ret.add(String.format(this.formatPitch, val));
val = ps.getYaw();
if (val != null) ret.add(String.format(this.formatYaw, val));
val = ps.getVelocityX();
if (val != null) ret.add(String.format(this.formatVelocityX, val));
val = ps.getVelocityY();
if (val != null) ret.add(String.format(this.formatVelocityY, val));
val = ps.getVelocityZ();
if (val != null) ret.add(String.format(this.formatVelocityZ, val));
return ret;
}
|
diff --git a/src/org/bouncycastle/asn1/DERVisibleString.java b/src/org/bouncycastle/asn1/DERVisibleString.java
index 13a3aadd..1c385b7a 100644
--- a/src/org/bouncycastle/asn1/DERVisibleString.java
+++ b/src/org/bouncycastle/asn1/DERVisibleString.java
@@ -1,123 +1,123 @@
package org.bouncycastle.asn1;
import java.io.IOException;
import org.bouncycastle.util.Arrays;
import org.bouncycastle.util.Strings;
/**
* DER VisibleString object.
*/
public class DERVisibleString
extends ASN1Primitive
implements ASN1String
{
private byte[] string;
/**
* return a Visible String from the passed in object.
*
* @exception IllegalArgumentException if the object cannot be converted.
*/
public static DERVisibleString getInstance(
Object obj)
{
if (obj == null || obj instanceof DERVisibleString)
{
return (DERVisibleString)obj;
}
throw new IllegalArgumentException("illegal object in getInstance: " + obj.getClass().getName());
}
/**
* return a Visible String from a tagged object.
*
* @param obj the tagged object holding the object we want
* @param explicit true if the object is meant to be explicitly
* tagged false otherwise.
* @exception IllegalArgumentException if the tagged object cannot
* be converted.
*/
public static DERVisibleString getInstance(
ASN1TaggedObject obj,
boolean explicit)
{
ASN1Primitive o = obj.getObject();
- if (explicit || o instanceof DERUTF8String)
+ if (explicit || o instanceof DERVisibleString)
{
return getInstance(o);
}
else
{
return new DERVisibleString(ASN1OctetString.getInstance(o).getOctets());
}
}
/**
* basic constructor - byte encoded string.
*/
DERVisibleString(
byte[] string)
{
this.string = string;
}
/**
* basic constructor
*/
public DERVisibleString(
String string)
{
this.string = Strings.toByteArray(string);
}
public String getString()
{
return Strings.fromByteArray(string);
}
public String toString()
{
return getString();
}
public byte[] getOctets()
{
return Arrays.clone(string);
}
boolean isConstructed()
{
return false;
}
int encodedLength()
{
return 1 + StreamUtil.calculateBodyLength(string.length) + string.length;
}
void encode(
ASN1OutputStream out)
throws IOException
{
out.writeEncoded(BERTags.VISIBLE_STRING, this.string);
}
boolean asn1Equals(
ASN1Primitive o)
{
if (!(o instanceof DERVisibleString))
{
return false;
}
return Arrays.areEqual(string, ((DERVisibleString)o).string);
}
public int hashCode()
{
return Arrays.hashCode(string);
}
}
| true | true | public static DERVisibleString getInstance(
ASN1TaggedObject obj,
boolean explicit)
{
ASN1Primitive o = obj.getObject();
if (explicit || o instanceof DERUTF8String)
{
return getInstance(o);
}
else
{
return new DERVisibleString(ASN1OctetString.getInstance(o).getOctets());
}
}
| public static DERVisibleString getInstance(
ASN1TaggedObject obj,
boolean explicit)
{
ASN1Primitive o = obj.getObject();
if (explicit || o instanceof DERVisibleString)
{
return getInstance(o);
}
else
{
return new DERVisibleString(ASN1OctetString.getInstance(o).getOctets());
}
}
|
diff --git a/Project2/src/Parser.java b/Project2/src/Parser.java
index 0f39866..042af52 100644
--- a/Project2/src/Parser.java
+++ b/Project2/src/Parser.java
@@ -1,232 +1,232 @@
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class Parser {
/**
* list of all publications
*/
private ArrayList<Publication> publications;
/**
* location of file to parse
*/
private String file_loc;
/**
* default constructor
*
* @param file_loc location of file to parse
*/
public Parser(String file_loc) {
publications= new ArrayList<Publication>();
if(isValidSearchName(file_loc))
setFileLoc(file_loc);
}
/**
* decides whether or not the entered search name is valid
*
* @param file_loc location of file to parse
* @return true if valid, false if not
*/
public boolean isValidSearchName(String file_loc) {
//ensure an program argument exists
if(file_loc.length() > 0)
return true;
else {
return false;
}
}
/**
* parses CSV file
*
* @return true on success, false on error
* @throws IOException
*/
public boolean parseFile() throws IOException {
if(isValidSearchName(getFileLoc())) {
FileReader DBReader = new FileReader(getFileLoc());
BufferedReader DBReaderBuffered = new BufferedReader(DBReader);
String next_line="";
int partNum = 1;
String type = "";
ArrayList<String> authors = new ArrayList<String>();
String titlePaper = "";
String titleSerial = "";
int pageStart = 0;
int pageEnd = 0;
String Month = "";
int year = 0;
int volume = 0;
int issue = 0;
String link = "";
while(DBReaderBuffered.ready())
{
next_line=DBReaderBuffered.readLine();
if(next_line.length() > 0)
{
if(partNum == 1)
{
type = next_line;
}
if(partNum == 2)
{
authors = parseAuthors(next_line);
}
if(partNum == 3)
{
titlePaper = next_line;
}
if(partNum == 4)
{
titleSerial = next_line;
}
if(partNum == 5)
{
- if(type.toLowerCase() == "conference paper") {
+ if(type.toLowerCase().equals("conference paper")) {
pageStart = Integer.parseInt(next_line.split("\\-")[0]);
pageEnd = Integer.parseInt(next_line.split("\\-")[1]);
- } else if(type.toLowerCase() == "journal article") {
+ } else if(type.toLowerCase().equals("journal article")) {
volume = Integer.parseInt(next_line.split("\\(")[0]);
issue = Integer.parseInt(next_line.split("\\(")[1].split("\\)")[0]);
- pageStart = Integer.parseInt(next_line.split("\\)")[1].split("\\-")[0]);
+ pageStart = Integer.parseInt(next_line.split("\\:")[1].split("\\-")[0]);
- pageEnd = Integer.parseInt(next_line.split("\\)")[1].split("\\-")[1]);
+ pageEnd = Integer.parseInt(next_line.split("\\:")[1].split("\\-")[1]);
}
}
if(partNum == 6)
{
Month = next_line.split("\\ ")[0];
year = Integer.parseInt(next_line.split("\\ ")[1]);
}
if(partNum == 7)
{
partNum=0;
if(!isType(next_line))
{
link = next_line;
}
if(type.toLowerCase().equals("conference paper"))
publications.add(new Publication(authors,titlePaper, titleSerial, pageStart, pageEnd, Month, year, link));
if(type.toLowerCase().equals("journal article"))
publications.add(new JournalArticle(authors,titlePaper, titleSerial, pageStart, pageEnd, Month, year, link, volume, issue));
}
partNum++;
}
}
DBReaderBuffered.close();
return true;
}
return false;
}
public boolean isType(String in) {
return in.toLowerCase().equals("conference paper") ||
in.toLowerCase().equals("journal article");
}
public ArrayList<String> parseAuthors(String authorsStr) {
String[] parts = authorsStr.split("\\; ");
ArrayList<String> out = new ArrayList<String>();
for(String author : parts)
{
if(author != null)
{
out.add(author);
}
}
return out;
}
/**
* writes resultant file to disk
*
* @return true on success, false on error
* @throws IOException
*/
public boolean writeFile() throws IOException {
return false;
}
/**
* searches CVS file for matching items
*
* @param search_term term for which to search
* @return string containing all results from search
*/
public String searchAuthor(String search_term) {
String results = "";
//for each from http://stackoverflow.com/questions/85190/how-does-the-java-for-each-loop-work with many modifications
for(Publication item : publications) {
//substring checking from
//http://stackoverflow.com/questions/2275004/in-java-how-to-check-if-a-string-contains-a-substring-ignoring-the-case
for(String author : item.getAuthors())
{
if(author.toLowerCase().contains(search_term.toLowerCase())) {
results+=item.toString() + "\n";
}
}
}
if(results == "")
return "No Results Found";
return results;
}
public String getFileLoc() {
if(isValidSearchName(file_loc)) {
return file_loc;
}
return "Invalid File Location";
}
public boolean setFileLoc(String file_loc) {
if(isValidSearchName(file_loc)) {
this.file_loc = file_loc;
return true;
}
return false;
}
public ArrayList<Publication> getPublications() {
return publications;
}
public void setPublications(ArrayList<Publication> publications) {
this.publications = publications;
}
}
| false | true | public boolean parseFile() throws IOException {
if(isValidSearchName(getFileLoc())) {
FileReader DBReader = new FileReader(getFileLoc());
BufferedReader DBReaderBuffered = new BufferedReader(DBReader);
String next_line="";
int partNum = 1;
String type = "";
ArrayList<String> authors = new ArrayList<String>();
String titlePaper = "";
String titleSerial = "";
int pageStart = 0;
int pageEnd = 0;
String Month = "";
int year = 0;
int volume = 0;
int issue = 0;
String link = "";
while(DBReaderBuffered.ready())
{
next_line=DBReaderBuffered.readLine();
if(next_line.length() > 0)
{
if(partNum == 1)
{
type = next_line;
}
if(partNum == 2)
{
authors = parseAuthors(next_line);
}
if(partNum == 3)
{
titlePaper = next_line;
}
if(partNum == 4)
{
titleSerial = next_line;
}
if(partNum == 5)
{
if(type.toLowerCase() == "conference paper") {
pageStart = Integer.parseInt(next_line.split("\\-")[0]);
pageEnd = Integer.parseInt(next_line.split("\\-")[1]);
} else if(type.toLowerCase() == "journal article") {
volume = Integer.parseInt(next_line.split("\\(")[0]);
issue = Integer.parseInt(next_line.split("\\(")[1].split("\\)")[0]);
pageStart = Integer.parseInt(next_line.split("\\)")[1].split("\\-")[0]);
pageEnd = Integer.parseInt(next_line.split("\\)")[1].split("\\-")[1]);
}
}
if(partNum == 6)
{
Month = next_line.split("\\ ")[0];
year = Integer.parseInt(next_line.split("\\ ")[1]);
}
if(partNum == 7)
{
partNum=0;
if(!isType(next_line))
{
link = next_line;
}
if(type.toLowerCase().equals("conference paper"))
publications.add(new Publication(authors,titlePaper, titleSerial, pageStart, pageEnd, Month, year, link));
if(type.toLowerCase().equals("journal article"))
publications.add(new JournalArticle(authors,titlePaper, titleSerial, pageStart, pageEnd, Month, year, link, volume, issue));
}
partNum++;
}
}
DBReaderBuffered.close();
return true;
}
return false;
}
| public boolean parseFile() throws IOException {
if(isValidSearchName(getFileLoc())) {
FileReader DBReader = new FileReader(getFileLoc());
BufferedReader DBReaderBuffered = new BufferedReader(DBReader);
String next_line="";
int partNum = 1;
String type = "";
ArrayList<String> authors = new ArrayList<String>();
String titlePaper = "";
String titleSerial = "";
int pageStart = 0;
int pageEnd = 0;
String Month = "";
int year = 0;
int volume = 0;
int issue = 0;
String link = "";
while(DBReaderBuffered.ready())
{
next_line=DBReaderBuffered.readLine();
if(next_line.length() > 0)
{
if(partNum == 1)
{
type = next_line;
}
if(partNum == 2)
{
authors = parseAuthors(next_line);
}
if(partNum == 3)
{
titlePaper = next_line;
}
if(partNum == 4)
{
titleSerial = next_line;
}
if(partNum == 5)
{
if(type.toLowerCase().equals("conference paper")) {
pageStart = Integer.parseInt(next_line.split("\\-")[0]);
pageEnd = Integer.parseInt(next_line.split("\\-")[1]);
} else if(type.toLowerCase().equals("journal article")) {
volume = Integer.parseInt(next_line.split("\\(")[0]);
issue = Integer.parseInt(next_line.split("\\(")[1].split("\\)")[0]);
pageStart = Integer.parseInt(next_line.split("\\:")[1].split("\\-")[0]);
pageEnd = Integer.parseInt(next_line.split("\\:")[1].split("\\-")[1]);
}
}
if(partNum == 6)
{
Month = next_line.split("\\ ")[0];
year = Integer.parseInt(next_line.split("\\ ")[1]);
}
if(partNum == 7)
{
partNum=0;
if(!isType(next_line))
{
link = next_line;
}
if(type.toLowerCase().equals("conference paper"))
publications.add(new Publication(authors,titlePaper, titleSerial, pageStart, pageEnd, Month, year, link));
if(type.toLowerCase().equals("journal article"))
publications.add(new JournalArticle(authors,titlePaper, titleSerial, pageStart, pageEnd, Month, year, link, volume, issue));
}
partNum++;
}
}
DBReaderBuffered.close();
return true;
}
return false;
}
|
diff --git a/src/java/com/android/internal/telephony/MccTable.java b/src/java/com/android/internal/telephony/MccTable.java
index 0839f2d..dd58646 100644
--- a/src/java/com/android/internal/telephony/MccTable.java
+++ b/src/java/com/android/internal/telephony/MccTable.java
@@ -1,573 +1,573 @@
/*
* Copyright (C) 2006 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.internal.telephony;
import android.app.ActivityManagerNative;
import android.app.AlarmManager;
import android.app.IActivityManager;
import android.content.Context;
import android.content.res.Configuration;
import android.net.wifi.WifiManager;
import android.os.RemoteException;
import android.os.SystemProperties;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.telephony.Rlog;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Locale;
import libcore.icu.TimeZoneNames;
/**
* Mobile Country Code
*
* {@hide}
*/
public final class MccTable
{
static final String LOG_TAG = "MccTable";
static ArrayList<MccEntry> sTable;
static class MccEntry implements Comparable<MccEntry>
{
int mMcc;
String mIso;
int mSmallestDigitsMnc;
String mLanguage;
MccEntry(int mnc, String iso, int smallestDigitsMCC) {
this(mnc, iso, smallestDigitsMCC, null);
}
MccEntry(int mnc, String iso, int smallestDigitsMCC, String language) {
mMcc = mnc;
mIso = iso;
mSmallestDigitsMnc = smallestDigitsMCC;
mLanguage = language;
}
@Override
public int compareTo(MccEntry o)
{
return mMcc - o.mMcc;
}
}
private static MccEntry
entryForMcc(int mcc)
{
int index;
MccEntry m;
m = new MccEntry(mcc, null, 0);
index = Collections.binarySearch(sTable, m);
if (index < 0) {
return null;
} else {
return sTable.get(index);
}
}
/**
* Returns a default time zone ID for the given MCC.
* @param mcc Mobile Country Code
* @return default TimeZone ID, or null if not specified
*/
public static String defaultTimeZoneForMcc(int mcc) {
MccEntry entry;
entry = entryForMcc(mcc);
if (entry == null || entry.mIso == null) {
return null;
} else {
Locale locale;
if (entry.mLanguage == null) {
locale = new Locale(entry.mIso);
} else {
locale = new Locale(entry.mLanguage, entry.mIso);
}
String[] tz = TimeZoneNames.forLocale(locale);
if (tz.length == 0) return null;
return tz[0];
}
}
/**
* Given a GSM Mobile Country Code, returns
* an ISO two-character country code if available.
* Returns "" if unavailable.
*/
public static String
countryCodeForMcc(int mcc)
{
MccEntry entry;
entry = entryForMcc(mcc);
if (entry == null) {
return "";
} else {
return entry.mIso;
}
}
/**
* Given a GSM Mobile Country Code, returns
* an ISO 2-3 character language code if available.
* Returns null if unavailable.
*/
public static String defaultLanguageForMcc(int mcc) {
MccEntry entry;
entry = entryForMcc(mcc);
if (entry == null) {
return null;
} else {
return entry.mLanguage;
}
}
/**
* Given a GSM Mobile Country Code, returns
* the smallest number of digits that M if available.
* Returns 2 if unavailable.
*/
public static int
smallestDigitsMccForMnc(int mcc)
{
MccEntry entry;
entry = entryForMcc(mcc);
if (entry == null) {
return 2;
} else {
return entry.mSmallestDigitsMnc;
}
}
/**
* Updates MCC and MNC device configuration information for application retrieving
* correct version of resources. If either MCC or MNC is 0, they will be ignored (not set).
* @param context Context to act on.
* @param mccmnc truncated imsi with just the MCC and MNC - MNC assumed to be from 4th to end
*/
public static void updateMccMncConfiguration(Context context, String mccmnc) {
if (!TextUtils.isEmpty(mccmnc)) {
int mcc, mnc;
try {
mcc = Integer.parseInt(mccmnc.substring(0,3));
mnc = Integer.parseInt(mccmnc.substring(3));
} catch (NumberFormatException e) {
Rlog.e(LOG_TAG, "Error parsing IMSI");
return;
}
Rlog.d(LOG_TAG, "updateMccMncConfiguration: mcc=" + mcc + ", mnc=" + mnc);
if (mcc != 0) {
setTimezoneFromMccIfNeeded(context, mcc);
setLocaleFromMccIfNeeded(context, mcc);
setWifiCountryCodeFromMcc(context, mcc);
}
try {
Configuration config = ActivityManagerNative.getDefault().getConfiguration();
if (mcc != 0) {
config.mcc = mcc;
}
if (mnc != 0) {
config.mnc = mnc;
}
ActivityManagerNative.getDefault().updateConfiguration(config);
} catch (RemoteException e) {
Rlog.e(LOG_TAG, "Can't update configuration", e);
}
}
}
/**
* Utility code to set the system locale if it's not set already
* @param context Context to act on.
* @param language Two character language code desired
* @param country Two character country code desired
*
* {@hide}
*/
public static void setSystemLocale(Context context, String language, String country) {
String l = SystemProperties.get("persist.sys.language");
String c = SystemProperties.get("persist.sys.country");
if (null == language) {
return; // no match possible
}
- language = language.toLowerCase();
+ language = language.toLowerCase(Locale.ROOT);
if (null == country) {
country = "";
}
- country = country.toUpperCase();
+ country = country.toUpperCase(Locale.ROOT);
if((null == l || 0 == l.length()) && (null == c || 0 == c.length())) {
try {
// try to find a good match
String[] locales = context.getAssets().getLocales();
final int N = locales.length;
String bestMatch = null;
for(int i = 0; i < N; i++) {
// only match full (lang + country) locales
if (locales[i]!=null && locales[i].length() >= 5 &&
locales[i].substring(0,2).equals(language)) {
if (locales[i].substring(3,5).equals(country)) {
bestMatch = locales[i];
break;
} else if (null == bestMatch) {
bestMatch = locales[i];
}
}
}
if (null != bestMatch) {
IActivityManager am = ActivityManagerNative.getDefault();
Configuration config = am.getConfiguration();
config.locale = new Locale(bestMatch.substring(0,2),
bestMatch.substring(3,5));
config.userSetLocale = true;
am.updateConfiguration(config);
}
} catch (Exception e) {
// Intentionally left blank
}
}
}
/**
* If the timezone is not already set, set it based on the MCC of the SIM.
* @param context Context to act on.
* @param mcc Mobile Country Code of the SIM or SIM-like entity (build prop on CDMA)
*/
private static void setTimezoneFromMccIfNeeded(Context context, int mcc) {
String timezone = SystemProperties.get(ServiceStateTracker.TIMEZONE_PROPERTY);
if (timezone == null || timezone.length() == 0) {
String zoneId = defaultTimeZoneForMcc(mcc);
if (zoneId != null && zoneId.length() > 0) {
// Set time zone based on MCC
AlarmManager alarm =
(AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarm.setTimeZone(zoneId);
Rlog.d(LOG_TAG, "timezone set to "+zoneId);
}
}
}
/**
* If the locale is not already set, set it based on the MCC of the SIM.
* @param context Context to act on.
* @param mcc Mobile Country Code of the SIM or SIM-like entity (build prop on CDMA)
*/
private static void setLocaleFromMccIfNeeded(Context context, int mcc) {
if (TelephonyManager.getLteOnCdmaModeStatic() == PhoneConstants.LTE_ON_CDMA_TRUE) {
// Avoid system locale is set from MCC table if CDMALTEPhone is used.
// The locale will be picked up based on EFpl/EFli once CSIM records are loaded.
return;
}
String language = MccTable.defaultLanguageForMcc(mcc);
String country = MccTable.countryCodeForMcc(mcc);
Rlog.d(LOG_TAG, "locale set to "+language+"_"+country);
setSystemLocale(context, language, country);
}
/**
* If the number of allowed wifi channels has not been set, set it based on
* the MCC of the SIM.
* @param context Context to act on.
* @param mcc Mobile Country Code of the SIM or SIM-like entity (build prop on CDMA)
*/
private static void setWifiCountryCodeFromMcc(Context context, int mcc) {
String country = MccTable.countryCodeForMcc(mcc);
if (!country.isEmpty()) {
Rlog.d(LOG_TAG, "WIFI_COUNTRY_CODE set to " + country);
WifiManager wM = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
//persist
wM.setCountryCode(country, true);
}
}
static {
sTable = new ArrayList<MccEntry>(240);
/*
* The table below is built from two resources:
*
* 1) ITU "Mobile Network Code (MNC) for the international
* identification plan for mobile terminals and mobile users"
* which is available as an annex to the ITU operational bulletin
* available here: http://www.itu.int/itu-t/bulletin/annex.html
*
* 2) The ISO 3166 country codes list, available here:
* http://www.iso.org/iso/en/prods-services/iso3166ma/02iso-3166-code-lists/index.html
*
* This table has not been verified.
*
*/
sTable.add(new MccEntry(202,"gr",2)); //Greece
sTable.add(new MccEntry(204,"nl",2,"nl")); //Netherlands (Kingdom of the)
sTable.add(new MccEntry(206,"be",2)); //Belgium
sTable.add(new MccEntry(208,"fr",2,"fr")); //France
sTable.add(new MccEntry(212,"mc",2)); //Monaco (Principality of)
sTable.add(new MccEntry(213,"ad",2)); //Andorra (Principality of)
sTable.add(new MccEntry(214,"es",2,"es")); //Spain
sTable.add(new MccEntry(216,"hu",2)); //Hungary (Republic of)
sTable.add(new MccEntry(218,"ba",2)); //Bosnia and Herzegovina
sTable.add(new MccEntry(219,"hr",2)); //Croatia (Republic of)
sTable.add(new MccEntry(220,"rs",2)); //Serbia and Montenegro
sTable.add(new MccEntry(222,"it",2,"it")); //Italy
sTable.add(new MccEntry(225,"va",2,"it")); //Vatican City State
sTable.add(new MccEntry(226,"ro",2)); //Romania
sTable.add(new MccEntry(228,"ch",2,"de")); //Switzerland (Confederation of)
sTable.add(new MccEntry(230,"cz",2,"cs")); //Czech Republic
sTable.add(new MccEntry(231,"sk",2)); //Slovak Republic
sTable.add(new MccEntry(232,"at",2,"de")); //Austria
sTable.add(new MccEntry(234,"gb",2,"en")); //United Kingdom of Great Britain and Northern Ireland
sTable.add(new MccEntry(235,"gb",2,"en")); //United Kingdom of Great Britain and Northern Ireland
sTable.add(new MccEntry(238,"dk",2)); //Denmark
sTable.add(new MccEntry(240,"se",2)); //Sweden
sTable.add(new MccEntry(242,"no",2)); //Norway
sTable.add(new MccEntry(244,"fi",2)); //Finland
sTable.add(new MccEntry(246,"lt",2)); //Lithuania (Republic of)
sTable.add(new MccEntry(247,"lv",2)); //Latvia (Republic of)
sTable.add(new MccEntry(248,"ee",2)); //Estonia (Republic of)
sTable.add(new MccEntry(250,"ru",2)); //Russian Federation
sTable.add(new MccEntry(255,"ua",2)); //Ukraine
sTable.add(new MccEntry(257,"by",2)); //Belarus (Republic of)
sTable.add(new MccEntry(259,"md",2)); //Moldova (Republic of)
sTable.add(new MccEntry(260,"pl",2)); //Poland (Republic of)
sTable.add(new MccEntry(262,"de",2,"de")); //Germany (Federal Republic of)
sTable.add(new MccEntry(266,"gi",2)); //Gibraltar
sTable.add(new MccEntry(268,"pt",2)); //Portugal
sTable.add(new MccEntry(270,"lu",2)); //Luxembourg
sTable.add(new MccEntry(272,"ie",2,"en")); //Ireland
sTable.add(new MccEntry(274,"is",2)); //Iceland
sTable.add(new MccEntry(276,"al",2)); //Albania (Republic of)
sTable.add(new MccEntry(278,"mt",2)); //Malta
sTable.add(new MccEntry(280,"cy",2)); //Cyprus (Republic of)
sTable.add(new MccEntry(282,"ge",2)); //Georgia
sTable.add(new MccEntry(283,"am",2)); //Armenia (Republic of)
sTable.add(new MccEntry(284,"bg",2)); //Bulgaria (Republic of)
sTable.add(new MccEntry(286,"tr",2)); //Turkey
sTable.add(new MccEntry(288,"fo",2)); //Faroe Islands
sTable.add(new MccEntry(289,"ge",2)); //Abkhazia (Georgia)
sTable.add(new MccEntry(290,"gl",2)); //Greenland (Denmark)
sTable.add(new MccEntry(292,"sm",2)); //San Marino (Republic of)
sTable.add(new MccEntry(293,"si",2)); //Slovenia (Republic of)
sTable.add(new MccEntry(294,"mk",2)); //The Former Yugoslav Republic of Macedonia
sTable.add(new MccEntry(295,"li",2)); //Liechtenstein (Principality of)
sTable.add(new MccEntry(297,"me",2)); //Montenegro (Republic of)
sTable.add(new MccEntry(302,"ca",3,"")); //Canada
sTable.add(new MccEntry(308,"pm",2)); //Saint Pierre and Miquelon (Collectivit territoriale de la Rpublique franaise)
sTable.add(new MccEntry(310,"us",3,"en")); //United States of America
sTable.add(new MccEntry(311,"us",3,"en")); //United States of America
sTable.add(new MccEntry(312,"us",3,"en")); //United States of America
sTable.add(new MccEntry(313,"us",3,"en")); //United States of America
sTable.add(new MccEntry(314,"us",3,"en")); //United States of America
sTable.add(new MccEntry(315,"us",3,"en")); //United States of America
sTable.add(new MccEntry(316,"us",3,"en")); //United States of America
sTable.add(new MccEntry(330,"pr",2)); //Puerto Rico
sTable.add(new MccEntry(332,"vi",2)); //United States Virgin Islands
sTable.add(new MccEntry(334,"mx",3)); //Mexico
sTable.add(new MccEntry(338,"jm",3)); //Jamaica
sTable.add(new MccEntry(340,"gp",2)); //Guadeloupe (French Department of)
sTable.add(new MccEntry(342,"bb",3)); //Barbados
sTable.add(new MccEntry(344,"ag",3)); //Antigua and Barbuda
sTable.add(new MccEntry(346,"ky",3)); //Cayman Islands
sTable.add(new MccEntry(348,"vg",3)); //British Virgin Islands
sTable.add(new MccEntry(350,"bm",2)); //Bermuda
sTable.add(new MccEntry(352,"gd",2)); //Grenada
sTable.add(new MccEntry(354,"ms",2)); //Montserrat
sTable.add(new MccEntry(356,"kn",2)); //Saint Kitts and Nevis
sTable.add(new MccEntry(358,"lc",2)); //Saint Lucia
sTable.add(new MccEntry(360,"vc",2)); //Saint Vincent and the Grenadines
sTable.add(new MccEntry(362,"ai",2)); //Netherlands Antilles
sTable.add(new MccEntry(363,"aw",2)); //Aruba
sTable.add(new MccEntry(364,"bs",2)); //Bahamas (Commonwealth of the)
sTable.add(new MccEntry(365,"ai",3)); //Anguilla
sTable.add(new MccEntry(366,"dm",2)); //Dominica (Commonwealth of)
sTable.add(new MccEntry(368,"cu",2)); //Cuba
sTable.add(new MccEntry(370,"do",2)); //Dominican Republic
sTable.add(new MccEntry(372,"ht",2)); //Haiti (Republic of)
sTable.add(new MccEntry(374,"tt",2)); //Trinidad and Tobago
sTable.add(new MccEntry(376,"tc",2)); //Turks and Caicos Islands
sTable.add(new MccEntry(400,"az",2)); //Azerbaijani Republic
sTable.add(new MccEntry(401,"kz",2)); //Kazakhstan (Republic of)
sTable.add(new MccEntry(402,"bt",2)); //Bhutan (Kingdom of)
sTable.add(new MccEntry(404,"in",2)); //India (Republic of)
sTable.add(new MccEntry(405,"in",2)); //India (Republic of)
sTable.add(new MccEntry(410,"pk",2)); //Pakistan (Islamic Republic of)
sTable.add(new MccEntry(412,"af",2)); //Afghanistan
sTable.add(new MccEntry(413,"lk",2)); //Sri Lanka (Democratic Socialist Republic of)
sTable.add(new MccEntry(414,"mm",2)); //Myanmar (Union of)
sTable.add(new MccEntry(415,"lb",2)); //Lebanon
sTable.add(new MccEntry(416,"jo",2)); //Jordan (Hashemite Kingdom of)
sTable.add(new MccEntry(417,"sy",2)); //Syrian Arab Republic
sTable.add(new MccEntry(418,"iq",2)); //Iraq (Republic of)
sTable.add(new MccEntry(419,"kw",2)); //Kuwait (State of)
sTable.add(new MccEntry(420,"sa",2)); //Saudi Arabia (Kingdom of)
sTable.add(new MccEntry(421,"ye",2)); //Yemen (Republic of)
sTable.add(new MccEntry(422,"om",2)); //Oman (Sultanate of)
sTable.add(new MccEntry(423,"ps",2)); //Palestine
sTable.add(new MccEntry(424,"ae",2)); //United Arab Emirates
sTable.add(new MccEntry(425,"il",2)); //Israel (State of)
sTable.add(new MccEntry(426,"bh",2)); //Bahrain (Kingdom of)
sTable.add(new MccEntry(427,"qa",2)); //Qatar (State of)
sTable.add(new MccEntry(428,"mn",2)); //Mongolia
sTable.add(new MccEntry(429,"np",2)); //Nepal
sTable.add(new MccEntry(430,"ae",2)); //United Arab Emirates
sTable.add(new MccEntry(431,"ae",2)); //United Arab Emirates
sTable.add(new MccEntry(432,"ir",2)); //Iran (Islamic Republic of)
sTable.add(new MccEntry(434,"uz",2)); //Uzbekistan (Republic of)
sTable.add(new MccEntry(436,"tj",2)); //Tajikistan (Republic of)
sTable.add(new MccEntry(437,"kg",2)); //Kyrgyz Republic
sTable.add(new MccEntry(438,"tm",2)); //Turkmenistan
sTable.add(new MccEntry(440,"jp",2,"ja")); //Japan
sTable.add(new MccEntry(441,"jp",2,"ja")); //Japan
sTable.add(new MccEntry(450,"kr",2,"ko")); //Korea (Republic of)
sTable.add(new MccEntry(452,"vn",2)); //Viet Nam (Socialist Republic of)
sTable.add(new MccEntry(454,"hk",2)); //"Hong Kong, China"
sTable.add(new MccEntry(455,"mo",2)); //"Macao, China"
sTable.add(new MccEntry(456,"kh",2)); //Cambodia (Kingdom of)
sTable.add(new MccEntry(457,"la",2)); //Lao People's Democratic Republic
sTable.add(new MccEntry(460,"cn",2,"zh")); //China (People's Republic of)
sTable.add(new MccEntry(461,"cn",2,"zh")); //China (People's Republic of)
sTable.add(new MccEntry(466,"tw",2)); //"Taiwan, China"
sTable.add(new MccEntry(467,"kp",2)); //Democratic People's Republic of Korea
sTable.add(new MccEntry(470,"bd",2)); //Bangladesh (People's Republic of)
sTable.add(new MccEntry(472,"mv",2)); //Maldives (Republic of)
sTable.add(new MccEntry(502,"my",2)); //Malaysia
sTable.add(new MccEntry(505,"au",2,"en")); //Australia
sTable.add(new MccEntry(510,"id",2)); //Indonesia (Republic of)
sTable.add(new MccEntry(514,"tl",2)); //Democratic Republic of Timor-Leste
sTable.add(new MccEntry(515,"ph",2)); //Philippines (Republic of the)
sTable.add(new MccEntry(520,"th",2)); //Thailand
sTable.add(new MccEntry(525,"sg",2,"en")); //Singapore (Republic of)
sTable.add(new MccEntry(528,"bn",2)); //Brunei Darussalam
sTable.add(new MccEntry(530,"nz",2, "en")); //New Zealand
sTable.add(new MccEntry(534,"mp",2)); //Northern Mariana Islands (Commonwealth of the)
sTable.add(new MccEntry(535,"gu",2)); //Guam
sTable.add(new MccEntry(536,"nr",2)); //Nauru (Republic of)
sTable.add(new MccEntry(537,"pg",2)); //Papua New Guinea
sTable.add(new MccEntry(539,"to",2)); //Tonga (Kingdom of)
sTable.add(new MccEntry(540,"sb",2)); //Solomon Islands
sTable.add(new MccEntry(541,"vu",2)); //Vanuatu (Republic of)
sTable.add(new MccEntry(542,"fj",2)); //Fiji (Republic of)
sTable.add(new MccEntry(543,"wf",2)); //Wallis and Futuna (Territoire franais d'outre-mer)
sTable.add(new MccEntry(544,"as",2)); //American Samoa
sTable.add(new MccEntry(545,"ki",2)); //Kiribati (Republic of)
sTable.add(new MccEntry(546,"nc",2)); //New Caledonia (Territoire franais d'outre-mer)
sTable.add(new MccEntry(547,"pf",2)); //French Polynesia (Territoire franais d'outre-mer)
sTable.add(new MccEntry(548,"ck",2)); //Cook Islands
sTable.add(new MccEntry(549,"ws",2)); //Samoa (Independent State of)
sTable.add(new MccEntry(550,"fm",2)); //Micronesia (Federated States of)
sTable.add(new MccEntry(551,"mh",2)); //Marshall Islands (Republic of the)
sTable.add(new MccEntry(552,"pw",2)); //Palau (Republic of)
sTable.add(new MccEntry(602,"eg",2)); //Egypt (Arab Republic of)
sTable.add(new MccEntry(603,"dz",2)); //Algeria (People's Democratic Republic of)
sTable.add(new MccEntry(604,"ma",2)); //Morocco (Kingdom of)
sTable.add(new MccEntry(605,"tn",2)); //Tunisia
sTable.add(new MccEntry(606,"ly",2)); //Libya (Socialist People's Libyan Arab Jamahiriya)
sTable.add(new MccEntry(607,"gm",2)); //Gambia (Republic of the)
sTable.add(new MccEntry(608,"sn",2)); //Senegal (Republic of)
sTable.add(new MccEntry(609,"mr",2)); //Mauritania (Islamic Republic of)
sTable.add(new MccEntry(610,"ml",2)); //Mali (Republic of)
sTable.add(new MccEntry(611,"gn",2)); //Guinea (Republic of)
sTable.add(new MccEntry(612,"ci",2)); //Cte d'Ivoire (Republic of)
sTable.add(new MccEntry(613,"bf",2)); //Burkina Faso
sTable.add(new MccEntry(614,"ne",2)); //Niger (Republic of the)
sTable.add(new MccEntry(615,"tg",2)); //Togolese Republic
sTable.add(new MccEntry(616,"bj",2)); //Benin (Republic of)
sTable.add(new MccEntry(617,"mu",2)); //Mauritius (Republic of)
sTable.add(new MccEntry(618,"lr",2)); //Liberia (Republic of)
sTable.add(new MccEntry(619,"sl",2)); //Sierra Leone
sTable.add(new MccEntry(620,"gh",2)); //Ghana
sTable.add(new MccEntry(621,"ng",2)); //Nigeria (Federal Republic of)
sTable.add(new MccEntry(622,"td",2)); //Chad (Republic of)
sTable.add(new MccEntry(623,"cf",2)); //Central African Republic
sTable.add(new MccEntry(624,"cm",2)); //Cameroon (Republic of)
sTable.add(new MccEntry(625,"cv",2)); //Cape Verde (Republic of)
sTable.add(new MccEntry(626,"st",2)); //Sao Tome and Principe (Democratic Republic of)
sTable.add(new MccEntry(627,"gq",2)); //Equatorial Guinea (Republic of)
sTable.add(new MccEntry(628,"ga",2)); //Gabonese Republic
sTable.add(new MccEntry(629,"cg",2)); //Congo (Republic of the)
sTable.add(new MccEntry(630,"cg",2)); //Democratic Republic of the Congo
sTable.add(new MccEntry(631,"ao",2)); //Angola (Republic of)
sTable.add(new MccEntry(632,"gw",2)); //Guinea-Bissau (Republic of)
sTable.add(new MccEntry(633,"sc",2)); //Seychelles (Republic of)
sTable.add(new MccEntry(634,"sd",2)); //Sudan (Republic of the)
sTable.add(new MccEntry(635,"rw",2)); //Rwanda (Republic of)
sTable.add(new MccEntry(636,"et",2)); //Ethiopia (Federal Democratic Republic of)
sTable.add(new MccEntry(637,"so",2)); //Somali Democratic Republic
sTable.add(new MccEntry(638,"dj",2)); //Djibouti (Republic of)
sTable.add(new MccEntry(639,"ke",2)); //Kenya (Republic of)
sTable.add(new MccEntry(640,"tz",2)); //Tanzania (United Republic of)
sTable.add(new MccEntry(641,"ug",2)); //Uganda (Republic of)
sTable.add(new MccEntry(642,"bi",2)); //Burundi (Republic of)
sTable.add(new MccEntry(643,"mz",2)); //Mozambique (Republic of)
sTable.add(new MccEntry(645,"zm",2)); //Zambia (Republic of)
sTable.add(new MccEntry(646,"mg",2)); //Madagascar (Republic of)
sTable.add(new MccEntry(647,"re",2)); //Reunion (French Department of)
sTable.add(new MccEntry(648,"zw",2)); //Zimbabwe (Republic of)
sTable.add(new MccEntry(649,"na",2)); //Namibia (Republic of)
sTable.add(new MccEntry(650,"mw",2)); //Malawi
sTable.add(new MccEntry(651,"ls",2)); //Lesotho (Kingdom of)
sTable.add(new MccEntry(652,"bw",2)); //Botswana (Republic of)
sTable.add(new MccEntry(653,"sz",2)); //Swaziland (Kingdom of)
sTable.add(new MccEntry(654,"km",2)); //Comoros (Union of the)
sTable.add(new MccEntry(655,"za",2,"en")); //South Africa (Republic of)
sTable.add(new MccEntry(657,"er",2)); //Eritrea
sTable.add(new MccEntry(702,"bz",2)); //Belize
sTable.add(new MccEntry(704,"gt",2)); //Guatemala (Republic of)
sTable.add(new MccEntry(706,"sv",2)); //El Salvador (Republic of)
sTable.add(new MccEntry(708,"hn",3)); //Honduras (Republic of)
sTable.add(new MccEntry(710,"ni",2)); //Nicaragua
sTable.add(new MccEntry(712,"cr",2)); //Costa Rica
sTable.add(new MccEntry(714,"pa",2)); //Panama (Republic of)
sTable.add(new MccEntry(716,"pe",2)); //Peru
sTable.add(new MccEntry(722,"ar",3)); //Argentine Republic
sTable.add(new MccEntry(724,"br",2)); //Brazil (Federative Republic of)
sTable.add(new MccEntry(730,"cl",2)); //Chile
sTable.add(new MccEntry(732,"co",3)); //Colombia (Republic of)
sTable.add(new MccEntry(734,"ve",2)); //Venezuela (Bolivarian Republic of)
sTable.add(new MccEntry(736,"bo",2)); //Bolivia (Republic of)
sTable.add(new MccEntry(738,"gy",2)); //Guyana
sTable.add(new MccEntry(740,"ec",2)); //Ecuador
sTable.add(new MccEntry(742,"gf",2)); //French Guiana (French Department of)
sTable.add(new MccEntry(744,"py",2)); //Paraguay (Republic of)
sTable.add(new MccEntry(746,"sr",2)); //Suriname (Republic of)
sTable.add(new MccEntry(748,"uy",2)); //Uruguay (Eastern Republic of)
sTable.add(new MccEntry(750,"fk",2)); //Falkland Islands (Malvinas)
//table.add(new MccEntry(901,"",2)); //"International Mobile, shared code"
Collections.sort(sTable);
}
}
| false | true | public static void setSystemLocale(Context context, String language, String country) {
String l = SystemProperties.get("persist.sys.language");
String c = SystemProperties.get("persist.sys.country");
if (null == language) {
return; // no match possible
}
language = language.toLowerCase();
if (null == country) {
country = "";
}
country = country.toUpperCase();
if((null == l || 0 == l.length()) && (null == c || 0 == c.length())) {
try {
// try to find a good match
String[] locales = context.getAssets().getLocales();
final int N = locales.length;
String bestMatch = null;
for(int i = 0; i < N; i++) {
// only match full (lang + country) locales
if (locales[i]!=null && locales[i].length() >= 5 &&
locales[i].substring(0,2).equals(language)) {
if (locales[i].substring(3,5).equals(country)) {
bestMatch = locales[i];
break;
} else if (null == bestMatch) {
bestMatch = locales[i];
}
}
}
if (null != bestMatch) {
IActivityManager am = ActivityManagerNative.getDefault();
Configuration config = am.getConfiguration();
config.locale = new Locale(bestMatch.substring(0,2),
bestMatch.substring(3,5));
config.userSetLocale = true;
am.updateConfiguration(config);
}
} catch (Exception e) {
// Intentionally left blank
}
}
}
| public static void setSystemLocale(Context context, String language, String country) {
String l = SystemProperties.get("persist.sys.language");
String c = SystemProperties.get("persist.sys.country");
if (null == language) {
return; // no match possible
}
language = language.toLowerCase(Locale.ROOT);
if (null == country) {
country = "";
}
country = country.toUpperCase(Locale.ROOT);
if((null == l || 0 == l.length()) && (null == c || 0 == c.length())) {
try {
// try to find a good match
String[] locales = context.getAssets().getLocales();
final int N = locales.length;
String bestMatch = null;
for(int i = 0; i < N; i++) {
// only match full (lang + country) locales
if (locales[i]!=null && locales[i].length() >= 5 &&
locales[i].substring(0,2).equals(language)) {
if (locales[i].substring(3,5).equals(country)) {
bestMatch = locales[i];
break;
} else if (null == bestMatch) {
bestMatch = locales[i];
}
}
}
if (null != bestMatch) {
IActivityManager am = ActivityManagerNative.getDefault();
Configuration config = am.getConfiguration();
config.locale = new Locale(bestMatch.substring(0,2),
bestMatch.substring(3,5));
config.userSetLocale = true;
am.updateConfiguration(config);
}
} catch (Exception e) {
// Intentionally left blank
}
}
}
|
diff --git a/src/Allocator.java b/src/Allocator.java
index 4b1b4f6..50a32c0 100644
--- a/src/Allocator.java
+++ b/src/Allocator.java
@@ -1,88 +1,88 @@
/*
SNARL/Allocator
James Current
4/28/12
*/
public class Allocator {
public final class Register {
private String name; //Printable name of this Register
private Register next; //Next Register in Registers
private boolean used; //Is register currently in use?
//Dummy Constructor. Makes sure that only Allocator can create Registers.
private Register () {}
//Constructor. Returns a new Register with given name, next, and used slots.
private Register (String name, Register next, boolean used) {
this.name = name;
this.next = next;
this.used = used;
}
//IsUsed. Returns if the Register is used or not.
public boolean isUsed(){
return used;
}
//ToString. Returns the name of the Register.
public String toString(){
return name;
}
}
public final Register fp = new Register("$fp", null, true); //$fp register
public final Register ra = new Register("$ra", null, true); //$ra register
public final Register sp = new Register("$sp", null, true); //$sp register
public final Register v0 = new Register("$v0", null, true); //$v0 register
public final Register zero = new Register("$zero", null, true); //$zero register
protected Register registers; //Linked stack of Registers to be allocated.
//Constructor. Returns a new Allocator with a linked stack of Registers $s0 through $s7.
public Allocator (){
Register s0 = new Register("$s0", null, false);
Register s1 = new Register("$s1", s0, false);
Register s2 = new Register("$s2", s1, false);
Register s3 = new Register("$s3", s2, false);
Register s4 = new Register("$s4", s3, false);
Register s5 = new Register("$s5", s4, false);
Register s6 = new Register("$s6", s5, false);
registers = new Register("$s7", s6, false);
}
//Request. Requests a register to be allocated, throws an exception if there are no registers available.
public Register request(){
if(registers == null){
- throw new SnarlCompilerException("Too many variables declared.");
+ throw new SnarlCompilerException("Out of memory.");
}
Register register = registers;
registers = register.next;
register.used = true;
return register;
}
//Release. Releases a register, throws an exception if the register has already been released.
public void release(Register register){
if(!register.isUsed()){
throw new RuntimeException("Register has already been released.");
}
register.used = false;
register.next = registers;
registers = register;
}
}
| true | true | public Register request(){
if(registers == null){
throw new SnarlCompilerException("Too many variables declared.");
}
Register register = registers;
registers = register.next;
register.used = true;
return register;
}
| public Register request(){
if(registers == null){
throw new SnarlCompilerException("Out of memory.");
}
Register register = registers;
registers = register.next;
register.used = true;
return register;
}
|
diff --git a/src/com/jidesoft/plaf/basic/BasicLookAndFeelExtension.java b/src/com/jidesoft/plaf/basic/BasicLookAndFeelExtension.java
index 393a367d..c2b8dde2 100644
--- a/src/com/jidesoft/plaf/basic/BasicLookAndFeelExtension.java
+++ b/src/com/jidesoft/plaf/basic/BasicLookAndFeelExtension.java
@@ -1,79 +1,78 @@
/*
* @(#)BasicLookAndFeelExtension.java 4/15/2007
*
* Copyright 2002 - 2007 JIDE Software Inc. All rights reserved.
*/
package com.jidesoft.plaf.basic;
import com.jidesoft.plaf.LookAndFeelExtension;
import com.jidesoft.plaf.LookAndFeelFactory;
import javax.swing.*;
/**
* Initialize the uiClassID to BasicComponentUI mapping for JIDE components. The JComponent classes define their own
* uiClassID constants (see AbstractComponent.getUIClassID). This table must map those constants to a BasicComponentUI
* class of the appropriate type.
*/
public class BasicLookAndFeelExtension implements LookAndFeelExtension {
/**
* Initializes class defaults.
*
* @param table UIDefaults table
*/
public static void initClassDefaults(UIDefaults table) {
int products = LookAndFeelFactory.getProductsUsed();
final String basicPackageName = "com.jidesoft.plaf.basic.";
// common
table.put("JidePopupMenuUI", basicPackageName + "BasicJidePopupMenuUI");
table.put("HeaderBoxUI", basicPackageName + "BasicHeaderBoxUI");
table.put("RangeSliderUI", basicPackageName + "BasicRangeSliderUI");
table.put("FolderChooserUI", basicPackageName + "BasicFolderChooserUI");
table.put("StyledLabelUI", basicPackageName + "BasicStyledLabelUI");
table.put("GripperUI", basicPackageName + "BasicGripperUI");
table.put("JidePopupUI", basicPackageName + "BasicJidePopupUI");
table.put("JideTabbedPaneUI", basicPackageName + "BasicJideTabbedPaneUI");
table.put("JideLabelUI", basicPackageName + "BasicJideLabelUI");
table.put("JideButtonUI", basicPackageName + "BasicJideButtonUI");
table.put("JideSplitButtonUI", basicPackageName + "BasicJideSplitButtonUI");
table.put("JideComboBoxUI", basicPackageName + "BasicJideComboBoxUI");
table.put("MeterProgressBarUI", basicPackageName + "MeterProgressBarUI");
- table.put("CheckBoxListUI", basicPackageName + "BasicCheckBoxListUI");
if ((products & PRODUCT_GRIDS) != 0) {
// grids
table.put("JideTableUI", basicPackageName + "BasicJideTableUI");
table.put("NavigableTableUI", basicPackageName + "BasicNavigableTableUI");
table.put("CellSpanTableUI", basicPackageName + "BasicCellSpanTableUI");
table.put("TreeTableUI", basicPackageName + "BasicTreeTableUI");
table.put("HierarchicalTableUI", basicPackageName + "BasicHierarchicalTableUI");
table.put("NestedTableHeaderUI", basicPackageName + "BasicNestedTableHeaderUI");
table.put("EditableTableHeaderUI", basicPackageName + "BasicEditableTableHeaderUI");
table.put("GroupListUI", basicPackageName + "BasicGroupListUI");
}
if ((products & PRODUCT_DOCK) != 0) {
// dock
table.put("SidePaneUI", basicPackageName + "BasicSidePaneUI");
table.put("DockableFrameUI", basicPackageName + "BasicDockableFrameUI");
}
if ((products & PRODUCT_COMPONENTS) != 0) {
// components
table.put("CollapsiblePaneUI", basicPackageName + "BasicCollapsiblePaneUI");
table.put("StatusBarSeparatorUI", basicPackageName + "BasicStatusBarSeparatorUI");
}
if ((products & PRODUCT_ACTION) != 0) {
// action
table.put("CommandBarUI", basicPackageName + "BasicCommandBarUI");
table.put("CommandBarSeparatorUI", basicPackageName + "BasicCommandBarSeparatorUI");
table.put("ChevronUI", basicPackageName + "BasicChevronUI");
table.put("CommandBarTitleBarUI", basicPackageName + "BasicCommandBarTitleBarUI");
}
}
}
| true | true | public static void initClassDefaults(UIDefaults table) {
int products = LookAndFeelFactory.getProductsUsed();
final String basicPackageName = "com.jidesoft.plaf.basic.";
// common
table.put("JidePopupMenuUI", basicPackageName + "BasicJidePopupMenuUI");
table.put("HeaderBoxUI", basicPackageName + "BasicHeaderBoxUI");
table.put("RangeSliderUI", basicPackageName + "BasicRangeSliderUI");
table.put("FolderChooserUI", basicPackageName + "BasicFolderChooserUI");
table.put("StyledLabelUI", basicPackageName + "BasicStyledLabelUI");
table.put("GripperUI", basicPackageName + "BasicGripperUI");
table.put("JidePopupUI", basicPackageName + "BasicJidePopupUI");
table.put("JideTabbedPaneUI", basicPackageName + "BasicJideTabbedPaneUI");
table.put("JideLabelUI", basicPackageName + "BasicJideLabelUI");
table.put("JideButtonUI", basicPackageName + "BasicJideButtonUI");
table.put("JideSplitButtonUI", basicPackageName + "BasicJideSplitButtonUI");
table.put("JideComboBoxUI", basicPackageName + "BasicJideComboBoxUI");
table.put("MeterProgressBarUI", basicPackageName + "MeterProgressBarUI");
table.put("CheckBoxListUI", basicPackageName + "BasicCheckBoxListUI");
if ((products & PRODUCT_GRIDS) != 0) {
// grids
table.put("JideTableUI", basicPackageName + "BasicJideTableUI");
table.put("NavigableTableUI", basicPackageName + "BasicNavigableTableUI");
table.put("CellSpanTableUI", basicPackageName + "BasicCellSpanTableUI");
table.put("TreeTableUI", basicPackageName + "BasicTreeTableUI");
table.put("HierarchicalTableUI", basicPackageName + "BasicHierarchicalTableUI");
table.put("NestedTableHeaderUI", basicPackageName + "BasicNestedTableHeaderUI");
table.put("EditableTableHeaderUI", basicPackageName + "BasicEditableTableHeaderUI");
table.put("GroupListUI", basicPackageName + "BasicGroupListUI");
}
if ((products & PRODUCT_DOCK) != 0) {
// dock
table.put("SidePaneUI", basicPackageName + "BasicSidePaneUI");
table.put("DockableFrameUI", basicPackageName + "BasicDockableFrameUI");
}
if ((products & PRODUCT_COMPONENTS) != 0) {
// components
table.put("CollapsiblePaneUI", basicPackageName + "BasicCollapsiblePaneUI");
table.put("StatusBarSeparatorUI", basicPackageName + "BasicStatusBarSeparatorUI");
}
if ((products & PRODUCT_ACTION) != 0) {
// action
table.put("CommandBarUI", basicPackageName + "BasicCommandBarUI");
table.put("CommandBarSeparatorUI", basicPackageName + "BasicCommandBarSeparatorUI");
table.put("ChevronUI", basicPackageName + "BasicChevronUI");
table.put("CommandBarTitleBarUI", basicPackageName + "BasicCommandBarTitleBarUI");
}
}
| public static void initClassDefaults(UIDefaults table) {
int products = LookAndFeelFactory.getProductsUsed();
final String basicPackageName = "com.jidesoft.plaf.basic.";
// common
table.put("JidePopupMenuUI", basicPackageName + "BasicJidePopupMenuUI");
table.put("HeaderBoxUI", basicPackageName + "BasicHeaderBoxUI");
table.put("RangeSliderUI", basicPackageName + "BasicRangeSliderUI");
table.put("FolderChooserUI", basicPackageName + "BasicFolderChooserUI");
table.put("StyledLabelUI", basicPackageName + "BasicStyledLabelUI");
table.put("GripperUI", basicPackageName + "BasicGripperUI");
table.put("JidePopupUI", basicPackageName + "BasicJidePopupUI");
table.put("JideTabbedPaneUI", basicPackageName + "BasicJideTabbedPaneUI");
table.put("JideLabelUI", basicPackageName + "BasicJideLabelUI");
table.put("JideButtonUI", basicPackageName + "BasicJideButtonUI");
table.put("JideSplitButtonUI", basicPackageName + "BasicJideSplitButtonUI");
table.put("JideComboBoxUI", basicPackageName + "BasicJideComboBoxUI");
table.put("MeterProgressBarUI", basicPackageName + "MeterProgressBarUI");
if ((products & PRODUCT_GRIDS) != 0) {
// grids
table.put("JideTableUI", basicPackageName + "BasicJideTableUI");
table.put("NavigableTableUI", basicPackageName + "BasicNavigableTableUI");
table.put("CellSpanTableUI", basicPackageName + "BasicCellSpanTableUI");
table.put("TreeTableUI", basicPackageName + "BasicTreeTableUI");
table.put("HierarchicalTableUI", basicPackageName + "BasicHierarchicalTableUI");
table.put("NestedTableHeaderUI", basicPackageName + "BasicNestedTableHeaderUI");
table.put("EditableTableHeaderUI", basicPackageName + "BasicEditableTableHeaderUI");
table.put("GroupListUI", basicPackageName + "BasicGroupListUI");
}
if ((products & PRODUCT_DOCK) != 0) {
// dock
table.put("SidePaneUI", basicPackageName + "BasicSidePaneUI");
table.put("DockableFrameUI", basicPackageName + "BasicDockableFrameUI");
}
if ((products & PRODUCT_COMPONENTS) != 0) {
// components
table.put("CollapsiblePaneUI", basicPackageName + "BasicCollapsiblePaneUI");
table.put("StatusBarSeparatorUI", basicPackageName + "BasicStatusBarSeparatorUI");
}
if ((products & PRODUCT_ACTION) != 0) {
// action
table.put("CommandBarUI", basicPackageName + "BasicCommandBarUI");
table.put("CommandBarSeparatorUI", basicPackageName + "BasicCommandBarSeparatorUI");
table.put("ChevronUI", basicPackageName + "BasicChevronUI");
table.put("CommandBarTitleBarUI", basicPackageName + "BasicCommandBarTitleBarUI");
}
}
|
diff --git a/net.sf.eclipsefp.haskell.debug.core/src/net/sf/eclipsefp/haskell/debug/core/internal/launch/AbstractHaskellLaunchDelegate.java b/net.sf.eclipsefp.haskell.debug.core/src/net/sf/eclipsefp/haskell/debug/core/internal/launch/AbstractHaskellLaunchDelegate.java
index d50b6fb0..4e27165b 100644
--- a/net.sf.eclipsefp.haskell.debug.core/src/net/sf/eclipsefp/haskell/debug/core/internal/launch/AbstractHaskellLaunchDelegate.java
+++ b/net.sf.eclipsefp.haskell.debug.core/src/net/sf/eclipsefp/haskell/debug/core/internal/launch/AbstractHaskellLaunchDelegate.java
@@ -1,413 +1,419 @@
/**
* Copyright (c) 2012 by JP Moresmau
* This code is made available under the terms of the Eclipse Public License,
* version 1.0 (EPL). See http://www.eclipse.org/legal/epl-v10.html
*/
package net.sf.eclipsefp.haskell.debug.core.internal.launch;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.eclipsefp.haskell.core.HaskellCorePlugin;
import net.sf.eclipsefp.haskell.core.util.ResourceUtil;
import net.sf.eclipsefp.haskell.debug.core.internal.HaskellDebugCore;
import net.sf.eclipsefp.haskell.debug.core.internal.util.CoreTexts;
import net.sf.eclipsefp.haskell.util.CommandLineUtil;
import net.sf.eclipsefp.haskell.util.NetworkUtil;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.debug.core.DebugException;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.ILaunchConfigurationType;
import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
import org.eclipse.debug.core.ILaunchManager;
import org.eclipse.debug.core.ILaunchesListener2;
import org.eclipse.debug.core.model.IProcess;
import org.eclipse.debug.core.model.LaunchConfigurationDelegate;
import org.eclipse.debug.ui.DebugUITools;
import org.eclipse.debug.ui.IDebugUIConstants;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.widgets.Display;
/**
* abstract base class for our launch delegates
* @author JP Moresmau
*
*/
public abstract class AbstractHaskellLaunchDelegate extends LaunchConfigurationDelegate{
public static IInteractiveLaunchOperationDelegate getDelegate(final ILaunchConfiguration configuration) throws CoreException{
String delegateClass=configuration.getAttribute( ILaunchAttributes.DELEGATE, "" ); //$NON-NLS-1$
IInteractiveLaunchOperationDelegate delegate=null;
if (delegateClass.length()>0){
try {
delegate = InteractiveDelegateManager.getContributors().get( delegateClass );
} catch (Throwable e){
HaskellDebugCore.log( e.getLocalizedMessage(), e );
}
}
return delegate;
}
@Override
public void launch( final ILaunchConfiguration configuration,
final String mode, final ILaunch launch, IProgressMonitor monitor )
throws CoreException {
if (monitor==null){
monitor=new NullProgressMonitor();
}
if( !monitor.isCanceled() ) {
try {
IInteractiveLaunchOperationDelegate delegate=getDelegate( configuration );
monitor.beginTask( configuration.getName(), 3 );
final IPath loc =delegate!=null?new Path(delegate.getExecutable()) :
getExecutableLocation( configuration );
+ if (loc==null){
+ String msg = CoreTexts.haskellLaunchDelegate_noExe;
+ String pluginId = HaskellDebugCore.getPluginId();
+ IStatus status = new Status( IStatus.ERROR, pluginId, 0, msg, null );
+ throw new CoreException( status );
+ }
checkCancellation( monitor );
String[] arguments = determineArguments( configuration,delegate,mode );
checkCancellation( monitor );
String[] cmdLine = createCmdLine( loc, arguments );
checkCancellation( monitor );
File workingDir = determineWorkingDir( configuration );
checkCancellation( monitor );
monitor.worked( 1 );
IProcess process = createProcess( configuration, mode, launch, loc,
cmdLine, workingDir );
monitor.worked( 1 );
if( process != null ) {
postProcessCreation( configuration, mode, launch, process );
}
monitor.done();
/*
* DebugPlugin.getDefault().getLaunchManager().addLaunchListener( new
* ILaunchesListener() {
*
* public void launchesRemoved( final ILaunch[] launches ) { for
* (ILaunch l:launches){ System.out.println("removed:" +l.toString()); }
*
* }
*
* public void launchesChanged( final ILaunch[] launches ) { for
* (ILaunch l:launches){ System.out.println("changed:" +l.toString()); }
*
* }
*
* public void launchesAdded( final ILaunch[] launches ) { for (ILaunch
* l:launches){ System.out.println("added:" +l.toString()); }
*
* } });
*/
if( process != null ) {
if ( isBackground( configuration ) || Display.findDisplay( Thread.currentThread())!=null) {
final IProcess theProcess = process;
Job endJob = new Job( NLS.bind( CoreTexts.running , loc.toOSString() )) {
@Override
protected IStatus run( final IProgressMonitor mon ) {
try {
while( !theProcess.isTerminated() ) {
try {
if( mon.isCanceled()) {
theProcess.terminate();
return Status.CANCEL_STATUS;
}
Thread.sleep( 50 );
} catch( InterruptedException iex ) {
// ignored
} catch ( DebugException ex ) {
// ignored
}
}
} finally {
try {
postProcessFinished(configuration);
} catch(CoreException ce){
HaskellCorePlugin.log( ce );
}
}
return Status.OK_STATUS;
}
};
endJob.schedule();
} else {
while( !process.isTerminated() ) {
try {
- if(monitor!=null && monitor.isCanceled() ) {
+ if(monitor.isCanceled() ) {
process.terminate();
break;
}
Thread.sleep( 50 );
} catch( InterruptedException iex ) {
// ignored
}
}
postProcessFinished(configuration);
}
}
} catch( LaunchCancelledException lcex ) {
// canceled on user request
}
}
}
protected abstract void postProcessCreation(final ILaunchConfiguration configuration,
final String mode,final ILaunch launch,IProcess process) throws CoreException;
protected abstract void preProcessCreation(final ILaunchConfiguration configuration,
final String mode,final ILaunch launch,Map<String, String> processAttribs) throws CoreException;
protected abstract void preProcessDefinitionCreation(final ILaunchConfiguration configuration,
final String mode,final ILaunch launch) throws CoreException;
protected abstract void postProcessFinished(final ILaunchConfiguration configuration) throws CoreException;
protected IProcess createProcess( final ILaunchConfiguration configuration,
final String mode, final ILaunch launch, final IPath location,
final String[] cmdLine, final File workingDir ) throws CoreException {
// Process proc = DebugPlugin.exec( cmdLine, workingDir );
ProcessBuilder pb = new ProcessBuilder( cmdLine );
pb.directory( workingDir );
if( configuration.getAttribute( ILaunchAttributes.SYNC_STREAMS, true ) ) {
pb.redirectErrorStream( true );
}
if (configuration.getAttribute( ILaunchAttributes.NEEDS_HTTP_PROXY, false ) ) {
NetworkUtil.addHTTP_PROXY_env( pb,NetworkUtil.HACKAGE_URL );
}
try {
preProcessDefinitionCreation( configuration, mode, launch );
Map<String, String> processAttrs = new HashMap<String, String>();
String programName = determineProgramName( location );
processAttrs.put( IProcess.ATTR_PROCESS_TYPE, programName );
preProcessCreation( configuration, mode, launch, processAttrs );
IProcess process = null;
Process proc = pb.start();
if( proc != null ) {
//String loc = location.toOSString();
// process = new RuntimeProcess( launch, proc, configuration.getName(), processAttrs){
// @Override
// protected org.eclipse.debug.core.model.IStreamsProxy createStreamsProxy() {
//
// String encoding = getLaunch().getAttribute(DebugPlugin.ATTR_CONSOLE_ENCODING);
// return new DelayedStreamsProxy(getSystemProcess(), encoding);
// }
// };
process=DebugPlugin.newProcess( launch, proc, configuration.getName(), processAttrs );
process.setAttribute( IProcess.ATTR_CMDLINE, CommandLineUtil
.renderCommandLine( cmdLine ) );
}
return process;
} catch( IOException e ) {
Status status = new Status( IStatus.ERROR,
HaskellDebugCore.getPluginId(),
CoreTexts.haskellLaunchDelegate_noProcess, e );
throw new CoreException( status );
}
}
private String[] createCmdLine(final IPath location, final String[] arguments ) {
int cmdLineLength = 1;
if( arguments != null ) {
cmdLineLength += arguments.length;
}
String[] cmdLine = new String[ cmdLineLength ];
cmdLine[ 0 ] = location.toOSString();
if( arguments != null ) {
System.arraycopy( arguments, 0, cmdLine, 1, arguments.length );
}
return cmdLine;
}
protected File determineWorkingDir( final ILaunchConfiguration config )
throws CoreException {
String name = ILaunchAttributes.WORKING_DIRECTORY;
String attribute = config.getAttribute( name, ( String )null );
File result = null;
if( attribute != null ) {
result = new Path( attribute ).toFile();
}
return result;
}
String[] determineArguments( final ILaunchConfiguration config,final IInteractiveLaunchOperationDelegate delegate,final String mode )
throws CoreException {
String extra = config.getAttribute( ILaunchAttributes.EXTRA_ARGUMENTS,
ILaunchAttributes.EMPTY );
String args = config.getAttribute( ILaunchAttributes.ARGUMENTS,
ILaunchAttributes.EMPTY );
String[] fullArgs=CommandLineUtil.parse( extra + " " + args ); //$NON-NLS-1$
String[] delegateArgs=getDelegateArguments(config,delegate,mode);
if (delegateArgs.length>0){
String[] newArgs=new String[fullArgs.length+delegateArgs.length];
System.arraycopy( fullArgs, 0, newArgs, 0, fullArgs.length );
System.arraycopy( delegateArgs, 0, newArgs, fullArgs.length, delegateArgs.length );
fullArgs=newArgs;
}
return fullArgs;
}
public static String[] getDelegateArguments(final ILaunchConfiguration config,final IInteractiveLaunchOperationDelegate delegate,final String mode)throws CoreException{
if (delegate!=null){
IProject p=getProject( config );
List<String> fileNames=config.getAttribute( ILaunchAttributes.FILES, new ArrayList<String>() );
IFile[] files=new IFile[fileNames.size()];
for (int a=0;a<fileNames.size();a++){
files[a]=p.getFile( fileNames.get(a) );
}
return delegate.createArguments(p , files,mode );
}
return new String[0];
}
private void checkCancellation( final IProgressMonitor monitor ) {
if(monitor!=null && monitor.isCanceled() ) {
throw new LaunchCancelledException();
}
}
private String determineProgramName( final IPath location ) {
String programName = location.lastSegment();
String extension = location.getFileExtension();
if( extension != null ) {
int len = programName.length() - ( extension.length() + 1 );
programName = programName.substring( 0, len );
}
return programName.toLowerCase();
}
// helping methods
// ////////////////
public IPath getExecutableLocation( final ILaunchConfiguration config )
throws CoreException {
String location = config.getAttribute( ILaunchAttributes.EXECUTABLE,
(String)null );
if( isEmpty( location ) ) {
String stanza = config.getAttribute( ILaunchAttributes.STANZA,
(String)null );
if (isEmpty( stanza )){
String msg = CoreTexts.haskellLaunchDelegate_noExe;
String pluginId = HaskellDebugCore.getPluginId();
IStatus status = new Status( IStatus.ERROR, pluginId, 0, msg, null );
throw new CoreException( status );
}
return ResourceUtil.getExecutableLocation( getProject( config ), stanza ).getLocation();
}
return new Path( location );
}
public static IProject getProject(final ILaunchConfiguration config)throws CoreException{
String prj=config.getAttribute( ILaunchAttributes.PROJECT_NAME, (String)null );
if (prj!=null){
IProject p=ResourcesPlugin.getWorkspace().getRoot().getProject( prj );
if (p!=null){
return p;
}
}
return null;
}
protected boolean isEmpty( final String location ) {
return location == null || location.trim().length() == 0;
}
private boolean isBackground( final ILaunchConfiguration config )
throws CoreException {
return config.getAttribute( ILaunchAttributes.RUN_IN_BACKGROUND, true );
}
private class LaunchCancelledException extends RuntimeException {
private static final long serialVersionUID = 1912643423745032866L;
private LaunchCancelledException() {
super();
}
}
public static void runInConsole(final IProject prj,final List<String> commands,final File directory,final String title,final boolean needsHTTP_PROXY) throws CoreException{
runInConsole( prj, commands, directory, title, needsHTTP_PROXY,null );
}
public static void runInConsole(final IProject prj,final List<String> commands,final File directory,final String title,final boolean needsHTTP_PROXY,final Runnable after) throws CoreException{
final ILaunchManager launchManager = DebugPlugin.getDefault().getLaunchManager();
String configTypeId = ExecutableHaskellLaunchDelegate.class.getName();
ILaunchConfigurationType configType = launchManager.getLaunchConfigurationType( configTypeId );
final ILaunchConfigurationWorkingCopy wc=configType.newInstance( null,launchManager.generateLaunchConfigurationName(title) );//launchManager.generateUniqueLaunchConfigurationNameFrom( title));
// if private, we don't get the save dialog for unsaved files in project
wc.setAttribute( IDebugUIConstants.ATTR_PRIVATE, prj==null );
wc.setAttribute( IDebugUIConstants.ATTR_LAUNCH_IN_BACKGROUND, false );
wc.setAttribute( IDebugUIConstants.ATTR_CAPTURE_IN_CONSOLE, true );
if (prj!=null){
wc.setAttribute(ILaunchAttributes.PROJECT_NAME,prj.getName());
}
wc.setAttribute(ILaunchAttributes.EXECUTABLE,commands.get( 0 ));
if (directory!=null){
wc.setAttribute(ILaunchAttributes.WORKING_DIRECTORY,directory.getAbsolutePath());
}
if (commands.size()>1){
wc.setAttribute(ILaunchAttributes.EXTRA_ARGUMENTS,CommandLineUtil.renderCommandLine( commands.subList( 1, commands.size() ) ));
}
wc.setAttribute( ILaunchAttributes.NEEDS_HTTP_PROXY, needsHTTP_PROXY );
if (after!=null){
ILaunchesListener2 l=new ILaunchesListener2() {
@Override
public void launchesRemoved( final ILaunch[] paramArrayOfILaunch ) {
// NOOP
}
@Override
public void launchesChanged( final ILaunch[] paramArrayOfILaunch ) {
// NOOP
}
@Override
public void launchesAdded( final ILaunch[] paramArrayOfILaunch ) {
// NOOP
}
@Override
public void launchesTerminated( final ILaunch[] paramArrayOfILaunch ) {
for (ILaunch la:paramArrayOfILaunch){
if (la.getLaunchConfiguration()==wc){
after.run();
launchManager.removeLaunchListener( this );
}
}
}
};
launchManager.addLaunchListener( l );
}
// makes the console opens consistently
DebugUITools.launch( wc, ILaunchManager.RUN_MODE );
}
}
| false | true | public void launch( final ILaunchConfiguration configuration,
final String mode, final ILaunch launch, IProgressMonitor monitor )
throws CoreException {
if (monitor==null){
monitor=new NullProgressMonitor();
}
if( !monitor.isCanceled() ) {
try {
IInteractiveLaunchOperationDelegate delegate=getDelegate( configuration );
monitor.beginTask( configuration.getName(), 3 );
final IPath loc =delegate!=null?new Path(delegate.getExecutable()) :
getExecutableLocation( configuration );
checkCancellation( monitor );
String[] arguments = determineArguments( configuration,delegate,mode );
checkCancellation( monitor );
String[] cmdLine = createCmdLine( loc, arguments );
checkCancellation( monitor );
File workingDir = determineWorkingDir( configuration );
checkCancellation( monitor );
monitor.worked( 1 );
IProcess process = createProcess( configuration, mode, launch, loc,
cmdLine, workingDir );
monitor.worked( 1 );
if( process != null ) {
postProcessCreation( configuration, mode, launch, process );
}
monitor.done();
/*
* DebugPlugin.getDefault().getLaunchManager().addLaunchListener( new
* ILaunchesListener() {
*
* public void launchesRemoved( final ILaunch[] launches ) { for
* (ILaunch l:launches){ System.out.println("removed:" +l.toString()); }
*
* }
*
* public void launchesChanged( final ILaunch[] launches ) { for
* (ILaunch l:launches){ System.out.println("changed:" +l.toString()); }
*
* }
*
* public void launchesAdded( final ILaunch[] launches ) { for (ILaunch
* l:launches){ System.out.println("added:" +l.toString()); }
*
* } });
*/
if( process != null ) {
if ( isBackground( configuration ) || Display.findDisplay( Thread.currentThread())!=null) {
final IProcess theProcess = process;
Job endJob = new Job( NLS.bind( CoreTexts.running , loc.toOSString() )) {
@Override
protected IStatus run( final IProgressMonitor mon ) {
try {
while( !theProcess.isTerminated() ) {
try {
if( mon.isCanceled()) {
theProcess.terminate();
return Status.CANCEL_STATUS;
}
Thread.sleep( 50 );
} catch( InterruptedException iex ) {
// ignored
} catch ( DebugException ex ) {
// ignored
}
}
} finally {
try {
postProcessFinished(configuration);
} catch(CoreException ce){
HaskellCorePlugin.log( ce );
}
}
return Status.OK_STATUS;
}
};
endJob.schedule();
} else {
while( !process.isTerminated() ) {
try {
if(monitor!=null && monitor.isCanceled() ) {
process.terminate();
break;
}
Thread.sleep( 50 );
} catch( InterruptedException iex ) {
// ignored
}
}
postProcessFinished(configuration);
}
}
} catch( LaunchCancelledException lcex ) {
// canceled on user request
}
}
}
| public void launch( final ILaunchConfiguration configuration,
final String mode, final ILaunch launch, IProgressMonitor monitor )
throws CoreException {
if (monitor==null){
monitor=new NullProgressMonitor();
}
if( !monitor.isCanceled() ) {
try {
IInteractiveLaunchOperationDelegate delegate=getDelegate( configuration );
monitor.beginTask( configuration.getName(), 3 );
final IPath loc =delegate!=null?new Path(delegate.getExecutable()) :
getExecutableLocation( configuration );
if (loc==null){
String msg = CoreTexts.haskellLaunchDelegate_noExe;
String pluginId = HaskellDebugCore.getPluginId();
IStatus status = new Status( IStatus.ERROR, pluginId, 0, msg, null );
throw new CoreException( status );
}
checkCancellation( monitor );
String[] arguments = determineArguments( configuration,delegate,mode );
checkCancellation( monitor );
String[] cmdLine = createCmdLine( loc, arguments );
checkCancellation( monitor );
File workingDir = determineWorkingDir( configuration );
checkCancellation( monitor );
monitor.worked( 1 );
IProcess process = createProcess( configuration, mode, launch, loc,
cmdLine, workingDir );
monitor.worked( 1 );
if( process != null ) {
postProcessCreation( configuration, mode, launch, process );
}
monitor.done();
/*
* DebugPlugin.getDefault().getLaunchManager().addLaunchListener( new
* ILaunchesListener() {
*
* public void launchesRemoved( final ILaunch[] launches ) { for
* (ILaunch l:launches){ System.out.println("removed:" +l.toString()); }
*
* }
*
* public void launchesChanged( final ILaunch[] launches ) { for
* (ILaunch l:launches){ System.out.println("changed:" +l.toString()); }
*
* }
*
* public void launchesAdded( final ILaunch[] launches ) { for (ILaunch
* l:launches){ System.out.println("added:" +l.toString()); }
*
* } });
*/
if( process != null ) {
if ( isBackground( configuration ) || Display.findDisplay( Thread.currentThread())!=null) {
final IProcess theProcess = process;
Job endJob = new Job( NLS.bind( CoreTexts.running , loc.toOSString() )) {
@Override
protected IStatus run( final IProgressMonitor mon ) {
try {
while( !theProcess.isTerminated() ) {
try {
if( mon.isCanceled()) {
theProcess.terminate();
return Status.CANCEL_STATUS;
}
Thread.sleep( 50 );
} catch( InterruptedException iex ) {
// ignored
} catch ( DebugException ex ) {
// ignored
}
}
} finally {
try {
postProcessFinished(configuration);
} catch(CoreException ce){
HaskellCorePlugin.log( ce );
}
}
return Status.OK_STATUS;
}
};
endJob.schedule();
} else {
while( !process.isTerminated() ) {
try {
if(monitor.isCanceled() ) {
process.terminate();
break;
}
Thread.sleep( 50 );
} catch( InterruptedException iex ) {
// ignored
}
}
postProcessFinished(configuration);
}
}
} catch( LaunchCancelledException lcex ) {
// canceled on user request
}
}
}
|
diff --git a/org.springframework.jms/src/main/java/org/springframework/jms/listener/AbstractPollingMessageListenerContainer.java b/org.springframework.jms/src/main/java/org/springframework/jms/listener/AbstractPollingMessageListenerContainer.java
index af0c0f8b2..cd7bcaa03 100644
--- a/org.springframework.jms/src/main/java/org/springframework/jms/listener/AbstractPollingMessageListenerContainer.java
+++ b/org.springframework.jms/src/main/java/org/springframework/jms/listener/AbstractPollingMessageListenerContainer.java
@@ -1,518 +1,518 @@
/*
* Copyright 2002-2010 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.jms.listener;
import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.Topic;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.jms.connection.ConnectionFactoryUtils;
import org.springframework.jms.connection.JmsResourceHolder;
import org.springframework.jms.connection.SingleConnectionFactory;
import org.springframework.jms.support.JmsUtils;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.transaction.support.ResourceTransactionManager;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.transaction.support.TransactionSynchronizationUtils;
/**
* Base class for listener container implementations which are based on polling.
* Provides support for listener handling based on {@link javax.jms.MessageConsumer},
* optionally participating in externally managed transactions.
*
* <p>This listener container variant is built for repeated polling attempts,
* each invoking the {@link #receiveAndExecute} method. The MessageConsumer used
* may be reobtained fo reach attempt or cached inbetween attempts; this is up
* to the concrete implementation. The receive timeout for each attempt can be
* configured through the {@link #setReceiveTimeout "receiveTimeout"} property.
*
* <p>The underlying mechanism is based on standard JMS MessageConsumer handling,
* which is perfectly compatible with both native JMS and JMS in a J2EE environment.
* Neither the JMS <code>MessageConsumer.setMessageListener</code> facility
* nor the JMS ServerSessionPool facility is required. A further advantage
* of this approach is full control over the listening process, allowing for
* custom scaling and throttling and of concurrent message processing
* (which is up to concrete subclasses).
*
* <p>Message reception and listener execution can automatically be wrapped
* in transactions through passing a Spring
* {@link org.springframework.transaction.PlatformTransactionManager} into the
* {@link #setTransactionManager "transactionManager"} property. This will usually
* be a {@link org.springframework.transaction.jta.JtaTransactionManager} in a
* J2EE enviroment, in combination with a JTA-aware JMS ConnectionFactory obtained
* from JNDI (check your J2EE server's documentation).
*
* <p>This base class does not assume any specific mechanism for asynchronous
* execution of polling invokers. Check out {@link DefaultMessageListenerContainer}
* for a concrete implementation which is based on Spring's
* {@link org.springframework.core.task.TaskExecutor} abstraction,
* including dynamic scaling of concurrent consumers and automatic self recovery.
*
* @author Juergen Hoeller
* @since 2.0.3
* @see #createListenerConsumer
* @see #receiveAndExecute
* @see #setTransactionManager
*/
public abstract class AbstractPollingMessageListenerContainer extends AbstractMessageListenerContainer
implements BeanNameAware {
/**
* The default receive timeout: 1000 ms = 1 second.
*/
public static final long DEFAULT_RECEIVE_TIMEOUT = 1000;
private final MessageListenerContainerResourceFactory transactionalResourceFactory =
new MessageListenerContainerResourceFactory();
private boolean sessionTransactedCalled = false;
private boolean pubSubNoLocal = false;
private PlatformTransactionManager transactionManager;
private DefaultTransactionDefinition transactionDefinition = new DefaultTransactionDefinition();
private long receiveTimeout = DEFAULT_RECEIVE_TIMEOUT;
public void setSessionTransacted(boolean sessionTransacted) {
super.setSessionTransacted(sessionTransacted);
this.sessionTransactedCalled = true;
}
/**
* Set whether to inhibit the delivery of messages published by its own connection.
* Default is "false".
* @see javax.jms.TopicSession#createSubscriber(javax.jms.Topic, String, boolean)
*/
public void setPubSubNoLocal(boolean pubSubNoLocal) {
this.pubSubNoLocal = pubSubNoLocal;
}
/**
* Return whether to inhibit the delivery of messages published by its own connection.
*/
protected boolean isPubSubNoLocal() {
return this.pubSubNoLocal;
}
/**
* Specify the Spring {@link org.springframework.transaction.PlatformTransactionManager}
* to use for transactional wrapping of message reception plus listener execution.
* <p>Default is none, not performing any transactional wrapping.
* If specified, this will usually be a Spring
* {@link org.springframework.transaction.jta.JtaTransactionManager} or one
* of its subclasses, in combination with a JTA-aware ConnectionFactory that
* this message listener container obtains its Connections from.
* <p><b>Note: Consider the use of local JMS transactions instead.</b>
* Simply switch the {@link #setSessionTransacted "sessionTransacted"} flag
* to "true" in order to use a locally transacted JMS Session for the entire
* receive processing, including any Session operations performed by a
* {@link SessionAwareMessageListener} (e.g. sending a response message).
* Alternatively, a {@link org.springframework.jms.connection.JmsTransactionManager}
* may be used for fully synchronized Spring transactions based on local JMS
* transactions. Check {@link AbstractMessageListenerContainer}'s javadoc for
* a discussion of transaction choices and message redelivery scenarios.
* @see org.springframework.transaction.jta.JtaTransactionManager
* @see org.springframework.jms.connection.JmsTransactionManager
*/
public void setTransactionManager(PlatformTransactionManager transactionManager) {
this.transactionManager = transactionManager;
}
/**
* Return the Spring PlatformTransactionManager to use for transactional
* wrapping of message reception plus listener execution.
*/
protected final PlatformTransactionManager getTransactionManager() {
return this.transactionManager;
}
/**
* Specify the transaction name to use for transactional wrapping.
* Default is the bean name of this listener container, if any.
* @see org.springframework.transaction.TransactionDefinition#getName()
*/
public void setTransactionName(String transactionName) {
this.transactionDefinition.setName(transactionName);
}
/**
* Specify the transaction timeout to use for transactional wrapping, in <b>seconds</b>.
* Default is none, using the transaction manager's default timeout.
* @see org.springframework.transaction.TransactionDefinition#getTimeout()
* @see #setReceiveTimeout
*/
public void setTransactionTimeout(int transactionTimeout) {
this.transactionDefinition.setTimeout(transactionTimeout);
}
/**
* Set the timeout to use for receive calls, in <b>milliseconds</b>.
* The default is 1000 ms, that is, 1 second.
* <p><b>NOTE:</b> This value needs to be smaller than the transaction
* timeout used by the transaction manager (in the appropriate unit,
* of course). -1 indicates no timeout at all; however, this is only
* feasible if not running within a transaction manager.
* @see javax.jms.MessageConsumer#receive(long)
* @see javax.jms.MessageConsumer#receive()
* @see #setTransactionTimeout
*/
public void setReceiveTimeout(long receiveTimeout) {
this.receiveTimeout = receiveTimeout;
}
public void initialize() {
// Set sessionTransacted=true in case of a non-JTA transaction manager.
if (!this.sessionTransactedCalled &&
this.transactionManager instanceof ResourceTransactionManager &&
!TransactionSynchronizationUtils.sameResourceFactory(
(ResourceTransactionManager) this.transactionManager, getConnectionFactory())) {
super.setSessionTransacted(true);
}
// Use bean name as default transaction name.
if (this.transactionDefinition.getName() == null) {
this.transactionDefinition.setName(getBeanName());
}
// Proceed with superclass initialization.
super.initialize();
}
/**
* Create a MessageConsumer for the given JMS Session,
* registering a MessageListener for the specified listener.
* @param session the JMS Session to work on
* @return the MessageConsumer
* @throws javax.jms.JMSException if thrown by JMS methods
* @see #receiveAndExecute
*/
protected MessageConsumer createListenerConsumer(Session session) throws JMSException {
Destination destination = getDestination();
if (destination == null) {
destination = resolveDestinationName(session, getDestinationName());
}
return createConsumer(session, destination);
}
/**
* Execute the listener for a message received from the given consumer,
* wrapping the entire operation in an external transaction if demanded.
* @param session the JMS Session to work on
* @param consumer the MessageConsumer to work on
* @return whether a message has been received
* @throws JMSException if thrown by JMS methods
* @see #doReceiveAndExecute
*/
protected boolean receiveAndExecute(Object invoker, Session session, MessageConsumer consumer)
throws JMSException {
if (this.transactionManager != null) {
// Execute receive within transaction.
TransactionStatus status = this.transactionManager.getTransaction(this.transactionDefinition);
boolean messageReceived;
try {
messageReceived = doReceiveAndExecute(invoker, session, consumer, status);
}
catch (JMSException ex) {
rollbackOnException(status, ex);
throw ex;
}
catch (RuntimeException ex) {
rollbackOnException(status, ex);
throw ex;
}
catch (Error err) {
rollbackOnException(status, err);
throw err;
}
this.transactionManager.commit(status);
return messageReceived;
}
else {
// Execute receive outside of transaction.
return doReceiveAndExecute(invoker, session, consumer, null);
}
}
/**
* Actually execute the listener for a message received from the given consumer,
* fetching all requires resources and invoking the listener.
* @param session the JMS Session to work on
* @param consumer the MessageConsumer to work on
* @param status the TransactionStatus (may be <code>null</code>)
* @return whether a message has been received
* @throws JMSException if thrown by JMS methods
* @see #doExecuteListener(javax.jms.Session, javax.jms.Message)
*/
protected boolean doReceiveAndExecute(
Object invoker, Session session, MessageConsumer consumer, TransactionStatus status)
throws JMSException {
Connection conToClose = null;
Session sessionToClose = null;
MessageConsumer consumerToClose = null;
try {
Session sessionToUse = session;
boolean transactional = false;
if (sessionToUse == null) {
sessionToUse = ConnectionFactoryUtils.doGetTransactionalSession(
getConnectionFactory(), this.transactionalResourceFactory, true);
transactional = (sessionToUse != null);
}
if (sessionToUse == null) {
Connection conToUse;
if (sharedConnectionEnabled()) {
conToUse = getSharedConnection();
}
else {
conToUse = createConnection();
conToClose = conToUse;
conToUse.start();
}
sessionToUse = createSession(conToUse);
sessionToClose = sessionToUse;
}
MessageConsumer consumerToUse = consumer;
if (consumerToUse == null) {
consumerToUse = createListenerConsumer(sessionToUse);
consumerToClose = consumerToUse;
}
Message message = receiveMessage(consumerToUse);
if (message != null) {
if (logger.isDebugEnabled()) {
logger.debug("Received message of type [" + message.getClass() + "] from consumer [" +
consumerToUse + "] of " + (transactional ? "transactional " : "") + "session [" +
sessionToUse + "]");
}
messageReceived(invoker, sessionToUse);
boolean exposeResource = (!transactional && isExposeListenerSession() &&
!TransactionSynchronizationManager.hasResource(getConnectionFactory()));
if (exposeResource) {
TransactionSynchronizationManager.bindResource(
getConnectionFactory(), new LocallyExposedJmsResourceHolder(sessionToUse));
}
try {
doExecuteListener(sessionToUse, message);
}
catch (Throwable ex) {
if (status != null) {
if (logger.isDebugEnabled()) {
logger.debug("Rolling back transaction because of listener exception thrown: " + ex);
}
status.setRollbackOnly();
}
handleListenerException(ex);
// Rethrow JMSException to indicate an infrastructure problem
// that may have to trigger recovery...
if (ex instanceof JMSException) {
throw (JMSException) ex;
}
}
finally {
if (exposeResource) {
TransactionSynchronizationManager.unbindResource(getConnectionFactory());
}
}
// Indicate that a message has been received.
return true;
}
else {
if (logger.isTraceEnabled()) {
logger.trace("Consumer [" + consumerToUse + "] of " + (transactional ? "transactional " : "") +
"session [" + sessionToUse + "] did not receive a message");
}
noMessageReceived(invoker, sessionToUse);
// Nevertheless call commit, in order to reset the transaction timeout (if any).
- commitIfNecessary(session, message);
+ commitIfNecessary(sessionToUse, message);
// Indicate that no message has been received.
return false;
}
}
finally {
JmsUtils.closeMessageConsumer(consumerToClose);
JmsUtils.closeSession(sessionToClose);
ConnectionFactoryUtils.releaseConnection(conToClose, getConnectionFactory(), true);
}
}
/**
* This implementation checks whether the Session is externally synchronized.
* In this case, the Session is not locally transacted, despite the listener
* container's "sessionTransacted" flag being set to "true".
* @see org.springframework.jms.connection.JmsResourceHolder
*/
protected boolean isSessionLocallyTransacted(Session session) {
if (!super.isSessionLocallyTransacted(session)) {
return false;
}
JmsResourceHolder resourceHolder =
(JmsResourceHolder) TransactionSynchronizationManager.getResource(getConnectionFactory());
return (resourceHolder == null || resourceHolder instanceof LocallyExposedJmsResourceHolder ||
!resourceHolder.containsSession(session));
}
/**
* Perform a rollback, handling rollback exceptions properly.
* @param status object representing the transaction
* @param ex the thrown listener exception or error
*/
private void rollbackOnException(TransactionStatus status, Throwable ex) {
logger.debug("Initiating transaction rollback on listener exception", ex);
try {
this.transactionManager.rollback(status);
}
catch (RuntimeException ex2) {
logger.error("Listener exception overridden by rollback exception", ex);
throw ex2;
}
catch (Error err) {
logger.error("Listener exception overridden by rollback error", ex);
throw err;
}
}
/**
* Receive a message from the given consumer.
* @param consumer the MessageConsumer to use
* @return the Message, or <code>null</code> if none
* @throws JMSException if thrown by JMS methods
*/
protected Message receiveMessage(MessageConsumer consumer) throws JMSException {
return (this.receiveTimeout < 0 ? consumer.receive() : consumer.receive(this.receiveTimeout));
}
/**
* Template method that gets called right when a new message has been received,
* before attempting to process it. Allows subclasses to react to the event
* of an actual incoming message, for example adapting their consumer count.
* @param invoker the invoker object (passed through)
* @param session the receiving JMS Session
*/
protected void messageReceived(Object invoker, Session session) {
}
/**
* Template method that gets called when <i>no</i> message has been received,
* before returning to the receive loop again. Allows subclasses to react to
* the event of no incoming message, for example marking the invoker as idle.
* @param invoker the invoker object (passed through)
* @param session the receiving JMS Session
*/
protected void noMessageReceived(Object invoker, Session session) {
}
//-------------------------------------------------------------------------
// JMS 1.1 factory methods, potentially overridden for JMS 1.0.2
//-------------------------------------------------------------------------
/**
* Fetch an appropriate Connection from the given JmsResourceHolder.
* <p>This implementation accepts any JMS 1.1 Connection.
* @param holder the JmsResourceHolder
* @return an appropriate Connection fetched from the holder,
* or <code>null</code> if none found
*/
protected Connection getConnection(JmsResourceHolder holder) {
return holder.getConnection();
}
/**
* Fetch an appropriate Session from the given JmsResourceHolder.
* <p>This implementation accepts any JMS 1.1 Session.
* @param holder the JmsResourceHolder
* @return an appropriate Session fetched from the holder,
* or <code>null</code> if none found
*/
protected Session getSession(JmsResourceHolder holder) {
return holder.getSession();
}
/**
* Create a JMS MessageConsumer for the given Session and Destination.
* <p>This implementation uses JMS 1.1 API.
* @param session the JMS Session to create a MessageConsumer for
* @param destination the JMS Destination to create a MessageConsumer for
* @return the new JMS MessageConsumer
* @throws javax.jms.JMSException if thrown by JMS API methods
*/
protected MessageConsumer createConsumer(Session session, Destination destination) throws JMSException {
// Only pass in the NoLocal flag in case of a Topic:
// Some JMS providers, such as WebSphere MQ 6.0, throw IllegalStateException
// in case of the NoLocal flag being specified for a Queue.
if (isPubSubDomain()) {
if (isSubscriptionDurable() && destination instanceof Topic) {
return session.createDurableSubscriber(
(Topic) destination, getDurableSubscriptionName(), getMessageSelector(), isPubSubNoLocal());
}
else {
return session.createConsumer(destination, getMessageSelector(), isPubSubNoLocal());
}
}
else {
return session.createConsumer(destination, getMessageSelector());
}
}
/**
* ResourceFactory implementation that delegates to this listener container's protected callback methods.
*/
private class MessageListenerContainerResourceFactory implements ConnectionFactoryUtils.ResourceFactory {
public Connection getConnection(JmsResourceHolder holder) {
return AbstractPollingMessageListenerContainer.this.getConnection(holder);
}
public Session getSession(JmsResourceHolder holder) {
return AbstractPollingMessageListenerContainer.this.getSession(holder);
}
public Connection createConnection() throws JMSException {
if (AbstractPollingMessageListenerContainer.this.sharedConnectionEnabled()) {
Connection sharedCon = AbstractPollingMessageListenerContainer.this.getSharedConnection();
return new SingleConnectionFactory(sharedCon).createConnection();
}
else {
return AbstractPollingMessageListenerContainer.this.createConnection();
}
}
public Session createSession(Connection con) throws JMSException {
return AbstractPollingMessageListenerContainer.this.createSession(con);
}
public boolean isSynchedLocalTransactionAllowed() {
return AbstractPollingMessageListenerContainer.this.isSessionTransacted();
}
}
}
| true | true | protected boolean doReceiveAndExecute(
Object invoker, Session session, MessageConsumer consumer, TransactionStatus status)
throws JMSException {
Connection conToClose = null;
Session sessionToClose = null;
MessageConsumer consumerToClose = null;
try {
Session sessionToUse = session;
boolean transactional = false;
if (sessionToUse == null) {
sessionToUse = ConnectionFactoryUtils.doGetTransactionalSession(
getConnectionFactory(), this.transactionalResourceFactory, true);
transactional = (sessionToUse != null);
}
if (sessionToUse == null) {
Connection conToUse;
if (sharedConnectionEnabled()) {
conToUse = getSharedConnection();
}
else {
conToUse = createConnection();
conToClose = conToUse;
conToUse.start();
}
sessionToUse = createSession(conToUse);
sessionToClose = sessionToUse;
}
MessageConsumer consumerToUse = consumer;
if (consumerToUse == null) {
consumerToUse = createListenerConsumer(sessionToUse);
consumerToClose = consumerToUse;
}
Message message = receiveMessage(consumerToUse);
if (message != null) {
if (logger.isDebugEnabled()) {
logger.debug("Received message of type [" + message.getClass() + "] from consumer [" +
consumerToUse + "] of " + (transactional ? "transactional " : "") + "session [" +
sessionToUse + "]");
}
messageReceived(invoker, sessionToUse);
boolean exposeResource = (!transactional && isExposeListenerSession() &&
!TransactionSynchronizationManager.hasResource(getConnectionFactory()));
if (exposeResource) {
TransactionSynchronizationManager.bindResource(
getConnectionFactory(), new LocallyExposedJmsResourceHolder(sessionToUse));
}
try {
doExecuteListener(sessionToUse, message);
}
catch (Throwable ex) {
if (status != null) {
if (logger.isDebugEnabled()) {
logger.debug("Rolling back transaction because of listener exception thrown: " + ex);
}
status.setRollbackOnly();
}
handleListenerException(ex);
// Rethrow JMSException to indicate an infrastructure problem
// that may have to trigger recovery...
if (ex instanceof JMSException) {
throw (JMSException) ex;
}
}
finally {
if (exposeResource) {
TransactionSynchronizationManager.unbindResource(getConnectionFactory());
}
}
// Indicate that a message has been received.
return true;
}
else {
if (logger.isTraceEnabled()) {
logger.trace("Consumer [" + consumerToUse + "] of " + (transactional ? "transactional " : "") +
"session [" + sessionToUse + "] did not receive a message");
}
noMessageReceived(invoker, sessionToUse);
// Nevertheless call commit, in order to reset the transaction timeout (if any).
commitIfNecessary(session, message);
// Indicate that no message has been received.
return false;
}
}
finally {
JmsUtils.closeMessageConsumer(consumerToClose);
JmsUtils.closeSession(sessionToClose);
ConnectionFactoryUtils.releaseConnection(conToClose, getConnectionFactory(), true);
}
}
| protected boolean doReceiveAndExecute(
Object invoker, Session session, MessageConsumer consumer, TransactionStatus status)
throws JMSException {
Connection conToClose = null;
Session sessionToClose = null;
MessageConsumer consumerToClose = null;
try {
Session sessionToUse = session;
boolean transactional = false;
if (sessionToUse == null) {
sessionToUse = ConnectionFactoryUtils.doGetTransactionalSession(
getConnectionFactory(), this.transactionalResourceFactory, true);
transactional = (sessionToUse != null);
}
if (sessionToUse == null) {
Connection conToUse;
if (sharedConnectionEnabled()) {
conToUse = getSharedConnection();
}
else {
conToUse = createConnection();
conToClose = conToUse;
conToUse.start();
}
sessionToUse = createSession(conToUse);
sessionToClose = sessionToUse;
}
MessageConsumer consumerToUse = consumer;
if (consumerToUse == null) {
consumerToUse = createListenerConsumer(sessionToUse);
consumerToClose = consumerToUse;
}
Message message = receiveMessage(consumerToUse);
if (message != null) {
if (logger.isDebugEnabled()) {
logger.debug("Received message of type [" + message.getClass() + "] from consumer [" +
consumerToUse + "] of " + (transactional ? "transactional " : "") + "session [" +
sessionToUse + "]");
}
messageReceived(invoker, sessionToUse);
boolean exposeResource = (!transactional && isExposeListenerSession() &&
!TransactionSynchronizationManager.hasResource(getConnectionFactory()));
if (exposeResource) {
TransactionSynchronizationManager.bindResource(
getConnectionFactory(), new LocallyExposedJmsResourceHolder(sessionToUse));
}
try {
doExecuteListener(sessionToUse, message);
}
catch (Throwable ex) {
if (status != null) {
if (logger.isDebugEnabled()) {
logger.debug("Rolling back transaction because of listener exception thrown: " + ex);
}
status.setRollbackOnly();
}
handleListenerException(ex);
// Rethrow JMSException to indicate an infrastructure problem
// that may have to trigger recovery...
if (ex instanceof JMSException) {
throw (JMSException) ex;
}
}
finally {
if (exposeResource) {
TransactionSynchronizationManager.unbindResource(getConnectionFactory());
}
}
// Indicate that a message has been received.
return true;
}
else {
if (logger.isTraceEnabled()) {
logger.trace("Consumer [" + consumerToUse + "] of " + (transactional ? "transactional " : "") +
"session [" + sessionToUse + "] did not receive a message");
}
noMessageReceived(invoker, sessionToUse);
// Nevertheless call commit, in order to reset the transaction timeout (if any).
commitIfNecessary(sessionToUse, message);
// Indicate that no message has been received.
return false;
}
}
finally {
JmsUtils.closeMessageConsumer(consumerToClose);
JmsUtils.closeSession(sessionToClose);
ConnectionFactoryUtils.releaseConnection(conToClose, getConnectionFactory(), true);
}
}
|
diff --git a/src/de/earthdawn/ECEWorker.java b/src/de/earthdawn/ECEWorker.java
index 2f9f114..0eb7b69 100644
--- a/src/de/earthdawn/ECEWorker.java
+++ b/src/de/earthdawn/ECEWorker.java
@@ -1,892 +1,892 @@
package de.earthdawn;
/******************************************************************************\
Copyright (C) 2010-2011 Holger von Rhein <[email protected]>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
\******************************************************************************/
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import de.earthdawn.config.ApplicationProperties;
import de.earthdawn.config.ECECapabilities;
import de.earthdawn.data.*;
/**
* Hilfsklasse zur Verarbeitung eines Earthdawn-Charakters.
*
* @author lortas
*/
public class ECEWorker {
public static final ApplicationProperties PROPERTIES=ApplicationProperties.create();
public static final String durabilityTalentName = PROPERTIES.getDurabilityName();
public static final String questorTalentName = PROPERTIES.getQuestorTalentName();
public static final ECECapabilities capabilities = new ECECapabilities(PROPERTIES.getCapabilities().getSKILLOrTALENT());
public static final List<KNACKBASEType> globalTalentKnackList = PROPERTIES.getTalentKnacks();
public static final boolean OptionalRule_SpellLegendPointCost=PROPERTIES.getOptionalRules().getSPELLLEGENDPOINTCOST().getUsed().equals(YesnoType.YES);
public static final boolean OptionalRule_KarmaLegendPointCost=PROPERTIES.getOptionalRules().getKARMALEGENDPOINTCOST().getUsed().equals(YesnoType.YES);
public static final boolean OptionalRule_QuestorTalentNeedLegendpoints=PROPERTIES.getOptionalRules().getQUESTORTALENTNEEDLEGENDPOINTS().getUsed().equals(YesnoType.YES);
public static final boolean OptionalRule_autoincrementDisciplinetalents=PROPERTIES.getOptionalRules().getAUTOINCREMENTDISCIPLINETALENTS().getUsed().equals(YesnoType.YES);
public static final boolean OptionalRule_LegendpointsForAttributeIncrease=PROPERTIES.getOptionalRules().getLEGENDPOINTSFORATTRIBUTEINCREASE().getUsed().equals(YesnoType.YES);
public static final boolean OptionalRule_AutoInsertLegendPointSpent=PROPERTIES.getOptionalRules().getAUTOINSERTLEGENDPOINTSPENT().getUsed().equals(YesnoType.YES);
private HashMap<String, ATTRIBUTEType> characterAttributes=null;
CALCULATEDLEGENDPOINTSType calculatedLP = null;
private static PrintStream errorout = System.err;
/**
* Verabeiten eines Charakters.
*/
public EDCHARACTER verarbeiteCharakter(EDCHARACTER charakter) {
CharacterContainer character = new CharacterContainer(charakter);
// Orignal berechnete LP sichern
CALCULATEDLEGENDPOINTSType oldcalculatedLP = character.getCopyOfCalculatedLegendpoints();
// Berechnete LP erstmal zurücksetzen
calculatedLP = character.resetCalculatedLegendpoints();
// Benötige Rasseneigenschaften der gewählten Rasse im Objekt "charakter":
NAMEGIVERABILITYType namegiver = character.getRace();
// Startgegenstände aus der Charaktererschaffung setzen, wenn gar kein Invetar vorhanden
List<ITEMType> itemList = character.getItems();
if( itemList.isEmpty() ) {
itemList.addAll(PROPERTIES.getStartingItems());
}
List<WEAPONType> magicWeapons = character.cutMagicWeaponFromNormalWeaponList();
List<WEAPONType> weaponList = character.getWeapons();
if( weaponList.isEmpty() ) {
// Startwaffen aus der Charaktererschaffung setzen, wenn gar keine Waffen vorhanden
weaponList.addAll(PROPERTIES.getStartingWeapons());
}
weaponList.addAll(magicWeapons);
// **ATTRIBUTE**
int karmaMaxBonus = PROPERTIES.getOptionalRules().getATTRIBUTE().getPoints();
// Der Bonus auf das Maximale Karma ergibt sich aus den übriggebliebenen Kaufpunkten bei der Charaktererschaffung
characterAttributes = character.getAttributes();
for (NAMEVALUEType raceattribute : namegiver.getATTRIBUTE()) {
// Pro Atributt wird nun dessen Werte, Stufe und Würfel bestimmt
ATTRIBUTEType attribute = characterAttributes.get(raceattribute.getName());
attribute.setRacevalue(raceattribute.getValue());
attribute.setCost(berechneAttriubteCost(attribute.getGenerationvalue()));
int value = attribute.getRacevalue() + attribute.getGenerationvalue();
attribute.setBasevalue(value);
value += attribute.getLpincrease();
attribute.setCurrentvalue(value);
STEPDICEType stepdice=attribute2StepAndDice(value);
attribute.setDice(stepdice.getDice());
attribute.setStep(stepdice.getStep());
karmaMaxBonus-=attribute.getCost();
if( OptionalRule_LegendpointsForAttributeIncrease ) calculatedLP.setAttributes(calculatedLP.getAttributes()+PROPERTIES.getCharacteristics().getAttributeTotalLP(attribute.getLpincrease()));
}
if( karmaMaxBonus <0 ) {
errorout.println("The character was generated with to many spent attribute buy points: "+(-karmaMaxBonus));
}
// **DEFENSE**
DEFENSEType defense = character.getDefence();
defense.setPhysical(berechneWiederstandskraft(characterAttributes.get("DEX").getCurrentvalue()));
defense.setSpell(berechneWiederstandskraft(characterAttributes.get("PER").getCurrentvalue()));
defense.setSocial(berechneWiederstandskraft(characterAttributes.get("CHA").getCurrentvalue()));
for(DEFENSEABILITYType racedefense : namegiver.getDEFENSE() ) {
switch (racedefense.getKind()) {
case PHYSICAL: defense.setPhysical(defense.getPhysical()+1); break;
case SPELL: defense.setSpell(defense.getSpell()+1); break;
case SOCIAL: defense.setSocial(defense.getSocial()+1); break;
}
}
// **INITIATIVE**
STEPDICEType initiativeStepdice=attribute2StepAndDice(characterAttributes.get("DEX").getCurrentvalue());
INITIATIVEType initiative = character.getInitiative();
// Setze alle Initiative Modifikatoren zurück, da diese im folgenden neu bestimmt werden.
initiative.setModification(0);
initiative.setBase(initiativeStepdice.getStep());
initiative.setStep(initiativeStepdice.getStep());
initiative.setDice(initiativeStepdice.getDice());
// **HEALTH**
CHARACTERISTICSHEALTHRATING newhealth = bestimmeHealth(characterAttributes.get("TOU").getCurrentvalue());
DEATHType death=character.getDeath();
DEATHType unconsciousness=character.getUnconsciousness();
death.setBase(newhealth.getDeath());
death.setAdjustment(0);
unconsciousness.setBase(newhealth.getUnconsciousness());
unconsciousness.setAdjustment(0);
character.getWound().setThreshold(newhealth.getWound()+namegiver.getWOUND().getThreshold());
RECOVERYType recovery = character.getRecovery();
recovery.setTestsperday(newhealth.getRecovery());
recovery.setStep(characterAttributes.get("TOU").getStep());
recovery.setDice(characterAttributes.get("TOU").getDice());
// **KARMA**
TALENTType karmaritualTalent = null;
final String KARMARITUAL = PROPERTIES.getKarmaritualName();
if( KARMARITUAL == null ) {
errorout.println("Karmaritual talent name is not defined for selected language.");
} else {
for( TALENTType talent : character.getTalentByName(KARMARITUAL) ) {
if( talent.getRealigned() == 0 ) {
karmaritualTalent=talent;
break;
}
}
if(karmaritualTalent == null ) {
errorout.println("No Karmaritual ("+KARMARITUAL+") could be found.");
}
}
int calculatedKarmaLP=calculateKarma(character.getKarma(), karmaritualTalent, namegiver.getKarmamodifier(), karmaMaxBonus);
if( OptionalRule_KarmaLegendPointCost ) {
calculatedLP.setKarma(calculatedLP.getKarma()+calculatedKarmaLP);
} else {
calculatedKarmaLP=0;
calculatedLP.setKarma(0);
}
// **MOVEMENT**
character.calculateMovement();
// **CARRYING**
character.calculateCarrying();
// Berechne Gewicht aller Münzen
for( COINSType coins : character.getAllCoins() ) {
// Mit doppelter Genauigkeit die Gewichte der Münzen addieren,
double weight = 0;
// Kupfermünzen: 1/3 Unze (oz)
weight += coins.getCopper() / 48.0;
// Silbermünzen: 1/4 Unze (oz)
weight += coins.getSilver() / 64.0;
// Goldmünzen: 1/5 Unze (oz)
weight += coins.getGold() / 80.0;
// Edelsteine mit Wert 50 Silber : 1/10 Unze (oz)
weight += coins.getGem50() / 160.0;
// Edelsteine mit Wert 100 Silber : 1/5 Unze (oz)
weight += coins.getGem100() / 80.0;
// Edelsteine mit Wert 200 Silber : 1/3 Unze (oz)
weight += coins.getGem200() / 48.0;
// Edelsteine mit Wert 500 Silber : 2/3 Unze (oz)
weight += coins.getGem500() / 24.0;
// Edelsteine mit Wert 1000 Silber : 1 3/5 Unzen (oz)
weight += coins.getGem1000()/ 10.0;
// Elementarmünzen: 1/10 Unze (oz)
weight += (double)( coins.getAir()+coins.getEarth()+coins.getFire()+coins.getWater()+coins.getOrichalcum() ) / 160.0;
// zum Abspeichern langt die einfache Genaugkeit
coins.setWeight((float)weight);
}
character.setAbilities(concatStrings(namegiver.getABILITY()));
// Lösche alle Diziplin Boni, damit diese unten wieder ergänzt werden können ohne auf duplikate Achten zu müssen
character.clearDisciplineBonuses();
// Stelle sicher dass ale Disziplin Talent eingügt werden
character.ensureDisciplinTalentsExits();
// Entferne alle Talente die zuhohle Kreise haben.
character.removeIllegalTalents();
// Entferne alle Optionalen Talente ohne Rang.
character.removeZeroRankOptionalTalents();
// Prüfe ob Talente realigned weren müssen.
character.realignOptionalTalents();
character.updateRealignedTalents();
// Sammle alle Namensgeber spezial Talente in einer Liste zusammen
HashMap<String,TALENTABILITYType> namegivertalents = new HashMap<String,TALENTABILITYType>();
for( TALENTABILITYType t : namegiver.getTALENT() ) {
namegivertalents.put(t.getName(), t);
}
// Wenn ein Charakter Weihepunkte erhalten hat, dann steht ihm das Questorentalent zur Verfügung
DEVOTIONType devotionPoints = character.getDevotionPoints();
if( (devotionPoints!=null) && (devotionPoints.getValue()>0) ) {
TALENTABILITYType talent = new TALENTABILITYType();
talent.setName(questorTalentName);
talent.setLimitation(devotionPoints.getPassion());
namegivertalents.put(questorTalentName, talent);
}
int maxKarmaStepBonus=0;
List<DISCIPLINEType> allDisciplines = character.getDisciplines();
HashMap<String,Integer> diciplineCircle = new HashMap<String, Integer>();
int disciplinenumber=0;
for( DISCIPLINEType currentDiscipline : allDisciplines ) {
disciplinenumber++;
List<TALENTType> durabilityTalents = new ArrayList<TALENTType>();
TalentsContainer currentTalents = new TalentsContainer(currentDiscipline);
for( TALENTType talent : currentTalents.getDisciplineAndOptionaltalents() ) ensureRankAndTeacher(talent);
HashMap<String, Integer> defaultOptionalTalents = PROPERTIES.getDefaultOptionalTalents(disciplinenumber);
int currentCircle = currentDiscipline.getCircle();
int minDisciplineCircle=character.getDisciplineMinCircle(disciplinenumber).getCircle();
calculateTalents(namegivertalents, defaultOptionalTalents, disciplinenumber, currentCircle, minDisciplineCircle, durabilityTalents, currentTalents.getDisciplinetalents(), true);
calculateTalents(namegivertalents, defaultOptionalTalents, disciplinenumber, currentCircle, minDisciplineCircle, durabilityTalents, currentTalents.getOptionaltalents(), false);
// Alle Namegiver Talente, die bis jetzt noch nicht enthalten waren,
// werden nun den optionalen Talenten beigefügt.
for( String t : namegivertalents.keySet() ) {
TALENTType talent = new TALENTType();
talent.setName(namegivertalents.get(t).getName());
talent.setLimitation(namegivertalents.get(t).getLimitation());
talent.setCircle(0);
capabilities.enforceCapabilityParams(talent);
talent.setTEACHER(new TALENTTEACHERType());
RANKType rank = new RANKType();
calculateCapabilityRank(rank,characterAttributes.get(talent.getAttribute().value()));
talent.setRANK(rank);
currentTalents.getOptionaltalents().add(talent);
}
namegivertalents.clear(); // Ist keine lokale Variable und Namensgebertalent sollen nur bei einer Disziplin einfügt werden
for( String t : defaultOptionalTalents.keySet() ) {
// Talente aus späteren Kreisen werden auch erst später eingefügt
int circle = defaultOptionalTalents.get(t);
if( circle > currentCircle ) continue;
TALENTType talent = new TALENTType();
talent.setName(t);
talent.setCircle(circle);
capabilities.enforceCapabilityParams(talent);
talent.setTEACHER(new TALENTTEACHERType());
RANKType rank = new RANKType();
calculateCapabilityRank(rank,characterAttributes.get(talent.getAttribute().value()));
talent.setRANK(rank);
currentTalents.getOptionaltalents().add(talent);
}
// Wenn Durability-Talente gefunden wurden, berechnen aus dessen Rank
// die Erhöhung von Todes- und Bewustlosigkeitsschwelle
for( TALENTType durabilityTalent : durabilityTalents ) {
DISCIPLINE disziplinProperties = PROPERTIES.getDisziplin(currentDiscipline.getName());
if( disziplinProperties != null ) {
DISCIPLINEDURABILITYType durability = disziplinProperties.getDURABILITY();
int rank = durabilityTalent.getRANK().getRank()-durabilityTalent.getRANK().getRealignedrank();
death.setAdjustment(death.getAdjustment()+(durability.getDeath()*rank));
unconsciousness.setAdjustment(unconsciousness.getAdjustment()+(durability.getUnconsciousness()*rank));
durabilityTalent.setLimitation(durability.getDeath()+"/"+durability.getUnconsciousness());
}
}
diciplineCircle.put(currentDiscipline.getName(), currentCircle);
// Nur der höchtse Bonus wird gewertet.
int currentKarmaStepBonus = getDisciplineKarmaStepBonus(currentDiscipline);
if( currentKarmaStepBonus > maxKarmaStepBonus ) maxKarmaStepBonus = currentKarmaStepBonus;
List<DISCIPLINEBONUSType> currentBonuses = currentDiscipline.getDISCIPLINEBONUS();
currentBonuses.clear();
currentBonuses.addAll(getDisciplineBonuses(currentDiscipline));
// TALENT KNACKS
for( TALENTType talent : currentTalents.getDisciplineAndOptionaltalents() ) checkTalentKnacks(talent,disciplinenumber);
}
// ** ARMOR **
// Zu erstmal alles entfernen was nicht eine Reale Rüstung ist:
List<ARMORType> totalarmor = character.removeVirtualArmorFromNormalArmorList();
// natural ARMOR bestimmen
ARMORType namegiverArmor = namegiver.getARMOR();
ARMORType naturalArmor = new ARMORType();
naturalArmor.setName(namegiverArmor.getName());
naturalArmor.setMysticarmor(namegiverArmor.getMysticarmor()+berechneMysticArmor(characterAttributes.get("WIL").getCurrentvalue()));
naturalArmor.setPhysicalarmor(namegiverArmor.getPhysicalarmor());
naturalArmor.setPenalty(namegiverArmor.getPenalty());
naturalArmor.setUsed(namegiverArmor.getUsed());
naturalArmor.setWeight(namegiverArmor.getWeight());
naturalArmor.setVirtual(YesnoType.YES);
// Natürliche Rüstung der Liste voranstellen
totalarmor.add(0, naturalArmor);
// magischen Rüstung/Rüstungsschutz anhängen:
totalarmor.addAll(character.getMagicArmor());
// Bestimme nun den aktuellen Gesamtrüstungsschutz
int mysticalarmor=0;
int physicalarmor=0;
int protectionpenalty=0;
for (ARMORType armor : totalarmor ) {
if( armor.getUsed().equals(YesnoType.YES) ) {
mysticalarmor+=armor.getMysticarmor();
physicalarmor+=armor.getPhysicalarmor();
protectionpenalty+=armor.getPenalty();
}
}
PROTECTIONType protection = character.getProtection();
protection.setMysticarmor(mysticalarmor);
protection.setPenalty(protectionpenalty);
protection.setPhysicalarmor(physicalarmor);
character.readjustInitiativeModifikator(-protectionpenalty);
// ** KARMA STEP **
KARMAType karma = character.getKarma();
karma.setStep(4 + maxKarmaStepBonus); // mindestens d6
karma.setDice(PROPERTIES.step2Dice(karma.getStep()));
int skillsStartranks=calculatedLP.getUSEDSTARTRANKS().getSkills();
character.removeEmptySkills();
List<SKILLType> skills = character.getSkills();
if( skills.isEmpty() ) {
for(SKILLType skilltemplate : PROPERTIES.getStartingSkills() ) {
SKILLType skill = new SKILLType();
skill.setName(skilltemplate.getName());
skill.setLimitation(skilltemplate.getLimitation());
RANKType rank = new RANKType();
rank.setRank(skilltemplate.getRANK().getRank());
rank.setStartrank(skilltemplate.getRANK().getStartrank());
skill.setRANK(rank);
skills.add(skill);
}
}
List<CAPABILITYType> defaultSkills = capabilities.getDefaultSkills(namegiver.getNOTDEFAULTSKILL());
for( SKILLType skill : skills ) {
RANKType rank = skill.getRANK();
int startrank = rank.getStartrank();
skillsStartranks+=startrank;
int lpcostfull= PROPERTIES.getCharacteristics().getSkillRankTotalLP(rank.getRank());
int lpcoststart= PROPERTIES.getCharacteristics().getSkillRankTotalLP(startrank);
rank.setLpcost(lpcostfull-lpcoststart);
rank.setBonus(0);
calculatedLP.setSkills(calculatedLP.getSkills()+rank.getLpcost());
capabilities.enforceCapabilityParams(skill);
if( skill.getAttribute() != null ) {
calculateCapabilityRank(rank,characterAttributes.get(skill.getAttribute().value()));
}
removeIfContains(defaultSkills,skill.getName());
}
calculatedLP.getUSEDSTARTRANKS().setSkills(skillsStartranks);
// Wenn gewünscht dann zeige auch die DefaultSkills mit an
if( PROPERTIES.getOptionalRules().getSHOWDEFAULTSKILLS().getUsed().equals(YesnoType.YES) ) {
for( CAPABILITYType defaultSkill : defaultSkills ) {
List<String> limitations = defaultSkill.getLIMITATION();
if( limitations.size()==0 ) limitations.add("");
for( String limitation : limitations ) {
SKILLType skill = new SKILLType();
RANKType rank = new RANKType();
skill.setRANK(rank);
skill.setName(defaultSkill.getName());
skill.setLimitation(limitation);
capabilities.enforceCapabilityParams(skill);
if( skill.getAttribute() != null ) {
calculateCapabilityRank(rank,characterAttributes.get(skill.getAttribute().value()));
}
skills.add(skill);
}
}
}
DEFENSEType disciplineDefense = getDisciplineDefense(diciplineCircle);
defense.setPhysical(defense.getPhysical()+disciplineDefense.getPhysical());
defense.setSocial(defense.getSocial()+disciplineDefense.getSocial());
defense.setSpell(defense.getSpell()+disciplineDefense.getSpell());
recovery.setStep(recovery.getStep()+getDisciplineRecoveryTestBonus(diciplineCircle));
recovery.setDice(PROPERTIES.step2Dice(recovery.getStep()));
character.readjustInitiativeModifikator(getDisciplineInitiative(diciplineCircle));
// ** SPELLS **
// Bestimme die wieviele Zaubersprüche bei der Charactererschaffung kostenlos dazu kamen
// und wieviel ein SpellAbility pro Kreis pro Disziplin kostenlos dazukamen.
int freespellranks = attribute2StepAndDice(characterAttributes.get("PER").getBasevalue()).getStep();
for( int sa : getDisciplineSpellAbility(diciplineCircle) ) freespellranks+=sa;
calculatedLP.setSpells(0);
HashMap<String, SPELLDEFType> spelllist = PROPERTIES.getSpells();
for( DISCIPLINEType discipline : character.getDisciplines() ) {
int usedSpellabilities=0;
for( SPELLType spell : discipline.getSPELL() ) {
SPELLDEFType spelldef = spelllist.get(spell.getName());
if( spelldef == null ) {
errorout.println("Unknown Spell '"+spell.getName()+"' in grimour found. Spell is left unmodified in grimour.");
} else {
spell.setCastingdifficulty(spelldef.getCastingdifficulty());
spell.setDuration(spelldef.getDuration());
spell.setEffect(spelldef.getEffect());
spell.setEffectarea(spelldef.getEffectarea());
spell.setRange(spelldef.getRange());
spell.setReattuningdifficulty(spelldef.getReattuningdifficulty());
spell.setThreads(spelldef.getThreads());
spell.setWeavingdifficulty(spelldef.getWeavingdifficulty());
spell.setBookref(spelldef.getBookref());
spell.setElement(spelldef.getElement());
}
// Wenn ein Zauber duch Spellability gelernt wurde, dann kostet er keine LPs
if( spell.getByspellability().equals(YesnoType.YES) ) {
usedSpellabilities++;
freespellranks-=spell.getCircle();
} else if( OptionalRule_SpellLegendPointCost ) {
// The cost of spells are equivalent to the cost of increasing a Novice Talent to a Rank equal to the Spell Circle
int lpcost=PROPERTIES.getCharacteristics().getSpellLP(spell.getCircle());
calculatedLP.setSpells(calculatedLP.getSpells()+lpcost);
}
}
discipline.setUsedspellabilities(usedSpellabilities);
}
calculatedLP.getUSEDSTARTRANKS().setSpells(-freespellranks);
for( BLOODCHARMITEMType item : character.getBloodCharmItem() ) {
if( item.getUsed().equals(YesnoType.YES) ) {
death.setAdjustment(death.getAdjustment()-item.getBlooddamage());
unconsciousness.setAdjustment(unconsciousness.getAdjustment()-item.getBlooddamage());
}
}
List<TALENTType> firstDisciplineOptionalTalents = null;
if( ! allDisciplines.isEmpty() ) firstDisciplineOptionalTalents = allDisciplines.get(0).getOPTIONALTALENT();
for( THREADITEMType item : character.getThreadItem() ) {
int rank = item.getWeaventhreadrank();
// If no thread is weaven to the this thread item, skip it.
if( rank < 1 ) continue;
THREADRANKType threadrank = item.getTHREADRANK().get(rank-1);
while( (threadrank==null) && (rank>1) ) {
// Wenn der Fadenrang nicht definiert ist, obwohl der Rang größer 1 ist, wähle den Fadenrang einen Rang kleiner.
if( threadrank == null ) {
errorout.println("Undefined Threadrank for "+item.getName()+" for rank "+rank );
}
rank--;
threadrank = item.getTHREADRANK().get(rank-1);
}
if( threadrank == null ) {
errorout.println("No Threadranks for "+item.getName()+" for rank "+item.getWeaventhreadrank()+" or less at all." );
continue;
}
for(DEFENSEABILITYType itemdefense : threadrank.getDEFENSE() ) {
switch (itemdefense.getKind()) {
case PHYSICAL: defense.setPhysical(defense.getPhysical()+1); break;
case SPELL: defense.setSpell(defense.getSpell()+1); break;
case SOCIAL: defense.setSocial(defense.getSocial()+1); break;
}
}
for(TALENTABILITYType itemtalent : threadrank.getTALENT() ) {
String limitation = itemtalent.getLimitation();
boolean notfound=true;
for( TALENTType talent : character.getTalentByName(itemtalent.getName()) ) {
if( limitation.isEmpty() || (talent.getLimitation().equals(limitation)) ) {
notfound=false;
RANKType talentrank = talent.getRANK();
talentrank.setBonus(talentrank.getBonus()+itemtalent.getBonus());
calculateCapabilityRank(talentrank,characterAttributes.get(talent.getAttribute().value()));
}
}
if( notfound && (firstDisciplineOptionalTalents!=null) ) {
if( limitation.isEmpty() ) limitation ="(#)";
else limitation += " (#)";
TALENTType bonusTalent = new TALENTType();
bonusTalent.setName(itemtalent.getName());
bonusTalent.setLimitation(limitation);
bonusTalent.setCircle(0);
capabilities.enforceCapabilityParams(bonusTalent);
RANKType bonusrank = new RANKType();
bonusrank.setRank(0);
- bonusrank.setBonus(1);
+ bonusrank.setBonus(itemtalent.getBonus());
calculateCapabilityRank(bonusrank,characterAttributes.get(bonusTalent.getAttribute().value()));
bonusTalent.setRANK(bonusrank);
TALENTTEACHERType teacher = new TALENTTEACHERType();
teacher.setByversatility(YesnoType.NO);
teacher.setTalentcircle(rank);
teacher.setTeachercircle(rank);
teacher.setName(item.getName());
bonusTalent.setTEACHER(teacher);
firstDisciplineOptionalTalents.add(bonusTalent);
}
}
for(DISZIPINABILITYType iteminitiative : threadrank.getINITIATIVE() ) {
character.readjustInitiativeModifikator(iteminitiative.getCount());
}
initiative.setStep(initiative.getBase()+initiative.getModification());
initiative.setDice(PROPERTIES.step2Dice(initiative.getStep()));
// TODO: other effects of MagicItems
// TODO:List<TALENTType> optTalents = allTalents.get(disciplinenumber).getOPTIONALTALENT();
}
// Veränderungen am death/unconsciousness adjustment sollen beachtet werden
death.setValue(death.getBase()+death.getAdjustment());
unconsciousness.setValue(unconsciousness.getBase()+unconsciousness.getAdjustment());
if( calculatedLP.getSpells() < 0 ) calculatedLP.setSpells(0);
calculatedLP.setTotal(calculatedLP.getAttributes()+calculatedLP.getDisciplinetalents()+
calculatedLP.getKarma()+calculatedLP.getMagicitems()+calculatedLP.getOptionaltalents()+
calculatedLP.getSkills()+calculatedLP.getSpells()+calculatedLP.getKnacks());
if( OptionalRule_AutoInsertLegendPointSpent ) character.addLegendPointsSpent(oldcalculatedLP);
character.calculateLegendPointsAndStatus();
character.calculateDevotionPoints();
return charakter;
}
private void checkTalentKnacks(TALENTType talent, int disciplinenumber) {
String talentname = talent.getName();
for( KNACKType knack : talent.getKNACK() ) {
String knackname = knack.getName();
for( KNACKBASEType k : globalTalentKnackList ) {
if( k.getName().equals(knackname) ) {
if( k.getBasename().equals(talentname) ) {
knack.setBookref(k.getBookref());
knack.setMinrank(k.getMinrank());
knack.setStrain(k.getStrain());
break; // Wenn er einmal gefunden wurde, brauch nicht mehr weitergesucht werden.
} else {
errorout.println("The knack '"+knackname+"' was learned for the talent '"+talentname+"', but should be learned for talent '"+k.getBasename()+"'. Will not enforce knack default values!");
}
}
}
int talentrank = talent.getRANK().getRank();
int knackminrank = knack.getMinrank();
if( talentrank < knackminrank ) {
errorout.println("The knack '"+knackname+"' was learned for the talent '"+talentname+"', but talent rank ("+talentrank+") is less than the knack minimum talent rank ("+knackminrank+")!");
}
CHARACTERISTICSCOST knackcost = PROPERTIES.getCharacteristics().getTalentRankLPIncreaseTable(disciplinenumber,talent.getCircle()).get(knackminrank);
if( knackcost == null ) {
errorout.println("Could not get knack lp costs for disciplinenumber="+disciplinenumber+", talent_circle="+talent.getCircle()+" and knackminrank="+knackminrank);
} else {
calculatedLP.setKnacks(calculatedLP.getKnacks()+knackcost.getCost());
}
}
}
public void ensureRankAndTeacher(TALENTType talent) {
if( talent.getRANK() == null ) talent.setRANK(new RANKType());
if( talent.getTEACHER() == null ) talent.setTEACHER(new TALENTTEACHERType());
}
private void calculateTalents(HashMap<String, TALENTABILITYType> namegivertalents, HashMap<String, Integer> defaultOptionalTalents, int disciplinenumber, int disciplinecircle, int minDisciplineCircle, List<TALENTType> durabilityTalents, List<TALENTType> talents, boolean disTalents) {
int totallpcost=0;
int startranks=calculatedLP.getUSEDSTARTRANKS().getTalents();
for( TALENTType talent : talents ) {
TALENTTEACHERType teacher = talent.getTEACHER();
if( teacher == null ) {
teacher = new TALENTTEACHERType();
talent.setTEACHER(teacher);
}
RANKType rank = talent.getRANK();
if( rank == null ) {
rank = new RANKType();
talent.setRANK(rank);
}
if( disTalents && OptionalRule_autoincrementDisciplinetalents &&
(talent.getCircle() < disciplinecircle) && (rank.getRank() < disciplinecircle) ) {
rank.setRank(disciplinecircle);
}
if( rank.getRank() < rank.getStartrank() ) rank.setRank(rank.getStartrank());
if( rank.getRank() < rank.getRealignedrank() ) rank.setRank(rank.getRealignedrank());
// Talente aus höheren Kreisen können keine Startranks haben, da Startranks nur bei der Charaktererschaffung vergeben werden.
if( (talent.getCircle()>1) && (rank.getStartrank()>0) ) rank.setStartrank(0);
capabilities.enforceCapabilityParams(talent);
rank.setBonus(talent.getBonus());
if( rank.getRank() < 1 ) {
// Wenn kein Rang exisitert, dann auch keine Rangvergangenheit.
talent.getRANKHISTORY().clear();
} else if( (disciplinenumber>1) && (minDisciplineCircle<5) ) {
// Wenn Talente von weiteren (nicht die erste) Disciplinen gelernt wurden,
// obwohl der kleinste Disziplinkreis nocht nicht 5 ist, muss dies erfasst werden.
List<RANKHISTORYType> rankHistories = talent.getRANKHISTORY();
RANKHISTORYType rankhistory;
if( rankHistories.isEmpty() ) {
// Wenn noch garkeine Rang-Vergangenheit erfasst wurde, füge ein erstes Element ein.
rankhistory = new RANKHISTORYType();
rankhistory.setMincircle(minDisciplineCircle);
rankHistories.add(rankhistory);
} else {
// Es exisitert bereits eine Rang-Vergangenheit, hole letztes Element
rankhistory = rankHistories.get(rankHistories.size()-1);
if( (rankhistory.getMincircle()!=minDisciplineCircle) && (rankhistory.getRank()!=rank.getRank()) ) {
// Sollte das letzte Element nicht dem aktuellen Disziplinkreis entsprechen und der Talentrang
// sich verändert haben, dann erstelle ein neues Element.
rankhistory = new RANKHISTORYType();
rankhistory.setMincircle(minDisciplineCircle);
rankHistories.add(rankhistory);
}
}
rankhistory.setRank(rank.getRank());
}
RANKHISTORYType lastrankhistory= new RANKHISTORYType();
lastrankhistory.setRank(0);
int newDisciplineTalentCost=0;
List<CHARACTERISTICSCOST> newDisciplineTalentCosts = PROPERTIES.getCharacteristics().getNewDisciplineTalentCost(disciplinenumber);
// Prüfe ob wir ein Kostentabelle haben
if( newDisciplineTalentCosts != null ) {
List<RANKHISTORYType> rankhistory = talent.getRANKHISTORY();
// Prüfe ob die RangHistory nicht leer ist
if( ! rankhistory.isEmpty() ) {
// Erstes Element enthält den kleines Disziplinkreis als der erste Ranges dieses Talents gelernt wurde
int mincircle = rankhistory.get(0).getMincircle()-1;
if( mincircle < newDisciplineTalentCosts.size() ) {
newDisciplineTalentCost = newDisciplineTalentCosts.get(mincircle).getCost();
}
}
}
// Nur in der Erstdisziplin kann ein Startrang existieren.
if( disciplinenumber!=1 ) rank.setStartrank(0);
final int lpcostfull=PROPERTIES.getCharacteristics().getTalentRankTotalLP(disciplinenumber,talent.getCircle(),rank.getRank());
final int lpcoststart=PROPERTIES.getCharacteristics().getTalentRankTotalLP(disciplinenumber,talent.getCircle(),rank.getStartrank());
final int lpcostrealigned=PROPERTIES.getCharacteristics().getTalentRankTotalLP(disciplinenumber,talent.getCircle(),rank.getRealignedrank());
if( lpcostrealigned > lpcoststart ) {
rank.setLpcost(newDisciplineTalentCost+lpcostfull-lpcostrealigned);
} else {
rank.setLpcost(newDisciplineTalentCost+lpcostfull-lpcoststart);
}
totallpcost+=rank.getLpcost();
startranks+=rank.getStartrank();
ATTRIBUTENameType attr = talent.getAttribute();
if( attr != null ) calculateCapabilityRank(rank,characterAttributes.get(attr.value()));
String talentname = talent.getName();
if( talentname.equals(durabilityTalentName)) durabilityTalents.add(talent);
calculateKnacks(disciplinenumber, talent, rank.getRank());
if( namegivertalents.containsKey(talentname) ) {
namegivertalents.remove(talentname);
}
if( defaultOptionalTalents.containsKey(talentname) ) {
defaultOptionalTalents.remove(talentname);
}
if( talent.getNotbyversatility().equals(YesnoType.YES) && teacher.getByversatility().equals(YesnoType.YES) ) {
errorout.println("Talent '"+talentname+"' was lernead by versatility, but is not allowed to be learned by versatility.");
}
}
calculatedLP.getUSEDSTARTRANKS().setTalents(startranks);
if( disTalents ) {
calculatedLP.setDisciplinetalents(calculatedLP.getDisciplinetalents()+totallpcost);
} else {
calculatedLP.setOptionaltalents(calculatedLP.getOptionaltalents()+totallpcost);
}
}
public static void removeIfContains(List<CAPABILITYType> defaultSkills, String name) {
List<CAPABILITYType> remove = new ArrayList<CAPABILITYType>();
for( CAPABILITYType skill : defaultSkills) {
if( skill.getName().equals(name)) {
remove.add(skill);
}
}
defaultSkills.removeAll(remove);
}
public static String concatStrings(List<String> strings) {
String result = "";
for ( String s : strings ) {
if( ! result.isEmpty() ) result += ", ";
result += s;
}
return result;
}
private static int calculateKarma(KARMAType karma, TALENTType karmaritualTalent, int karmaModifier, int karmaMaxBonus) {
karma.setMaxmodificator(karmaMaxBonus);
if( (karmaritualTalent != null) && (karmaritualTalent.getRANK() != null) ) {
karma.setMax( karmaMaxBonus + (karmaModifier * karmaritualTalent.getRANK().getRank()) );
} else {
errorout.println("No karmaritual talent found, skipping maximal karma calculation.");
}
List<Integer> k = CharacterContainer.calculateAccounting(karma.getKARMAPOINTS());
karma.setCurrent(karmaModifier+k.get(0)-k.get(1));
return 10*k.get(0); // KarmaLP
}
private void calculateKnacks(int disciplinenumber, TALENTType talent, int rank) {
for( KNACKType knack : talent.getKNACK() ) {
if( knack.getMinrank() > rank ) {
errorout.println("The rank of the talent '"+talent.getName()+"' is lower than the minimal rank for the kack '"+knack.getName()+"': "
+rank+" vs. "+knack.getMinrank());
}
int lp = PROPERTIES.getCharacteristics().getTalentRankLPIncreaseTable(disciplinenumber,talent.getCircle()).get(knack.getMinrank()).getCost();
calculatedLP.setKnacks(calculatedLP.getKnacks()+lp);
}
}
private static int getDisciplineKarmaStepBonus(DISCIPLINEType discipline) {
int result = 0;
int circlenr=0;
DISCIPLINE disziplinProperties = ApplicationProperties.create().getDisziplin(discipline.getName());
if( disziplinProperties == null ) return result;
for( DISCIPLINECIRCLEType circle : disziplinProperties.getCIRCLE()) {
circlenr++;
if( circlenr > discipline.getCircle() ) break;
for( DISZIPINABILITYType karmastep : circle.getKARMASTEP()) {
result += karmastep.getCount();
}
}
return result;
}
private static int getDisciplineRecoveryTestBonus(HashMap<String,Integer> diciplineCircle) {
int result = 0;
for( String discipline : diciplineCircle.keySet() ) {
DISCIPLINE d = ApplicationProperties.create().getDisziplin(discipline);
if( d == null ) continue;
int tmp = 0;
int circlenr=0;
for( DISCIPLINECIRCLEType circle : d.getCIRCLE() ) {
circlenr++;
if( circlenr > diciplineCircle.get(discipline) ) break;
for( DISZIPINABILITYType recoverytest : circle.getRECOVERYTEST() ) {
tmp += recoverytest.getCount();
}
}
if( tmp > result ) result=tmp;
}
return result;
}
private static int getDisciplineInitiative(HashMap<String,Integer> diciplineCircle) {
int result = 0;
for( String discipline : diciplineCircle.keySet() ) {
DISCIPLINE d = ApplicationProperties.create().getDisziplin(discipline);
if( d == null ) continue;
int tmp = 0;
int circlenr=0;
for( DISCIPLINECIRCLEType circle : d.getCIRCLE() ) {
circlenr++;
if( circlenr > diciplineCircle.get(discipline) ) break;
for( DISZIPINABILITYType initiative : circle.getINITIATIVE() ) {
tmp += initiative.getCount();
}
}
if( tmp > result ) result=tmp;
}
return result;
}
// Der Defense Bonus wird nicht über Alle Disziplinen addiert, sondern
// der Character erhält von des Disziplinen nur den jeweils höchsten DefenseBonus
private static DEFENSEType getDisciplineDefense(HashMap<String,Integer> diciplineCircle) {
DEFENSEType result = new DEFENSEType();
result.setPhysical(0);
result.setSocial(0);
result.setSpell(0);
for( String discipline : diciplineCircle.keySet() ) {
DISCIPLINE d = ApplicationProperties.create().getDisziplin(discipline);
if( d == null ) continue;
DEFENSEType tmp = new DEFENSEType();
tmp.setPhysical(0);
tmp.setSocial(0);
tmp.setSpell(0);
int circlenr = 0;
for( DISCIPLINECIRCLEType circle : d.getCIRCLE() ) {
circlenr++;
if( circlenr > diciplineCircle.get(discipline) ) break;
for( DEFENSEABILITYType defense : circle.getDEFENSE() ) {
switch( defense.getKind() ) {
case PHYSICAL: tmp.setPhysical(tmp.getPhysical()+1); break;
case SOCIAL: tmp.setSocial(tmp.getSocial()+1); break;
case SPELL: tmp.setSpell(tmp.getSpell()+1); break;
}
}
}
if( tmp.getPhysical() > result.getPhysical() ) result.setPhysical(tmp.getPhysical());
if( tmp.getSocial() > result.getSocial() ) result.setSocial(tmp.getSocial());
if( tmp.getSpell() > result.getSpell() ) result.setSpell(tmp.getSpell());
}
return result;
}
private static List<Integer> getDisciplineSpellAbility(HashMap<String,Integer> diciplineCircle) {
List<Integer> result = new ArrayList<Integer>();
for( String discipline : diciplineCircle.keySet() ) {
DISCIPLINE d = PROPERTIES.getDisziplin(discipline);
if( d == null ) continue;
int circlenr = 0;
for( DISCIPLINECIRCLEType circle : d.getCIRCLE() ) {
circlenr++;
if( circlenr > diciplineCircle.get(discipline) ) break;
for( DISZIPINABILITYType spell : circle.getSPELLABILITY() ) {
for(int i=0; i<spell.getCount(); i++) result.add(circlenr);
}
}
}
return result;
}
public static int berechneWiederstandskraft(int value) {
int defense=0;
for (CHARACTERISTICSDEFENSERAITING defenserating : ApplicationProperties.create().getCharacteristics().getDEFENSERAITING() ) {
// errorout.println("berechneWiederstandskraft value "+value+" defense "+defense+" defenserating "+defenserating.getAttribute());
if( (value >= defenserating.getAttribute()) && (defense<defenserating.getDefense()) ) {
defense=defenserating.getDefense();
}
}
return defense;
}
public static int berechneAttriubteCost(int modifier) {
if ( modifier < -2 ) {
errorout.println("The generation attribute value was to low. Value will increased to -2.");
modifier = -2;
}
if ( modifier > 8 ) {
errorout.println("The generation attribute value was to high. Value will be lower down to 8.");
modifier = 8;
}
HashMap<Integer,Integer> attributecost = ApplicationProperties.create().getCharacteristics().getATTRIBUTECOST();
return attributecost.get(modifier);
}
public static CHARACTERISTICSHEALTHRATING bestimmeHealth(int value) {
HashMap<Integer,CHARACTERISTICSHEALTHRATING> healthrating = ApplicationProperties.create().getCharacteristics().getHEALTHRATING();
return healthrating.get(value);
}
public static int berechneMysticArmor(int value) {
List<Integer> mysticArmorTable = ApplicationProperties.create().getCharacteristics().getMYSTICARMOR();
int mysticArmor=-1;
for( int attribute : mysticArmorTable ) {
if( attribute > value ) break;
mysticArmor++;
}
return mysticArmor;
}
public static STEPDICEType attribute2StepAndDice(int value) {
while( value >= 0 ) {
CHARACTERISTICSSTEPDICETABLE result = ApplicationProperties.create().getCharacteristics().getSTEPDICEbyAttribute(value);
if( result != null ) {
return result;
}
value--;
}
// Not found
return null;
}
public void calculateCapabilityRank(RANKType talentRank, ATTRIBUTEType attr) {
// Da der talent.bonus bereits im talent.rank.bonus enhalten ist, muss er hier
// explizit nicht mehr weiter beachtet werden.
if( attr == null ) {
talentRank.setStep(talentRank.getRank()+talentRank.getBonus());
} else {
talentRank.setStep(talentRank.getRank()+talentRank.getBonus()+attr.getStep());
}
talentRank.setDice(PROPERTIES.step2Dice(talentRank.getStep()));
}
public static List<DISCIPLINEBONUSType> getDisciplineBonuses(DISCIPLINEType discipline) {
List<DISCIPLINEBONUSType> bonuses = new ArrayList<DISCIPLINEBONUSType>();
int circlenr=0;
DISCIPLINE disziplinProperties = ApplicationProperties.create().getDisziplin(discipline.getName());
if( disziplinProperties == null ) return bonuses;
for(DISCIPLINECIRCLEType circle : disziplinProperties.getCIRCLE()) {
circlenr++;
if( circlenr > discipline.getCircle() ) break;
for( KARMAABILITYType karma : circle.getKARMA() ) {
DISCIPLINEBONUSType bonus = new DISCIPLINEBONUSType();
bonus.setCircle(circlenr);
bonus.setBonus("Can spend Karma for "+karma.getSpend());
bonuses.add(bonus);
}
for( String ability : circle.getABILITY() ) {
DISCIPLINEBONUSType bonus = new DISCIPLINEBONUSType();
bonus.setCircle(circlenr);
bonus.setBonus("Ability: "+ability);
bonuses.add(bonus);
}
}
return bonuses;
}
public PrintStream getErrorout() {
return errorout;
}
public void setErrorout(PrintStream stream) {
errorout = stream;
}
}
| true | true | public EDCHARACTER verarbeiteCharakter(EDCHARACTER charakter) {
CharacterContainer character = new CharacterContainer(charakter);
// Orignal berechnete LP sichern
CALCULATEDLEGENDPOINTSType oldcalculatedLP = character.getCopyOfCalculatedLegendpoints();
// Berechnete LP erstmal zurücksetzen
calculatedLP = character.resetCalculatedLegendpoints();
// Benötige Rasseneigenschaften der gewählten Rasse im Objekt "charakter":
NAMEGIVERABILITYType namegiver = character.getRace();
// Startgegenstände aus der Charaktererschaffung setzen, wenn gar kein Invetar vorhanden
List<ITEMType> itemList = character.getItems();
if( itemList.isEmpty() ) {
itemList.addAll(PROPERTIES.getStartingItems());
}
List<WEAPONType> magicWeapons = character.cutMagicWeaponFromNormalWeaponList();
List<WEAPONType> weaponList = character.getWeapons();
if( weaponList.isEmpty() ) {
// Startwaffen aus der Charaktererschaffung setzen, wenn gar keine Waffen vorhanden
weaponList.addAll(PROPERTIES.getStartingWeapons());
}
weaponList.addAll(magicWeapons);
// **ATTRIBUTE**
int karmaMaxBonus = PROPERTIES.getOptionalRules().getATTRIBUTE().getPoints();
// Der Bonus auf das Maximale Karma ergibt sich aus den übriggebliebenen Kaufpunkten bei der Charaktererschaffung
characterAttributes = character.getAttributes();
for (NAMEVALUEType raceattribute : namegiver.getATTRIBUTE()) {
// Pro Atributt wird nun dessen Werte, Stufe und Würfel bestimmt
ATTRIBUTEType attribute = characterAttributes.get(raceattribute.getName());
attribute.setRacevalue(raceattribute.getValue());
attribute.setCost(berechneAttriubteCost(attribute.getGenerationvalue()));
int value = attribute.getRacevalue() + attribute.getGenerationvalue();
attribute.setBasevalue(value);
value += attribute.getLpincrease();
attribute.setCurrentvalue(value);
STEPDICEType stepdice=attribute2StepAndDice(value);
attribute.setDice(stepdice.getDice());
attribute.setStep(stepdice.getStep());
karmaMaxBonus-=attribute.getCost();
if( OptionalRule_LegendpointsForAttributeIncrease ) calculatedLP.setAttributes(calculatedLP.getAttributes()+PROPERTIES.getCharacteristics().getAttributeTotalLP(attribute.getLpincrease()));
}
if( karmaMaxBonus <0 ) {
errorout.println("The character was generated with to many spent attribute buy points: "+(-karmaMaxBonus));
}
// **DEFENSE**
DEFENSEType defense = character.getDefence();
defense.setPhysical(berechneWiederstandskraft(characterAttributes.get("DEX").getCurrentvalue()));
defense.setSpell(berechneWiederstandskraft(characterAttributes.get("PER").getCurrentvalue()));
defense.setSocial(berechneWiederstandskraft(characterAttributes.get("CHA").getCurrentvalue()));
for(DEFENSEABILITYType racedefense : namegiver.getDEFENSE() ) {
switch (racedefense.getKind()) {
case PHYSICAL: defense.setPhysical(defense.getPhysical()+1); break;
case SPELL: defense.setSpell(defense.getSpell()+1); break;
case SOCIAL: defense.setSocial(defense.getSocial()+1); break;
}
}
// **INITIATIVE**
STEPDICEType initiativeStepdice=attribute2StepAndDice(characterAttributes.get("DEX").getCurrentvalue());
INITIATIVEType initiative = character.getInitiative();
// Setze alle Initiative Modifikatoren zurück, da diese im folgenden neu bestimmt werden.
initiative.setModification(0);
initiative.setBase(initiativeStepdice.getStep());
initiative.setStep(initiativeStepdice.getStep());
initiative.setDice(initiativeStepdice.getDice());
// **HEALTH**
CHARACTERISTICSHEALTHRATING newhealth = bestimmeHealth(characterAttributes.get("TOU").getCurrentvalue());
DEATHType death=character.getDeath();
DEATHType unconsciousness=character.getUnconsciousness();
death.setBase(newhealth.getDeath());
death.setAdjustment(0);
unconsciousness.setBase(newhealth.getUnconsciousness());
unconsciousness.setAdjustment(0);
character.getWound().setThreshold(newhealth.getWound()+namegiver.getWOUND().getThreshold());
RECOVERYType recovery = character.getRecovery();
recovery.setTestsperday(newhealth.getRecovery());
recovery.setStep(characterAttributes.get("TOU").getStep());
recovery.setDice(characterAttributes.get("TOU").getDice());
// **KARMA**
TALENTType karmaritualTalent = null;
final String KARMARITUAL = PROPERTIES.getKarmaritualName();
if( KARMARITUAL == null ) {
errorout.println("Karmaritual talent name is not defined for selected language.");
} else {
for( TALENTType talent : character.getTalentByName(KARMARITUAL) ) {
if( talent.getRealigned() == 0 ) {
karmaritualTalent=talent;
break;
}
}
if(karmaritualTalent == null ) {
errorout.println("No Karmaritual ("+KARMARITUAL+") could be found.");
}
}
int calculatedKarmaLP=calculateKarma(character.getKarma(), karmaritualTalent, namegiver.getKarmamodifier(), karmaMaxBonus);
if( OptionalRule_KarmaLegendPointCost ) {
calculatedLP.setKarma(calculatedLP.getKarma()+calculatedKarmaLP);
} else {
calculatedKarmaLP=0;
calculatedLP.setKarma(0);
}
// **MOVEMENT**
character.calculateMovement();
// **CARRYING**
character.calculateCarrying();
// Berechne Gewicht aller Münzen
for( COINSType coins : character.getAllCoins() ) {
// Mit doppelter Genauigkeit die Gewichte der Münzen addieren,
double weight = 0;
// Kupfermünzen: 1/3 Unze (oz)
weight += coins.getCopper() / 48.0;
// Silbermünzen: 1/4 Unze (oz)
weight += coins.getSilver() / 64.0;
// Goldmünzen: 1/5 Unze (oz)
weight += coins.getGold() / 80.0;
// Edelsteine mit Wert 50 Silber : 1/10 Unze (oz)
weight += coins.getGem50() / 160.0;
// Edelsteine mit Wert 100 Silber : 1/5 Unze (oz)
weight += coins.getGem100() / 80.0;
// Edelsteine mit Wert 200 Silber : 1/3 Unze (oz)
weight += coins.getGem200() / 48.0;
// Edelsteine mit Wert 500 Silber : 2/3 Unze (oz)
weight += coins.getGem500() / 24.0;
// Edelsteine mit Wert 1000 Silber : 1 3/5 Unzen (oz)
weight += coins.getGem1000()/ 10.0;
// Elementarmünzen: 1/10 Unze (oz)
weight += (double)( coins.getAir()+coins.getEarth()+coins.getFire()+coins.getWater()+coins.getOrichalcum() ) / 160.0;
// zum Abspeichern langt die einfache Genaugkeit
coins.setWeight((float)weight);
}
character.setAbilities(concatStrings(namegiver.getABILITY()));
// Lösche alle Diziplin Boni, damit diese unten wieder ergänzt werden können ohne auf duplikate Achten zu müssen
character.clearDisciplineBonuses();
// Stelle sicher dass ale Disziplin Talent eingügt werden
character.ensureDisciplinTalentsExits();
// Entferne alle Talente die zuhohle Kreise haben.
character.removeIllegalTalents();
// Entferne alle Optionalen Talente ohne Rang.
character.removeZeroRankOptionalTalents();
// Prüfe ob Talente realigned weren müssen.
character.realignOptionalTalents();
character.updateRealignedTalents();
// Sammle alle Namensgeber spezial Talente in einer Liste zusammen
HashMap<String,TALENTABILITYType> namegivertalents = new HashMap<String,TALENTABILITYType>();
for( TALENTABILITYType t : namegiver.getTALENT() ) {
namegivertalents.put(t.getName(), t);
}
// Wenn ein Charakter Weihepunkte erhalten hat, dann steht ihm das Questorentalent zur Verfügung
DEVOTIONType devotionPoints = character.getDevotionPoints();
if( (devotionPoints!=null) && (devotionPoints.getValue()>0) ) {
TALENTABILITYType talent = new TALENTABILITYType();
talent.setName(questorTalentName);
talent.setLimitation(devotionPoints.getPassion());
namegivertalents.put(questorTalentName, talent);
}
int maxKarmaStepBonus=0;
List<DISCIPLINEType> allDisciplines = character.getDisciplines();
HashMap<String,Integer> diciplineCircle = new HashMap<String, Integer>();
int disciplinenumber=0;
for( DISCIPLINEType currentDiscipline : allDisciplines ) {
disciplinenumber++;
List<TALENTType> durabilityTalents = new ArrayList<TALENTType>();
TalentsContainer currentTalents = new TalentsContainer(currentDiscipline);
for( TALENTType talent : currentTalents.getDisciplineAndOptionaltalents() ) ensureRankAndTeacher(talent);
HashMap<String, Integer> defaultOptionalTalents = PROPERTIES.getDefaultOptionalTalents(disciplinenumber);
int currentCircle = currentDiscipline.getCircle();
int minDisciplineCircle=character.getDisciplineMinCircle(disciplinenumber).getCircle();
calculateTalents(namegivertalents, defaultOptionalTalents, disciplinenumber, currentCircle, minDisciplineCircle, durabilityTalents, currentTalents.getDisciplinetalents(), true);
calculateTalents(namegivertalents, defaultOptionalTalents, disciplinenumber, currentCircle, minDisciplineCircle, durabilityTalents, currentTalents.getOptionaltalents(), false);
// Alle Namegiver Talente, die bis jetzt noch nicht enthalten waren,
// werden nun den optionalen Talenten beigefügt.
for( String t : namegivertalents.keySet() ) {
TALENTType talent = new TALENTType();
talent.setName(namegivertalents.get(t).getName());
talent.setLimitation(namegivertalents.get(t).getLimitation());
talent.setCircle(0);
capabilities.enforceCapabilityParams(talent);
talent.setTEACHER(new TALENTTEACHERType());
RANKType rank = new RANKType();
calculateCapabilityRank(rank,characterAttributes.get(talent.getAttribute().value()));
talent.setRANK(rank);
currentTalents.getOptionaltalents().add(talent);
}
namegivertalents.clear(); // Ist keine lokale Variable und Namensgebertalent sollen nur bei einer Disziplin einfügt werden
for( String t : defaultOptionalTalents.keySet() ) {
// Talente aus späteren Kreisen werden auch erst später eingefügt
int circle = defaultOptionalTalents.get(t);
if( circle > currentCircle ) continue;
TALENTType talent = new TALENTType();
talent.setName(t);
talent.setCircle(circle);
capabilities.enforceCapabilityParams(talent);
talent.setTEACHER(new TALENTTEACHERType());
RANKType rank = new RANKType();
calculateCapabilityRank(rank,characterAttributes.get(talent.getAttribute().value()));
talent.setRANK(rank);
currentTalents.getOptionaltalents().add(talent);
}
// Wenn Durability-Talente gefunden wurden, berechnen aus dessen Rank
// die Erhöhung von Todes- und Bewustlosigkeitsschwelle
for( TALENTType durabilityTalent : durabilityTalents ) {
DISCIPLINE disziplinProperties = PROPERTIES.getDisziplin(currentDiscipline.getName());
if( disziplinProperties != null ) {
DISCIPLINEDURABILITYType durability = disziplinProperties.getDURABILITY();
int rank = durabilityTalent.getRANK().getRank()-durabilityTalent.getRANK().getRealignedrank();
death.setAdjustment(death.getAdjustment()+(durability.getDeath()*rank));
unconsciousness.setAdjustment(unconsciousness.getAdjustment()+(durability.getUnconsciousness()*rank));
durabilityTalent.setLimitation(durability.getDeath()+"/"+durability.getUnconsciousness());
}
}
diciplineCircle.put(currentDiscipline.getName(), currentCircle);
// Nur der höchtse Bonus wird gewertet.
int currentKarmaStepBonus = getDisciplineKarmaStepBonus(currentDiscipline);
if( currentKarmaStepBonus > maxKarmaStepBonus ) maxKarmaStepBonus = currentKarmaStepBonus;
List<DISCIPLINEBONUSType> currentBonuses = currentDiscipline.getDISCIPLINEBONUS();
currentBonuses.clear();
currentBonuses.addAll(getDisciplineBonuses(currentDiscipline));
// TALENT KNACKS
for( TALENTType talent : currentTalents.getDisciplineAndOptionaltalents() ) checkTalentKnacks(talent,disciplinenumber);
}
// ** ARMOR **
// Zu erstmal alles entfernen was nicht eine Reale Rüstung ist:
List<ARMORType> totalarmor = character.removeVirtualArmorFromNormalArmorList();
// natural ARMOR bestimmen
ARMORType namegiverArmor = namegiver.getARMOR();
ARMORType naturalArmor = new ARMORType();
naturalArmor.setName(namegiverArmor.getName());
naturalArmor.setMysticarmor(namegiverArmor.getMysticarmor()+berechneMysticArmor(characterAttributes.get("WIL").getCurrentvalue()));
naturalArmor.setPhysicalarmor(namegiverArmor.getPhysicalarmor());
naturalArmor.setPenalty(namegiverArmor.getPenalty());
naturalArmor.setUsed(namegiverArmor.getUsed());
naturalArmor.setWeight(namegiverArmor.getWeight());
naturalArmor.setVirtual(YesnoType.YES);
// Natürliche Rüstung der Liste voranstellen
totalarmor.add(0, naturalArmor);
// magischen Rüstung/Rüstungsschutz anhängen:
totalarmor.addAll(character.getMagicArmor());
// Bestimme nun den aktuellen Gesamtrüstungsschutz
int mysticalarmor=0;
int physicalarmor=0;
int protectionpenalty=0;
for (ARMORType armor : totalarmor ) {
if( armor.getUsed().equals(YesnoType.YES) ) {
mysticalarmor+=armor.getMysticarmor();
physicalarmor+=armor.getPhysicalarmor();
protectionpenalty+=armor.getPenalty();
}
}
PROTECTIONType protection = character.getProtection();
protection.setMysticarmor(mysticalarmor);
protection.setPenalty(protectionpenalty);
protection.setPhysicalarmor(physicalarmor);
character.readjustInitiativeModifikator(-protectionpenalty);
// ** KARMA STEP **
KARMAType karma = character.getKarma();
karma.setStep(4 + maxKarmaStepBonus); // mindestens d6
karma.setDice(PROPERTIES.step2Dice(karma.getStep()));
int skillsStartranks=calculatedLP.getUSEDSTARTRANKS().getSkills();
character.removeEmptySkills();
List<SKILLType> skills = character.getSkills();
if( skills.isEmpty() ) {
for(SKILLType skilltemplate : PROPERTIES.getStartingSkills() ) {
SKILLType skill = new SKILLType();
skill.setName(skilltemplate.getName());
skill.setLimitation(skilltemplate.getLimitation());
RANKType rank = new RANKType();
rank.setRank(skilltemplate.getRANK().getRank());
rank.setStartrank(skilltemplate.getRANK().getStartrank());
skill.setRANK(rank);
skills.add(skill);
}
}
List<CAPABILITYType> defaultSkills = capabilities.getDefaultSkills(namegiver.getNOTDEFAULTSKILL());
for( SKILLType skill : skills ) {
RANKType rank = skill.getRANK();
int startrank = rank.getStartrank();
skillsStartranks+=startrank;
int lpcostfull= PROPERTIES.getCharacteristics().getSkillRankTotalLP(rank.getRank());
int lpcoststart= PROPERTIES.getCharacteristics().getSkillRankTotalLP(startrank);
rank.setLpcost(lpcostfull-lpcoststart);
rank.setBonus(0);
calculatedLP.setSkills(calculatedLP.getSkills()+rank.getLpcost());
capabilities.enforceCapabilityParams(skill);
if( skill.getAttribute() != null ) {
calculateCapabilityRank(rank,characterAttributes.get(skill.getAttribute().value()));
}
removeIfContains(defaultSkills,skill.getName());
}
calculatedLP.getUSEDSTARTRANKS().setSkills(skillsStartranks);
// Wenn gewünscht dann zeige auch die DefaultSkills mit an
if( PROPERTIES.getOptionalRules().getSHOWDEFAULTSKILLS().getUsed().equals(YesnoType.YES) ) {
for( CAPABILITYType defaultSkill : defaultSkills ) {
List<String> limitations = defaultSkill.getLIMITATION();
if( limitations.size()==0 ) limitations.add("");
for( String limitation : limitations ) {
SKILLType skill = new SKILLType();
RANKType rank = new RANKType();
skill.setRANK(rank);
skill.setName(defaultSkill.getName());
skill.setLimitation(limitation);
capabilities.enforceCapabilityParams(skill);
if( skill.getAttribute() != null ) {
calculateCapabilityRank(rank,characterAttributes.get(skill.getAttribute().value()));
}
skills.add(skill);
}
}
}
DEFENSEType disciplineDefense = getDisciplineDefense(diciplineCircle);
defense.setPhysical(defense.getPhysical()+disciplineDefense.getPhysical());
defense.setSocial(defense.getSocial()+disciplineDefense.getSocial());
defense.setSpell(defense.getSpell()+disciplineDefense.getSpell());
recovery.setStep(recovery.getStep()+getDisciplineRecoveryTestBonus(diciplineCircle));
recovery.setDice(PROPERTIES.step2Dice(recovery.getStep()));
character.readjustInitiativeModifikator(getDisciplineInitiative(diciplineCircle));
// ** SPELLS **
// Bestimme die wieviele Zaubersprüche bei der Charactererschaffung kostenlos dazu kamen
// und wieviel ein SpellAbility pro Kreis pro Disziplin kostenlos dazukamen.
int freespellranks = attribute2StepAndDice(characterAttributes.get("PER").getBasevalue()).getStep();
for( int sa : getDisciplineSpellAbility(diciplineCircle) ) freespellranks+=sa;
calculatedLP.setSpells(0);
HashMap<String, SPELLDEFType> spelllist = PROPERTIES.getSpells();
for( DISCIPLINEType discipline : character.getDisciplines() ) {
int usedSpellabilities=0;
for( SPELLType spell : discipline.getSPELL() ) {
SPELLDEFType spelldef = spelllist.get(spell.getName());
if( spelldef == null ) {
errorout.println("Unknown Spell '"+spell.getName()+"' in grimour found. Spell is left unmodified in grimour.");
} else {
spell.setCastingdifficulty(spelldef.getCastingdifficulty());
spell.setDuration(spelldef.getDuration());
spell.setEffect(spelldef.getEffect());
spell.setEffectarea(spelldef.getEffectarea());
spell.setRange(spelldef.getRange());
spell.setReattuningdifficulty(spelldef.getReattuningdifficulty());
spell.setThreads(spelldef.getThreads());
spell.setWeavingdifficulty(spelldef.getWeavingdifficulty());
spell.setBookref(spelldef.getBookref());
spell.setElement(spelldef.getElement());
}
// Wenn ein Zauber duch Spellability gelernt wurde, dann kostet er keine LPs
if( spell.getByspellability().equals(YesnoType.YES) ) {
usedSpellabilities++;
freespellranks-=spell.getCircle();
} else if( OptionalRule_SpellLegendPointCost ) {
// The cost of spells are equivalent to the cost of increasing a Novice Talent to a Rank equal to the Spell Circle
int lpcost=PROPERTIES.getCharacteristics().getSpellLP(spell.getCircle());
calculatedLP.setSpells(calculatedLP.getSpells()+lpcost);
}
}
discipline.setUsedspellabilities(usedSpellabilities);
}
calculatedLP.getUSEDSTARTRANKS().setSpells(-freespellranks);
for( BLOODCHARMITEMType item : character.getBloodCharmItem() ) {
if( item.getUsed().equals(YesnoType.YES) ) {
death.setAdjustment(death.getAdjustment()-item.getBlooddamage());
unconsciousness.setAdjustment(unconsciousness.getAdjustment()-item.getBlooddamage());
}
}
List<TALENTType> firstDisciplineOptionalTalents = null;
if( ! allDisciplines.isEmpty() ) firstDisciplineOptionalTalents = allDisciplines.get(0).getOPTIONALTALENT();
for( THREADITEMType item : character.getThreadItem() ) {
int rank = item.getWeaventhreadrank();
// If no thread is weaven to the this thread item, skip it.
if( rank < 1 ) continue;
THREADRANKType threadrank = item.getTHREADRANK().get(rank-1);
while( (threadrank==null) && (rank>1) ) {
// Wenn der Fadenrang nicht definiert ist, obwohl der Rang größer 1 ist, wähle den Fadenrang einen Rang kleiner.
if( threadrank == null ) {
errorout.println("Undefined Threadrank for "+item.getName()+" for rank "+rank );
}
rank--;
threadrank = item.getTHREADRANK().get(rank-1);
}
if( threadrank == null ) {
errorout.println("No Threadranks for "+item.getName()+" for rank "+item.getWeaventhreadrank()+" or less at all." );
continue;
}
for(DEFENSEABILITYType itemdefense : threadrank.getDEFENSE() ) {
switch (itemdefense.getKind()) {
case PHYSICAL: defense.setPhysical(defense.getPhysical()+1); break;
case SPELL: defense.setSpell(defense.getSpell()+1); break;
case SOCIAL: defense.setSocial(defense.getSocial()+1); break;
}
}
for(TALENTABILITYType itemtalent : threadrank.getTALENT() ) {
String limitation = itemtalent.getLimitation();
boolean notfound=true;
for( TALENTType talent : character.getTalentByName(itemtalent.getName()) ) {
if( limitation.isEmpty() || (talent.getLimitation().equals(limitation)) ) {
notfound=false;
RANKType talentrank = talent.getRANK();
talentrank.setBonus(talentrank.getBonus()+itemtalent.getBonus());
calculateCapabilityRank(talentrank,characterAttributes.get(talent.getAttribute().value()));
}
}
if( notfound && (firstDisciplineOptionalTalents!=null) ) {
if( limitation.isEmpty() ) limitation ="(#)";
else limitation += " (#)";
TALENTType bonusTalent = new TALENTType();
bonusTalent.setName(itemtalent.getName());
bonusTalent.setLimitation(limitation);
bonusTalent.setCircle(0);
capabilities.enforceCapabilityParams(bonusTalent);
RANKType bonusrank = new RANKType();
bonusrank.setRank(0);
bonusrank.setBonus(1);
calculateCapabilityRank(bonusrank,characterAttributes.get(bonusTalent.getAttribute().value()));
bonusTalent.setRANK(bonusrank);
TALENTTEACHERType teacher = new TALENTTEACHERType();
teacher.setByversatility(YesnoType.NO);
teacher.setTalentcircle(rank);
teacher.setTeachercircle(rank);
teacher.setName(item.getName());
bonusTalent.setTEACHER(teacher);
firstDisciplineOptionalTalents.add(bonusTalent);
}
}
for(DISZIPINABILITYType iteminitiative : threadrank.getINITIATIVE() ) {
character.readjustInitiativeModifikator(iteminitiative.getCount());
}
initiative.setStep(initiative.getBase()+initiative.getModification());
initiative.setDice(PROPERTIES.step2Dice(initiative.getStep()));
// TODO: other effects of MagicItems
// TODO:List<TALENTType> optTalents = allTalents.get(disciplinenumber).getOPTIONALTALENT();
}
// Veränderungen am death/unconsciousness adjustment sollen beachtet werden
death.setValue(death.getBase()+death.getAdjustment());
unconsciousness.setValue(unconsciousness.getBase()+unconsciousness.getAdjustment());
if( calculatedLP.getSpells() < 0 ) calculatedLP.setSpells(0);
calculatedLP.setTotal(calculatedLP.getAttributes()+calculatedLP.getDisciplinetalents()+
calculatedLP.getKarma()+calculatedLP.getMagicitems()+calculatedLP.getOptionaltalents()+
calculatedLP.getSkills()+calculatedLP.getSpells()+calculatedLP.getKnacks());
if( OptionalRule_AutoInsertLegendPointSpent ) character.addLegendPointsSpent(oldcalculatedLP);
character.calculateLegendPointsAndStatus();
character.calculateDevotionPoints();
return charakter;
}
| public EDCHARACTER verarbeiteCharakter(EDCHARACTER charakter) {
CharacterContainer character = new CharacterContainer(charakter);
// Orignal berechnete LP sichern
CALCULATEDLEGENDPOINTSType oldcalculatedLP = character.getCopyOfCalculatedLegendpoints();
// Berechnete LP erstmal zurücksetzen
calculatedLP = character.resetCalculatedLegendpoints();
// Benötige Rasseneigenschaften der gewählten Rasse im Objekt "charakter":
NAMEGIVERABILITYType namegiver = character.getRace();
// Startgegenstände aus der Charaktererschaffung setzen, wenn gar kein Invetar vorhanden
List<ITEMType> itemList = character.getItems();
if( itemList.isEmpty() ) {
itemList.addAll(PROPERTIES.getStartingItems());
}
List<WEAPONType> magicWeapons = character.cutMagicWeaponFromNormalWeaponList();
List<WEAPONType> weaponList = character.getWeapons();
if( weaponList.isEmpty() ) {
// Startwaffen aus der Charaktererschaffung setzen, wenn gar keine Waffen vorhanden
weaponList.addAll(PROPERTIES.getStartingWeapons());
}
weaponList.addAll(magicWeapons);
// **ATTRIBUTE**
int karmaMaxBonus = PROPERTIES.getOptionalRules().getATTRIBUTE().getPoints();
// Der Bonus auf das Maximale Karma ergibt sich aus den übriggebliebenen Kaufpunkten bei der Charaktererschaffung
characterAttributes = character.getAttributes();
for (NAMEVALUEType raceattribute : namegiver.getATTRIBUTE()) {
// Pro Atributt wird nun dessen Werte, Stufe und Würfel bestimmt
ATTRIBUTEType attribute = characterAttributes.get(raceattribute.getName());
attribute.setRacevalue(raceattribute.getValue());
attribute.setCost(berechneAttriubteCost(attribute.getGenerationvalue()));
int value = attribute.getRacevalue() + attribute.getGenerationvalue();
attribute.setBasevalue(value);
value += attribute.getLpincrease();
attribute.setCurrentvalue(value);
STEPDICEType stepdice=attribute2StepAndDice(value);
attribute.setDice(stepdice.getDice());
attribute.setStep(stepdice.getStep());
karmaMaxBonus-=attribute.getCost();
if( OptionalRule_LegendpointsForAttributeIncrease ) calculatedLP.setAttributes(calculatedLP.getAttributes()+PROPERTIES.getCharacteristics().getAttributeTotalLP(attribute.getLpincrease()));
}
if( karmaMaxBonus <0 ) {
errorout.println("The character was generated with to many spent attribute buy points: "+(-karmaMaxBonus));
}
// **DEFENSE**
DEFENSEType defense = character.getDefence();
defense.setPhysical(berechneWiederstandskraft(characterAttributes.get("DEX").getCurrentvalue()));
defense.setSpell(berechneWiederstandskraft(characterAttributes.get("PER").getCurrentvalue()));
defense.setSocial(berechneWiederstandskraft(characterAttributes.get("CHA").getCurrentvalue()));
for(DEFENSEABILITYType racedefense : namegiver.getDEFENSE() ) {
switch (racedefense.getKind()) {
case PHYSICAL: defense.setPhysical(defense.getPhysical()+1); break;
case SPELL: defense.setSpell(defense.getSpell()+1); break;
case SOCIAL: defense.setSocial(defense.getSocial()+1); break;
}
}
// **INITIATIVE**
STEPDICEType initiativeStepdice=attribute2StepAndDice(characterAttributes.get("DEX").getCurrentvalue());
INITIATIVEType initiative = character.getInitiative();
// Setze alle Initiative Modifikatoren zurück, da diese im folgenden neu bestimmt werden.
initiative.setModification(0);
initiative.setBase(initiativeStepdice.getStep());
initiative.setStep(initiativeStepdice.getStep());
initiative.setDice(initiativeStepdice.getDice());
// **HEALTH**
CHARACTERISTICSHEALTHRATING newhealth = bestimmeHealth(characterAttributes.get("TOU").getCurrentvalue());
DEATHType death=character.getDeath();
DEATHType unconsciousness=character.getUnconsciousness();
death.setBase(newhealth.getDeath());
death.setAdjustment(0);
unconsciousness.setBase(newhealth.getUnconsciousness());
unconsciousness.setAdjustment(0);
character.getWound().setThreshold(newhealth.getWound()+namegiver.getWOUND().getThreshold());
RECOVERYType recovery = character.getRecovery();
recovery.setTestsperday(newhealth.getRecovery());
recovery.setStep(characterAttributes.get("TOU").getStep());
recovery.setDice(characterAttributes.get("TOU").getDice());
// **KARMA**
TALENTType karmaritualTalent = null;
final String KARMARITUAL = PROPERTIES.getKarmaritualName();
if( KARMARITUAL == null ) {
errorout.println("Karmaritual talent name is not defined for selected language.");
} else {
for( TALENTType talent : character.getTalentByName(KARMARITUAL) ) {
if( talent.getRealigned() == 0 ) {
karmaritualTalent=talent;
break;
}
}
if(karmaritualTalent == null ) {
errorout.println("No Karmaritual ("+KARMARITUAL+") could be found.");
}
}
int calculatedKarmaLP=calculateKarma(character.getKarma(), karmaritualTalent, namegiver.getKarmamodifier(), karmaMaxBonus);
if( OptionalRule_KarmaLegendPointCost ) {
calculatedLP.setKarma(calculatedLP.getKarma()+calculatedKarmaLP);
} else {
calculatedKarmaLP=0;
calculatedLP.setKarma(0);
}
// **MOVEMENT**
character.calculateMovement();
// **CARRYING**
character.calculateCarrying();
// Berechne Gewicht aller Münzen
for( COINSType coins : character.getAllCoins() ) {
// Mit doppelter Genauigkeit die Gewichte der Münzen addieren,
double weight = 0;
// Kupfermünzen: 1/3 Unze (oz)
weight += coins.getCopper() / 48.0;
// Silbermünzen: 1/4 Unze (oz)
weight += coins.getSilver() / 64.0;
// Goldmünzen: 1/5 Unze (oz)
weight += coins.getGold() / 80.0;
// Edelsteine mit Wert 50 Silber : 1/10 Unze (oz)
weight += coins.getGem50() / 160.0;
// Edelsteine mit Wert 100 Silber : 1/5 Unze (oz)
weight += coins.getGem100() / 80.0;
// Edelsteine mit Wert 200 Silber : 1/3 Unze (oz)
weight += coins.getGem200() / 48.0;
// Edelsteine mit Wert 500 Silber : 2/3 Unze (oz)
weight += coins.getGem500() / 24.0;
// Edelsteine mit Wert 1000 Silber : 1 3/5 Unzen (oz)
weight += coins.getGem1000()/ 10.0;
// Elementarmünzen: 1/10 Unze (oz)
weight += (double)( coins.getAir()+coins.getEarth()+coins.getFire()+coins.getWater()+coins.getOrichalcum() ) / 160.0;
// zum Abspeichern langt die einfache Genaugkeit
coins.setWeight((float)weight);
}
character.setAbilities(concatStrings(namegiver.getABILITY()));
// Lösche alle Diziplin Boni, damit diese unten wieder ergänzt werden können ohne auf duplikate Achten zu müssen
character.clearDisciplineBonuses();
// Stelle sicher dass ale Disziplin Talent eingügt werden
character.ensureDisciplinTalentsExits();
// Entferne alle Talente die zuhohle Kreise haben.
character.removeIllegalTalents();
// Entferne alle Optionalen Talente ohne Rang.
character.removeZeroRankOptionalTalents();
// Prüfe ob Talente realigned weren müssen.
character.realignOptionalTalents();
character.updateRealignedTalents();
// Sammle alle Namensgeber spezial Talente in einer Liste zusammen
HashMap<String,TALENTABILITYType> namegivertalents = new HashMap<String,TALENTABILITYType>();
for( TALENTABILITYType t : namegiver.getTALENT() ) {
namegivertalents.put(t.getName(), t);
}
// Wenn ein Charakter Weihepunkte erhalten hat, dann steht ihm das Questorentalent zur Verfügung
DEVOTIONType devotionPoints = character.getDevotionPoints();
if( (devotionPoints!=null) && (devotionPoints.getValue()>0) ) {
TALENTABILITYType talent = new TALENTABILITYType();
talent.setName(questorTalentName);
talent.setLimitation(devotionPoints.getPassion());
namegivertalents.put(questorTalentName, talent);
}
int maxKarmaStepBonus=0;
List<DISCIPLINEType> allDisciplines = character.getDisciplines();
HashMap<String,Integer> diciplineCircle = new HashMap<String, Integer>();
int disciplinenumber=0;
for( DISCIPLINEType currentDiscipline : allDisciplines ) {
disciplinenumber++;
List<TALENTType> durabilityTalents = new ArrayList<TALENTType>();
TalentsContainer currentTalents = new TalentsContainer(currentDiscipline);
for( TALENTType talent : currentTalents.getDisciplineAndOptionaltalents() ) ensureRankAndTeacher(talent);
HashMap<String, Integer> defaultOptionalTalents = PROPERTIES.getDefaultOptionalTalents(disciplinenumber);
int currentCircle = currentDiscipline.getCircle();
int minDisciplineCircle=character.getDisciplineMinCircle(disciplinenumber).getCircle();
calculateTalents(namegivertalents, defaultOptionalTalents, disciplinenumber, currentCircle, minDisciplineCircle, durabilityTalents, currentTalents.getDisciplinetalents(), true);
calculateTalents(namegivertalents, defaultOptionalTalents, disciplinenumber, currentCircle, minDisciplineCircle, durabilityTalents, currentTalents.getOptionaltalents(), false);
// Alle Namegiver Talente, die bis jetzt noch nicht enthalten waren,
// werden nun den optionalen Talenten beigefügt.
for( String t : namegivertalents.keySet() ) {
TALENTType talent = new TALENTType();
talent.setName(namegivertalents.get(t).getName());
talent.setLimitation(namegivertalents.get(t).getLimitation());
talent.setCircle(0);
capabilities.enforceCapabilityParams(talent);
talent.setTEACHER(new TALENTTEACHERType());
RANKType rank = new RANKType();
calculateCapabilityRank(rank,characterAttributes.get(talent.getAttribute().value()));
talent.setRANK(rank);
currentTalents.getOptionaltalents().add(talent);
}
namegivertalents.clear(); // Ist keine lokale Variable und Namensgebertalent sollen nur bei einer Disziplin einfügt werden
for( String t : defaultOptionalTalents.keySet() ) {
// Talente aus späteren Kreisen werden auch erst später eingefügt
int circle = defaultOptionalTalents.get(t);
if( circle > currentCircle ) continue;
TALENTType talent = new TALENTType();
talent.setName(t);
talent.setCircle(circle);
capabilities.enforceCapabilityParams(talent);
talent.setTEACHER(new TALENTTEACHERType());
RANKType rank = new RANKType();
calculateCapabilityRank(rank,characterAttributes.get(talent.getAttribute().value()));
talent.setRANK(rank);
currentTalents.getOptionaltalents().add(talent);
}
// Wenn Durability-Talente gefunden wurden, berechnen aus dessen Rank
// die Erhöhung von Todes- und Bewustlosigkeitsschwelle
for( TALENTType durabilityTalent : durabilityTalents ) {
DISCIPLINE disziplinProperties = PROPERTIES.getDisziplin(currentDiscipline.getName());
if( disziplinProperties != null ) {
DISCIPLINEDURABILITYType durability = disziplinProperties.getDURABILITY();
int rank = durabilityTalent.getRANK().getRank()-durabilityTalent.getRANK().getRealignedrank();
death.setAdjustment(death.getAdjustment()+(durability.getDeath()*rank));
unconsciousness.setAdjustment(unconsciousness.getAdjustment()+(durability.getUnconsciousness()*rank));
durabilityTalent.setLimitation(durability.getDeath()+"/"+durability.getUnconsciousness());
}
}
diciplineCircle.put(currentDiscipline.getName(), currentCircle);
// Nur der höchtse Bonus wird gewertet.
int currentKarmaStepBonus = getDisciplineKarmaStepBonus(currentDiscipline);
if( currentKarmaStepBonus > maxKarmaStepBonus ) maxKarmaStepBonus = currentKarmaStepBonus;
List<DISCIPLINEBONUSType> currentBonuses = currentDiscipline.getDISCIPLINEBONUS();
currentBonuses.clear();
currentBonuses.addAll(getDisciplineBonuses(currentDiscipline));
// TALENT KNACKS
for( TALENTType talent : currentTalents.getDisciplineAndOptionaltalents() ) checkTalentKnacks(talent,disciplinenumber);
}
// ** ARMOR **
// Zu erstmal alles entfernen was nicht eine Reale Rüstung ist:
List<ARMORType> totalarmor = character.removeVirtualArmorFromNormalArmorList();
// natural ARMOR bestimmen
ARMORType namegiverArmor = namegiver.getARMOR();
ARMORType naturalArmor = new ARMORType();
naturalArmor.setName(namegiverArmor.getName());
naturalArmor.setMysticarmor(namegiverArmor.getMysticarmor()+berechneMysticArmor(characterAttributes.get("WIL").getCurrentvalue()));
naturalArmor.setPhysicalarmor(namegiverArmor.getPhysicalarmor());
naturalArmor.setPenalty(namegiverArmor.getPenalty());
naturalArmor.setUsed(namegiverArmor.getUsed());
naturalArmor.setWeight(namegiverArmor.getWeight());
naturalArmor.setVirtual(YesnoType.YES);
// Natürliche Rüstung der Liste voranstellen
totalarmor.add(0, naturalArmor);
// magischen Rüstung/Rüstungsschutz anhängen:
totalarmor.addAll(character.getMagicArmor());
// Bestimme nun den aktuellen Gesamtrüstungsschutz
int mysticalarmor=0;
int physicalarmor=0;
int protectionpenalty=0;
for (ARMORType armor : totalarmor ) {
if( armor.getUsed().equals(YesnoType.YES) ) {
mysticalarmor+=armor.getMysticarmor();
physicalarmor+=armor.getPhysicalarmor();
protectionpenalty+=armor.getPenalty();
}
}
PROTECTIONType protection = character.getProtection();
protection.setMysticarmor(mysticalarmor);
protection.setPenalty(protectionpenalty);
protection.setPhysicalarmor(physicalarmor);
character.readjustInitiativeModifikator(-protectionpenalty);
// ** KARMA STEP **
KARMAType karma = character.getKarma();
karma.setStep(4 + maxKarmaStepBonus); // mindestens d6
karma.setDice(PROPERTIES.step2Dice(karma.getStep()));
int skillsStartranks=calculatedLP.getUSEDSTARTRANKS().getSkills();
character.removeEmptySkills();
List<SKILLType> skills = character.getSkills();
if( skills.isEmpty() ) {
for(SKILLType skilltemplate : PROPERTIES.getStartingSkills() ) {
SKILLType skill = new SKILLType();
skill.setName(skilltemplate.getName());
skill.setLimitation(skilltemplate.getLimitation());
RANKType rank = new RANKType();
rank.setRank(skilltemplate.getRANK().getRank());
rank.setStartrank(skilltemplate.getRANK().getStartrank());
skill.setRANK(rank);
skills.add(skill);
}
}
List<CAPABILITYType> defaultSkills = capabilities.getDefaultSkills(namegiver.getNOTDEFAULTSKILL());
for( SKILLType skill : skills ) {
RANKType rank = skill.getRANK();
int startrank = rank.getStartrank();
skillsStartranks+=startrank;
int lpcostfull= PROPERTIES.getCharacteristics().getSkillRankTotalLP(rank.getRank());
int lpcoststart= PROPERTIES.getCharacteristics().getSkillRankTotalLP(startrank);
rank.setLpcost(lpcostfull-lpcoststart);
rank.setBonus(0);
calculatedLP.setSkills(calculatedLP.getSkills()+rank.getLpcost());
capabilities.enforceCapabilityParams(skill);
if( skill.getAttribute() != null ) {
calculateCapabilityRank(rank,characterAttributes.get(skill.getAttribute().value()));
}
removeIfContains(defaultSkills,skill.getName());
}
calculatedLP.getUSEDSTARTRANKS().setSkills(skillsStartranks);
// Wenn gewünscht dann zeige auch die DefaultSkills mit an
if( PROPERTIES.getOptionalRules().getSHOWDEFAULTSKILLS().getUsed().equals(YesnoType.YES) ) {
for( CAPABILITYType defaultSkill : defaultSkills ) {
List<String> limitations = defaultSkill.getLIMITATION();
if( limitations.size()==0 ) limitations.add("");
for( String limitation : limitations ) {
SKILLType skill = new SKILLType();
RANKType rank = new RANKType();
skill.setRANK(rank);
skill.setName(defaultSkill.getName());
skill.setLimitation(limitation);
capabilities.enforceCapabilityParams(skill);
if( skill.getAttribute() != null ) {
calculateCapabilityRank(rank,characterAttributes.get(skill.getAttribute().value()));
}
skills.add(skill);
}
}
}
DEFENSEType disciplineDefense = getDisciplineDefense(diciplineCircle);
defense.setPhysical(defense.getPhysical()+disciplineDefense.getPhysical());
defense.setSocial(defense.getSocial()+disciplineDefense.getSocial());
defense.setSpell(defense.getSpell()+disciplineDefense.getSpell());
recovery.setStep(recovery.getStep()+getDisciplineRecoveryTestBonus(diciplineCircle));
recovery.setDice(PROPERTIES.step2Dice(recovery.getStep()));
character.readjustInitiativeModifikator(getDisciplineInitiative(diciplineCircle));
// ** SPELLS **
// Bestimme die wieviele Zaubersprüche bei der Charactererschaffung kostenlos dazu kamen
// und wieviel ein SpellAbility pro Kreis pro Disziplin kostenlos dazukamen.
int freespellranks = attribute2StepAndDice(characterAttributes.get("PER").getBasevalue()).getStep();
for( int sa : getDisciplineSpellAbility(diciplineCircle) ) freespellranks+=sa;
calculatedLP.setSpells(0);
HashMap<String, SPELLDEFType> spelllist = PROPERTIES.getSpells();
for( DISCIPLINEType discipline : character.getDisciplines() ) {
int usedSpellabilities=0;
for( SPELLType spell : discipline.getSPELL() ) {
SPELLDEFType spelldef = spelllist.get(spell.getName());
if( spelldef == null ) {
errorout.println("Unknown Spell '"+spell.getName()+"' in grimour found. Spell is left unmodified in grimour.");
} else {
spell.setCastingdifficulty(spelldef.getCastingdifficulty());
spell.setDuration(spelldef.getDuration());
spell.setEffect(spelldef.getEffect());
spell.setEffectarea(spelldef.getEffectarea());
spell.setRange(spelldef.getRange());
spell.setReattuningdifficulty(spelldef.getReattuningdifficulty());
spell.setThreads(spelldef.getThreads());
spell.setWeavingdifficulty(spelldef.getWeavingdifficulty());
spell.setBookref(spelldef.getBookref());
spell.setElement(spelldef.getElement());
}
// Wenn ein Zauber duch Spellability gelernt wurde, dann kostet er keine LPs
if( spell.getByspellability().equals(YesnoType.YES) ) {
usedSpellabilities++;
freespellranks-=spell.getCircle();
} else if( OptionalRule_SpellLegendPointCost ) {
// The cost of spells are equivalent to the cost of increasing a Novice Talent to a Rank equal to the Spell Circle
int lpcost=PROPERTIES.getCharacteristics().getSpellLP(spell.getCircle());
calculatedLP.setSpells(calculatedLP.getSpells()+lpcost);
}
}
discipline.setUsedspellabilities(usedSpellabilities);
}
calculatedLP.getUSEDSTARTRANKS().setSpells(-freespellranks);
for( BLOODCHARMITEMType item : character.getBloodCharmItem() ) {
if( item.getUsed().equals(YesnoType.YES) ) {
death.setAdjustment(death.getAdjustment()-item.getBlooddamage());
unconsciousness.setAdjustment(unconsciousness.getAdjustment()-item.getBlooddamage());
}
}
List<TALENTType> firstDisciplineOptionalTalents = null;
if( ! allDisciplines.isEmpty() ) firstDisciplineOptionalTalents = allDisciplines.get(0).getOPTIONALTALENT();
for( THREADITEMType item : character.getThreadItem() ) {
int rank = item.getWeaventhreadrank();
// If no thread is weaven to the this thread item, skip it.
if( rank < 1 ) continue;
THREADRANKType threadrank = item.getTHREADRANK().get(rank-1);
while( (threadrank==null) && (rank>1) ) {
// Wenn der Fadenrang nicht definiert ist, obwohl der Rang größer 1 ist, wähle den Fadenrang einen Rang kleiner.
if( threadrank == null ) {
errorout.println("Undefined Threadrank for "+item.getName()+" for rank "+rank );
}
rank--;
threadrank = item.getTHREADRANK().get(rank-1);
}
if( threadrank == null ) {
errorout.println("No Threadranks for "+item.getName()+" for rank "+item.getWeaventhreadrank()+" or less at all." );
continue;
}
for(DEFENSEABILITYType itemdefense : threadrank.getDEFENSE() ) {
switch (itemdefense.getKind()) {
case PHYSICAL: defense.setPhysical(defense.getPhysical()+1); break;
case SPELL: defense.setSpell(defense.getSpell()+1); break;
case SOCIAL: defense.setSocial(defense.getSocial()+1); break;
}
}
for(TALENTABILITYType itemtalent : threadrank.getTALENT() ) {
String limitation = itemtalent.getLimitation();
boolean notfound=true;
for( TALENTType talent : character.getTalentByName(itemtalent.getName()) ) {
if( limitation.isEmpty() || (talent.getLimitation().equals(limitation)) ) {
notfound=false;
RANKType talentrank = talent.getRANK();
talentrank.setBonus(talentrank.getBonus()+itemtalent.getBonus());
calculateCapabilityRank(talentrank,characterAttributes.get(talent.getAttribute().value()));
}
}
if( notfound && (firstDisciplineOptionalTalents!=null) ) {
if( limitation.isEmpty() ) limitation ="(#)";
else limitation += " (#)";
TALENTType bonusTalent = new TALENTType();
bonusTalent.setName(itemtalent.getName());
bonusTalent.setLimitation(limitation);
bonusTalent.setCircle(0);
capabilities.enforceCapabilityParams(bonusTalent);
RANKType bonusrank = new RANKType();
bonusrank.setRank(0);
bonusrank.setBonus(itemtalent.getBonus());
calculateCapabilityRank(bonusrank,characterAttributes.get(bonusTalent.getAttribute().value()));
bonusTalent.setRANK(bonusrank);
TALENTTEACHERType teacher = new TALENTTEACHERType();
teacher.setByversatility(YesnoType.NO);
teacher.setTalentcircle(rank);
teacher.setTeachercircle(rank);
teacher.setName(item.getName());
bonusTalent.setTEACHER(teacher);
firstDisciplineOptionalTalents.add(bonusTalent);
}
}
for(DISZIPINABILITYType iteminitiative : threadrank.getINITIATIVE() ) {
character.readjustInitiativeModifikator(iteminitiative.getCount());
}
initiative.setStep(initiative.getBase()+initiative.getModification());
initiative.setDice(PROPERTIES.step2Dice(initiative.getStep()));
// TODO: other effects of MagicItems
// TODO:List<TALENTType> optTalents = allTalents.get(disciplinenumber).getOPTIONALTALENT();
}
// Veränderungen am death/unconsciousness adjustment sollen beachtet werden
death.setValue(death.getBase()+death.getAdjustment());
unconsciousness.setValue(unconsciousness.getBase()+unconsciousness.getAdjustment());
if( calculatedLP.getSpells() < 0 ) calculatedLP.setSpells(0);
calculatedLP.setTotal(calculatedLP.getAttributes()+calculatedLP.getDisciplinetalents()+
calculatedLP.getKarma()+calculatedLP.getMagicitems()+calculatedLP.getOptionaltalents()+
calculatedLP.getSkills()+calculatedLP.getSpells()+calculatedLP.getKnacks());
if( OptionalRule_AutoInsertLegendPointSpent ) character.addLegendPointsSpent(oldcalculatedLP);
character.calculateLegendPointsAndStatus();
character.calculateDevotionPoints();
return charakter;
}
|
diff --git a/ini/trakem2/utils/Search.java b/ini/trakem2/utils/Search.java
index a5607081..321426b8 100644
--- a/ini/trakem2/utils/Search.java
+++ b/ini/trakem2/utils/Search.java
@@ -1,417 +1,418 @@
/**
TrakEM2 plugin for ImageJ(C).
Copyright (C) 2005-2009 Albert Cardona and Rodney Douglas.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation (http://www.gnu.org/licenses/gpl.txt )
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
You may contact Albert Cardona at acardona at ini.phys.ethz.ch
Institute of Neuroinformatics, University of Zurich / ETH, Switzerland.
**/
package ini.trakem2.utils;
import ini.trakem2.Project;
import ini.trakem2.persistence.DBObject;
import ini.trakem2.display.*;
import ini.trakem2.ControlWindow;
import javax.swing.*;
import javax.swing.table.*;
import java.awt.event.*;
import java.awt.Dimension;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Vector;
import java.util.regex.*;
import java.util.Map;
public class Search {
private JFrame search_frame = null;
private JTabbedPane search_tabs = null;
private JTextField search_field = null;
private JComboBox pulldown = null;
private KeyListener kl = null;
static private Search instance = null;
private Class[] types = null;
/** Creates the GUI for searching text in any TrakEM2 element. */
public Search() {
if (null != instance) {
instance.makeGUI();
} else {
instance = this;
types = new Class[]{DBObject.class, Displayable.class, DLabel.class, Patch.class, AreaList.class, Profile.class, Pipe.class, Ball.class, Layer.class, Dissector.class};
makeGUI();
}
}
private void tryCloseTab(KeyEvent ke) {
switch (ke.getKeyCode()) {
case KeyEvent.VK_W:
if (!ke.isControlDown()) return;
int ntabs = search_tabs.getTabCount();
if (0 == ntabs) {
instance.destroy();
return;
}
search_tabs.remove(search_tabs.getSelectedIndex());
return;
default:
return;
}
}
private void makeGUI() {
// create GUI if not there
if (null == search_frame) {
search_frame = ControlWindow.createJFrame("Search");
search_frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
instance.destroy();
}
});
search_tabs = new JTabbedPane(JTabbedPane.TOP);
kl = new KeyAdapter() {
public void keyPressed(KeyEvent ke) {
tryCloseTab(ke);
}
};
search_tabs.addKeyListener(kl);
search_field = new JTextField(14);
search_field.addKeyListener(new VKEnterListener());
JButton b = new JButton("Search");
b.addActionListener(new ButtonListener());
pulldown = new JComboBox(new String[]{"All", "All displayables", "Labels", "Images", "Area Lists", "Profiles", "Pipes", "Balls", "Layers", "Dissectors"});
JPanel top = new JPanel();
top.add(search_field);
top.add(b);
top.add(pulldown);
top.setMinimumSize(new Dimension(400, 30));
top.setMaximumSize(new Dimension(10000, 30));
top.setPreferredSize(new Dimension(400, 30));
JPanel all = new JPanel();
all.setPreferredSize(new Dimension(400, 400));
BoxLayout bl = new BoxLayout(all, BoxLayout.Y_AXIS);
all.setLayout(bl);
all.add(top);
all.add(search_tabs);
search_frame.getContentPane().add(all);
search_frame.pack();
search_frame.setVisible(true);
} else {
search_frame.toFront();
}
}
synchronized private void destroy() {
if (null != instance) {
if (null != search_frame) search_frame.dispose();
search_frame = null;
search_tabs = null;
search_field = null;
pulldown = null;
types = null;
kl = null;
// deregister
instance = null;
}
}
private class DisplayableTableModel extends AbstractTableModel {
private Vector v_obs;
private Vector v_txt;
DisplayableTableModel(Vector v_obs, Vector v_txt) {
super();
this.v_obs = v_obs;
this.v_txt = v_txt;
}
public String getColumnName(int col) {
if (0 == col) return "Type";
else if (1 == col) return "Info";
else if (2 == col) return "Matched";
else return "";
}
public int getRowCount() { return v_obs.size(); }
public int getColumnCount() { return 3; }
public Object getValueAt(int row, int col) {
if (0 == col) return Project.getName(v_obs.get(row).getClass());
else if (1 == col) return ((DBObject)v_obs.get(row)).getShortTitle();
else if (2 == col) return v_txt.get(row).toString();
else return "";
}
public DBObject getDBObjectAt(int row) {
return (DBObject)v_obs.get(row);
}
public Displayable getDisplayableAt(int row) {
return (Displayable)v_obs.get(row);
}
public boolean isCellEditable(int row, int col) {
return false;
}
public void setValueAt(Object value, int row, int col) {
// nothing
//fireTableCellUpdated(row, col);
}
public boolean remove(Displayable displ) {
int i = v_obs.indexOf(displ);
if (-1 != i) {
v_obs.remove(i);
v_txt.remove(i);
return true;
}
return false;
}
public boolean contains(Object ob) {
return v_obs.contains(ob);
}
}
private void executeSearch() {
String pattern = search_field.getText();
if (null == pattern || 0 == pattern.length()) {
return;
}
// fix pattern
final String typed_pattern = pattern;
final StringBuffer sb = new StringBuffer(); // I hate java
if (!pattern.startsWith("^")) sb.append("^.*");
for (int i=0; i<pattern.length(); i++) {
sb.append(pattern.charAt(i));
}
if (!pattern.endsWith("$")) sb.append(".*$");
pattern = sb.toString();
final Pattern pat = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
//Utils.log2("pattern after: " + pattern);
final ArrayList al = new ArrayList();
//Utils.log("types[pulldown] = " + types[pulldown.getSelectedIndex()]);
find(ControlWindow.getActive().getRootLayerSet(), al, types[pulldown.getSelectedIndex()]);
//Utils.log2("found labels: " + al.size());
if (0 == al.size()) return;
final Vector v_obs = new Vector();
final Vector v_txt = new Vector();
for (Iterator it = al.iterator(); it.hasNext(); ) {
final DBObject dbo = (DBObject)it.next();
boolean matched = false;
// Search in its title
String txt = dbo instanceof Displayable ?
dbo.getProject().getMeaningfulTitle((Displayable)dbo)
: dbo.getTitle();
+ if (null == txt || 0 == txt.trim().length()) continue;
matched = pat.matcher(txt).matches();
long id = dbo.getId();
if (!matched) {
// Search also in its toString()
txt = dbo.toString();
matched = pat.matcher(txt).matches();
}
if (!matched) {
// Search also in its id
txt = Long.toString(dbo.getId());
matched = pat.matcher(txt).matches();
if (matched) txt = "id: #" + txt;
}
if (!matched && dbo instanceof Displayable) {
// Search also in its properties
Map<String,String> props = ((Displayable)dbo).getProperties();
if (null != props) {
for (final Map.Entry<String,String> e : props.entrySet()) {
if (pat.matcher(e.getKey()).matches()
|| pat.matcher(e.getValue()).matches()) {
matched = true;
txt = e.getKey() + " => " + e.getValue() + " [property]";
}
}
}
if (!matched) {
Map<Displayable,Map<String,String>> linked_props = ((Displayable)dbo).getLinkedProperties();
if (null != linked_props) {
for (final Map.Entry<Displayable,Map<String,String>> e : linked_props.entrySet()) {
Displayable d = e.getKey();
for (final Map.Entry<String,String> ee : e.getValue().entrySet()) {
if (pat.matcher(ee.getKey()).matches()
|| pat.matcher(ee.getValue()).matches()) {
matched = true;
txt = ee.getKey() + " => " + e.getValue() + " [linked property]";
}
}
}
}
}
}
if (!matched) continue;
//txt = txt.length() > 30 ? txt.substring(0, 27) + "..." : txt;
v_obs.add(dbo);
v_txt.add(txt);
}
if (0 == v_obs.size()) {
Utils.showMessage("Nothing found.");
return;
}
final JScrollPane jsp = makeTable(new DisplayableTableModel(v_obs, v_txt));
search_tabs.addTab(typed_pattern, jsp);
search_tabs.setSelectedComponent(jsp);
search_frame.pack();
}
private JScrollPane makeTable(TableModel model) {
JTable table = new JTable(model);
//java 1.6.0 only!! //table.setAutoCreateRowSorter(true);
table.addMouseListener(new DisplayableListListener());
table.addKeyListener(kl);
JScrollPane jsp = new JScrollPane(table);
jsp.setPreferredSize(new Dimension(500, 500));
return jsp;
}
/** Listen to the search button. */
private class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent ae) {
executeSearch();
}
}
/** Listen to the search field. */
private class VKEnterListener extends KeyAdapter {
public void keyPressed(KeyEvent ke) {
if (ke.getKeyCode() == KeyEvent.VK_ENTER) {
executeSearch();
return;
}
tryCloseTab(ke);
}
}
/** Listen to double clicks in the table rows. */
private class DisplayableListListener extends MouseAdapter {
public void mousePressed(MouseEvent me) {
final JTable table = (JTable)me.getSource();
final DBObject ob = ((DisplayableTableModel)table.getModel()).getDBObjectAt(table.rowAtPoint(me.getPoint()));
if (2 == me.getClickCount()) {
// is a table//Utils.log2("LLL source is " + me.getSource());
// JTable is AN ABSOLUTE PAIN to work with
// ???? THERE IS NO OBVIOUS WAY to retrieve the data. How lame.
// Ah, a "model" ... since when a model holds the DATA (!!), same with JTree, how lame.
if (ob instanceof Displayable) {
Displayable displ = (Displayable)ob;
Display.showCentered(displ.getLayer(), displ, true, me.isShiftDown());
} else if (ob instanceof Layer) {
Display.showFront((Layer)ob);
} else {
Utils.log2("Search: Unhandable table selection: " + ob);
}
} else if (Utils.isPopupTrigger(me)) {
JPopupMenu popup = new JPopupMenu();
final String show2D = "Show";
final String select = "Select in display";
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent ae) {
final String command = ae.getActionCommand();
if (command.equals(show2D)) {
if (ob instanceof Displayable) {
Displayable displ = (Displayable)ob;
Display.showCentered(displ.getLayer(), displ, true, 0 != (ae.getModifiers() & ActionEvent.SHIFT_MASK));
} else if (ob instanceof Layer) {
Display.showFront((Layer)ob);
}
} else if (command.equals(select)) {
if (ob instanceof Layer) {
Display.showFront((Layer)ob);
} else if (ob instanceof Displayable) {
Displayable displ = (Displayable)ob;
if (!displ.isVisible()) displ.setVisible(true);
Display display = Display.getFront(displ.getProject());
if (null == display) return;
boolean shift_down = 0 != (ae.getModifiers() & ActionEvent.SHIFT_MASK);
display.select(displ, shift_down);
}
}
}
};
JMenuItem item = new JMenuItem(show2D); popup.add(item); item.addActionListener(listener);
item = new JMenuItem(select); popup.add(item); item.addActionListener(listener);
popup.show(table, me.getX(), me.getY());
}
}
}
/** Recursive search into nested LayerSet instances, accumulating instances of type into the list al. */
private void find(final LayerSet set, final ArrayList al, final Class type) {
if (type == DBObject.class) {
al.add(set);
}
for (ZDisplayable zd : set.getZDisplayables()) {
if (DBObject.class == type || Displayable.class == type) {
al.add(zd);
} else if (zd.getClass() == type) {
al.add(zd);
}
}
for (Layer layer : set.getLayers()) {
if (DBObject.class == type || Layer.class == type) {
al.add(layer);
}
for (Displayable ob : layer.getDisplayables()) {
if (DBObject.class == type || Displayable.class == type) {
if (ob instanceof LayerSet) find((LayerSet)ob, al, type);
else al.add(ob);
} else if (ob.getClass() == type) {
al.add(ob);
}
}
}
}
/** Remove from the tables if there. */
static public void remove(final Displayable displ) {
if (null == displ || null == instance) return;
final int n_tabs = instance.search_tabs.getTabCount();
boolean repaint = false;
final int selected = instance.search_tabs.getSelectedIndex();
for (int t=0; t<n_tabs; t++) {
java.awt.Component c = instance.search_tabs.getComponentAt(t);
JTable table = (JTable)((JScrollPane)c).getViewport().getComponent(0);
DisplayableTableModel data = (DisplayableTableModel)table.getModel();
if (data.remove(displ)) {
// remake table (can't delete just a row, only columns??)
String name = instance.search_tabs.getTitleAt(t);
instance.search_tabs.removeTabAt(t);
// need to think about it TODO // if (0 == data.getRowCount()) continue;
instance.search_tabs.insertTab(name, null, instance.makeTable(data), "", t);
if (t == selected) repaint = true;
try { Thread.sleep(100); } catch (Exception e) {} // I love swing
}
}
if (repaint) {
Utils.updateComponent(instance.search_frame);
instance.search_tabs.setSelectedIndex(selected);
}
}
/** Repaint (refresh the text in the cells) only if any of the selected tabs in any of the search frames contains the given object in its rows. */
static public void repaint(final Object ob) {
if (null == instance) return;
final int selected = instance.search_tabs.getSelectedIndex();
if (-1 == selected) return;
java.awt.Component c = instance.search_tabs.getComponentAt(selected);
JTable table = (JTable)((JScrollPane)c).getViewport().getComponent(0);
DisplayableTableModel data = (DisplayableTableModel)table.getModel();
if (data.contains(ob)) {
Utils.updateComponent(instance.search_frame);
}
}
}
| true | true | private void executeSearch() {
String pattern = search_field.getText();
if (null == pattern || 0 == pattern.length()) {
return;
}
// fix pattern
final String typed_pattern = pattern;
final StringBuffer sb = new StringBuffer(); // I hate java
if (!pattern.startsWith("^")) sb.append("^.*");
for (int i=0; i<pattern.length(); i++) {
sb.append(pattern.charAt(i));
}
if (!pattern.endsWith("$")) sb.append(".*$");
pattern = sb.toString();
final Pattern pat = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
//Utils.log2("pattern after: " + pattern);
final ArrayList al = new ArrayList();
//Utils.log("types[pulldown] = " + types[pulldown.getSelectedIndex()]);
find(ControlWindow.getActive().getRootLayerSet(), al, types[pulldown.getSelectedIndex()]);
//Utils.log2("found labels: " + al.size());
if (0 == al.size()) return;
final Vector v_obs = new Vector();
final Vector v_txt = new Vector();
for (Iterator it = al.iterator(); it.hasNext(); ) {
final DBObject dbo = (DBObject)it.next();
boolean matched = false;
// Search in its title
String txt = dbo instanceof Displayable ?
dbo.getProject().getMeaningfulTitle((Displayable)dbo)
: dbo.getTitle();
matched = pat.matcher(txt).matches();
long id = dbo.getId();
if (!matched) {
// Search also in its toString()
txt = dbo.toString();
matched = pat.matcher(txt).matches();
}
if (!matched) {
// Search also in its id
txt = Long.toString(dbo.getId());
matched = pat.matcher(txt).matches();
if (matched) txt = "id: #" + txt;
}
if (!matched && dbo instanceof Displayable) {
// Search also in its properties
Map<String,String> props = ((Displayable)dbo).getProperties();
if (null != props) {
for (final Map.Entry<String,String> e : props.entrySet()) {
if (pat.matcher(e.getKey()).matches()
|| pat.matcher(e.getValue()).matches()) {
matched = true;
txt = e.getKey() + " => " + e.getValue() + " [property]";
}
}
}
if (!matched) {
Map<Displayable,Map<String,String>> linked_props = ((Displayable)dbo).getLinkedProperties();
if (null != linked_props) {
for (final Map.Entry<Displayable,Map<String,String>> e : linked_props.entrySet()) {
Displayable d = e.getKey();
for (final Map.Entry<String,String> ee : e.getValue().entrySet()) {
if (pat.matcher(ee.getKey()).matches()
|| pat.matcher(ee.getValue()).matches()) {
matched = true;
txt = ee.getKey() + " => " + e.getValue() + " [linked property]";
}
}
}
}
}
}
if (!matched) continue;
//txt = txt.length() > 30 ? txt.substring(0, 27) + "..." : txt;
v_obs.add(dbo);
v_txt.add(txt);
}
if (0 == v_obs.size()) {
Utils.showMessage("Nothing found.");
return;
}
final JScrollPane jsp = makeTable(new DisplayableTableModel(v_obs, v_txt));
search_tabs.addTab(typed_pattern, jsp);
search_tabs.setSelectedComponent(jsp);
search_frame.pack();
}
| private void executeSearch() {
String pattern = search_field.getText();
if (null == pattern || 0 == pattern.length()) {
return;
}
// fix pattern
final String typed_pattern = pattern;
final StringBuffer sb = new StringBuffer(); // I hate java
if (!pattern.startsWith("^")) sb.append("^.*");
for (int i=0; i<pattern.length(); i++) {
sb.append(pattern.charAt(i));
}
if (!pattern.endsWith("$")) sb.append(".*$");
pattern = sb.toString();
final Pattern pat = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
//Utils.log2("pattern after: " + pattern);
final ArrayList al = new ArrayList();
//Utils.log("types[pulldown] = " + types[pulldown.getSelectedIndex()]);
find(ControlWindow.getActive().getRootLayerSet(), al, types[pulldown.getSelectedIndex()]);
//Utils.log2("found labels: " + al.size());
if (0 == al.size()) return;
final Vector v_obs = new Vector();
final Vector v_txt = new Vector();
for (Iterator it = al.iterator(); it.hasNext(); ) {
final DBObject dbo = (DBObject)it.next();
boolean matched = false;
// Search in its title
String txt = dbo instanceof Displayable ?
dbo.getProject().getMeaningfulTitle((Displayable)dbo)
: dbo.getTitle();
if (null == txt || 0 == txt.trim().length()) continue;
matched = pat.matcher(txt).matches();
long id = dbo.getId();
if (!matched) {
// Search also in its toString()
txt = dbo.toString();
matched = pat.matcher(txt).matches();
}
if (!matched) {
// Search also in its id
txt = Long.toString(dbo.getId());
matched = pat.matcher(txt).matches();
if (matched) txt = "id: #" + txt;
}
if (!matched && dbo instanceof Displayable) {
// Search also in its properties
Map<String,String> props = ((Displayable)dbo).getProperties();
if (null != props) {
for (final Map.Entry<String,String> e : props.entrySet()) {
if (pat.matcher(e.getKey()).matches()
|| pat.matcher(e.getValue()).matches()) {
matched = true;
txt = e.getKey() + " => " + e.getValue() + " [property]";
}
}
}
if (!matched) {
Map<Displayable,Map<String,String>> linked_props = ((Displayable)dbo).getLinkedProperties();
if (null != linked_props) {
for (final Map.Entry<Displayable,Map<String,String>> e : linked_props.entrySet()) {
Displayable d = e.getKey();
for (final Map.Entry<String,String> ee : e.getValue().entrySet()) {
if (pat.matcher(ee.getKey()).matches()
|| pat.matcher(ee.getValue()).matches()) {
matched = true;
txt = ee.getKey() + " => " + e.getValue() + " [linked property]";
}
}
}
}
}
}
if (!matched) continue;
//txt = txt.length() > 30 ? txt.substring(0, 27) + "..." : txt;
v_obs.add(dbo);
v_txt.add(txt);
}
if (0 == v_obs.size()) {
Utils.showMessage("Nothing found.");
return;
}
final JScrollPane jsp = makeTable(new DisplayableTableModel(v_obs, v_txt));
search_tabs.addTab(typed_pattern, jsp);
search_tabs.setSelectedComponent(jsp);
search_frame.pack();
}
|
diff --git a/jlinda-core/src/test/java/org/jlinda/core/coregistration/cross/CrossGeometryTest.java b/jlinda-core/src/test/java/org/jlinda/core/coregistration/cross/CrossGeometryTest.java
index 88ac46f..ce2be8e 100644
--- a/jlinda-core/src/test/java/org/jlinda/core/coregistration/cross/CrossGeometryTest.java
+++ b/jlinda-core/src/test/java/org/jlinda/core/coregistration/cross/CrossGeometryTest.java
@@ -1,356 +1,356 @@
package org.jlinda.core.coregistration.cross;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import org.apache.commons.lang.ArrayUtils;
import org.jblas.DoubleMatrix;
import org.jlinda.core.Window;
import org.jlinda.core.utils.MathUtils;
import org.jlinda.core.utils.PolyUtils;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.LoggerFactory;
import javax.media.jai.WarpGeneralPolynomial;
import javax.media.jai.WarpPolynomial;
import java.awt.geom.Point2D;
import static org.jlinda.core.utils.PolyUtils.normalize2;
import static org.jlinda.core.utils.PolyUtils.polyFit2D;
import static org.jlinda.core.utils.PolyUtils.polyval;
/**
* User: [email protected]
* Date: 6/13/13
* Time: 12:25 PM
* Description: Unit test and prototypes for Cross Interferometry
*/
public class CrossGeometryTest {
// logger
private static final Logger logger = (Logger) LoggerFactory.getLogger(CrossGeometryTest.class);
// data extent
private static long lineLo = 1;
private static long pixelLo = 1;
private static long lineHi = 27000;
private static long pixelHi = 5100;
// ORIGINAL GEOMETRY : ENVISAT paramaters
private static double prfASAR = 1652.4156494140625; // [Hz]
private static double rsrASAR = 19.20768 * 1000; // [Hz]
// TARGET GEOMETRY : ERS2 paramaters
private static double prfERS = 1679.902; // 1679.95828476786; // [Hz]
private static double rsrERS = 18.962468 * 1000; //18.96245929824155 * 1000; // [Hz]
// Estimation Parameters
private static final int NUM_OF_WINDOWS = 5000;
private static final int POLY_DEGREE = 2;
@BeforeClass
public static void setUp() throws Exception {
// define logger level
logger.setLevel(Level.TRACE);
}
@Test
public void testComputeCoefficients() {
CrossGeometry crossGeometry = new CrossGeometry();
crossGeometry.setPrfOriginal(prfERS);
crossGeometry.setRsrOriginal(rsrERS);
crossGeometry.setPrfTarget(prfASAR);
crossGeometry.setRsrTarget(rsrASAR);
crossGeometry.setDataWindow(new Window(lineLo, lineHi, pixelLo, pixelHi));
// optional!
// crossGeometry.setNumberOfWindows(NUM_OF_WINDOWS);
// crossGeometry.setPolyDegree(POLY_DEGREE);
crossGeometry.computeCoefficients();
double[] coeffsAz = crossGeometry.getCoeffsAz();
double[] coeffsRg = crossGeometry.getCoeffsRg();
// show polynomials
logger.debug("coeffsAZ : estimated with PolyUtils.polyFit2D : {}", ArrayUtils.toString(coeffsAz));
logger.debug("coeffsRg : estimated with PolyUtils.polyFit2D : {}", ArrayUtils.toString(coeffsRg));
}
/* Prototype implementation:
* - based on matlab code
* - there is a small ~10^-8 numerical difference between prototype and class implementation
* - this difference is due to different (and in prototype inconsistent) use of data windows for normalization and estimation
* */
public void computeCrossPolynomial() {
// estimation parameters
int numOfObs = NUM_OF_WINDOWS;
// ratios of frequencies
double ratioRSR = rsrERS / rsrASAR;
double ratioPRF = prfERS / prfASAR;
// -----------------------------------------------
// define solution spaces - ASAR geometry is 'slave' : SLAVE - MASTER
// -----------------------------------------------
// Window ersWindow = new Window(1, lineERS, 1, pixERS);
Window asarWindow = new Window(0, lineHi - 1, 0, pixelHi - 1); // start from 0 pixelHi
// -----------------------------------------------
// distribute points
// -----------------------------------------------
double[][] sourceGrid = MathUtils.distributePointsDoubles(NUM_OF_WINDOWS, asarWindow);
// -----------------------------------------------
// create synthetic offsets
// -----------------------------------------------
double[][] targetGrid = new double[NUM_OF_WINDOWS][2];
for (int i = 0; i < NUM_OF_WINDOWS; i++) {
targetGrid[i][0] = sourceGrid[i][0] * ratioPRF;
targetGrid[i][1] = sourceGrid[i][1] * ratioRSR;
}
double[][] offsetGrid = new double[NUM_OF_WINDOWS][2];
for (int i = 0; i < NUM_OF_WINDOWS; i++) {
offsetGrid[i][0] = sourceGrid[i][0] - targetGrid[i][0];
offsetGrid[i][1] = sourceGrid[i][1] - targetGrid[i][1];
}
// -----------------------------------------------
// estimation of (dummy) coregistration polynomial
// -----------------------------------------------
DoubleMatrix linesNorm = new DoubleMatrix(numOfObs, 1);
DoubleMatrix pixelsNorm = new DoubleMatrix(numOfObs, 1);
DoubleMatrix offset_lines = new DoubleMatrix(numOfObs, 1);
DoubleMatrix offset_pixels = new DoubleMatrix(numOfObs, 1);
// normalize, and store into jblas matrices
for (int i = 0; i < numOfObs; i++) {
linesNorm.put(i, PolyUtils.normalize2(targetGrid[i][0], 1, lineHi));
pixelsNorm.put(i, PolyUtils.normalize2(targetGrid[i][1], 1, pixelHi));
offset_lines.put(i, offsetGrid[i][0]);
offset_pixels.put(i, offsetGrid[i][1]);
}
double[] coeffsAz = PolyUtils.polyFit2D(pixelsNorm, linesNorm, offset_lines, POLY_DEGREE);
double[] coeffsRg = PolyUtils.polyFit2D(pixelsNorm, linesNorm, offset_pixels, POLY_DEGREE);
// show polynomials
logger.debug("coeffsAZ (polyfit) = {}", ArrayUtils.toString(coeffsAz));
logger.debug("coeffsRg (polyfit) = {}", ArrayUtils.toString(coeffsRg));
/*
// --------------------------------------------------
// Internal implementation of coefficients estimation
// --------------------------------------------------
DoubleMatrix A = SystemOfEquations.constructDesignMatrix(linesNorm, pixelsNorm, POLY_DEGREE);
logger.debug("Solving linear system of equations with Cholesky");
DoubleMatrix N = A.transpose().mmul(A);
DoubleMatrix rhsL = A.transpose().mmul(offset_lines);
DoubleMatrix rhsP = A.transpose().mmul(offset_pixels);
rhsL = Solve.solveSymmetric(N, rhsL);
rhsP = Solve.solveSymmetric(N, rhsP);
logger.debug("coeffsAZ = {}", ArrayUtils.toString(rhsL.toArray()));
logger.debug("coeffsRg = {}", ArrayUtils.toString(rhsP.toArray()));
*/
}
/* Prototype and experimental implementation for:
* - shoot out between different polynomial estimation and evaluation methods
* 1st method - jLinda.polyFit2D
* 2nd method - jLinda.polyFit2D with normalized variables
* 3rd method - JAI.WarpPolynomial
* 4th method - polynomial estimation using jLinda, evaluation using JAI
* - it is based on matlab and javaschool closed-source code
* - this implementation exposes problems and inconsistencies with polyUtils
* - note that JAI seems to introduces bias in evaluation of polynomial
* */
// ToDo - to be removed after operator committed
// @Test
public void computeAndEvaluateCrossPoly() {
long yMin = lineLo; // = 0;
long xMin = pixelLo; // = 0;
- long yMax = lineLo;
+ long yMax = lineHi;
long xMax = pixelHi;
// Target Geometry Parameters (ENVISAT paramaters)
double targetFactorY = prfASAR; // PRF of ASAR [Hz]
double targetFactorX = rsrASAR; // RSR of ASAR [Hz]
// Source Geometry Parameters (ERS2 paramaters)
double sourceFactorY = prfERS; // PRF of ERS [Hz]
double sourceFactorX = rsrERS; // RSR of ERS [Hz]
// Estimation Parameters
int numberOfObservations = NUM_OF_WINDOWS;
int polyDegree = POLY_DEGREE;
Window win = new Window(yMin, yMax, xMin, xMax);
// ratios of scaling factors
double ratioX = sourceFactorX / targetFactorX;
double ratioY = sourceFactorY / targetFactorY;
// distribute points for estimation
int[][] srcArray = MathUtils.distributePoints(numberOfObservations, win);
// create synthetic offset between source and target geometries
double[][] tgtArray = new double[numberOfObservations][2];
for (int i = 0; i < numberOfObservations; i++) {
tgtArray[i][0] = srcArray[i][0] * ratioY;
tgtArray[i][1] = srcArray[i][1] * ratioX;
}
// semantics is : source - target
double[][] dltArray = new double[numberOfObservations][2];
for (int i = 0; i < numberOfObservations; i++) {
dltArray[i][0] = srcArray[i][0] - tgtArray[i][0];
dltArray[i][1] = srcArray[i][1] - tgtArray[i][1];
}
/*
* estimation of (dummy) resampling polynomial
*/
// first declare jBlas matrices
DoubleMatrix srcY = new DoubleMatrix(numberOfObservations, 1);
DoubleMatrix srcX = new DoubleMatrix(numberOfObservations, 1);
DoubleMatrix srcYNorm = new DoubleMatrix(numberOfObservations, 1);
DoubleMatrix srcXNorm = new DoubleMatrix(numberOfObservations, 1);
DoubleMatrix txtY = new DoubleMatrix(numberOfObservations, 1);
DoubleMatrix tgtX = new DoubleMatrix(numberOfObservations, 1);
DoubleMatrix dltY = new DoubleMatrix(numberOfObservations, 1);
DoubleMatrix dltX = new DoubleMatrix(numberOfObservations, 1);
// repackage observation and design matrices into jblas, also normalize
for (int i = 0; i < numberOfObservations; i++) {
srcY.put(i, srcArray[i][0]);
srcX.put(i, srcArray[i][1]);
txtY.put(i, tgtArray[i][0]);
tgtX.put(i, tgtArray[i][1]);
srcYNorm.put(i, normalize2(srcArray[i][0], win.linelo, win.linehi));
srcXNorm.put(i, normalize2(srcArray[i][1], win.pixlo, win.pixhi));
dltY.put(i, dltArray[i][0]);
dltX.put(i, dltArray[i][1]);
}
// compute coefficients using polyFit2D
// ...NOTE: order in which input axis are given => (x,y,z) <=
double[] coeffsX = polyFit2D(srcY, srcX, dltX, polyDegree);
double[] coeffsY = polyFit2D(srcY, srcX, dltY, polyDegree);
double[] coeffsXNorm = polyFit2D(srcYNorm, srcXNorm, dltX, polyDegree);
double[] coeffsYNorm = polyFit2D(srcYNorm, srcXNorm, dltY, polyDegree);
double[] coeffsXTemp = polyFit2D(srcY, srcX, tgtX, polyDegree);
double[] coeffsYTemp = polyFit2D(srcY, srcX, txtY, polyDegree);
// show polynomials depending on logger level <- not in production
logger.debug("coeffsXNorm : estimated with PolyUtils.polyFit2D : {}", org.apache.commons.lang3.ArrayUtils.toString(coeffsXNorm));
logger.debug("coeffsYNorm : estimated with PolyUtils.polyFit2D : {}", org.apache.commons.lang3.ArrayUtils.toString(coeffsYNorm));
// show polynomials depending on logger level <- not in production
logger.debug("coeffsX : estimated with PolyUtils.polyFit2D : {}", org.apache.commons.lang3.ArrayUtils.toString(coeffsX));
logger.debug("coeffsY : estimated with PolyUtils.polyFit2D : {}", org.apache.commons.lang3.ArrayUtils.toString(coeffsY));
/* JAI Example */
float[] src1DArray = new float[2 * numberOfObservations];
float[] tgt1DArray = new float[2 * numberOfObservations];
// declare src1DArray and dest
for (int i = 0; i < numberOfObservations; ++i) {
int j = 2 * i;
src1DArray[j] = (float) (srcX.get(i));
src1DArray[j + 1] = (float) (srcY.get(i));
tgt1DArray[j] = (float) tgtX.get(i);
tgt1DArray[j + 1] = (float) txtY.get(i);
}
float preScaleX = 1.0F / xMax;
float postScaleX = (float) xMax;
float preScaleY = 1.0F / yMax;
float postScaleY = (float) yMax;
/* Note: Warp semantic (transforms coordinates from destination to srcArray) is the
* opposite of jLinda semantic (transforms coordinates from srcArray to
* destination). We have to interchange srcArray and destination arrays for the
* direct transform.
*/
WarpPolynomial warpTotal = WarpPolynomial.createWarp(tgt1DArray, 0, src1DArray, 0, 2 * numberOfObservations, preScaleX, preScaleY, postScaleX, postScaleY, polyDegree);
// show polynomials depending on logger level <- not in production
logger.debug("coeffsAZ : estimated with JAI.WarpPolynomial.createWarp : {}", org.apache.commons.lang3.ArrayUtils.toString(warpTotal.getYCoeffs()));
logger.debug("coeffsX : estimated with JAI.WarpPolynomial.createWarp : {}", org.apache.commons.lang3.ArrayUtils.toString(warpTotal.getXCoeffs()));
float[] xCoeffs = new float[coeffsXTemp.length];
float[] yCoeffs = new float[coeffsYTemp.length];
for (int i = 0; i < coeffsY.length; i++) {
yCoeffs[i] = (float) coeffsYTemp[i];
xCoeffs[i] = (float) coeffsXTemp[i];
}
WarpPolynomial warpInterp = new WarpGeneralPolynomial(xCoeffs, yCoeffs);
// Point2D srcPoint = new Point2D.Double(1354, 23214);
Point2D srcPoint = new Point2D.Double(2523, 2683);
Point2D tgtPointExp = new Point2D.Double(srcPoint.getX() * ratioX, srcPoint.getY() * ratioY);
Point2D srcPointNorm = new Point2D.Double(
normalize2(srcPoint.getX(), win.pixlo, win.pixhi),
normalize2(srcPoint.getY(), win.linelo, win.linehi));
Point2D tgtPoint_JAI_1 = warpTotal.mapDestPoint(srcPoint);
Point2D tgtPoint_JAI_2 = warpInterp.mapDestPoint(srcPoint);
double tgtX_polyfit = srcPoint.getX() - polyval(srcPoint.getX(), srcPoint.getY(), coeffsX);
double tgtY_polyfit = srcPoint.getY() - polyval(srcPoint.getX(), srcPoint.getY(), coeffsY);
double tgtX_polyfit_norm = srcPoint.getX() - polyval(srcPointNorm.getX(), srcPointNorm.getY(), coeffsXNorm);
double tgtY_polyfit_norm = srcPoint.getY() - polyval(srcPointNorm.getX(), srcPointNorm.getY(), coeffsYNorm);
logger.debug("============ ");
logger.debug("Input Test Point (x,y): {}, {}", srcPoint.getX(), srcPoint.getY());
logger.debug("============ ");
logger.debug("Target Expected: {}, {}", tgtPointExp.getX(), tgtPointExp.getY());
logger.debug("Offset Expected: {}, {}", srcPoint.getX() - tgtPointExp.getX(), srcPoint.getY() - tgtPointExp.getY());
logger.debug("============ ");
logger.debug("Target - JAI-Impl-1: {}, {}", tgtPoint_JAI_1.getX(), tgtPoint_JAI_1.getY());
logger.debug("Target - JAI-Impl-2: {}, {}", tgtPoint_JAI_2.getX(), tgtPoint_JAI_2.getY());
logger.debug(" ---- ");
logger.debug("Target - polyFit : {}, {}", tgtX_polyfit, tgtY_polyfit);
logger.debug("Target - polyFit-Norm: {}, {}", tgtX_polyfit_norm, tgtY_polyfit_norm);
logger.debug("============ ");
logger.debug("Error - JAI-Impl-1: {}, {}", tgtPoint_JAI_1.getX() - tgtPointExp.getX(), tgtPoint_JAI_1.getY() - tgtPointExp.getY());
logger.debug("Error - JAI-Impl-2: {}, {}", tgtPoint_JAI_2.getX() - tgtPointExp.getX(), tgtPoint_JAI_2.getY() - tgtPointExp.getY());
logger.debug(" ---- ");
logger.debug("Error - polyFit : {}, {}", tgtX_polyfit - tgtPointExp.getX(), tgtY_polyfit - tgtPointExp.getY());
logger.debug("Error - polyFit-Norm: {}, {}", tgtX_polyfit_norm - tgtPointExp.getX(), tgtY_polyfit_norm - tgtPointExp.getY());
}
}
| true | true | public void computeAndEvaluateCrossPoly() {
long yMin = lineLo; // = 0;
long xMin = pixelLo; // = 0;
long yMax = lineLo;
long xMax = pixelHi;
// Target Geometry Parameters (ENVISAT paramaters)
double targetFactorY = prfASAR; // PRF of ASAR [Hz]
double targetFactorX = rsrASAR; // RSR of ASAR [Hz]
// Source Geometry Parameters (ERS2 paramaters)
double sourceFactorY = prfERS; // PRF of ERS [Hz]
double sourceFactorX = rsrERS; // RSR of ERS [Hz]
// Estimation Parameters
int numberOfObservations = NUM_OF_WINDOWS;
int polyDegree = POLY_DEGREE;
Window win = new Window(yMin, yMax, xMin, xMax);
// ratios of scaling factors
double ratioX = sourceFactorX / targetFactorX;
double ratioY = sourceFactorY / targetFactorY;
// distribute points for estimation
int[][] srcArray = MathUtils.distributePoints(numberOfObservations, win);
// create synthetic offset between source and target geometries
double[][] tgtArray = new double[numberOfObservations][2];
for (int i = 0; i < numberOfObservations; i++) {
tgtArray[i][0] = srcArray[i][0] * ratioY;
tgtArray[i][1] = srcArray[i][1] * ratioX;
}
// semantics is : source - target
double[][] dltArray = new double[numberOfObservations][2];
for (int i = 0; i < numberOfObservations; i++) {
dltArray[i][0] = srcArray[i][0] - tgtArray[i][0];
dltArray[i][1] = srcArray[i][1] - tgtArray[i][1];
}
/*
* estimation of (dummy) resampling polynomial
*/
// first declare jBlas matrices
DoubleMatrix srcY = new DoubleMatrix(numberOfObservations, 1);
DoubleMatrix srcX = new DoubleMatrix(numberOfObservations, 1);
DoubleMatrix srcYNorm = new DoubleMatrix(numberOfObservations, 1);
DoubleMatrix srcXNorm = new DoubleMatrix(numberOfObservations, 1);
DoubleMatrix txtY = new DoubleMatrix(numberOfObservations, 1);
DoubleMatrix tgtX = new DoubleMatrix(numberOfObservations, 1);
DoubleMatrix dltY = new DoubleMatrix(numberOfObservations, 1);
DoubleMatrix dltX = new DoubleMatrix(numberOfObservations, 1);
// repackage observation and design matrices into jblas, also normalize
for (int i = 0; i < numberOfObservations; i++) {
srcY.put(i, srcArray[i][0]);
srcX.put(i, srcArray[i][1]);
txtY.put(i, tgtArray[i][0]);
tgtX.put(i, tgtArray[i][1]);
srcYNorm.put(i, normalize2(srcArray[i][0], win.linelo, win.linehi));
srcXNorm.put(i, normalize2(srcArray[i][1], win.pixlo, win.pixhi));
dltY.put(i, dltArray[i][0]);
dltX.put(i, dltArray[i][1]);
}
// compute coefficients using polyFit2D
// ...NOTE: order in which input axis are given => (x,y,z) <=
double[] coeffsX = polyFit2D(srcY, srcX, dltX, polyDegree);
double[] coeffsY = polyFit2D(srcY, srcX, dltY, polyDegree);
double[] coeffsXNorm = polyFit2D(srcYNorm, srcXNorm, dltX, polyDegree);
double[] coeffsYNorm = polyFit2D(srcYNorm, srcXNorm, dltY, polyDegree);
double[] coeffsXTemp = polyFit2D(srcY, srcX, tgtX, polyDegree);
double[] coeffsYTemp = polyFit2D(srcY, srcX, txtY, polyDegree);
// show polynomials depending on logger level <- not in production
logger.debug("coeffsXNorm : estimated with PolyUtils.polyFit2D : {}", org.apache.commons.lang3.ArrayUtils.toString(coeffsXNorm));
logger.debug("coeffsYNorm : estimated with PolyUtils.polyFit2D : {}", org.apache.commons.lang3.ArrayUtils.toString(coeffsYNorm));
// show polynomials depending on logger level <- not in production
logger.debug("coeffsX : estimated with PolyUtils.polyFit2D : {}", org.apache.commons.lang3.ArrayUtils.toString(coeffsX));
logger.debug("coeffsY : estimated with PolyUtils.polyFit2D : {}", org.apache.commons.lang3.ArrayUtils.toString(coeffsY));
/* JAI Example */
float[] src1DArray = new float[2 * numberOfObservations];
float[] tgt1DArray = new float[2 * numberOfObservations];
// declare src1DArray and dest
for (int i = 0; i < numberOfObservations; ++i) {
int j = 2 * i;
src1DArray[j] = (float) (srcX.get(i));
src1DArray[j + 1] = (float) (srcY.get(i));
tgt1DArray[j] = (float) tgtX.get(i);
tgt1DArray[j + 1] = (float) txtY.get(i);
}
float preScaleX = 1.0F / xMax;
float postScaleX = (float) xMax;
float preScaleY = 1.0F / yMax;
float postScaleY = (float) yMax;
/* Note: Warp semantic (transforms coordinates from destination to srcArray) is the
* opposite of jLinda semantic (transforms coordinates from srcArray to
* destination). We have to interchange srcArray and destination arrays for the
* direct transform.
*/
WarpPolynomial warpTotal = WarpPolynomial.createWarp(tgt1DArray, 0, src1DArray, 0, 2 * numberOfObservations, preScaleX, preScaleY, postScaleX, postScaleY, polyDegree);
// show polynomials depending on logger level <- not in production
logger.debug("coeffsAZ : estimated with JAI.WarpPolynomial.createWarp : {}", org.apache.commons.lang3.ArrayUtils.toString(warpTotal.getYCoeffs()));
logger.debug("coeffsX : estimated with JAI.WarpPolynomial.createWarp : {}", org.apache.commons.lang3.ArrayUtils.toString(warpTotal.getXCoeffs()));
float[] xCoeffs = new float[coeffsXTemp.length];
float[] yCoeffs = new float[coeffsYTemp.length];
for (int i = 0; i < coeffsY.length; i++) {
yCoeffs[i] = (float) coeffsYTemp[i];
xCoeffs[i] = (float) coeffsXTemp[i];
}
WarpPolynomial warpInterp = new WarpGeneralPolynomial(xCoeffs, yCoeffs);
// Point2D srcPoint = new Point2D.Double(1354, 23214);
Point2D srcPoint = new Point2D.Double(2523, 2683);
Point2D tgtPointExp = new Point2D.Double(srcPoint.getX() * ratioX, srcPoint.getY() * ratioY);
Point2D srcPointNorm = new Point2D.Double(
normalize2(srcPoint.getX(), win.pixlo, win.pixhi),
normalize2(srcPoint.getY(), win.linelo, win.linehi));
Point2D tgtPoint_JAI_1 = warpTotal.mapDestPoint(srcPoint);
Point2D tgtPoint_JAI_2 = warpInterp.mapDestPoint(srcPoint);
double tgtX_polyfit = srcPoint.getX() - polyval(srcPoint.getX(), srcPoint.getY(), coeffsX);
double tgtY_polyfit = srcPoint.getY() - polyval(srcPoint.getX(), srcPoint.getY(), coeffsY);
double tgtX_polyfit_norm = srcPoint.getX() - polyval(srcPointNorm.getX(), srcPointNorm.getY(), coeffsXNorm);
double tgtY_polyfit_norm = srcPoint.getY() - polyval(srcPointNorm.getX(), srcPointNorm.getY(), coeffsYNorm);
logger.debug("============ ");
logger.debug("Input Test Point (x,y): {}, {}", srcPoint.getX(), srcPoint.getY());
logger.debug("============ ");
logger.debug("Target Expected: {}, {}", tgtPointExp.getX(), tgtPointExp.getY());
logger.debug("Offset Expected: {}, {}", srcPoint.getX() - tgtPointExp.getX(), srcPoint.getY() - tgtPointExp.getY());
logger.debug("============ ");
logger.debug("Target - JAI-Impl-1: {}, {}", tgtPoint_JAI_1.getX(), tgtPoint_JAI_1.getY());
logger.debug("Target - JAI-Impl-2: {}, {}", tgtPoint_JAI_2.getX(), tgtPoint_JAI_2.getY());
logger.debug(" ---- ");
logger.debug("Target - polyFit : {}, {}", tgtX_polyfit, tgtY_polyfit);
logger.debug("Target - polyFit-Norm: {}, {}", tgtX_polyfit_norm, tgtY_polyfit_norm);
logger.debug("============ ");
logger.debug("Error - JAI-Impl-1: {}, {}", tgtPoint_JAI_1.getX() - tgtPointExp.getX(), tgtPoint_JAI_1.getY() - tgtPointExp.getY());
logger.debug("Error - JAI-Impl-2: {}, {}", tgtPoint_JAI_2.getX() - tgtPointExp.getX(), tgtPoint_JAI_2.getY() - tgtPointExp.getY());
logger.debug(" ---- ");
logger.debug("Error - polyFit : {}, {}", tgtX_polyfit - tgtPointExp.getX(), tgtY_polyfit - tgtPointExp.getY());
logger.debug("Error - polyFit-Norm: {}, {}", tgtX_polyfit_norm - tgtPointExp.getX(), tgtY_polyfit_norm - tgtPointExp.getY());
}
| public void computeAndEvaluateCrossPoly() {
long yMin = lineLo; // = 0;
long xMin = pixelLo; // = 0;
long yMax = lineHi;
long xMax = pixelHi;
// Target Geometry Parameters (ENVISAT paramaters)
double targetFactorY = prfASAR; // PRF of ASAR [Hz]
double targetFactorX = rsrASAR; // RSR of ASAR [Hz]
// Source Geometry Parameters (ERS2 paramaters)
double sourceFactorY = prfERS; // PRF of ERS [Hz]
double sourceFactorX = rsrERS; // RSR of ERS [Hz]
// Estimation Parameters
int numberOfObservations = NUM_OF_WINDOWS;
int polyDegree = POLY_DEGREE;
Window win = new Window(yMin, yMax, xMin, xMax);
// ratios of scaling factors
double ratioX = sourceFactorX / targetFactorX;
double ratioY = sourceFactorY / targetFactorY;
// distribute points for estimation
int[][] srcArray = MathUtils.distributePoints(numberOfObservations, win);
// create synthetic offset between source and target geometries
double[][] tgtArray = new double[numberOfObservations][2];
for (int i = 0; i < numberOfObservations; i++) {
tgtArray[i][0] = srcArray[i][0] * ratioY;
tgtArray[i][1] = srcArray[i][1] * ratioX;
}
// semantics is : source - target
double[][] dltArray = new double[numberOfObservations][2];
for (int i = 0; i < numberOfObservations; i++) {
dltArray[i][0] = srcArray[i][0] - tgtArray[i][0];
dltArray[i][1] = srcArray[i][1] - tgtArray[i][1];
}
/*
* estimation of (dummy) resampling polynomial
*/
// first declare jBlas matrices
DoubleMatrix srcY = new DoubleMatrix(numberOfObservations, 1);
DoubleMatrix srcX = new DoubleMatrix(numberOfObservations, 1);
DoubleMatrix srcYNorm = new DoubleMatrix(numberOfObservations, 1);
DoubleMatrix srcXNorm = new DoubleMatrix(numberOfObservations, 1);
DoubleMatrix txtY = new DoubleMatrix(numberOfObservations, 1);
DoubleMatrix tgtX = new DoubleMatrix(numberOfObservations, 1);
DoubleMatrix dltY = new DoubleMatrix(numberOfObservations, 1);
DoubleMatrix dltX = new DoubleMatrix(numberOfObservations, 1);
// repackage observation and design matrices into jblas, also normalize
for (int i = 0; i < numberOfObservations; i++) {
srcY.put(i, srcArray[i][0]);
srcX.put(i, srcArray[i][1]);
txtY.put(i, tgtArray[i][0]);
tgtX.put(i, tgtArray[i][1]);
srcYNorm.put(i, normalize2(srcArray[i][0], win.linelo, win.linehi));
srcXNorm.put(i, normalize2(srcArray[i][1], win.pixlo, win.pixhi));
dltY.put(i, dltArray[i][0]);
dltX.put(i, dltArray[i][1]);
}
// compute coefficients using polyFit2D
// ...NOTE: order in which input axis are given => (x,y,z) <=
double[] coeffsX = polyFit2D(srcY, srcX, dltX, polyDegree);
double[] coeffsY = polyFit2D(srcY, srcX, dltY, polyDegree);
double[] coeffsXNorm = polyFit2D(srcYNorm, srcXNorm, dltX, polyDegree);
double[] coeffsYNorm = polyFit2D(srcYNorm, srcXNorm, dltY, polyDegree);
double[] coeffsXTemp = polyFit2D(srcY, srcX, tgtX, polyDegree);
double[] coeffsYTemp = polyFit2D(srcY, srcX, txtY, polyDegree);
// show polynomials depending on logger level <- not in production
logger.debug("coeffsXNorm : estimated with PolyUtils.polyFit2D : {}", org.apache.commons.lang3.ArrayUtils.toString(coeffsXNorm));
logger.debug("coeffsYNorm : estimated with PolyUtils.polyFit2D : {}", org.apache.commons.lang3.ArrayUtils.toString(coeffsYNorm));
// show polynomials depending on logger level <- not in production
logger.debug("coeffsX : estimated with PolyUtils.polyFit2D : {}", org.apache.commons.lang3.ArrayUtils.toString(coeffsX));
logger.debug("coeffsY : estimated with PolyUtils.polyFit2D : {}", org.apache.commons.lang3.ArrayUtils.toString(coeffsY));
/* JAI Example */
float[] src1DArray = new float[2 * numberOfObservations];
float[] tgt1DArray = new float[2 * numberOfObservations];
// declare src1DArray and dest
for (int i = 0; i < numberOfObservations; ++i) {
int j = 2 * i;
src1DArray[j] = (float) (srcX.get(i));
src1DArray[j + 1] = (float) (srcY.get(i));
tgt1DArray[j] = (float) tgtX.get(i);
tgt1DArray[j + 1] = (float) txtY.get(i);
}
float preScaleX = 1.0F / xMax;
float postScaleX = (float) xMax;
float preScaleY = 1.0F / yMax;
float postScaleY = (float) yMax;
/* Note: Warp semantic (transforms coordinates from destination to srcArray) is the
* opposite of jLinda semantic (transforms coordinates from srcArray to
* destination). We have to interchange srcArray and destination arrays for the
* direct transform.
*/
WarpPolynomial warpTotal = WarpPolynomial.createWarp(tgt1DArray, 0, src1DArray, 0, 2 * numberOfObservations, preScaleX, preScaleY, postScaleX, postScaleY, polyDegree);
// show polynomials depending on logger level <- not in production
logger.debug("coeffsAZ : estimated with JAI.WarpPolynomial.createWarp : {}", org.apache.commons.lang3.ArrayUtils.toString(warpTotal.getYCoeffs()));
logger.debug("coeffsX : estimated with JAI.WarpPolynomial.createWarp : {}", org.apache.commons.lang3.ArrayUtils.toString(warpTotal.getXCoeffs()));
float[] xCoeffs = new float[coeffsXTemp.length];
float[] yCoeffs = new float[coeffsYTemp.length];
for (int i = 0; i < coeffsY.length; i++) {
yCoeffs[i] = (float) coeffsYTemp[i];
xCoeffs[i] = (float) coeffsXTemp[i];
}
WarpPolynomial warpInterp = new WarpGeneralPolynomial(xCoeffs, yCoeffs);
// Point2D srcPoint = new Point2D.Double(1354, 23214);
Point2D srcPoint = new Point2D.Double(2523, 2683);
Point2D tgtPointExp = new Point2D.Double(srcPoint.getX() * ratioX, srcPoint.getY() * ratioY);
Point2D srcPointNorm = new Point2D.Double(
normalize2(srcPoint.getX(), win.pixlo, win.pixhi),
normalize2(srcPoint.getY(), win.linelo, win.linehi));
Point2D tgtPoint_JAI_1 = warpTotal.mapDestPoint(srcPoint);
Point2D tgtPoint_JAI_2 = warpInterp.mapDestPoint(srcPoint);
double tgtX_polyfit = srcPoint.getX() - polyval(srcPoint.getX(), srcPoint.getY(), coeffsX);
double tgtY_polyfit = srcPoint.getY() - polyval(srcPoint.getX(), srcPoint.getY(), coeffsY);
double tgtX_polyfit_norm = srcPoint.getX() - polyval(srcPointNorm.getX(), srcPointNorm.getY(), coeffsXNorm);
double tgtY_polyfit_norm = srcPoint.getY() - polyval(srcPointNorm.getX(), srcPointNorm.getY(), coeffsYNorm);
logger.debug("============ ");
logger.debug("Input Test Point (x,y): {}, {}", srcPoint.getX(), srcPoint.getY());
logger.debug("============ ");
logger.debug("Target Expected: {}, {}", tgtPointExp.getX(), tgtPointExp.getY());
logger.debug("Offset Expected: {}, {}", srcPoint.getX() - tgtPointExp.getX(), srcPoint.getY() - tgtPointExp.getY());
logger.debug("============ ");
logger.debug("Target - JAI-Impl-1: {}, {}", tgtPoint_JAI_1.getX(), tgtPoint_JAI_1.getY());
logger.debug("Target - JAI-Impl-2: {}, {}", tgtPoint_JAI_2.getX(), tgtPoint_JAI_2.getY());
logger.debug(" ---- ");
logger.debug("Target - polyFit : {}, {}", tgtX_polyfit, tgtY_polyfit);
logger.debug("Target - polyFit-Norm: {}, {}", tgtX_polyfit_norm, tgtY_polyfit_norm);
logger.debug("============ ");
logger.debug("Error - JAI-Impl-1: {}, {}", tgtPoint_JAI_1.getX() - tgtPointExp.getX(), tgtPoint_JAI_1.getY() - tgtPointExp.getY());
logger.debug("Error - JAI-Impl-2: {}, {}", tgtPoint_JAI_2.getX() - tgtPointExp.getX(), tgtPoint_JAI_2.getY() - tgtPointExp.getY());
logger.debug(" ---- ");
logger.debug("Error - polyFit : {}, {}", tgtX_polyfit - tgtPointExp.getX(), tgtY_polyfit - tgtPointExp.getY());
logger.debug("Error - polyFit-Norm: {}, {}", tgtX_polyfit_norm - tgtPointExp.getX(), tgtY_polyfit_norm - tgtPointExp.getY());
}
|
diff --git a/src/com/hyperactivity/android_app/core/ScrollPickerItem.java b/src/com/hyperactivity/android_app/core/ScrollPickerItem.java
index fc8425f..b1e9bf3 100644
--- a/src/com/hyperactivity/android_app/core/ScrollPickerItem.java
+++ b/src/com/hyperactivity/android_app/core/ScrollPickerItem.java
@@ -1,131 +1,131 @@
package com.hyperactivity.android_app.core;
import android.graphics.*;
import com.hyperactivity.android_app.forum.models.Category;
public class ScrollPickerItem {
private boolean visible;
private float centerX;
private float centerY;
private float radius;
private String text;
private boolean showText;
private float textMargin;
private Paint textPaint;
private Bitmap image;
private Bitmap renderImage;
private Category category;
public ScrollPickerItem(Bitmap image, String text, int textColor, Category category) {
this.image = image;
this.category = category;
visible = false;
centerX = 0f;
centerY = 0f;
radius = 0f;
this.text = text;
this.showText = false;
this.textMargin = 0f;
textPaint = new Paint();
- textPaint.setTextSize(24f);
+ textPaint.setTextSize(26f);
textPaint.setColor(textColor);
renderImage = image;
}
public void doUpdate(float delta) {
}
public void doDraw(Canvas canvas) {
if (visible) {
canvas.drawBitmap(renderImage, centerX - radius, centerY - radius, null);
if (showText) {
Rect bounds = new Rect();
textPaint.getTextBounds(text, 0, text.length(), bounds);
canvas.drawText(text, centerX - bounds.width()/2f, centerY + radius + textMargin + bounds.height()/3f, textPaint);
}
}
}
public void setVisible(boolean visible) {
this.visible = visible;
}
public void setCenterX(float centerX) {
this.centerX = centerX;
}
public void setCenterY(float centerY) {
this.centerY = centerY;
}
public void setRadius(float radius) {
this.radius = radius;
resizeImage();
}
/*public void setCirclePaint(Paint circlePaint) {
this.circlePaint = circlePaint;
}*/
public boolean isVisible() {
return visible;
}
public float getCenterX() {
return centerX;
}
public float getCenterY() {
return centerY;
}
public float getRadius() {
return radius;
}
// public Paint getCirclePaint() {
// return circlePaint;
// }
public void setShowText(boolean show) {
this.showText = show;
}
public void setTextMargin(float margin) {
this.textMargin = margin;
}
public void resizeImage() {
try {
renderImage = Bitmap.createScaledBitmap(image, (int)radius*2, (int)radius*2, true);
} catch (Exception e) {
e.printStackTrace();
}
}
public Bitmap getImage() {
return image;
}
@Override
public boolean equals(Object o) {
if (o instanceof ScrollPickerItem) {
ScrollPickerItem obj = (ScrollPickerItem) o;
if (isVisible() == obj.isVisible() && getRadius() == obj.getRadius() && getCenterX() == obj.getCenterX() && getCenterY() == obj.getCenterY() && image.equals(((ScrollPickerItem) o).getImage())) {
return true;
}
}
return false;
}
public Category getCategory() {
return category;
}
}
| true | true | public ScrollPickerItem(Bitmap image, String text, int textColor, Category category) {
this.image = image;
this.category = category;
visible = false;
centerX = 0f;
centerY = 0f;
radius = 0f;
this.text = text;
this.showText = false;
this.textMargin = 0f;
textPaint = new Paint();
textPaint.setTextSize(24f);
textPaint.setColor(textColor);
renderImage = image;
}
| public ScrollPickerItem(Bitmap image, String text, int textColor, Category category) {
this.image = image;
this.category = category;
visible = false;
centerX = 0f;
centerY = 0f;
radius = 0f;
this.text = text;
this.showText = false;
this.textMargin = 0f;
textPaint = new Paint();
textPaint.setTextSize(26f);
textPaint.setColor(textColor);
renderImage = image;
}
|
diff --git a/src/uk/me/graphe/client/DrawingImpl.java b/src/uk/me/graphe/client/DrawingImpl.java
index 61d6a7d..5d174da 100644
--- a/src/uk/me/graphe/client/DrawingImpl.java
+++ b/src/uk/me/graphe/client/DrawingImpl.java
@@ -1,1687 +1,1688 @@
package uk.me.graphe.client;
import java.util.Collection;
import com.google.gwt.widgetideas.graphics.client.Color;
import com.google.gwt.widgetideas.graphics.client.GWTCanvas;
public class DrawingImpl implements Drawing {
//used for panning
public int offsetX, offsetY;
public double zoom;
private static native void runJavascript(String script) /*-{
eval(script);
}-*/;
// JSNI method for WebGL
private static native void drawGraph3D() /*-{
var circleCoords = new Array(1000);
for(i=0;i<circleCoords.length;i++)circleCoords[i] = new Array(1000);
var gl;
var shaderProgram;
var mvMatrix;
var mvMatrixStack = [];
var colors = [[0.0, 0.0, 0.0], // BLACK 0
[1.0, 1.0, 1.0], // WHITE 1
[1.0, 0.0, 0.0], // RED 2
[0.0, 1.0, 0.0], // GREEN 3
[0.0, 0.0, 1.0], // BLUE 4
[1.0, 1.0, 0.0], // YELLOW 5
[1.0, 0.317, 1.0], // PINK 6
[0.5, 0.5, 0.5], // GREY 7
];
var hersheyFont=[
[0,16,//Ascii32
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[8,10,//Ascii33
5,21,5,7,-1,-1,5,2,4,1,5,0,6,1,5,2,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[5,16,//Ascii34
4,21,4,14,-1,-1,12,21,12,14,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[11,21,//Ascii35
11,25,4,-7,-1,-1,17,25,10,-7,-1,-1,4,12,18,12,-1,-1,3,6,17,6,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[26,20,//Ascii36
8,25,8,-4,-1,-1,12,25,12,-4,-1,-1,17,18,15,20,12,21,8,21,5,20,3,
18,3,16,4,14,5,13,7,12,13,10,15,9,16,8,17,6,17,3,15,1,12,0,
8,0,5,1,3,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[31,24,//Ascii37
21,21,3,0,-1,-1,8,21,10,19,10,17,9,15,7,14,5,14,3,16,3,18,4,
20,6,21,8,21,10,20,13,19,16,19,19,20,21,21,-1,-1,17,7,15,6,14,4,
14,2,16,0,18,0,20,1,21,3,21,5,19,7,17,7,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[34,26,//Ascii38
23,12,23,13,22,14,21,14,20,13,19,11,17,6,15,3,13,1,11,0,7,0,5,
1,4,2,3,4,3,6,4,8,5,9,12,13,13,14,14,16,14,18,13,20,11,21,
9,20,8,18,8,16,9,13,11,10,16,3,18,1,20,0,22,0,23,1,23,2,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[7,10,//Ascii39
5,19,4,20,5,21,6,20,6,18,5,16,4,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[10,14,//Ascii40
11,25,9,23,7,20,5,16,4,11,4,7,5,2,7,-2,9,-5,11,-7,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[10,14,//Ascii41
3,25,5,23,7,20,9,16,10,11,10,7,9,2,7,-2,5,-5,3,-7,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[8,16,//Ascii42
8,21,8,9,-1,-1,3,18,13,12,-1,-1,13,18,3,12,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[5,26,//Ascii43
13,18,13,0,-1,-1,4,9,22,9,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[8,10,//Ascii44
6,1,5,0,4,1,5,2,6,1,6,-1,5,-3,4,-4,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[2,26,//Ascii45
4,9,22,9,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[5,10,//Ascii46
5,2,4,1,5,0,6,1,5,2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[2,22,//Ascii47
20,25,2,-7,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[17,20,//Ascii48
9,21,6,20,4,17,3,12,3,9,4,4,6,1,9,0,11,0,14,1,16,4,17,
9,17,12,16,17,14,20,11,21,9,21,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[4,20,//Ascii49
6,17,8,18,11,21,11,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[14,20,//Ascii50
4,16,4,17,5,19,6,20,8,21,12,21,14,20,15,19,16,17,16,15,15,13,13,
10,3,0,17,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[15,20,//Ascii51
5,21,16,21,10,13,13,13,15,12,16,11,17,8,17,6,16,3,14,1,11,0,8,
0,5,1,4,2,3,4,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[6,20,//Ascii52
13,21,3,7,18,7,-1,-1,13,21,13,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[17,20,//Ascii53
15,21,5,21,4,12,5,13,8,14,11,14,14,13,16,11,17,8,17,6,16,3,14,
1,11,0,8,0,5,1,4,2,3,4,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[23,20,//Ascii54
16,18,15,20,12,21,10,21,7,20,5,17,4,12,4,7,5,3,7,1,10,0,11,
0,14,1,16,3,17,6,17,7,16,10,14,12,11,13,10,13,7,12,5,10,4,7,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[5,20,//Ascii55
17,21,7,0,-1,-1,3,21,17,21,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[29,20,//Ascii56
8,21,5,20,4,18,4,16,5,14,7,13,11,12,14,11,16,9,17,7,17,4,16,
2,15,1,12,0,8,0,5,1,4,2,3,4,3,7,4,9,6,11,9,12,13,13,
15,14,16,16,16,18,15,20,12,21,8,21,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[23,20,//Ascii57
16,14,15,11,13,9,10,8,9,8,6,9,4,11,3,14,3,15,4,18,6,20,9,
21,10,21,13,20,15,18,16,14,16,9,15,4,13,1,10,0,8,0,5,1,4,3,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[11,10,//Ascii58
5,14,4,13,5,12,6,13,5,14,-1,-1,5,2,4,1,5,0,6,1,5,2,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[14,10,//Ascii59
5,14,4,13,5,12,6,13,5,14,-1,-1,6,1,5,0,4,1,5,2,6,1,6,
-1,5,-3,4,-4,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[3,24,//Ascii60
20,18,4,9,20,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[5,26,//Ascii61
4,12,22,12,-1,-1,4,6,22,6,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[3,24,//Ascii62
4,18,20,9,4,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[20,18,//Ascii63
3,16,3,17,4,19,5,20,7,21,11,21,13,20,14,19,15,17,15,15,14,13,13,
12,9,10,9,7,-1,-1,9,2,8,1,9,0,10,1,9,2,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[55,27,//Ascii64
18,13,17,15,15,16,12,16,10,15,9,14,8,11,8,8,9,6,11,5,14,5,16,
6,17,8,-1,-1,12,16,10,14,9,11,9,8,10,6,11,5,-1,-1,18,16,17,8,
17,6,19,5,21,5,23,7,24,10,24,12,23,15,22,17,20,19,18,20,15,21,12,
21,9,20,7,19,5,17,4,15,3,12,3,9,4,6,5,4,7,2,9,1,12,0,
15,0,18,1,20,2,21,3,-1,-1,19,16,18,8,18,6,19,5,],
[8,18,//Ascii65
9,21,1,0,-1,-1,9,21,17,0,-1,-1,4,7,14,7,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[23,21,//Ascii66
4,21,4,0,-1,-1,4,21,13,21,16,20,17,19,18,17,18,15,17,13,16,12,13,
11,-1,-1,4,11,13,11,16,10,17,9,18,7,18,4,17,2,16,1,13,0,4,0,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[18,21,//Ascii67
18,16,17,18,15,20,13,21,9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,
3,7,1,9,0,13,0,15,1,17,3,18,5,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[15,21,//Ascii68
4,21,4,0,-1,-1,4,21,11,21,14,20,16,18,17,16,18,13,18,8,17,5,16,
3,14,1,11,0,4,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[11,19,//Ascii69
4,21,4,0,-1,-1,4,21,17,21,-1,-1,4,11,12,11,-1,-1,4,0,17,0,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[8,18,//Ascii70
4,21,4,0,-1,-1,4,21,17,21,-1,-1,4,11,12,11,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[22,21,//Ascii71
18,16,17,18,15,20,13,21,9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,
3,7,1,9,0,13,0,15,1,17,3,18,5,18,8,-1,-1,13,8,18,8,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[8,22,//Ascii72
4,21,4,0,-1,-1,18,21,18,0,-1,-1,4,11,18,11,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[2,8,//Ascii73
4,21,4,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[10,16,//Ascii74
12,21,12,5,11,2,10,1,8,0,6,0,4,1,3,2,2,5,2,7,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[8,21,//Ascii75
4,21,4,0,-1,-1,18,21,4,7,-1,-1,9,12,18,0,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[5,17,//Ascii76
4,21,4,0,-1,-1,4,0,16,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[11,24,//Ascii77
4,21,4,0,-1,-1,4,21,12,0,-1,-1,20,21,12,0,-1,-1,20,21,20,0,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[8,22,//Ascii78
4,21,4,0,-1,-1,4,21,18,0,-1,-1,18,21,18,0,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[21,22,//Ascii79
9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,
1,17,3,18,5,19,8,19,13,18,16,17,18,15,20,13,21,9,21,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[13,21,//Ascii80
4,21,4,0,-1,-1,4,21,13,21,16,20,17,19,18,17,18,14,17,12,16,11,13,
10,4,10,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[24,22,//Ascii81
9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,
1,17,3,18,5,19,8,19,13,18,16,17,18,15,20,13,21,9,21,-1,-1,12,4,
18,-2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[16,21,//Ascii82
4,21,4,0,-1,-1,4,21,13,21,16,20,17,19,18,17,18,15,17,13,16,12,13,
11,4,11,-1,-1,11,11,18,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[20,20,//Ascii83
17,18,15,20,12,21,8,21,5,20,3,18,3,16,4,14,5,13,7,12,13,10,15,
9,16,8,17,6,17,3,15,1,12,0,8,0,5,1,3,3,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[5,16,//Ascii84
8,21,8,0,-1,-1,1,21,15,21,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[10,22,//Ascii85
4,21,4,6,5,3,7,1,10,0,12,0,15,1,17,3,18,6,18,21,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[5,18,//Ascii86
1,21,9,0,-1,-1,17,21,9,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[11,24,//Ascii87
2,21,7,0,-1,-1,12,21,7,0,-1,-1,12,21,17,0,-1,-1,22,21,17,0,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[5,20,//Ascii88
3,21,17,0,-1,-1,17,21,3,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[6,18,//Ascii89
1,21,9,11,9,0,-1,-1,17,21,9,11,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[8,20,//Ascii90
17,21,3,0,-1,-1,3,21,17,21,-1,-1,3,0,17,0,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[11,14,//Ascii91
4,25,4,-7,-1,-1,5,25,5,-7,-1,-1,4,25,11,25,-1,-1,4,-7,11,-7,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[2,14,//Ascii92
0,21,14,-3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[11,14,//Ascii93
9,25,9,-7,-1,-1,10,25,10,-7,-1,-1,3,25,10,25,-1,-1,3,-7,10,-7,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[10,16,//Ascii94
6,15,8,18,10,15,-1,-1,3,12,8,17,13,12,-1,-1,8,17,8,0,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[2,16,//Ascii95
0,-2,16,-2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[7,10,//Ascii96
6,21,5,20,4,18,4,16,5,15,6,16,5,17,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[17,19,//Ascii97
15,14,15,0,-1,-1,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,
3,6,1,8,0,11,0,13,1,15,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[17,19,//Ascii98
4,21,4,0,-1,-1,4,11,6,13,8,14,11,14,13,13,15,11,16,8,16,6,15,
3,13,1,11,0,8,0,6,1,4,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[14,18,//Ascii99
15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,
0,13,1,15,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[17,19,//Ascii100
15,21,15,0,-1,-1,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,
3,6,1,8,0,11,0,13,1,15,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[17,18,//Ascii101
3,8,15,8,15,10,14,12,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,
3,6,1,8,0,11,0,13,1,15,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[8,12,//Ascii102
10,21,8,21,6,20,5,17,5,0,-1,-1,2,14,9,14,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[22,19,//Ascii103
15,14,15,-2,14,-5,13,-6,11,-7,8,-7,6,-6,-1,-1,15,11,13,13,11,14,8,
14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[10,19,//Ascii104
4,21,4,0,-1,-1,4,10,7,13,9,14,12,14,14,13,15,10,15,0,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[8,8,//Ascii105
3,21,4,20,5,21,4,22,3,21,-1,-1,4,14,4,0,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[11,10,//Ascii106
5,21,6,20,7,21,6,22,5,21,-1,-1,6,14,6,-3,5,-6,3,-7,1,-7,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[8,17,//Ascii107
4,21,4,0,-1,-1,14,14,4,4,-1,-1,8,8,15,0,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[2,8,//Ascii108
4,21,4,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[18,30,//Ascii109
4,14,4,0,-1,-1,4,10,7,13,9,14,12,14,14,13,15,10,15,0,-1,-1,15,
10,18,13,20,14,23,14,25,13,26,10,26,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[10,19,//Ascii110
4,14,4,0,-1,-1,4,10,7,13,9,14,12,14,14,13,15,10,15,0,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[17,19,//Ascii111
8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3,16,
6,16,8,15,11,13,13,11,14,8,14,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[17,19,//Ascii112
4,14,4,-7,-1,-1,4,11,6,13,8,14,11,14,13,13,15,11,16,8,16,6,15,
3,13,1,11,0,8,0,6,1,4,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[17,19,//Ascii113
15,14,15,-7,-1,-1,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,
3,6,1,8,0,11,0,13,1,15,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[8,13,//Ascii114
4,14,4,0,-1,-1,4,8,5,11,7,13,9,14,12,14,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[17,17,//Ascii115
14,11,13,13,10,14,7,14,4,13,3,11,4,9,6,8,11,7,13,6,14,4,14,
3,13,1,10,0,7,0,4,1,3,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[8,12,//Ascii116
5,21,5,4,6,1,8,0,10,0,-1,-1,2,14,9,14,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[10,19,//Ascii117
4,14,4,4,5,1,7,0,10,0,12,1,15,4,-1,-1,15,14,15,0,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[5,16,//Ascii118
2,14,8,0,-1,-1,14,14,8,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[11,22,//Ascii119
3,14,7,0,-1,-1,11,14,7,0,-1,-1,11,14,15,0,-1,-1,19,14,15,0,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[5,17,//Ascii120
3,14,14,0,-1,-1,14,14,3,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[9,16,//Ascii121
2,14,8,0,-1,-1,14,14,8,0,6,-4,4,-6,2,-7,1,-7,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[8,17,//Ascii122
14,14,3,0,-1,-1,3,14,14,14,-1,-1,3,0,14,0,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[39,14,//Ascii123
9,25,7,24,6,23,5,21,5,19,6,17,7,16,8,14,8,12,6,10,-1,-1,7,
24,6,22,6,20,7,18,8,17,9,15,9,13,8,11,4,9,8,7,9,5,9,3,
8,1,7,0,6,-2,6,-4,7,-6,-1,-1,6,8,8,6,8,4,7,2,6,1,5,
-1,5,-3,6,-5,7,-6,9,-7,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[2,8,//Ascii124
4,25,4,-7,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[39,14,//Ascii125
5,25,7,24,8,23,9,21,9,19,8,17,7,16,6,14,6,12,8,10,-1,-1,7,
24,8,22,8,20,7,18,6,17,5,15,5,13,6,11,10,9,6,7,5,5,5,3,
6,1,7,0,8,-2,8,-4,7,-6,-1,-1,8,8,6,6,6,4,7,2,8,1,9,
-1,9,-3,8,-5,7,-6,5,-7,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[23,24,//Ascii126
3,6,3,8,4,11,6,12,8,12,10,11,14,8,16,7,18,7,20,8,21,10,-1,
-1,3,8,4,10,6,11,8,11,10,10,14,7,16,6,18,6,20,7,21,10,21,12,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,]
];
// Sylvester.js Libary
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('9 17={3i:\'0.1.3\',16:1e-6};l v(){}v.23={e:l(i){8(i<1||i>7.4.q)?w:7.4[i-1]},2R:l(){8 7.4.q},1u:l(){8 F.1x(7.2u(7))},24:l(a){9 n=7.4.q;9 V=a.4||a;o(n!=V.q){8 1L}J{o(F.13(7.4[n-1]-V[n-1])>17.16){8 1L}}H(--n);8 2x},1q:l(){8 v.u(7.4)},1b:l(a){9 b=[];7.28(l(x,i){b.19(a(x,i))});8 v.u(b)},28:l(a){9 n=7.4.q,k=n,i;J{i=k-n;a(7.4[i],i+1)}H(--n)},2q:l(){9 r=7.1u();o(r===0){8 7.1q()}8 7.1b(l(x){8 x/r})},1C:l(a){9 V=a.4||a;9 n=7.4.q,k=n,i;o(n!=V.q){8 w}9 b=0,1D=0,1F=0;7.28(l(x,i){b+=x*V[i-1];1D+=x*x;1F+=V[i-1]*V[i-1]});1D=F.1x(1D);1F=F.1x(1F);o(1D*1F===0){8 w}9 c=b/(1D*1F);o(c<-1){c=-1}o(c>1){c=1}8 F.37(c)},1m:l(a){9 b=7.1C(a);8(b===w)?w:(b<=17.16)},34:l(a){9 b=7.1C(a);8(b===w)?w:(F.13(b-F.1A)<=17.16)},2k:l(a){9 b=7.2u(a);8(b===w)?w:(F.13(b)<=17.16)},2j:l(a){9 V=a.4||a;o(7.4.q!=V.q){8 w}8 7.1b(l(x,i){8 x+V[i-1]})},2C:l(a){9 V=a.4||a;o(7.4.q!=V.q){8 w}8 7.1b(l(x,i){8 x-V[i-1]})},22:l(k){8 7.1b(l(x){8 x*k})},x:l(k){8 7.22(k)},2u:l(a){9 V=a.4||a;9 i,2g=0,n=7.4.q;o(n!=V.q){8 w}J{2g+=7.4[n-1]*V[n-1]}H(--n);8 2g},2f:l(a){9 B=a.4||a;o(7.4.q!=3||B.q!=3){8 w}9 A=7.4;8 v.u([(A[1]*B[2])-(A[2]*B[1]),(A[2]*B[0])-(A[0]*B[2]),(A[0]*B[1])-(A[1]*B[0])])},2A:l(){9 m=0,n=7.4.q,k=n,i;J{i=k-n;o(F.13(7.4[i])>F.13(m)){m=7.4[i]}}H(--n);8 m},2Z:l(x){9 a=w,n=7.4.q,k=n,i;J{i=k-n;o(a===w&&7.4[i]==x){a=i+1}}H(--n);8 a},3g:l(){8 S.2X(7.4)},2d:l(){8 7.1b(l(x){8 F.2d(x)})},2V:l(x){8 7.1b(l(y){8(F.13(y-x)<=17.16)?x:y})},1o:l(a){o(a.K){8 a.1o(7)}9 V=a.4||a;o(V.q!=7.4.q){8 w}9 b=0,2b;7.28(l(x,i){2b=x-V[i-1];b+=2b*2b});8 F.1x(b)},3a:l(a){8 a.1h(7)},2T:l(a){8 a.1h(7)},1V:l(t,a){9 V,R,x,y,z;2S(7.4.q){27 2:V=a.4||a;o(V.q!=2){8 w}R=S.1R(t).4;x=7.4[0]-V[0];y=7.4[1]-V[1];8 v.u([V[0]+R[0][0]*x+R[0][1]*y,V[1]+R[1][0]*x+R[1][1]*y]);1I;27 3:o(!a.U){8 w}9 C=a.1r(7).4;R=S.1R(t,a.U).4;x=7.4[0]-C[0];y=7.4[1]-C[1];z=7.4[2]-C[2];8 v.u([C[0]+R[0][0]*x+R[0][1]*y+R[0][2]*z,C[1]+R[1][0]*x+R[1][1]*y+R[1][2]*z,C[2]+R[2][0]*x+R[2][1]*y+R[2][2]*z]);1I;2P:8 w}},1t:l(a){o(a.K){9 P=7.4.2O();9 C=a.1r(P).4;8 v.u([C[0]+(C[0]-P[0]),C[1]+(C[1]-P[1]),C[2]+(C[2]-(P[2]||0))])}1d{9 Q=a.4||a;o(7.4.q!=Q.q){8 w}8 7.1b(l(x,i){8 Q[i-1]+(Q[i-1]-x)})}},1N:l(){9 V=7.1q();2S(V.4.q){27 3:1I;27 2:V.4.19(0);1I;2P:8 w}8 V},2n:l(){8\'[\'+7.4.2K(\', \')+\']\'},26:l(a){7.4=(a.4||a).2O();8 7}};v.u=l(a){9 V=25 v();8 V.26(a)};v.i=v.u([1,0,0]);v.j=v.u([0,1,0]);v.k=v.u([0,0,1]);v.2J=l(n){9 a=[];J{a.19(F.2F())}H(--n);8 v.u(a)};v.1j=l(n){9 a=[];J{a.19(0)}H(--n);8 v.u(a)};l S(){}S.23={e:l(i,j){o(i<1||i>7.4.q||j<1||j>7.4[0].q){8 w}8 7.4[i-1][j-1]},33:l(i){o(i>7.4.q){8 w}8 v.u(7.4[i-1])},2E:l(j){o(j>7.4[0].q){8 w}9 a=[],n=7.4.q,k=n,i;J{i=k-n;a.19(7.4[i][j-1])}H(--n);8 v.u(a)},2R:l(){8{2D:7.4.q,1p:7.4[0].q}},2D:l(){8 7.4.q},1p:l(){8 7.4[0].q},24:l(a){9 M=a.4||a;o(1g(M[0][0])==\'1f\'){M=S.u(M).4}o(7.4.q!=M.q||7.4[0].q!=M[0].q){8 1L}9 b=7.4.q,15=b,i,G,10=7.4[0].q,j;J{i=15-b;G=10;J{j=10-G;o(F.13(7.4[i][j]-M[i][j])>17.16){8 1L}}H(--G)}H(--b);8 2x},1q:l(){8 S.u(7.4)},1b:l(a){9 b=[],12=7.4.q,15=12,i,G,10=7.4[0].q,j;J{i=15-12;G=10;b[i]=[];J{j=10-G;b[i][j]=a(7.4[i][j],i+1,j+1)}H(--G)}H(--12);8 S.u(b)},2i:l(a){9 M=a.4||a;o(1g(M[0][0])==\'1f\'){M=S.u(M).4}8(7.4.q==M.q&&7.4[0].q==M[0].q)},2j:l(a){9 M=a.4||a;o(1g(M[0][0])==\'1f\'){M=S.u(M).4}o(!7.2i(M)){8 w}8 7.1b(l(x,i,j){8 x+M[i-1][j-1]})},2C:l(a){9 M=a.4||a;o(1g(M[0][0])==\'1f\'){M=S.u(M).4}o(!7.2i(M)){8 w}8 7.1b(l(x,i,j){8 x-M[i-1][j-1]})},2B:l(a){9 M=a.4||a;o(1g(M[0][0])==\'1f\'){M=S.u(M).4}8(7.4[0].q==M.q)},22:l(a){o(!a.4){8 7.1b(l(x){8 x*a})}9 b=a.1u?2x:1L;9 M=a.4||a;o(1g(M[0][0])==\'1f\'){M=S.u(M).4}o(!7.2B(M)){8 w}9 d=7.4.q,15=d,i,G,10=M[0].q,j;9 e=7.4[0].q,4=[],21,20,c;J{i=15-d;4[i]=[];G=10;J{j=10-G;21=0;20=e;J{c=e-20;21+=7.4[i][c]*M[c][j]}H(--20);4[i][j]=21}H(--G)}H(--d);9 M=S.u(4);8 b?M.2E(1):M},x:l(a){8 7.22(a)},32:l(a,b,c,d){9 e=[],12=c,i,G,j;9 f=7.4.q,1p=7.4[0].q;J{i=c-12;e[i]=[];G=d;J{j=d-G;e[i][j]=7.4[(a+i-1)%f][(b+j-1)%1p]}H(--G)}H(--12);8 S.u(e)},31:l(){9 a=7.4.q,1p=7.4[0].q;9 b=[],12=1p,i,G,j;J{i=1p-12;b[i]=[];G=a;J{j=a-G;b[i][j]=7.4[j][i]}H(--G)}H(--12);8 S.u(b)},1y:l(){8(7.4.q==7.4[0].q)},2A:l(){9 m=0,12=7.4.q,15=12,i,G,10=7.4[0].q,j;J{i=15-12;G=10;J{j=10-G;o(F.13(7.4[i][j])>F.13(m)){m=7.4[i][j]}}H(--G)}H(--12);8 m},2Z:l(x){9 a=w,12=7.4.q,15=12,i,G,10=7.4[0].q,j;J{i=15-12;G=10;J{j=10-G;o(7.4[i][j]==x){8{i:i+1,j:j+1}}}H(--G)}H(--12);8 w},30:l(){o(!7.1y){8 w}9 a=[],n=7.4.q,k=n,i;J{i=k-n;a.19(7.4[i][i])}H(--n);8 v.u(a)},1K:l(){9 M=7.1q(),1c;9 n=7.4.q,k=n,i,1s,1n=7.4[0].q,p;J{i=k-n;o(M.4[i][i]==0){2e(j=i+1;j<k;j++){o(M.4[j][i]!=0){1c=[];1s=1n;J{p=1n-1s;1c.19(M.4[i][p]+M.4[j][p])}H(--1s);M.4[i]=1c;1I}}}o(M.4[i][i]!=0){2e(j=i+1;j<k;j++){9 a=M.4[j][i]/M.4[i][i];1c=[];1s=1n;J{p=1n-1s;1c.19(p<=i?0:M.4[j][p]-M.4[i][p]*a)}H(--1s);M.4[j]=1c}}}H(--n);8 M},3h:l(){8 7.1K()},2z:l(){o(!7.1y()){8 w}9 M=7.1K();9 a=M.4[0][0],n=M.4.q-1,k=n,i;J{i=k-n+1;a=a*M.4[i][i]}H(--n);8 a},3f:l(){8 7.2z()},2y:l(){8(7.1y()&&7.2z()===0)},2Y:l(){o(!7.1y()){8 w}9 a=7.4[0][0],n=7.4.q-1,k=n,i;J{i=k-n+1;a+=7.4[i][i]}H(--n);8 a},3e:l(){8 7.2Y()},1Y:l(){9 M=7.1K(),1Y=0;9 a=7.4.q,15=a,i,G,10=7.4[0].q,j;J{i=15-a;G=10;J{j=10-G;o(F.13(M.4[i][j])>17.16){1Y++;1I}}H(--G)}H(--a);8 1Y},3d:l(){8 7.1Y()},2W:l(a){9 M=a.4||a;o(1g(M[0][0])==\'1f\'){M=S.u(M).4}9 T=7.1q(),1p=T.4[0].q;9 b=T.4.q,15=b,i,G,10=M[0].q,j;o(b!=M.q){8 w}J{i=15-b;G=10;J{j=10-G;T.4[i][1p+j]=M[i][j]}H(--G)}H(--b);8 T},2w:l(){o(!7.1y()||7.2y()){8 w}9 a=7.4.q,15=a,i,j;9 M=7.2W(S.I(a)).1K();9 b,1n=M.4[0].q,p,1c,2v;9 c=[],2c;J{i=a-1;1c=[];b=1n;c[i]=[];2v=M.4[i][i];J{p=1n-b;2c=M.4[i][p]/2v;1c.19(2c);o(p>=15){c[i].19(2c)}}H(--b);M.4[i]=1c;2e(j=0;j<i;j++){1c=[];b=1n;J{p=1n-b;1c.19(M.4[j][p]-M.4[i][p]*M.4[j][i])}H(--b);M.4[j]=1c}}H(--a);8 S.u(c)},3c:l(){8 7.2w()},2d:l(){8 7.1b(l(x){8 F.2d(x)})},2V:l(x){8 7.1b(l(p){8(F.13(p-x)<=17.16)?x:p})},2n:l(){9 a=[];9 n=7.4.q,k=n,i;J{i=k-n;a.19(v.u(7.4[i]).2n())}H(--n);8 a.2K(\'\\n\')},26:l(a){9 i,4=a.4||a;o(1g(4[0][0])!=\'1f\'){9 b=4.q,15=b,G,10,j;7.4=[];J{i=15-b;G=4[i].q;10=G;7.4[i]=[];J{j=10-G;7.4[i][j]=4[i][j]}H(--G)}H(--b);8 7}9 n=4.q,k=n;7.4=[];J{i=k-n;7.4.19([4[i]])}H(--n);8 7}};S.u=l(a){9 M=25 S();8 M.26(a)};S.I=l(n){9 a=[],k=n,i,G,j;J{i=k-n;a[i]=[];G=k;J{j=k-G;a[i][j]=(i==j)?1:0}H(--G)}H(--n);8 S.u(a)};S.2X=l(a){9 n=a.q,k=n,i;9 M=S.I(n);J{i=k-n;M.4[i][i]=a[i]}H(--n);8 M};S.1R=l(b,a){o(!a){8 S.u([[F.1H(b),-F.1G(b)],[F.1G(b),F.1H(b)]])}9 d=a.1q();o(d.4.q!=3){8 w}9 e=d.1u();9 x=d.4[0]/e,y=d.4[1]/e,z=d.4[2]/e;9 s=F.1G(b),c=F.1H(b),t=1-c;8 S.u([[t*x*x+c,t*x*y-s*z,t*x*z+s*y],[t*x*y+s*z,t*y*y+c,t*y*z-s*x],[t*x*z-s*y,t*y*z+s*x,t*z*z+c]])};S.3b=l(t){9 c=F.1H(t),s=F.1G(t);8 S.u([[1,0,0],[0,c,-s],[0,s,c]])};S.39=l(t){9 c=F.1H(t),s=F.1G(t);8 S.u([[c,0,s],[0,1,0],[-s,0,c]])};S.38=l(t){9 c=F.1H(t),s=F.1G(t);8 S.u([[c,-s,0],[s,c,0],[0,0,1]])};S.2J=l(n,m){8 S.1j(n,m).1b(l(){8 F.2F()})};S.1j=l(n,m){9 a=[],12=n,i,G,j;J{i=n-12;a[i]=[];G=m;J{j=m-G;a[i][j]=0}H(--G)}H(--12);8 S.u(a)};l 14(){}14.23={24:l(a){8(7.1m(a)&&7.1h(a.K))},1q:l(){8 14.u(7.K,7.U)},2U:l(a){9 V=a.4||a;8 14.u([7.K.4[0]+V[0],7.K.4[1]+V[1],7.K.4[2]+(V[2]||0)],7.U)},1m:l(a){o(a.W){8 a.1m(7)}9 b=7.U.1C(a.U);8(F.13(b)<=17.16||F.13(b-F.1A)<=17.16)},1o:l(a){o(a.W){8 a.1o(7)}o(a.U){o(7.1m(a)){8 7.1o(a.K)}9 N=7.U.2f(a.U).2q().4;9 A=7.K.4,B=a.K.4;8 F.13((A[0]-B[0])*N[0]+(A[1]-B[1])*N[1]+(A[2]-B[2])*N[2])}1d{9 P=a.4||a;9 A=7.K.4,D=7.U.4;9 b=P[0]-A[0],2a=P[1]-A[1],29=(P[2]||0)-A[2];9 c=F.1x(b*b+2a*2a+29*29);o(c===0)8 0;9 d=(b*D[0]+2a*D[1]+29*D[2])/c;9 e=1-d*d;8 F.13(c*F.1x(e<0?0:e))}},1h:l(a){9 b=7.1o(a);8(b!==w&&b<=17.16)},2T:l(a){8 a.1h(7)},1v:l(a){o(a.W){8 a.1v(7)}8(!7.1m(a)&&7.1o(a)<=17.16)},1U:l(a){o(a.W){8 a.1U(7)}o(!7.1v(a)){8 w}9 P=7.K.4,X=7.U.4,Q=a.K.4,Y=a.U.4;9 b=X[0],1z=X[1],1B=X[2],1T=Y[0],1S=Y[1],1M=Y[2];9 c=P[0]-Q[0],2s=P[1]-Q[1],2r=P[2]-Q[2];9 d=-b*c-1z*2s-1B*2r;9 e=1T*c+1S*2s+1M*2r;9 f=b*b+1z*1z+1B*1B;9 g=1T*1T+1S*1S+1M*1M;9 h=b*1T+1z*1S+1B*1M;9 k=(d*g/f+h*e)/(g-h*h);8 v.u([P[0]+k*b,P[1]+k*1z,P[2]+k*1B])},1r:l(a){o(a.U){o(7.1v(a)){8 7.1U(a)}o(7.1m(a)){8 w}9 D=7.U.4,E=a.U.4;9 b=D[0],1l=D[1],1k=D[2],1P=E[0],1O=E[1],1Q=E[2];9 x=(1k*1P-b*1Q),y=(b*1O-1l*1P),z=(1l*1Q-1k*1O);9 N=v.u([x*1Q-y*1O,y*1P-z*1Q,z*1O-x*1P]);9 P=11.u(a.K,N);8 P.1U(7)}1d{9 P=a.4||a;o(7.1h(P)){8 v.u(P)}9 A=7.K.4,D=7.U.4;9 b=D[0],1l=D[1],1k=D[2],1w=A[0],18=A[1],1a=A[2];9 x=b*(P[1]-18)-1l*(P[0]-1w),y=1l*((P[2]||0)-1a)-1k*(P[1]-18),z=1k*(P[0]-1w)-b*((P[2]||0)-1a);9 V=v.u([1l*x-1k*z,1k*y-b*x,b*z-1l*y]);9 k=7.1o(P)/V.1u();8 v.u([P[0]+V.4[0]*k,P[1]+V.4[1]*k,(P[2]||0)+V.4[2]*k])}},1V:l(t,a){o(1g(a.U)==\'1f\'){a=14.u(a.1N(),v.k)}9 R=S.1R(t,a.U).4;9 C=a.1r(7.K).4;9 A=7.K.4,D=7.U.4;9 b=C[0],1E=C[1],1J=C[2],1w=A[0],18=A[1],1a=A[2];9 x=1w-b,y=18-1E,z=1a-1J;8 14.u([b+R[0][0]*x+R[0][1]*y+R[0][2]*z,1E+R[1][0]*x+R[1][1]*y+R[1][2]*z,1J+R[2][0]*x+R[2][1]*y+R[2][2]*z],[R[0][0]*D[0]+R[0][1]*D[1]+R[0][2]*D[2],R[1][0]*D[0]+R[1][1]*D[1]+R[1][2]*D[2],R[2][0]*D[0]+R[2][1]*D[1]+R[2][2]*D[2]])},1t:l(a){o(a.W){9 A=7.K.4,D=7.U.4;9 b=A[0],18=A[1],1a=A[2],2N=D[0],1l=D[1],1k=D[2];9 c=7.K.1t(a).4;9 d=b+2N,2h=18+1l,2o=1a+1k;9 Q=a.1r([d,2h,2o]).4;9 e=[Q[0]+(Q[0]-d)-c[0],Q[1]+(Q[1]-2h)-c[1],Q[2]+(Q[2]-2o)-c[2]];8 14.u(c,e)}1d o(a.U){8 7.1V(F.1A,a)}1d{9 P=a.4||a;8 14.u(7.K.1t([P[0],P[1],(P[2]||0)]),7.U)}},1Z:l(a,b){a=v.u(a);b=v.u(b);o(a.4.q==2){a.4.19(0)}o(b.4.q==2){b.4.19(0)}o(a.4.q>3||b.4.q>3){8 w}9 c=b.1u();o(c===0){8 w}7.K=a;7.U=v.u([b.4[0]/c,b.4[1]/c,b.4[2]/c]);8 7}};14.u=l(a,b){9 L=25 14();8 L.1Z(a,b)};14.X=14.u(v.1j(3),v.i);14.Y=14.u(v.1j(3),v.j);14.Z=14.u(v.1j(3),v.k);l 11(){}11.23={24:l(a){8(7.1h(a.K)&&7.1m(a))},1q:l(){8 11.u(7.K,7.W)},2U:l(a){9 V=a.4||a;8 11.u([7.K.4[0]+V[0],7.K.4[1]+V[1],7.K.4[2]+(V[2]||0)],7.W)},1m:l(a){9 b;o(a.W){b=7.W.1C(a.W);8(F.13(b)<=17.16||F.13(F.1A-b)<=17.16)}1d o(a.U){8 7.W.2k(a.U)}8 w},2k:l(a){9 b=7.W.1C(a.W);8(F.13(F.1A/2-b)<=17.16)},1o:l(a){o(7.1v(a)||7.1h(a)){8 0}o(a.K){9 A=7.K.4,B=a.K.4,N=7.W.4;8 F.13((A[0]-B[0])*N[0]+(A[1]-B[1])*N[1]+(A[2]-B[2])*N[2])}1d{9 P=a.4||a;9 A=7.K.4,N=7.W.4;8 F.13((A[0]-P[0])*N[0]+(A[1]-P[1])*N[1]+(A[2]-(P[2]||0))*N[2])}},1h:l(a){o(a.W){8 w}o(a.U){8(7.1h(a.K)&&7.1h(a.K.2j(a.U)))}1d{9 P=a.4||a;9 A=7.K.4,N=7.W.4;9 b=F.13(N[0]*(A[0]-P[0])+N[1]*(A[1]-P[1])+N[2]*(A[2]-(P[2]||0)));8(b<=17.16)}},1v:l(a){o(1g(a.U)==\'1f\'&&1g(a.W)==\'1f\'){8 w}8!7.1m(a)},1U:l(a){o(!7.1v(a)){8 w}o(a.U){9 A=a.K.4,D=a.U.4,P=7.K.4,N=7.W.4;9 b=(N[0]*(P[0]-A[0])+N[1]*(P[1]-A[1])+N[2]*(P[2]-A[2]))/(N[0]*D[0]+N[1]*D[1]+N[2]*D[2]);8 v.u([A[0]+D[0]*b,A[1]+D[1]*b,A[2]+D[2]*b])}1d o(a.W){9 c=7.W.2f(a.W).2q();9 N=7.W.4,A=7.K.4,O=a.W.4,B=a.K.4;9 d=S.1j(2,2),i=0;H(d.2y()){i++;d=S.u([[N[i%3],N[(i+1)%3]],[O[i%3],O[(i+1)%3]]])}9 e=d.2w().4;9 x=N[0]*A[0]+N[1]*A[1]+N[2]*A[2];9 y=O[0]*B[0]+O[1]*B[1]+O[2]*B[2];9 f=[e[0][0]*x+e[0][1]*y,e[1][0]*x+e[1][1]*y];9 g=[];2e(9 j=1;j<=3;j++){g.19((i==j)?0:f[(j+(5-i)%3)%3])}8 14.u(g,c)}},1r:l(a){9 P=a.4||a;9 A=7.K.4,N=7.W.4;9 b=(A[0]-P[0])*N[0]+(A[1]-P[1])*N[1]+(A[2]-(P[2]||0))*N[2];8 v.u([P[0]+N[0]*b,P[1]+N[1]*b,(P[2]||0)+N[2]*b])},1V:l(t,a){9 R=S.1R(t,a.U).4;9 C=a.1r(7.K).4;9 A=7.K.4,N=7.W.4;9 b=C[0],1E=C[1],1J=C[2],1w=A[0],18=A[1],1a=A[2];9 x=1w-b,y=18-1E,z=1a-1J;8 11.u([b+R[0][0]*x+R[0][1]*y+R[0][2]*z,1E+R[1][0]*x+R[1][1]*y+R[1][2]*z,1J+R[2][0]*x+R[2][1]*y+R[2][2]*z],[R[0][0]*N[0]+R[0][1]*N[1]+R[0][2]*N[2],R[1][0]*N[0]+R[1][1]*N[1]+R[1][2]*N[2],R[2][0]*N[0]+R[2][1]*N[1]+R[2][2]*N[2]])},1t:l(a){o(a.W){9 A=7.K.4,N=7.W.4;9 b=A[0],18=A[1],1a=A[2],2M=N[0],2L=N[1],2Q=N[2];9 c=7.K.1t(a).4;9 d=b+2M,2p=18+2L,2m=1a+2Q;9 Q=a.1r([d,2p,2m]).4;9 e=[Q[0]+(Q[0]-d)-c[0],Q[1]+(Q[1]-2p)-c[1],Q[2]+(Q[2]-2m)-c[2]];8 11.u(c,e)}1d o(a.U){8 7.1V(F.1A,a)}1d{9 P=a.4||a;8 11.u(7.K.1t([P[0],P[1],(P[2]||0)]),7.W)}},1Z:l(a,b,c){a=v.u(a);a=a.1N();o(a===w){8 w}b=v.u(b);b=b.1N();o(b===w){8 w}o(1g(c)==\'1f\'){c=w}1d{c=v.u(c);c=c.1N();o(c===w){8 w}}9 d=a.4[0],18=a.4[1],1a=a.4[2];9 e=b.4[0],1W=b.4[1],1X=b.4[2];9 f,1i;o(c!==w){9 g=c.4[0],2l=c.4[1],2t=c.4[2];f=v.u([(1W-18)*(2t-1a)-(1X-1a)*(2l-18),(1X-1a)*(g-d)-(e-d)*(2t-1a),(e-d)*(2l-18)-(1W-18)*(g-d)]);1i=f.1u();o(1i===0){8 w}f=v.u([f.4[0]/1i,f.4[1]/1i,f.4[2]/1i])}1d{1i=F.1x(e*e+1W*1W+1X*1X);o(1i===0){8 w}f=v.u([b.4[0]/1i,b.4[1]/1i,b.4[2]/1i])}7.K=a;7.W=f;8 7}};11.u=l(a,b,c){9 P=25 11();8 P.1Z(a,b,c)};11.2I=11.u(v.1j(3),v.k);11.2H=11.u(v.1j(3),v.i);11.2G=11.u(v.1j(3),v.j);11.36=11.2I;11.35=11.2H;11.3j=11.2G;9 $V=v.u;9 $M=S.u;9 $L=14.u;9 $P=11.u;',62,206,'||||elements|||this|return|var||||||||||||function|||if||length||||create|Vector|null|||||||||Math|nj|while||do|anchor||||||||Matrix||direction||normal||||kj|Plane|ni|abs|Line|ki|precision|Sylvester|A2|push|A3|map|els|else||undefined|typeof|contains|mod|Zero|D3|D2|isParallelTo|kp|distanceFrom|cols|dup|pointClosestTo|np|reflectionIn|modulus|intersects|A1|sqrt|isSquare|X2|PI|X3|angleFrom|mod1|C2|mod2|sin|cos|break|C3|toRightTriangular|false|Y3|to3D|E2|E1|E3|Rotation|Y2|Y1|intersectionWith|rotate|v12|v13|rank|setVectors|nc|sum|multiply|prototype|eql|new|setElements|case|each|PA3|PA2|part|new_element|round|for|cross|product|AD2|isSameSizeAs|add|isPerpendicularTo|v22|AN3|inspect|AD3|AN2|toUnitVector|PsubQ3|PsubQ2|v23|dot|divisor|inverse|true|isSingular|determinant|max|canMultiplyFromLeft|subtract|rows|col|random|ZX|YZ|XY|Random|join|N2|N1|D1|slice|default|N3|dimensions|switch|liesIn|translate|snapTo|augment|Diagonal|trace|indexOf|diagonal|transpose|minor|row|isAntiparallelTo|ZY|YX|acos|RotationZ|RotationY|liesOn|RotationX|inv|rk|tr|det|toDiagonalMatrix|toUpperTriangular|version|XZ'.split('|'),0,{}))
// gtUtils.js Libary
Matrix.Translation = function (v)
{
if (v.elements.length == 2) {
var r = Matrix.I(3);
r.elements[2][0] = v.elements[0];
r.elements[2][1] = v.elements[1];
return r;
}
if (v.elements.length == 3) {
var r = Matrix.I(4);
r.elements[0][3] = v.elements[0];
r.elements[1][3] = v.elements[1];
r.elements[2][3] = v.elements[2];
return r;
}
throw "Invalid length for Translation";
}
Matrix.prototype.flatten = function ()
{
var result = [];
if (this.elements.length == 0)
return [];
for (var j = 0; j < this.elements[0].length; j++)
for (var i = 0; i < this.elements.length; i++)
result.push(this.elements[i][j]);
return result;
}
Matrix.prototype.ensure4x4 = function()
{
if (this.elements.length == 4 &&
this.elements[0].length == 4)
return this;
if (this.elements.length > 4 ||
this.elements[0].length > 4)
return null;
for (var i = 0; i < this.elements.length; i++) {
for (var j = this.elements[i].length; j < 4; j++) {
if (i == j)
this.elements[i].push(1);
else
this.elements[i].push(0);
}
}
for (var i = this.elements.length; i < 4; i++) {
if (i == 0)
this.elements.push([1, 0, 0, 0]);
else if (i == 1)
this.elements.push([0, 1, 0, 0]);
else if (i == 2)
this.elements.push([0, 0, 1, 0]);
else if (i == 3)
this.elements.push([0, 0, 0, 1]);
}
return this;
};
Matrix.prototype.make3x3 = function()
{
if (this.elements.length != 4 ||
this.elements[0].length != 4)
return null;
return Matrix.create([[this.elements[0][0], this.elements[0][1], this.elements[0][2]],
[this.elements[1][0], this.elements[1][1], this.elements[1][2]],
[this.elements[2][0], this.elements[2][1], this.elements[2][2]]]);
};
Vector.prototype.flatten = function ()
{
return this.elements;
};
function mht(m) {
var s = "";
if (m.length == 16) {
for (var i = 0; i < 4; i++) {
s += "<span style='font-family: monospace'>[" + m[i*4+0].toFixed(4) + "," + m[i*4+1].toFixed(4) + "," + m[i*4+2].toFixed(4) + "," + m[i*4+3].toFixed(4) + "]</span><br>";
}
} else if (m.length == 9) {
for (var i = 0; i < 3; i++) {
s += "<span style='font-family: monospace'>[" + m[i*3+0].toFixed(4) + "," + m[i*3+1].toFixed(4) + "," + m[i*3+2].toFixed(4) + "]</font><br>";
}
} else {
return m.toString();
}
return s;
}
function makeLookAt(ex, ey, ez,
cx, cy, cz,
ux, uy, uz)
{
var eye = $V([ex, ey, ez]);
var center = $V([cx, cy, cz]);
var up = $V([ux, uy, uz]);
var mag;
var z = eye.subtract(center).toUnitVector();
var x = up.cross(z).toUnitVector();
var y = z.cross(x).toUnitVector();
var m = $M([[x.e(1), x.e(2), x.e(3), 0],
[y.e(1), y.e(2), y.e(3), 0],
[z.e(1), z.e(2), z.e(3), 0],
[0, 0, 0, 1]]);
var t = $M([[1, 0, 0, -ex],
[0, 1, 0, -ey],
[0, 0, 1, -ez],
[0, 0, 0, 1]]);
return m.x(t);
}
function makePerspective(fovy, aspect, znear, zfar)
{
var ymax = znear * Math.tan(fovy * Math.PI / 360.0);
var ymin = -ymax;
var xmin = ymin * aspect;
var xmax = ymax * aspect;
return makeFrustum(xmin, xmax, ymin, ymax, znear, zfar);
}
function makeFrustum(left, right,
bottom, top,
znear, zfar)
{
var X = 2*znear/(right-left);
var Y = 2*znear/(top-bottom);
var A = (right+left)/(right-left);
var B = (top+bottom)/(top-bottom);
var C = -(zfar+znear)/(zfar-znear);
var D = -2*zfar*znear/(zfar-znear);
return $M([[X, 0, A, 0],
[0, Y, B, 0],
[0, 0, C, D],
[0, 0, -1, 0]]);
}
function makeOrtho(left, right, bottom, top, znear, zfar)
{
var tx = - (right + left) / (right - left);
var ty = - (top + bottom) / (top - bottom);
var tz = - (zfar + znear) / (zfar - znear);
return $M([[2 / (right - left), 0, 0, tx],
[0, 2 / (top - bottom), 0, ty],
[0, 0, -2 / (zfar - znear), tz],
[0, 0, 0, 1]]);
}
// End of Libaries
function initGL(canvas) {
try {
gl = canvas.getContext("experimental-webgl");
gl.viewportWidth = canvas.width;
gl.viewportHeight = canvas.height;
} catch(e) {
}
if (!gl) {
alert("Could not initialise WebGL");
}
}
function getShader(gl, id) {
var shaderScript = document.getElementById(id);
if (!shaderScript) {
return null;
}
var str = "";
var k = shaderScript.firstChild;
while (k) {
if (k.nodeType == 3) {
str += k.textContent;
}
k = k.nextSibling;
}
var shader;
if (shaderScript.type == "x-shader/x-fragment") {
shader = gl.createShader(gl.FRAGMENT_SHADER);
} else if (shaderScript.type == "x-shader/x-vertex") {
shader = gl.createShader(gl.VERTEX_SHADER);
} else {
return null;
}
gl.shaderSource(shader, str);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
alert(gl.getShaderInfoLog(shader));
return null;
}
return shader;
}
function initShaders() {
var fragmentShader = getShader(gl, "shader-fs");
var vertexShader = getShader(gl, "shader-vs");
shaderProgram = gl.createProgram();
gl.attachShader(shaderProgram, vertexShader);
gl.attachShader(shaderProgram, fragmentShader);
gl.linkProgram(shaderProgram);
if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
alert("Could not initialise shaders");
}
gl.useProgram(shaderProgram);
shaderProgram.vertexPositionAttribute
= gl.getAttribLocation(shaderProgram, "aVertexPosition");
gl.enableVertexAttribArray(shaderProgram.vertexPositionAttribute);
shaderProgram.vertexColorAttribute
= gl.getAttribLocation(shaderProgram, "aVertexColor");
gl.enableVertexAttribArray(shaderProgram.vertexColorAttribute);
shaderProgram.pMatrixUniform
= gl.getUniformLocation(shaderProgram, "uPMatrix");
shaderProgram.mvMatrixUniform
= gl.getUniformLocation(shaderProgram, "uMVMatrix");
}
function mvPushMatrix(m) {
if (m) {
mvMatrixStack.push(m.dup());
mvMatrix = m.dup();
} else {
mvMatrixStack.push(mvMatrix.dup());
}
}
function mvPopMatrix() {
if (mvMatrixStack.length == 0) {
throw "Invalid popMatrix!";
}
mvMatrix = mvMatrixStack.pop();
return mvMatrix;
}
function loadIdentity() {
mvMatrix = Matrix.I(4);
}
function multMatrix(m) {
mvMatrix = mvMatrix.x(m);
}
function mvTranslate(v) {
var m = Matrix.Translation($V([v[0], v[1], v[2]])).ensure4x4();
multMatrix(m);
}
function mvRotate(ang, v) {
var arad = ang * Math.PI / 180.0;
var m = Matrix.Rotation(arad, $V([v[0], v[1], v[2]])).ensure4x4();
multMatrix(m);
}
var pMatrix;
function perspective(fovy, aspect, znear, zfar) {
pMatrix = makePerspective(fovy, aspect, znear, zfar);
}
function setMatrixUniforms() {
gl.uniformMatrix4fv(shaderProgram.pMatrixUniform,
false, new Float32Array(pMatrix.flatten()));
gl.uniformMatrix4fv(shaderProgram.mvMatrixUniform,
false, new Float32Array(mvMatrix.flatten()));
}
function compareXValue(array1, array2)
{
var value1 = array1[0];
var value2 = array2[0];
if (value1 > value2) return 1;
if (value1 < value2) return -1;
return 0;
}
function setupShaders(){
var headID = document.getElementsByTagName("head")[0];
var fsScript = document.createElement('script');
fsScript.id="shader-fs";
fsScript.type = 'x-shader/x-fragment';
fsScript.text = "#ifdef GL_ES\n\
precision highp float;\n\
#endif\n\
varying vec4 vColor;\n\
void main(void) {\n\
gl_FragColor = vColor;\n\
}";
var vsScript = document.createElement('script');
vsScript.id="shader-vs";
vsScript.type = 'x-shader/x-vertex';
vsScript.text = "attribute vec3 aVertexPosition;\n\
attribute vec4 aVertexColor;\n\
\n\
uniform mat4 uMVMatrix;\n\
uniform mat4 uPMatrix;\n\
\n\
varying vec4 vColor;\n\
\n\
void main(void) {\n\
gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);\n\
vColor = aVertexColor;\n\
}";
headID.appendChild(vsScript);
headID.appendChild(fsScript);
initShaders();
}
function setupCanvas(){
canvas1 = document.getElementsByTagName("canvas")[1];
canvas1.style.position = "absolute";
canvas1.style.zIndex = 10;
canvas1.style.opacity = 0.5;
canvas = document.getElementsByTagName("canvas")[0];
canvas.style.zIndex = 0;
initGL(canvas);
}
function setupGL(){
setupCanvas();
setupShaders();
gl.clearColor(1.0, 1.0, 1.0, 1.0);
gl.clearDepth(1.0);
gl.enable(gl.DEPTH_TEST);
gl.depthFunc(gl.LEQUAL);
gl.viewport(0, 0, gl.viewportWidth, gl.viewportHeight);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
perspective(45, gl.viewportWidth / gl.viewportHeight, 0.1, 100.0);
loadIdentity();
var uTop = 2.478;
var uLeft = -uTop;
mvTranslate([uLeft,uTop, -10.0])
mvPushMatrix();
}
// Drawing functions
function drawPolygon(pixelVertices,color)
{
var factor;
var glWidth = 4.92;
var vertices = new Float32Array(1000);
var polygonColors = new Float32Array(1000);
var vl = 0;
if(canvas.width>=canvas.height) factor = glWidth/canvas.height;
else factor = glWidth/canvas.width;
for(var i=0;i<pixelVertices.length;i++){
pixelVertices[i] = (pixelVertices[i])*factor;
if (i%2){
vertices[vl] = -pixelVertices[i];
vl++;
vertices[vl] = (4.0);
}
else
{
vertices[vl] = (pixelVertices[i]);
}
vl++;
}
vertexPositionBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vertexPositionBuffer);
gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
vertexPositionBuffer.itemSize = 3;
vertexPositionBuffer.numItems = vl / 3.0;
vertexColorBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vertexColorBuffer);
for(var i=0;i<(vl / 3.0)*4;i+=4){
polygonColors[i] = color[0];
polygonColors[i+1] = color[1];
polygonColors[i+2] = color[2];
polygonColors[i+3] = color[3];
}
gl.bufferData(gl.ARRAY_BUFFER, polygonColors, gl.STATIC_DRAW);
vertexColorBuffer.itemSize = 4;
vertexColorBuffer.numItems = vl / 3.0;
gl.bindBuffer(gl.ARRAY_BUFFER, vertexPositionBuffer);
gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute,
vertexPositionBuffer.itemSize, gl.FLOAT, false, 0, 0);
gl.bindBuffer(gl.ARRAY_BUFFER, vertexColorBuffer);
gl.vertexAttribPointer(shaderProgram.vertexColorAttribute,
vertexColorBuffer.itemSize, gl.FLOAT, false, 0, 0);
setMatrixUniforms();
gl.drawArrays(gl.TRIANGLE_STRIP, 0, vl / 3.0);
}
function drawLine(left1,top1,left2,top2,width,color)
{
if(top1 <= top2){
var temp1 = left1;
var temp2 = top1;
left1 = left2;
top1 = top2;
left2 = temp1;
top2 = temp2;
}
var length = Math.sqrt(((top2-top1)*(top2-top1))+((left2-left1)*(left2-left1)));
var vHeight = top1-top2;
var hWidth = left1-left2;
var deg = 180/Math.PI;
var angle = Math.atan(vHeight/hWidth);
var angle2 = ((Math.PI/2)-angle);
var height2 = Math.sin(angle2)*(width/2);
var width2 = Math.sqrt(((width/2)*(width/2))-(height2*height2));
if(angle*deg<0)
{
var topRightX = left1-(width2);
var topRightY = top1-height2;
var topLeftX = left1+(width2);
var topLeftY = top1+height2;
var bottomRightX = left2-(width2);
var bottomRightY = top2-height2;
var bottomLeftX = left2+(width2);
var bottomLeftY = top2+height2;
}
else
{
var topRightX = left1-(width2);
var topRightY = top1+height2;
var topLeftX = left1+(width2);
var topLeftY = top1-height2;
var bottomRightX = left2-(width2);
var bottomRightY = top2+height2;
var bottomLeftX = left2+(width2);
var bottomLeftY = top2-height2;
}
var pvertices = new Float32Array([
topRightX, topRightY,
topLeftX, topLeftY,
bottomRightX, bottomRightY,
bottomLeftX, bottomLeftY
]);
drawPolygon(pvertices,color);
}
function drawSquare(left,top,width,height,rotation,color){drawSquareComplex(left,top,width,height,rotation,height,width,color);}
function drawSquareComplex(left,top,width,height,rotation,vHeight,hWidth,color){
var diam = width/2;
var topOffset = Math.round(Math.sin(rotation)*diam);
var leftOffset = Math.round(Math.cos(rotation)*diam);
drawLine(left-leftOffset,top-topOffset,left+leftOffset,top+topOffset,height,color);
}
function drawDiamond(left,top,width,height,color)
{
var halfWidth = width/2;
var halfHeight = height/2;
var pvertices = new Float32Array(8);
pvertices[0] = left;
pvertices[1] = top-halfHeight;
pvertices[2] = left-halfWidth;
pvertices[3] = top;
pvertices[4] = left+halfWidth;
pvertices[5] = top;
pvertices[6] = left;
pvertices[7] = top+halfHeight;
drawPolygon(pvertices,color);
}
function drawTriang(left,top,width,height,rotation,color)
{
var halfWidth = width/2;
var halfHeight = height/2;
var pvertices = new Float32Array(6);
pvertices[0] = 0;
pvertices[1] = 0-halfHeight;
pvertices[2] = 0-halfWidth;
pvertices[3] = 0+halfHeight;
pvertices[4] = 0+halfWidth;
pvertices[5] = 0+halfHeight;
var j = 0;
for (i=0;i<3;i++)
{
var tempX = pvertices[j];
var tempY = pvertices[j+1];
pvertices[j] = (Math.cos(rotation)*tempX)-(Math.sin(rotation)*tempY)
pvertices[j] = Math.round(pvertices[j]+left);
j++;
pvertices[j] = (Math.sin(rotation)*tempX)+(Math.cos(rotation)*tempY)
pvertices[j] = Math.round(pvertices[j]+top);
j++;
}
drawPolygon(pvertices,color);
}
function drawCircle(left,top,width,color){drawCircleDim(left,top,width,width,color)};
function drawCircleDim(left,top,width,height,color){
left = Math.round(left);
top = Math.round(top);
width = Math.round(width);
height = Math.round(height);
var w = Math.round(width/2);
var h = Math.round(height/2);
var numSections;
if(width>height)numSections = width*2;
else numSections = height*2;
if(numSections>33)numSections = 33;
if(numSections<10)numSections = 10;
var delta_theta = 2.0 * Math.PI / numSections
var theta = 0
if(circleCoords[w][h]==undefined)
{
//alert("make circle "+r);
circleCoords[w][h] = new Array(numSections);
circleCoords[w][h] = new Array(numSections);
for (i = 0; i < numSections ; i++) {
circleCoords[w][h][i] = new Array(2);
x = (w * Math.cos(theta));
y = (h * Math.sin(theta));
x = Math.round(x*1000)/1000
y = Math.round(y*1000)/1000
circleCoords[w][h][i][1] = x;
circleCoords[w][h][i][0] = y;
theta += delta_theta
}
circleCoords[w][h].sort(compareXValue);
for(var i = 0;i<numSections-1;i++)
{
if(circleCoords[w][h][i][0] == circleCoords[w][h][i+1][0] && circleCoords[w][h][i][1]<circleCoords[w][h][i+1][1])
{
temp = circleCoords[w][h][i];
circleCoords[w][h][i] = circleCoords[w][h][i+1];
circleCoords[w][h][i+1] = temp;
}
}
}
var j = 0;
var pvertices = new Float32Array(numSections*2);
for (i=0;i<numSections;i++)
{
pvertices[j] = circleCoords[w][h][i][1]+left;
j++;
pvertices[j] = circleCoords[w][h][i][0]+top;
j++;
}
drawPolygon(pvertices,color);
}
function drawLineArrow(left1,top1,left2,top2,width,color)
{
var opp = top1-top2;
var adj = left1-left2;
var angle = Math.atan(opp/adj)+Math.PI/2;
if(left1>left2 )angle+=Math.PI;
drawLine(left1,top1,left2,top2,width,color);
var triLeft = left1-Math.round(adj/2);
var triTop = top1-Math.round(opp/2);
drawTriang(triLeft,triTop,20,20,angle,color);
}
function stringPixelLength(string)
{
var code;
var width = 0;
for(i=0;i<string.length;i++)
{
code = string.charCodeAt(i)-32;
width += hersheyFont[code][1];
}
return width;
}
function printChar(left,top,character,color,thickness,size)
{
var code = character.charCodeAt(0)-32;
var verticesNeeded = hersheyFont[code][0];
var width = hersheyFont[code][1];
var lef1;
var top1;
var left2;
var top2;
var j = 0;
var i = 2;
var fHeight = 10*size;
while(i<(verticesNeeded*2)+2)
{
j++;
left1 = hersheyFont[code][i]*size+left;
top1 = (fHeight-hersheyFont[code][i+1]*size)+top;
if(hersheyFont[code][i] != -1 && hersheyFont[code][i+1] != -1)
{
if(i>2 && hersheyFont[code][i-1] != -1 && hersheyFont[code][i-2] != -1)
{
drawLine(left2,top2,left1,top1,thickness,color);
}
if(hersheyFont[code][i+2] != -1 && hersheyFont[code][i+3] != -1)
{
left2 = hersheyFont[code][i+2]*size+left;
top2 = (fHeight-hersheyFont[code][i+3]*size)+top;
drawLine(left1,top1,left2,top2,thickness,color);
}
i+=4;
}
else
{
i+=2;
}
}
return width*size;
}
function printString(left,top,string,color,thickness,size)
{
var wordArray = string.split(" ");
var numWords = wordArray.length;
var length = (stringPixelLength(string)/2)*size;
var offset = -length;
for(i=0;i<string.length;i++)
{
offset += printChar(left+offset,top,string[i],color,thickness,size);
}
}
//Styling functions
function getColor(index)
{
var temp = new Array(4);
temp = [colors[index][0],colors[index][1],colors[index][2],1.0]
return temp;
}
function flowTerminator(left,top,width,height,color,strokeSize,strokeColor)
{
var sOff = strokeSize*2;
flowTerminatorNoStroke(left,top,width,height,strokeColor);
flowTerminatorNoStroke(left,top,width-sOff,height-sOff,color);
}
function flowTerminatorNoStroke(left,top,width,height,color)
{
var cWidth = height;
var cOff = (width/2)-(cWidth/2);
drawCircle(left-cOff,top,cWidth,color);
drawCircle(left+cOff,top,cWidth,color);
drawSquare(left,top,cOff*2,height,0,color);
}
function flowProcess(left,top,width,height,color,strokeSize,strokeColor)
{
var sOff = strokeSize*2;
drawSquare(left,top,width,height,0,strokeColor);
drawSquare(left,top,width-sOff,height-sOff,0,color);
}
function diamondStrokeAlgorithm(width, height, strokeSize)
{
var angle1 = Math.atan(height/width);
var angle2 = Math.PI/2 - angle1;
var opp = strokeSize*Math.sin(angle2);
var width1Sq = (strokeSize*strokeSize)-(opp*opp);
var width1 = Math.sqrt(width1Sq);
var width2 = opp/(Math.tan(angle1));
var fWidth = (width1+width2)*2;
return fWidth;
}
function flowDecision(left,top,width,height,color,strokeSize,strokeColor)
{
var wOff = diamondStrokeAlgorithm(width/2, height/2, strokeSize);
var hOff = diamondStrokeAlgorithm(height/2, width/2, strokeSize);
drawDiamond(left,top,width,height,strokeColor);
drawDiamond(left,top,width-wOff,height-hOff,color);
}
// BLACK 0
// WHITE 1
// RED 2
// GREEN 3
// BLUE 4
// YELLOW 5
// PINK 6
// GREY 7
function drawEdge(left1,top1, left2,top2,style){
switch(style){
case 100: // FLOW CHART
// Draw line with Arrow at end
drawLineArrow(left1,top1,left2,top2,2,getColor(0));
break;
case -100:
// Draw line with Arrow at end - HIGHLIGHTED
drawLineArrow(left1,top1,left2,top2,2,getColor(6));
break;
case -10:
drawLine(left1,top1,left2,top2,2,getColor(6));
break;
default:
//Default edge style: black line
drawLine(left1,top1,left2,top2,2,getColor(0));
}
}
function drawVertex(left,top,width,height,style,text,c1,c2,c3)
{
var flowStrokeHighColor = getColor(5);
var flowStrokeColor = getColor(0);
var flowColor = getColor(7);
var flowStrokeSize = 2;
var flowTextColor = getColor(0);
var customColor = [c1,c2,c3,1.0];
switch(style){
case 100: // (100 - 199) FLOW CHART SYMBOLS
// Terminator, start stop
flowTerminator(left,top,width,height,flowColor,flowStrokeSize,flowStrokeColor);
printString(left,top,text,flowTextColor,2,0.75);
break;
case -100:
// Terminator, start stop - HIGHLIGHTED
flowTerminator(left,top,width,height,flowColor,flowStrokeSize,flowStrokeHighColor);
printString(left,top,text,flowTextColor,2,0.75);
break;
case 101:
// Process, process or action step
flowProcess(left,top,width,height,flowColor,flowStrokeSize,flowStrokeColor);
printString(left,top,text,flowTextColor,2,0.75);
break;
case -101:
// Process, process or action step - HIGHLIGHTED
flowProcess(left,top,width,height,flowColor,flowStrokeSize,flowStrokeHighColor);
printString(left,top,text,flowTextColor,2,0.75);
break;
case 102:
// Decision, question or branch
flowDecision(left,top,width,height,flowColor,flowStrokeSize,flowStrokeColor);
printString(left,top,text,flowTextColor,2,0.75);
break;
case -102:
// Decision, question or branch - HIGHLIGHTED
flowDecision(left,top,width,height,flowColor,flowStrokeSize,flowStrokeHighColor);
printString(left,top,text,flowTextColor,2,0.75);
break;
case 5:
// Circle
var sOff = flowStrokeSize*2;
drawCircleDim(left,top,width,height,flowStrokeColor);
drawCircleDim(left,top,width-sOff,height-sOff,customColor);
printString(left,top,text,flowTextColor,2,0.75);
break;
case -5:
// Circle
var sOff = flowStrokeSize*2;
drawCircleDim(left,top,width,height,flowStrokeHighColor);
drawCircleDim(left,top,width-sOff,height-sOff,customColor);
printString(left,top,text,flowTextColor,2,0.75);
break;
case 1:
// Smiley Face
drawCircle(left,top,width,5);
drawCircle(left,top,width*0.7,0);
drawCircle(left,top,width*0.5,5);
drawSquare(left,top,width*0.7,width*0.2,0,5);
drawSquare(left,top-width*0.1,width*0.70,width*0.2,0,5);
drawSquare(left,top-width*0.2,width*0.60,width*0.2,0,5);
drawSquare(left,top-width*0.3,width*0.40,width*0.1,0,5);
drawCircle(left-(width*0.20),top-(width*0.2),width*0.2,0);
drawCircle(left+(width*0.20),top-(width*0.2),width*0.2,0);
break;
case 2:
// Bart Simpson
drawSquare(left,top,width*0.9,width*1.1,0,0);
drawSquare(left,top,width*0.85,width*1.05,0,5);
drawSquare(left-width*0.27,top+width*0.2,width*0.35,width*1.2,0,0);
drawSquare(left-width*0.27,top+width*0.2,width*0.31,width*1.16,0,5);
drawCircle(left+width*0.15,top+width*0.45,width*0.6,0);
drawCircle(left+width*0.15,top+width*0.45,width*0.545,5);
drawSquare(left,top+width*0.27,width*0.85,width*0.5,0,5);
drawSquare(left-width*0.31,top-width*0.55,width*0.2,width*0.2,(Math.PI/4),0)
drawSquare(left-width*0.31,top-width*0.55,width*0.16,width*0.16,(Math.PI/4),5)
drawSquare(left-width*0.06,top-width*0.55,width*0.2,width*0.2,(Math.PI/4),0)
drawSquare(left-width*0.06,top-width*0.55,width*0.16,width*0.16,(Math.PI/4),5)
drawSquare(left+width*0.19,top-width*0.55,width*0.2,width*0.2,(Math.PI/4),0)
drawSquare(left+width*0.19,top-width*0.55,width*0.16,width*0.16,(Math.PI/4),5)
drawSquare(left+width*0.32,top-width*0.55,width*0.2,width*0.2,(Math.PI/4),0)
drawSquare(left+width*0.32,top-width*0.55,width*0.16,width*0.16,(Math.PI/4),5)
drawSquare(left,top-width*0.3,width*0.85,width*0.5,0,5);
drawSquare(left,top-width*0.23,width*0.85,width*0.5,0,5);
drawSquare(left-width*0.15,top+width*0.53,width*0.15,width*0.02,-(Math.PI/5),0)
drawCircle(left+width*0.3,top-width*0.1,width*0.4,0);
drawCircle(left+width*0.3,top-width*0.1,width*0.35,1);
drawCircle(left+width*0.3,top+width*0.1,width*0.2,0);
drawCircle(left+width*0.3,top+width*0.1,width*0.15,5);
drawSquare(left+width*0.2,top+width*0.1,width*0.2,width*0.2,0,0);
drawSquare(left+width*0.2,top+width*0.1,width*0.2,width*0.15,0,5);
drawCircle(left+width*0.05,top-width*0.1,width*0.4,0);
drawCircle(left+width*0.05,top-width*0.1,width*0.35,1);
drawCircle(left+width*0.3,top-width*0.1,width*0.05,0);
drawCircle(left+width*0.05,top-width*0.1,width*0.05,0);
break;
case -10:
drawCircleDim(left,top,width,height,6);
break;
default:
// Default vertex style: black circle
drawCircleDim(left,top,width,height,0);
}
}
function drawGraph() {
setupGL();
for(var i=0;i<edgeNumber;i++)
{
var left1 = parseInt(edgeArray[i][0]);
var top1 = parseInt(edgeArray[i][1]);
var left2 = parseInt(edgeArray[i][2]);
var top2 = parseInt(edgeArray[i][3]);
var style = parseInt(edgeArray[i][4]);
drawEdge( left1,top1,left2,top2,style);
}
for(var i=0;i<verticeNumber;i++)
{
var left = parseInt(verticeArray[i][0]);
var top = parseInt(verticeArray[i][1]);
var width = parseInt(verticeArray[i][2]);
var height = parseInt(verticeArray[i][3]);
var style = parseInt(verticeArray[i][4]);
var text = verticeArray[i][5];
var c1 = verticeArray[i][6];
var c2 = verticeArray[i][7];
var c3 = verticeArray[i][8];
drawVertex(left,top,width,height,style,text,c1,c2,c3);
}
}
drawGraph();
}-*/;
private static native int setupJSNI()/*-{
$wnd.edgeNumber = 0;
$wnd.verticeNumber = 0;
$wnd.edgeArray = new Array(1000);
for(i=0;i<edgeArray.length;i++)edgeArray[i] = new Array(5);
$wnd.verticeArray = new Array(1000);
for(i=0;i<verticeArray.length;i++)verticeArray[i] = new Array(9);
}-*/;
private static native int addEdge(double startX,double startY,double endX,double endY,int style)/*-{
edgeArray[edgeNumber][0] = parseInt(startX);
edgeArray[edgeNumber][1] = parseInt(startY);
edgeArray[edgeNumber][2] = parseInt(endX);
edgeArray[edgeNumber][3] = parseInt(endY);
edgeArray[edgeNumber][4] = parseInt(style);
edgeNumber++;
}-*/;
private static native int addVertice(double centreX,double centreY,double width,double height,int style,String label,double c1,double c2,double c3)/*-{
verticeArray[verticeNumber][0] = parseInt(centreX);
verticeArray[verticeNumber][1] = parseInt(centreY);
verticeArray[verticeNumber][2] = parseInt(width);
verticeArray[verticeNumber][3] = parseInt(height);
verticeArray[verticeNumber][4] = parseInt(style);
verticeArray[verticeNumber][5] = label;
verticeArray[verticeNumber][6] = c1;
verticeArray[verticeNumber][7] = c1;
verticeArray[verticeNumber][8] = c1;
verticeNumber++;
}-*/;
private static native int webglCheck()/*-{
if (typeof Float32Array != "undefined")return 1;
return 0;
}-*/;
public void renderGraph(GWTCanvas canvas, Collection<EdgeDrawable> edges,
Collection<VertexDrawable> vertices) {
// Do a (kind of reliable) check for webgl
if (webglCheck() == 1) { // Can do WebGL
// At the moment coordinates are passed to JavaScript as comma
// separated strings // This will most probably change in the
// future.
setupJSNI();
String edgesString = "";
String veticesString = "";
String separator = ",";
String label = "";
int vertexStyle;
int edgeStyle;
for (EdgeDrawable thisEdge : edges) {
double startX = (thisEdge.getStartX() + offsetX)*zoom;
double startY = (thisEdge.getStartY() + offsetY)*zoom;
double endX = (thisEdge.getEndX() + offsetX)*zoom;
double endY = (thisEdge.getEndY() + offsetY)*zoom;
//edgeStyle = thisEdge.getStyle();
edgeStyle = 100;
if(thisEdge.isHilighted())edgeStyle = -100;
addEdge(startX,startY,endX,endY,edgeStyle);
}
for (VertexDrawable thisVertex : vertices) {
double centreX = (thisVertex.getCenterX() + offsetX)*zoom;
double centreY = (thisVertex.getCenterY() + offsetY)*zoom;
double width = (0.5 * thisVertex.getWidth())*zoom;
double height = (0.5 * thisVertex.getHeight())*zoom;
vertexStyle = thisVertex.getStyle();
switch (vertexStyle) {
case VertexDrawable.STROKED_TERM_STYLE:
vertexStyle = 100;
break;
case VertexDrawable.STROKED_SQUARE_STYLE:
vertexStyle = 101;
break;
case VertexDrawable.STROKED_DIAMOND_STYLE:
vertexStyle = 102;
break;
default:
vertexStyle = 100;
break;
}
label = thisVertex.getLabel();
int[] customColor = {0,0,0};
if(thisVertex.getStyle() == VertexDrawable.COLORED_FILLED_CIRCLE)
{
vertexStyle = 5;
customColor = thisVertex.getColor();
}
if(thisVertex.isHilighted())vertexStyle = -vertexStyle;
+ runJavascript("alert("+vertexStyle+")");
addVertice(centreX,centreY,width,height,vertexStyle,label,customColor[0],customColor[1],customColor[2]);
}
// JSNI method used to draw webGL graph version
drawGraph3D();
}
else {
// Cant do webGL so draw on 2d Canvas
renderGraph2d(canvas, edges, vertices);
}
}
public void renderGraph2d(GWTCanvas canvas, Collection<EdgeDrawable> edges,
Collection<VertexDrawable> vertices) {
canvas.setLineWidth(1);
canvas.setStrokeStyle(Color.BLACK);
canvas.setFillStyle(Color.BLACK);
canvas.setFillStyle(Color.WHITE);
canvas.fillRect(0, 0, 2000, 2000);
canvas.setFillStyle(Color.BLACK);
drawGraph(edges, vertices, canvas);
}
// Draws a single vertex, currently only draws circular nodes
private void drawVertex(VertexDrawable vertex, GWTCanvas canvas) {
double centreX = (vertex.getLeft() + 0.5 * vertex.getWidth() + offsetX) * zoom;
double centreY = (vertex.getTop() + 0.5 * vertex.getHeight() + offsetY) * zoom;
double radius = (0.25 * vertex.getWidth()) * zoom;
canvas.moveTo(centreX, centreY);
canvas.beginPath();
canvas.arc(centreX, centreY, radius, 0, 360, false);
canvas.closePath();
canvas.stroke();
canvas.fill();
}
// Draws a line from coordinates to other coordinates
private void drawEdge(EdgeDrawable edge, GWTCanvas canvas) {
double startX = (edge.getStartX() + offsetX)*zoom;
double startY = (edge.getStartY() + offsetY)*zoom;
double endX = (edge.getEndX() + offsetX)*zoom;
double endY = (edge.getEndY() + offsetY)*zoom;
canvas.beginPath();
canvas.moveTo(startX, startY);
canvas.lineTo(endX, endY);
canvas.closePath();
canvas.stroke();
}
// Takes collections of edges and vertices and draws a graph on a specified
// canvas.
private void drawGraph(Collection<EdgeDrawable> edges,
Collection<VertexDrawable> vertices, GWTCanvas canvas) {
for (EdgeDrawable thisEdge : edges) {
drawEdge(thisEdge, canvas);
}
for (VertexDrawable thisVertex : vertices) {
drawVertex(thisVertex, canvas);
}
}
// set offset in the event of a pan
public void setOffset(int x, int y) {
offsetX = x;
offsetY = y;
}
// getters for offsets
public int getOffsetX() {
return offsetX;
}
public int getOffsetY() {
return offsetY;
}
//set zoom
public void setZoom(double z) {
zoom = z;
}
public double getZoom(){
return zoom;
}
}
| true | true | private static native void drawGraph3D() /*-{
var circleCoords = new Array(1000);
for(i=0;i<circleCoords.length;i++)circleCoords[i] = new Array(1000);
var gl;
var shaderProgram;
var mvMatrix;
var mvMatrixStack = [];
var colors = [[0.0, 0.0, 0.0], // BLACK 0
[1.0, 1.0, 1.0], // WHITE 1
[1.0, 0.0, 0.0], // RED 2
[0.0, 1.0, 0.0], // GREEN 3
[0.0, 0.0, 1.0], // BLUE 4
[1.0, 1.0, 0.0], // YELLOW 5
[1.0, 0.317, 1.0], // PINK 6
[0.5, 0.5, 0.5], // GREY 7
];
var hersheyFont=[
[0,16,//Ascii32
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[8,10,//Ascii33
5,21,5,7,-1,-1,5,2,4,1,5,0,6,1,5,2,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[5,16,//Ascii34
4,21,4,14,-1,-1,12,21,12,14,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[11,21,//Ascii35
11,25,4,-7,-1,-1,17,25,10,-7,-1,-1,4,12,18,12,-1,-1,3,6,17,6,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[26,20,//Ascii36
8,25,8,-4,-1,-1,12,25,12,-4,-1,-1,17,18,15,20,12,21,8,21,5,20,3,
18,3,16,4,14,5,13,7,12,13,10,15,9,16,8,17,6,17,3,15,1,12,0,
8,0,5,1,3,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[31,24,//Ascii37
21,21,3,0,-1,-1,8,21,10,19,10,17,9,15,7,14,5,14,3,16,3,18,4,
20,6,21,8,21,10,20,13,19,16,19,19,20,21,21,-1,-1,17,7,15,6,14,4,
14,2,16,0,18,0,20,1,21,3,21,5,19,7,17,7,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[34,26,//Ascii38
23,12,23,13,22,14,21,14,20,13,19,11,17,6,15,3,13,1,11,0,7,0,5,
1,4,2,3,4,3,6,4,8,5,9,12,13,13,14,14,16,14,18,13,20,11,21,
9,20,8,18,8,16,9,13,11,10,16,3,18,1,20,0,22,0,23,1,23,2,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[7,10,//Ascii39
5,19,4,20,5,21,6,20,6,18,5,16,4,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[10,14,//Ascii40
11,25,9,23,7,20,5,16,4,11,4,7,5,2,7,-2,9,-5,11,-7,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[10,14,//Ascii41
3,25,5,23,7,20,9,16,10,11,10,7,9,2,7,-2,5,-5,3,-7,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[8,16,//Ascii42
8,21,8,9,-1,-1,3,18,13,12,-1,-1,13,18,3,12,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[5,26,//Ascii43
13,18,13,0,-1,-1,4,9,22,9,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[8,10,//Ascii44
6,1,5,0,4,1,5,2,6,1,6,-1,5,-3,4,-4,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[2,26,//Ascii45
4,9,22,9,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[5,10,//Ascii46
5,2,4,1,5,0,6,1,5,2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[2,22,//Ascii47
20,25,2,-7,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[17,20,//Ascii48
9,21,6,20,4,17,3,12,3,9,4,4,6,1,9,0,11,0,14,1,16,4,17,
9,17,12,16,17,14,20,11,21,9,21,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[4,20,//Ascii49
6,17,8,18,11,21,11,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[14,20,//Ascii50
4,16,4,17,5,19,6,20,8,21,12,21,14,20,15,19,16,17,16,15,15,13,13,
10,3,0,17,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[15,20,//Ascii51
5,21,16,21,10,13,13,13,15,12,16,11,17,8,17,6,16,3,14,1,11,0,8,
0,5,1,4,2,3,4,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[6,20,//Ascii52
13,21,3,7,18,7,-1,-1,13,21,13,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[17,20,//Ascii53
15,21,5,21,4,12,5,13,8,14,11,14,14,13,16,11,17,8,17,6,16,3,14,
1,11,0,8,0,5,1,4,2,3,4,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[23,20,//Ascii54
16,18,15,20,12,21,10,21,7,20,5,17,4,12,4,7,5,3,7,1,10,0,11,
0,14,1,16,3,17,6,17,7,16,10,14,12,11,13,10,13,7,12,5,10,4,7,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[5,20,//Ascii55
17,21,7,0,-1,-1,3,21,17,21,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[29,20,//Ascii56
8,21,5,20,4,18,4,16,5,14,7,13,11,12,14,11,16,9,17,7,17,4,16,
2,15,1,12,0,8,0,5,1,4,2,3,4,3,7,4,9,6,11,9,12,13,13,
15,14,16,16,16,18,15,20,12,21,8,21,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[23,20,//Ascii57
16,14,15,11,13,9,10,8,9,8,6,9,4,11,3,14,3,15,4,18,6,20,9,
21,10,21,13,20,15,18,16,14,16,9,15,4,13,1,10,0,8,0,5,1,4,3,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[11,10,//Ascii58
5,14,4,13,5,12,6,13,5,14,-1,-1,5,2,4,1,5,0,6,1,5,2,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[14,10,//Ascii59
5,14,4,13,5,12,6,13,5,14,-1,-1,6,1,5,0,4,1,5,2,6,1,6,
-1,5,-3,4,-4,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[3,24,//Ascii60
20,18,4,9,20,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[5,26,//Ascii61
4,12,22,12,-1,-1,4,6,22,6,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[3,24,//Ascii62
4,18,20,9,4,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[20,18,//Ascii63
3,16,3,17,4,19,5,20,7,21,11,21,13,20,14,19,15,17,15,15,14,13,13,
12,9,10,9,7,-1,-1,9,2,8,1,9,0,10,1,9,2,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[55,27,//Ascii64
18,13,17,15,15,16,12,16,10,15,9,14,8,11,8,8,9,6,11,5,14,5,16,
6,17,8,-1,-1,12,16,10,14,9,11,9,8,10,6,11,5,-1,-1,18,16,17,8,
17,6,19,5,21,5,23,7,24,10,24,12,23,15,22,17,20,19,18,20,15,21,12,
21,9,20,7,19,5,17,4,15,3,12,3,9,4,6,5,4,7,2,9,1,12,0,
15,0,18,1,20,2,21,3,-1,-1,19,16,18,8,18,6,19,5,],
[8,18,//Ascii65
9,21,1,0,-1,-1,9,21,17,0,-1,-1,4,7,14,7,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[23,21,//Ascii66
4,21,4,0,-1,-1,4,21,13,21,16,20,17,19,18,17,18,15,17,13,16,12,13,
11,-1,-1,4,11,13,11,16,10,17,9,18,7,18,4,17,2,16,1,13,0,4,0,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[18,21,//Ascii67
18,16,17,18,15,20,13,21,9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,
3,7,1,9,0,13,0,15,1,17,3,18,5,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[15,21,//Ascii68
4,21,4,0,-1,-1,4,21,11,21,14,20,16,18,17,16,18,13,18,8,17,5,16,
3,14,1,11,0,4,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[11,19,//Ascii69
4,21,4,0,-1,-1,4,21,17,21,-1,-1,4,11,12,11,-1,-1,4,0,17,0,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[8,18,//Ascii70
4,21,4,0,-1,-1,4,21,17,21,-1,-1,4,11,12,11,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[22,21,//Ascii71
18,16,17,18,15,20,13,21,9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,
3,7,1,9,0,13,0,15,1,17,3,18,5,18,8,-1,-1,13,8,18,8,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[8,22,//Ascii72
4,21,4,0,-1,-1,18,21,18,0,-1,-1,4,11,18,11,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[2,8,//Ascii73
4,21,4,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[10,16,//Ascii74
12,21,12,5,11,2,10,1,8,0,6,0,4,1,3,2,2,5,2,7,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[8,21,//Ascii75
4,21,4,0,-1,-1,18,21,4,7,-1,-1,9,12,18,0,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[5,17,//Ascii76
4,21,4,0,-1,-1,4,0,16,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[11,24,//Ascii77
4,21,4,0,-1,-1,4,21,12,0,-1,-1,20,21,12,0,-1,-1,20,21,20,0,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[8,22,//Ascii78
4,21,4,0,-1,-1,4,21,18,0,-1,-1,18,21,18,0,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[21,22,//Ascii79
9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,
1,17,3,18,5,19,8,19,13,18,16,17,18,15,20,13,21,9,21,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[13,21,//Ascii80
4,21,4,0,-1,-1,4,21,13,21,16,20,17,19,18,17,18,14,17,12,16,11,13,
10,4,10,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[24,22,//Ascii81
9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,
1,17,3,18,5,19,8,19,13,18,16,17,18,15,20,13,21,9,21,-1,-1,12,4,
18,-2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[16,21,//Ascii82
4,21,4,0,-1,-1,4,21,13,21,16,20,17,19,18,17,18,15,17,13,16,12,13,
11,4,11,-1,-1,11,11,18,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[20,20,//Ascii83
17,18,15,20,12,21,8,21,5,20,3,18,3,16,4,14,5,13,7,12,13,10,15,
9,16,8,17,6,17,3,15,1,12,0,8,0,5,1,3,3,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[5,16,//Ascii84
8,21,8,0,-1,-1,1,21,15,21,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[10,22,//Ascii85
4,21,4,6,5,3,7,1,10,0,12,0,15,1,17,3,18,6,18,21,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[5,18,//Ascii86
1,21,9,0,-1,-1,17,21,9,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[11,24,//Ascii87
2,21,7,0,-1,-1,12,21,7,0,-1,-1,12,21,17,0,-1,-1,22,21,17,0,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[5,20,//Ascii88
3,21,17,0,-1,-1,17,21,3,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[6,18,//Ascii89
1,21,9,11,9,0,-1,-1,17,21,9,11,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[8,20,//Ascii90
17,21,3,0,-1,-1,3,21,17,21,-1,-1,3,0,17,0,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[11,14,//Ascii91
4,25,4,-7,-1,-1,5,25,5,-7,-1,-1,4,25,11,25,-1,-1,4,-7,11,-7,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[2,14,//Ascii92
0,21,14,-3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[11,14,//Ascii93
9,25,9,-7,-1,-1,10,25,10,-7,-1,-1,3,25,10,25,-1,-1,3,-7,10,-7,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[10,16,//Ascii94
6,15,8,18,10,15,-1,-1,3,12,8,17,13,12,-1,-1,8,17,8,0,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[2,16,//Ascii95
0,-2,16,-2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[7,10,//Ascii96
6,21,5,20,4,18,4,16,5,15,6,16,5,17,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[17,19,//Ascii97
15,14,15,0,-1,-1,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,
3,6,1,8,0,11,0,13,1,15,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[17,19,//Ascii98
4,21,4,0,-1,-1,4,11,6,13,8,14,11,14,13,13,15,11,16,8,16,6,15,
3,13,1,11,0,8,0,6,1,4,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[14,18,//Ascii99
15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,
0,13,1,15,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[17,19,//Ascii100
15,21,15,0,-1,-1,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,
3,6,1,8,0,11,0,13,1,15,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[17,18,//Ascii101
3,8,15,8,15,10,14,12,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,
3,6,1,8,0,11,0,13,1,15,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[8,12,//Ascii102
10,21,8,21,6,20,5,17,5,0,-1,-1,2,14,9,14,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[22,19,//Ascii103
15,14,15,-2,14,-5,13,-6,11,-7,8,-7,6,-6,-1,-1,15,11,13,13,11,14,8,
14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[10,19,//Ascii104
4,21,4,0,-1,-1,4,10,7,13,9,14,12,14,14,13,15,10,15,0,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[8,8,//Ascii105
3,21,4,20,5,21,4,22,3,21,-1,-1,4,14,4,0,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[11,10,//Ascii106
5,21,6,20,7,21,6,22,5,21,-1,-1,6,14,6,-3,5,-6,3,-7,1,-7,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[8,17,//Ascii107
4,21,4,0,-1,-1,14,14,4,4,-1,-1,8,8,15,0,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[2,8,//Ascii108
4,21,4,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[18,30,//Ascii109
4,14,4,0,-1,-1,4,10,7,13,9,14,12,14,14,13,15,10,15,0,-1,-1,15,
10,18,13,20,14,23,14,25,13,26,10,26,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[10,19,//Ascii110
4,14,4,0,-1,-1,4,10,7,13,9,14,12,14,14,13,15,10,15,0,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[17,19,//Ascii111
8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3,16,
6,16,8,15,11,13,13,11,14,8,14,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[17,19,//Ascii112
4,14,4,-7,-1,-1,4,11,6,13,8,14,11,14,13,13,15,11,16,8,16,6,15,
3,13,1,11,0,8,0,6,1,4,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[17,19,//Ascii113
15,14,15,-7,-1,-1,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,
3,6,1,8,0,11,0,13,1,15,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[8,13,//Ascii114
4,14,4,0,-1,-1,4,8,5,11,7,13,9,14,12,14,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[17,17,//Ascii115
14,11,13,13,10,14,7,14,4,13,3,11,4,9,6,8,11,7,13,6,14,4,14,
3,13,1,10,0,7,0,4,1,3,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[8,12,//Ascii116
5,21,5,4,6,1,8,0,10,0,-1,-1,2,14,9,14,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[10,19,//Ascii117
4,14,4,4,5,1,7,0,10,0,12,1,15,4,-1,-1,15,14,15,0,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[5,16,//Ascii118
2,14,8,0,-1,-1,14,14,8,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[11,22,//Ascii119
3,14,7,0,-1,-1,11,14,7,0,-1,-1,11,14,15,0,-1,-1,19,14,15,0,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[5,17,//Ascii120
3,14,14,0,-1,-1,14,14,3,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[9,16,//Ascii121
2,14,8,0,-1,-1,14,14,8,0,6,-4,4,-6,2,-7,1,-7,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[8,17,//Ascii122
14,14,3,0,-1,-1,3,14,14,14,-1,-1,3,0,14,0,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[39,14,//Ascii123
9,25,7,24,6,23,5,21,5,19,6,17,7,16,8,14,8,12,6,10,-1,-1,7,
24,6,22,6,20,7,18,8,17,9,15,9,13,8,11,4,9,8,7,9,5,9,3,
8,1,7,0,6,-2,6,-4,7,-6,-1,-1,6,8,8,6,8,4,7,2,6,1,5,
-1,5,-3,6,-5,7,-6,9,-7,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[2,8,//Ascii124
4,25,4,-7,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[39,14,//Ascii125
5,25,7,24,8,23,9,21,9,19,8,17,7,16,6,14,6,12,8,10,-1,-1,7,
24,8,22,8,20,7,18,6,17,5,15,5,13,6,11,10,9,6,7,5,5,5,3,
6,1,7,0,8,-2,8,-4,7,-6,-1,-1,8,8,6,6,6,4,7,2,8,1,9,
-1,9,-3,8,-5,7,-6,5,-7,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[23,24,//Ascii126
3,6,3,8,4,11,6,12,8,12,10,11,14,8,16,7,18,7,20,8,21,10,-1,
-1,3,8,4,10,6,11,8,11,10,10,14,7,16,6,18,6,20,7,21,10,21,12,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,]
];
// Sylvester.js Libary
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('9 17={3i:\'0.1.3\',16:1e-6};l v(){}v.23={e:l(i){8(i<1||i>7.4.q)?w:7.4[i-1]},2R:l(){8 7.4.q},1u:l(){8 F.1x(7.2u(7))},24:l(a){9 n=7.4.q;9 V=a.4||a;o(n!=V.q){8 1L}J{o(F.13(7.4[n-1]-V[n-1])>17.16){8 1L}}H(--n);8 2x},1q:l(){8 v.u(7.4)},1b:l(a){9 b=[];7.28(l(x,i){b.19(a(x,i))});8 v.u(b)},28:l(a){9 n=7.4.q,k=n,i;J{i=k-n;a(7.4[i],i+1)}H(--n)},2q:l(){9 r=7.1u();o(r===0){8 7.1q()}8 7.1b(l(x){8 x/r})},1C:l(a){9 V=a.4||a;9 n=7.4.q,k=n,i;o(n!=V.q){8 w}9 b=0,1D=0,1F=0;7.28(l(x,i){b+=x*V[i-1];1D+=x*x;1F+=V[i-1]*V[i-1]});1D=F.1x(1D);1F=F.1x(1F);o(1D*1F===0){8 w}9 c=b/(1D*1F);o(c<-1){c=-1}o(c>1){c=1}8 F.37(c)},1m:l(a){9 b=7.1C(a);8(b===w)?w:(b<=17.16)},34:l(a){9 b=7.1C(a);8(b===w)?w:(F.13(b-F.1A)<=17.16)},2k:l(a){9 b=7.2u(a);8(b===w)?w:(F.13(b)<=17.16)},2j:l(a){9 V=a.4||a;o(7.4.q!=V.q){8 w}8 7.1b(l(x,i){8 x+V[i-1]})},2C:l(a){9 V=a.4||a;o(7.4.q!=V.q){8 w}8 7.1b(l(x,i){8 x-V[i-1]})},22:l(k){8 7.1b(l(x){8 x*k})},x:l(k){8 7.22(k)},2u:l(a){9 V=a.4||a;9 i,2g=0,n=7.4.q;o(n!=V.q){8 w}J{2g+=7.4[n-1]*V[n-1]}H(--n);8 2g},2f:l(a){9 B=a.4||a;o(7.4.q!=3||B.q!=3){8 w}9 A=7.4;8 v.u([(A[1]*B[2])-(A[2]*B[1]),(A[2]*B[0])-(A[0]*B[2]),(A[0]*B[1])-(A[1]*B[0])])},2A:l(){9 m=0,n=7.4.q,k=n,i;J{i=k-n;o(F.13(7.4[i])>F.13(m)){m=7.4[i]}}H(--n);8 m},2Z:l(x){9 a=w,n=7.4.q,k=n,i;J{i=k-n;o(a===w&&7.4[i]==x){a=i+1}}H(--n);8 a},3g:l(){8 S.2X(7.4)},2d:l(){8 7.1b(l(x){8 F.2d(x)})},2V:l(x){8 7.1b(l(y){8(F.13(y-x)<=17.16)?x:y})},1o:l(a){o(a.K){8 a.1o(7)}9 V=a.4||a;o(V.q!=7.4.q){8 w}9 b=0,2b;7.28(l(x,i){2b=x-V[i-1];b+=2b*2b});8 F.1x(b)},3a:l(a){8 a.1h(7)},2T:l(a){8 a.1h(7)},1V:l(t,a){9 V,R,x,y,z;2S(7.4.q){27 2:V=a.4||a;o(V.q!=2){8 w}R=S.1R(t).4;x=7.4[0]-V[0];y=7.4[1]-V[1];8 v.u([V[0]+R[0][0]*x+R[0][1]*y,V[1]+R[1][0]*x+R[1][1]*y]);1I;27 3:o(!a.U){8 w}9 C=a.1r(7).4;R=S.1R(t,a.U).4;x=7.4[0]-C[0];y=7.4[1]-C[1];z=7.4[2]-C[2];8 v.u([C[0]+R[0][0]*x+R[0][1]*y+R[0][2]*z,C[1]+R[1][0]*x+R[1][1]*y+R[1][2]*z,C[2]+R[2][0]*x+R[2][1]*y+R[2][2]*z]);1I;2P:8 w}},1t:l(a){o(a.K){9 P=7.4.2O();9 C=a.1r(P).4;8 v.u([C[0]+(C[0]-P[0]),C[1]+(C[1]-P[1]),C[2]+(C[2]-(P[2]||0))])}1d{9 Q=a.4||a;o(7.4.q!=Q.q){8 w}8 7.1b(l(x,i){8 Q[i-1]+(Q[i-1]-x)})}},1N:l(){9 V=7.1q();2S(V.4.q){27 3:1I;27 2:V.4.19(0);1I;2P:8 w}8 V},2n:l(){8\'[\'+7.4.2K(\', \')+\']\'},26:l(a){7.4=(a.4||a).2O();8 7}};v.u=l(a){9 V=25 v();8 V.26(a)};v.i=v.u([1,0,0]);v.j=v.u([0,1,0]);v.k=v.u([0,0,1]);v.2J=l(n){9 a=[];J{a.19(F.2F())}H(--n);8 v.u(a)};v.1j=l(n){9 a=[];J{a.19(0)}H(--n);8 v.u(a)};l S(){}S.23={e:l(i,j){o(i<1||i>7.4.q||j<1||j>7.4[0].q){8 w}8 7.4[i-1][j-1]},33:l(i){o(i>7.4.q){8 w}8 v.u(7.4[i-1])},2E:l(j){o(j>7.4[0].q){8 w}9 a=[],n=7.4.q,k=n,i;J{i=k-n;a.19(7.4[i][j-1])}H(--n);8 v.u(a)},2R:l(){8{2D:7.4.q,1p:7.4[0].q}},2D:l(){8 7.4.q},1p:l(){8 7.4[0].q},24:l(a){9 M=a.4||a;o(1g(M[0][0])==\'1f\'){M=S.u(M).4}o(7.4.q!=M.q||7.4[0].q!=M[0].q){8 1L}9 b=7.4.q,15=b,i,G,10=7.4[0].q,j;J{i=15-b;G=10;J{j=10-G;o(F.13(7.4[i][j]-M[i][j])>17.16){8 1L}}H(--G)}H(--b);8 2x},1q:l(){8 S.u(7.4)},1b:l(a){9 b=[],12=7.4.q,15=12,i,G,10=7.4[0].q,j;J{i=15-12;G=10;b[i]=[];J{j=10-G;b[i][j]=a(7.4[i][j],i+1,j+1)}H(--G)}H(--12);8 S.u(b)},2i:l(a){9 M=a.4||a;o(1g(M[0][0])==\'1f\'){M=S.u(M).4}8(7.4.q==M.q&&7.4[0].q==M[0].q)},2j:l(a){9 M=a.4||a;o(1g(M[0][0])==\'1f\'){M=S.u(M).4}o(!7.2i(M)){8 w}8 7.1b(l(x,i,j){8 x+M[i-1][j-1]})},2C:l(a){9 M=a.4||a;o(1g(M[0][0])==\'1f\'){M=S.u(M).4}o(!7.2i(M)){8 w}8 7.1b(l(x,i,j){8 x-M[i-1][j-1]})},2B:l(a){9 M=a.4||a;o(1g(M[0][0])==\'1f\'){M=S.u(M).4}8(7.4[0].q==M.q)},22:l(a){o(!a.4){8 7.1b(l(x){8 x*a})}9 b=a.1u?2x:1L;9 M=a.4||a;o(1g(M[0][0])==\'1f\'){M=S.u(M).4}o(!7.2B(M)){8 w}9 d=7.4.q,15=d,i,G,10=M[0].q,j;9 e=7.4[0].q,4=[],21,20,c;J{i=15-d;4[i]=[];G=10;J{j=10-G;21=0;20=e;J{c=e-20;21+=7.4[i][c]*M[c][j]}H(--20);4[i][j]=21}H(--G)}H(--d);9 M=S.u(4);8 b?M.2E(1):M},x:l(a){8 7.22(a)},32:l(a,b,c,d){9 e=[],12=c,i,G,j;9 f=7.4.q,1p=7.4[0].q;J{i=c-12;e[i]=[];G=d;J{j=d-G;e[i][j]=7.4[(a+i-1)%f][(b+j-1)%1p]}H(--G)}H(--12);8 S.u(e)},31:l(){9 a=7.4.q,1p=7.4[0].q;9 b=[],12=1p,i,G,j;J{i=1p-12;b[i]=[];G=a;J{j=a-G;b[i][j]=7.4[j][i]}H(--G)}H(--12);8 S.u(b)},1y:l(){8(7.4.q==7.4[0].q)},2A:l(){9 m=0,12=7.4.q,15=12,i,G,10=7.4[0].q,j;J{i=15-12;G=10;J{j=10-G;o(F.13(7.4[i][j])>F.13(m)){m=7.4[i][j]}}H(--G)}H(--12);8 m},2Z:l(x){9 a=w,12=7.4.q,15=12,i,G,10=7.4[0].q,j;J{i=15-12;G=10;J{j=10-G;o(7.4[i][j]==x){8{i:i+1,j:j+1}}}H(--G)}H(--12);8 w},30:l(){o(!7.1y){8 w}9 a=[],n=7.4.q,k=n,i;J{i=k-n;a.19(7.4[i][i])}H(--n);8 v.u(a)},1K:l(){9 M=7.1q(),1c;9 n=7.4.q,k=n,i,1s,1n=7.4[0].q,p;J{i=k-n;o(M.4[i][i]==0){2e(j=i+1;j<k;j++){o(M.4[j][i]!=0){1c=[];1s=1n;J{p=1n-1s;1c.19(M.4[i][p]+M.4[j][p])}H(--1s);M.4[i]=1c;1I}}}o(M.4[i][i]!=0){2e(j=i+1;j<k;j++){9 a=M.4[j][i]/M.4[i][i];1c=[];1s=1n;J{p=1n-1s;1c.19(p<=i?0:M.4[j][p]-M.4[i][p]*a)}H(--1s);M.4[j]=1c}}}H(--n);8 M},3h:l(){8 7.1K()},2z:l(){o(!7.1y()){8 w}9 M=7.1K();9 a=M.4[0][0],n=M.4.q-1,k=n,i;J{i=k-n+1;a=a*M.4[i][i]}H(--n);8 a},3f:l(){8 7.2z()},2y:l(){8(7.1y()&&7.2z()===0)},2Y:l(){o(!7.1y()){8 w}9 a=7.4[0][0],n=7.4.q-1,k=n,i;J{i=k-n+1;a+=7.4[i][i]}H(--n);8 a},3e:l(){8 7.2Y()},1Y:l(){9 M=7.1K(),1Y=0;9 a=7.4.q,15=a,i,G,10=7.4[0].q,j;J{i=15-a;G=10;J{j=10-G;o(F.13(M.4[i][j])>17.16){1Y++;1I}}H(--G)}H(--a);8 1Y},3d:l(){8 7.1Y()},2W:l(a){9 M=a.4||a;o(1g(M[0][0])==\'1f\'){M=S.u(M).4}9 T=7.1q(),1p=T.4[0].q;9 b=T.4.q,15=b,i,G,10=M[0].q,j;o(b!=M.q){8 w}J{i=15-b;G=10;J{j=10-G;T.4[i][1p+j]=M[i][j]}H(--G)}H(--b);8 T},2w:l(){o(!7.1y()||7.2y()){8 w}9 a=7.4.q,15=a,i,j;9 M=7.2W(S.I(a)).1K();9 b,1n=M.4[0].q,p,1c,2v;9 c=[],2c;J{i=a-1;1c=[];b=1n;c[i]=[];2v=M.4[i][i];J{p=1n-b;2c=M.4[i][p]/2v;1c.19(2c);o(p>=15){c[i].19(2c)}}H(--b);M.4[i]=1c;2e(j=0;j<i;j++){1c=[];b=1n;J{p=1n-b;1c.19(M.4[j][p]-M.4[i][p]*M.4[j][i])}H(--b);M.4[j]=1c}}H(--a);8 S.u(c)},3c:l(){8 7.2w()},2d:l(){8 7.1b(l(x){8 F.2d(x)})},2V:l(x){8 7.1b(l(p){8(F.13(p-x)<=17.16)?x:p})},2n:l(){9 a=[];9 n=7.4.q,k=n,i;J{i=k-n;a.19(v.u(7.4[i]).2n())}H(--n);8 a.2K(\'\\n\')},26:l(a){9 i,4=a.4||a;o(1g(4[0][0])!=\'1f\'){9 b=4.q,15=b,G,10,j;7.4=[];J{i=15-b;G=4[i].q;10=G;7.4[i]=[];J{j=10-G;7.4[i][j]=4[i][j]}H(--G)}H(--b);8 7}9 n=4.q,k=n;7.4=[];J{i=k-n;7.4.19([4[i]])}H(--n);8 7}};S.u=l(a){9 M=25 S();8 M.26(a)};S.I=l(n){9 a=[],k=n,i,G,j;J{i=k-n;a[i]=[];G=k;J{j=k-G;a[i][j]=(i==j)?1:0}H(--G)}H(--n);8 S.u(a)};S.2X=l(a){9 n=a.q,k=n,i;9 M=S.I(n);J{i=k-n;M.4[i][i]=a[i]}H(--n);8 M};S.1R=l(b,a){o(!a){8 S.u([[F.1H(b),-F.1G(b)],[F.1G(b),F.1H(b)]])}9 d=a.1q();o(d.4.q!=3){8 w}9 e=d.1u();9 x=d.4[0]/e,y=d.4[1]/e,z=d.4[2]/e;9 s=F.1G(b),c=F.1H(b),t=1-c;8 S.u([[t*x*x+c,t*x*y-s*z,t*x*z+s*y],[t*x*y+s*z,t*y*y+c,t*y*z-s*x],[t*x*z-s*y,t*y*z+s*x,t*z*z+c]])};S.3b=l(t){9 c=F.1H(t),s=F.1G(t);8 S.u([[1,0,0],[0,c,-s],[0,s,c]])};S.39=l(t){9 c=F.1H(t),s=F.1G(t);8 S.u([[c,0,s],[0,1,0],[-s,0,c]])};S.38=l(t){9 c=F.1H(t),s=F.1G(t);8 S.u([[c,-s,0],[s,c,0],[0,0,1]])};S.2J=l(n,m){8 S.1j(n,m).1b(l(){8 F.2F()})};S.1j=l(n,m){9 a=[],12=n,i,G,j;J{i=n-12;a[i]=[];G=m;J{j=m-G;a[i][j]=0}H(--G)}H(--12);8 S.u(a)};l 14(){}14.23={24:l(a){8(7.1m(a)&&7.1h(a.K))},1q:l(){8 14.u(7.K,7.U)},2U:l(a){9 V=a.4||a;8 14.u([7.K.4[0]+V[0],7.K.4[1]+V[1],7.K.4[2]+(V[2]||0)],7.U)},1m:l(a){o(a.W){8 a.1m(7)}9 b=7.U.1C(a.U);8(F.13(b)<=17.16||F.13(b-F.1A)<=17.16)},1o:l(a){o(a.W){8 a.1o(7)}o(a.U){o(7.1m(a)){8 7.1o(a.K)}9 N=7.U.2f(a.U).2q().4;9 A=7.K.4,B=a.K.4;8 F.13((A[0]-B[0])*N[0]+(A[1]-B[1])*N[1]+(A[2]-B[2])*N[2])}1d{9 P=a.4||a;9 A=7.K.4,D=7.U.4;9 b=P[0]-A[0],2a=P[1]-A[1],29=(P[2]||0)-A[2];9 c=F.1x(b*b+2a*2a+29*29);o(c===0)8 0;9 d=(b*D[0]+2a*D[1]+29*D[2])/c;9 e=1-d*d;8 F.13(c*F.1x(e<0?0:e))}},1h:l(a){9 b=7.1o(a);8(b!==w&&b<=17.16)},2T:l(a){8 a.1h(7)},1v:l(a){o(a.W){8 a.1v(7)}8(!7.1m(a)&&7.1o(a)<=17.16)},1U:l(a){o(a.W){8 a.1U(7)}o(!7.1v(a)){8 w}9 P=7.K.4,X=7.U.4,Q=a.K.4,Y=a.U.4;9 b=X[0],1z=X[1],1B=X[2],1T=Y[0],1S=Y[1],1M=Y[2];9 c=P[0]-Q[0],2s=P[1]-Q[1],2r=P[2]-Q[2];9 d=-b*c-1z*2s-1B*2r;9 e=1T*c+1S*2s+1M*2r;9 f=b*b+1z*1z+1B*1B;9 g=1T*1T+1S*1S+1M*1M;9 h=b*1T+1z*1S+1B*1M;9 k=(d*g/f+h*e)/(g-h*h);8 v.u([P[0]+k*b,P[1]+k*1z,P[2]+k*1B])},1r:l(a){o(a.U){o(7.1v(a)){8 7.1U(a)}o(7.1m(a)){8 w}9 D=7.U.4,E=a.U.4;9 b=D[0],1l=D[1],1k=D[2],1P=E[0],1O=E[1],1Q=E[2];9 x=(1k*1P-b*1Q),y=(b*1O-1l*1P),z=(1l*1Q-1k*1O);9 N=v.u([x*1Q-y*1O,y*1P-z*1Q,z*1O-x*1P]);9 P=11.u(a.K,N);8 P.1U(7)}1d{9 P=a.4||a;o(7.1h(P)){8 v.u(P)}9 A=7.K.4,D=7.U.4;9 b=D[0],1l=D[1],1k=D[2],1w=A[0],18=A[1],1a=A[2];9 x=b*(P[1]-18)-1l*(P[0]-1w),y=1l*((P[2]||0)-1a)-1k*(P[1]-18),z=1k*(P[0]-1w)-b*((P[2]||0)-1a);9 V=v.u([1l*x-1k*z,1k*y-b*x,b*z-1l*y]);9 k=7.1o(P)/V.1u();8 v.u([P[0]+V.4[0]*k,P[1]+V.4[1]*k,(P[2]||0)+V.4[2]*k])}},1V:l(t,a){o(1g(a.U)==\'1f\'){a=14.u(a.1N(),v.k)}9 R=S.1R(t,a.U).4;9 C=a.1r(7.K).4;9 A=7.K.4,D=7.U.4;9 b=C[0],1E=C[1],1J=C[2],1w=A[0],18=A[1],1a=A[2];9 x=1w-b,y=18-1E,z=1a-1J;8 14.u([b+R[0][0]*x+R[0][1]*y+R[0][2]*z,1E+R[1][0]*x+R[1][1]*y+R[1][2]*z,1J+R[2][0]*x+R[2][1]*y+R[2][2]*z],[R[0][0]*D[0]+R[0][1]*D[1]+R[0][2]*D[2],R[1][0]*D[0]+R[1][1]*D[1]+R[1][2]*D[2],R[2][0]*D[0]+R[2][1]*D[1]+R[2][2]*D[2]])},1t:l(a){o(a.W){9 A=7.K.4,D=7.U.4;9 b=A[0],18=A[1],1a=A[2],2N=D[0],1l=D[1],1k=D[2];9 c=7.K.1t(a).4;9 d=b+2N,2h=18+1l,2o=1a+1k;9 Q=a.1r([d,2h,2o]).4;9 e=[Q[0]+(Q[0]-d)-c[0],Q[1]+(Q[1]-2h)-c[1],Q[2]+(Q[2]-2o)-c[2]];8 14.u(c,e)}1d o(a.U){8 7.1V(F.1A,a)}1d{9 P=a.4||a;8 14.u(7.K.1t([P[0],P[1],(P[2]||0)]),7.U)}},1Z:l(a,b){a=v.u(a);b=v.u(b);o(a.4.q==2){a.4.19(0)}o(b.4.q==2){b.4.19(0)}o(a.4.q>3||b.4.q>3){8 w}9 c=b.1u();o(c===0){8 w}7.K=a;7.U=v.u([b.4[0]/c,b.4[1]/c,b.4[2]/c]);8 7}};14.u=l(a,b){9 L=25 14();8 L.1Z(a,b)};14.X=14.u(v.1j(3),v.i);14.Y=14.u(v.1j(3),v.j);14.Z=14.u(v.1j(3),v.k);l 11(){}11.23={24:l(a){8(7.1h(a.K)&&7.1m(a))},1q:l(){8 11.u(7.K,7.W)},2U:l(a){9 V=a.4||a;8 11.u([7.K.4[0]+V[0],7.K.4[1]+V[1],7.K.4[2]+(V[2]||0)],7.W)},1m:l(a){9 b;o(a.W){b=7.W.1C(a.W);8(F.13(b)<=17.16||F.13(F.1A-b)<=17.16)}1d o(a.U){8 7.W.2k(a.U)}8 w},2k:l(a){9 b=7.W.1C(a.W);8(F.13(F.1A/2-b)<=17.16)},1o:l(a){o(7.1v(a)||7.1h(a)){8 0}o(a.K){9 A=7.K.4,B=a.K.4,N=7.W.4;8 F.13((A[0]-B[0])*N[0]+(A[1]-B[1])*N[1]+(A[2]-B[2])*N[2])}1d{9 P=a.4||a;9 A=7.K.4,N=7.W.4;8 F.13((A[0]-P[0])*N[0]+(A[1]-P[1])*N[1]+(A[2]-(P[2]||0))*N[2])}},1h:l(a){o(a.W){8 w}o(a.U){8(7.1h(a.K)&&7.1h(a.K.2j(a.U)))}1d{9 P=a.4||a;9 A=7.K.4,N=7.W.4;9 b=F.13(N[0]*(A[0]-P[0])+N[1]*(A[1]-P[1])+N[2]*(A[2]-(P[2]||0)));8(b<=17.16)}},1v:l(a){o(1g(a.U)==\'1f\'&&1g(a.W)==\'1f\'){8 w}8!7.1m(a)},1U:l(a){o(!7.1v(a)){8 w}o(a.U){9 A=a.K.4,D=a.U.4,P=7.K.4,N=7.W.4;9 b=(N[0]*(P[0]-A[0])+N[1]*(P[1]-A[1])+N[2]*(P[2]-A[2]))/(N[0]*D[0]+N[1]*D[1]+N[2]*D[2]);8 v.u([A[0]+D[0]*b,A[1]+D[1]*b,A[2]+D[2]*b])}1d o(a.W){9 c=7.W.2f(a.W).2q();9 N=7.W.4,A=7.K.4,O=a.W.4,B=a.K.4;9 d=S.1j(2,2),i=0;H(d.2y()){i++;d=S.u([[N[i%3],N[(i+1)%3]],[O[i%3],O[(i+1)%3]]])}9 e=d.2w().4;9 x=N[0]*A[0]+N[1]*A[1]+N[2]*A[2];9 y=O[0]*B[0]+O[1]*B[1]+O[2]*B[2];9 f=[e[0][0]*x+e[0][1]*y,e[1][0]*x+e[1][1]*y];9 g=[];2e(9 j=1;j<=3;j++){g.19((i==j)?0:f[(j+(5-i)%3)%3])}8 14.u(g,c)}},1r:l(a){9 P=a.4||a;9 A=7.K.4,N=7.W.4;9 b=(A[0]-P[0])*N[0]+(A[1]-P[1])*N[1]+(A[2]-(P[2]||0))*N[2];8 v.u([P[0]+N[0]*b,P[1]+N[1]*b,(P[2]||0)+N[2]*b])},1V:l(t,a){9 R=S.1R(t,a.U).4;9 C=a.1r(7.K).4;9 A=7.K.4,N=7.W.4;9 b=C[0],1E=C[1],1J=C[2],1w=A[0],18=A[1],1a=A[2];9 x=1w-b,y=18-1E,z=1a-1J;8 11.u([b+R[0][0]*x+R[0][1]*y+R[0][2]*z,1E+R[1][0]*x+R[1][1]*y+R[1][2]*z,1J+R[2][0]*x+R[2][1]*y+R[2][2]*z],[R[0][0]*N[0]+R[0][1]*N[1]+R[0][2]*N[2],R[1][0]*N[0]+R[1][1]*N[1]+R[1][2]*N[2],R[2][0]*N[0]+R[2][1]*N[1]+R[2][2]*N[2]])},1t:l(a){o(a.W){9 A=7.K.4,N=7.W.4;9 b=A[0],18=A[1],1a=A[2],2M=N[0],2L=N[1],2Q=N[2];9 c=7.K.1t(a).4;9 d=b+2M,2p=18+2L,2m=1a+2Q;9 Q=a.1r([d,2p,2m]).4;9 e=[Q[0]+(Q[0]-d)-c[0],Q[1]+(Q[1]-2p)-c[1],Q[2]+(Q[2]-2m)-c[2]];8 11.u(c,e)}1d o(a.U){8 7.1V(F.1A,a)}1d{9 P=a.4||a;8 11.u(7.K.1t([P[0],P[1],(P[2]||0)]),7.W)}},1Z:l(a,b,c){a=v.u(a);a=a.1N();o(a===w){8 w}b=v.u(b);b=b.1N();o(b===w){8 w}o(1g(c)==\'1f\'){c=w}1d{c=v.u(c);c=c.1N();o(c===w){8 w}}9 d=a.4[0],18=a.4[1],1a=a.4[2];9 e=b.4[0],1W=b.4[1],1X=b.4[2];9 f,1i;o(c!==w){9 g=c.4[0],2l=c.4[1],2t=c.4[2];f=v.u([(1W-18)*(2t-1a)-(1X-1a)*(2l-18),(1X-1a)*(g-d)-(e-d)*(2t-1a),(e-d)*(2l-18)-(1W-18)*(g-d)]);1i=f.1u();o(1i===0){8 w}f=v.u([f.4[0]/1i,f.4[1]/1i,f.4[2]/1i])}1d{1i=F.1x(e*e+1W*1W+1X*1X);o(1i===0){8 w}f=v.u([b.4[0]/1i,b.4[1]/1i,b.4[2]/1i])}7.K=a;7.W=f;8 7}};11.u=l(a,b,c){9 P=25 11();8 P.1Z(a,b,c)};11.2I=11.u(v.1j(3),v.k);11.2H=11.u(v.1j(3),v.i);11.2G=11.u(v.1j(3),v.j);11.36=11.2I;11.35=11.2H;11.3j=11.2G;9 $V=v.u;9 $M=S.u;9 $L=14.u;9 $P=11.u;',62,206,'||||elements|||this|return|var||||||||||||function|||if||length||||create|Vector|null|||||||||Math|nj|while||do|anchor||||||||Matrix||direction||normal||||kj|Plane|ni|abs|Line|ki|precision|Sylvester|A2|push|A3|map|els|else||undefined|typeof|contains|mod|Zero|D3|D2|isParallelTo|kp|distanceFrom|cols|dup|pointClosestTo|np|reflectionIn|modulus|intersects|A1|sqrt|isSquare|X2|PI|X3|angleFrom|mod1|C2|mod2|sin|cos|break|C3|toRightTriangular|false|Y3|to3D|E2|E1|E3|Rotation|Y2|Y1|intersectionWith|rotate|v12|v13|rank|setVectors|nc|sum|multiply|prototype|eql|new|setElements|case|each|PA3|PA2|part|new_element|round|for|cross|product|AD2|isSameSizeAs|add|isPerpendicularTo|v22|AN3|inspect|AD3|AN2|toUnitVector|PsubQ3|PsubQ2|v23|dot|divisor|inverse|true|isSingular|determinant|max|canMultiplyFromLeft|subtract|rows|col|random|ZX|YZ|XY|Random|join|N2|N1|D1|slice|default|N3|dimensions|switch|liesIn|translate|snapTo|augment|Diagonal|trace|indexOf|diagonal|transpose|minor|row|isAntiparallelTo|ZY|YX|acos|RotationZ|RotationY|liesOn|RotationX|inv|rk|tr|det|toDiagonalMatrix|toUpperTriangular|version|XZ'.split('|'),0,{}))
// gtUtils.js Libary
Matrix.Translation = function (v)
{
if (v.elements.length == 2) {
var r = Matrix.I(3);
r.elements[2][0] = v.elements[0];
r.elements[2][1] = v.elements[1];
return r;
}
if (v.elements.length == 3) {
var r = Matrix.I(4);
r.elements[0][3] = v.elements[0];
r.elements[1][3] = v.elements[1];
r.elements[2][3] = v.elements[2];
return r;
}
throw "Invalid length for Translation";
}
Matrix.prototype.flatten = function ()
{
var result = [];
if (this.elements.length == 0)
return [];
for (var j = 0; j < this.elements[0].length; j++)
for (var i = 0; i < this.elements.length; i++)
result.push(this.elements[i][j]);
return result;
}
Matrix.prototype.ensure4x4 = function()
{
if (this.elements.length == 4 &&
this.elements[0].length == 4)
return this;
if (this.elements.length > 4 ||
this.elements[0].length > 4)
return null;
for (var i = 0; i < this.elements.length; i++) {
for (var j = this.elements[i].length; j < 4; j++) {
if (i == j)
this.elements[i].push(1);
else
this.elements[i].push(0);
}
}
for (var i = this.elements.length; i < 4; i++) {
if (i == 0)
this.elements.push([1, 0, 0, 0]);
else if (i == 1)
this.elements.push([0, 1, 0, 0]);
else if (i == 2)
this.elements.push([0, 0, 1, 0]);
else if (i == 3)
this.elements.push([0, 0, 0, 1]);
}
return this;
};
Matrix.prototype.make3x3 = function()
{
if (this.elements.length != 4 ||
this.elements[0].length != 4)
return null;
return Matrix.create([[this.elements[0][0], this.elements[0][1], this.elements[0][2]],
[this.elements[1][0], this.elements[1][1], this.elements[1][2]],
[this.elements[2][0], this.elements[2][1], this.elements[2][2]]]);
};
Vector.prototype.flatten = function ()
{
return this.elements;
};
function mht(m) {
var s = "";
if (m.length == 16) {
for (var i = 0; i < 4; i++) {
s += "<span style='font-family: monospace'>[" + m[i*4+0].toFixed(4) + "," + m[i*4+1].toFixed(4) + "," + m[i*4+2].toFixed(4) + "," + m[i*4+3].toFixed(4) + "]</span><br>";
}
} else if (m.length == 9) {
for (var i = 0; i < 3; i++) {
s += "<span style='font-family: monospace'>[" + m[i*3+0].toFixed(4) + "," + m[i*3+1].toFixed(4) + "," + m[i*3+2].toFixed(4) + "]</font><br>";
}
} else {
return m.toString();
}
return s;
}
function makeLookAt(ex, ey, ez,
cx, cy, cz,
ux, uy, uz)
{
var eye = $V([ex, ey, ez]);
var center = $V([cx, cy, cz]);
var up = $V([ux, uy, uz]);
var mag;
var z = eye.subtract(center).toUnitVector();
var x = up.cross(z).toUnitVector();
var y = z.cross(x).toUnitVector();
var m = $M([[x.e(1), x.e(2), x.e(3), 0],
[y.e(1), y.e(2), y.e(3), 0],
[z.e(1), z.e(2), z.e(3), 0],
[0, 0, 0, 1]]);
var t = $M([[1, 0, 0, -ex],
[0, 1, 0, -ey],
[0, 0, 1, -ez],
[0, 0, 0, 1]]);
return m.x(t);
}
function makePerspective(fovy, aspect, znear, zfar)
{
var ymax = znear * Math.tan(fovy * Math.PI / 360.0);
var ymin = -ymax;
var xmin = ymin * aspect;
var xmax = ymax * aspect;
return makeFrustum(xmin, xmax, ymin, ymax, znear, zfar);
}
function makeFrustum(left, right,
bottom, top,
znear, zfar)
{
var X = 2*znear/(right-left);
var Y = 2*znear/(top-bottom);
var A = (right+left)/(right-left);
var B = (top+bottom)/(top-bottom);
var C = -(zfar+znear)/(zfar-znear);
var D = -2*zfar*znear/(zfar-znear);
return $M([[X, 0, A, 0],
[0, Y, B, 0],
[0, 0, C, D],
[0, 0, -1, 0]]);
}
function makeOrtho(left, right, bottom, top, znear, zfar)
{
var tx = - (right + left) / (right - left);
var ty = - (top + bottom) / (top - bottom);
var tz = - (zfar + znear) / (zfar - znear);
return $M([[2 / (right - left), 0, 0, tx],
[0, 2 / (top - bottom), 0, ty],
[0, 0, -2 / (zfar - znear), tz],
[0, 0, 0, 1]]);
}
// End of Libaries
function initGL(canvas) {
try {
gl = canvas.getContext("experimental-webgl");
gl.viewportWidth = canvas.width;
gl.viewportHeight = canvas.height;
} catch(e) {
}
if (!gl) {
alert("Could not initialise WebGL");
}
}
function getShader(gl, id) {
var shaderScript = document.getElementById(id);
if (!shaderScript) {
return null;
}
var str = "";
var k = shaderScript.firstChild;
while (k) {
if (k.nodeType == 3) {
str += k.textContent;
}
k = k.nextSibling;
}
var shader;
if (shaderScript.type == "x-shader/x-fragment") {
shader = gl.createShader(gl.FRAGMENT_SHADER);
} else if (shaderScript.type == "x-shader/x-vertex") {
shader = gl.createShader(gl.VERTEX_SHADER);
} else {
return null;
}
gl.shaderSource(shader, str);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
alert(gl.getShaderInfoLog(shader));
return null;
}
return shader;
}
function initShaders() {
var fragmentShader = getShader(gl, "shader-fs");
var vertexShader = getShader(gl, "shader-vs");
shaderProgram = gl.createProgram();
gl.attachShader(shaderProgram, vertexShader);
gl.attachShader(shaderProgram, fragmentShader);
gl.linkProgram(shaderProgram);
if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
alert("Could not initialise shaders");
}
gl.useProgram(shaderProgram);
shaderProgram.vertexPositionAttribute
= gl.getAttribLocation(shaderProgram, "aVertexPosition");
gl.enableVertexAttribArray(shaderProgram.vertexPositionAttribute);
shaderProgram.vertexColorAttribute
= gl.getAttribLocation(shaderProgram, "aVertexColor");
gl.enableVertexAttribArray(shaderProgram.vertexColorAttribute);
shaderProgram.pMatrixUniform
= gl.getUniformLocation(shaderProgram, "uPMatrix");
shaderProgram.mvMatrixUniform
= gl.getUniformLocation(shaderProgram, "uMVMatrix");
}
function mvPushMatrix(m) {
if (m) {
mvMatrixStack.push(m.dup());
mvMatrix = m.dup();
} else {
mvMatrixStack.push(mvMatrix.dup());
}
}
function mvPopMatrix() {
if (mvMatrixStack.length == 0) {
throw "Invalid popMatrix!";
}
mvMatrix = mvMatrixStack.pop();
return mvMatrix;
}
function loadIdentity() {
mvMatrix = Matrix.I(4);
}
function multMatrix(m) {
mvMatrix = mvMatrix.x(m);
}
function mvTranslate(v) {
var m = Matrix.Translation($V([v[0], v[1], v[2]])).ensure4x4();
multMatrix(m);
}
function mvRotate(ang, v) {
var arad = ang * Math.PI / 180.0;
var m = Matrix.Rotation(arad, $V([v[0], v[1], v[2]])).ensure4x4();
multMatrix(m);
}
var pMatrix;
function perspective(fovy, aspect, znear, zfar) {
pMatrix = makePerspective(fovy, aspect, znear, zfar);
}
function setMatrixUniforms() {
gl.uniformMatrix4fv(shaderProgram.pMatrixUniform,
false, new Float32Array(pMatrix.flatten()));
gl.uniformMatrix4fv(shaderProgram.mvMatrixUniform,
false, new Float32Array(mvMatrix.flatten()));
}
function compareXValue(array1, array2)
{
var value1 = array1[0];
var value2 = array2[0];
if (value1 > value2) return 1;
if (value1 < value2) return -1;
return 0;
}
function setupShaders(){
var headID = document.getElementsByTagName("head")[0];
var fsScript = document.createElement('script');
fsScript.id="shader-fs";
fsScript.type = 'x-shader/x-fragment';
fsScript.text = "#ifdef GL_ES\n\
precision highp float;\n\
#endif\n\
varying vec4 vColor;\n\
void main(void) {\n\
gl_FragColor = vColor;\n\
}";
var vsScript = document.createElement('script');
vsScript.id="shader-vs";
vsScript.type = 'x-shader/x-vertex';
vsScript.text = "attribute vec3 aVertexPosition;\n\
attribute vec4 aVertexColor;\n\
\n\
uniform mat4 uMVMatrix;\n\
uniform mat4 uPMatrix;\n\
\n\
varying vec4 vColor;\n\
\n\
void main(void) {\n\
gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);\n\
vColor = aVertexColor;\n\
}";
headID.appendChild(vsScript);
headID.appendChild(fsScript);
initShaders();
}
function setupCanvas(){
canvas1 = document.getElementsByTagName("canvas")[1];
canvas1.style.position = "absolute";
canvas1.style.zIndex = 10;
canvas1.style.opacity = 0.5;
canvas = document.getElementsByTagName("canvas")[0];
canvas.style.zIndex = 0;
initGL(canvas);
}
function setupGL(){
setupCanvas();
setupShaders();
gl.clearColor(1.0, 1.0, 1.0, 1.0);
gl.clearDepth(1.0);
gl.enable(gl.DEPTH_TEST);
gl.depthFunc(gl.LEQUAL);
gl.viewport(0, 0, gl.viewportWidth, gl.viewportHeight);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
perspective(45, gl.viewportWidth / gl.viewportHeight, 0.1, 100.0);
loadIdentity();
var uTop = 2.478;
var uLeft = -uTop;
mvTranslate([uLeft,uTop, -10.0])
mvPushMatrix();
}
// Drawing functions
function drawPolygon(pixelVertices,color)
{
var factor;
var glWidth = 4.92;
var vertices = new Float32Array(1000);
var polygonColors = new Float32Array(1000);
var vl = 0;
if(canvas.width>=canvas.height) factor = glWidth/canvas.height;
else factor = glWidth/canvas.width;
for(var i=0;i<pixelVertices.length;i++){
pixelVertices[i] = (pixelVertices[i])*factor;
if (i%2){
vertices[vl] = -pixelVertices[i];
vl++;
vertices[vl] = (4.0);
}
else
{
vertices[vl] = (pixelVertices[i]);
}
vl++;
}
vertexPositionBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vertexPositionBuffer);
gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
vertexPositionBuffer.itemSize = 3;
vertexPositionBuffer.numItems = vl / 3.0;
vertexColorBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vertexColorBuffer);
for(var i=0;i<(vl / 3.0)*4;i+=4){
polygonColors[i] = color[0];
polygonColors[i+1] = color[1];
polygonColors[i+2] = color[2];
polygonColors[i+3] = color[3];
}
gl.bufferData(gl.ARRAY_BUFFER, polygonColors, gl.STATIC_DRAW);
vertexColorBuffer.itemSize = 4;
vertexColorBuffer.numItems = vl / 3.0;
gl.bindBuffer(gl.ARRAY_BUFFER, vertexPositionBuffer);
gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute,
vertexPositionBuffer.itemSize, gl.FLOAT, false, 0, 0);
gl.bindBuffer(gl.ARRAY_BUFFER, vertexColorBuffer);
gl.vertexAttribPointer(shaderProgram.vertexColorAttribute,
vertexColorBuffer.itemSize, gl.FLOAT, false, 0, 0);
setMatrixUniforms();
gl.drawArrays(gl.TRIANGLE_STRIP, 0, vl / 3.0);
}
function drawLine(left1,top1,left2,top2,width,color)
{
if(top1 <= top2){
var temp1 = left1;
var temp2 = top1;
left1 = left2;
top1 = top2;
left2 = temp1;
top2 = temp2;
}
var length = Math.sqrt(((top2-top1)*(top2-top1))+((left2-left1)*(left2-left1)));
var vHeight = top1-top2;
var hWidth = left1-left2;
var deg = 180/Math.PI;
var angle = Math.atan(vHeight/hWidth);
var angle2 = ((Math.PI/2)-angle);
var height2 = Math.sin(angle2)*(width/2);
var width2 = Math.sqrt(((width/2)*(width/2))-(height2*height2));
if(angle*deg<0)
{
var topRightX = left1-(width2);
var topRightY = top1-height2;
var topLeftX = left1+(width2);
var topLeftY = top1+height2;
var bottomRightX = left2-(width2);
var bottomRightY = top2-height2;
var bottomLeftX = left2+(width2);
var bottomLeftY = top2+height2;
}
else
{
var topRightX = left1-(width2);
var topRightY = top1+height2;
var topLeftX = left1+(width2);
var topLeftY = top1-height2;
var bottomRightX = left2-(width2);
var bottomRightY = top2+height2;
var bottomLeftX = left2+(width2);
var bottomLeftY = top2-height2;
}
var pvertices = new Float32Array([
topRightX, topRightY,
topLeftX, topLeftY,
bottomRightX, bottomRightY,
bottomLeftX, bottomLeftY
]);
drawPolygon(pvertices,color);
}
function drawSquare(left,top,width,height,rotation,color){drawSquareComplex(left,top,width,height,rotation,height,width,color);}
function drawSquareComplex(left,top,width,height,rotation,vHeight,hWidth,color){
var diam = width/2;
var topOffset = Math.round(Math.sin(rotation)*diam);
var leftOffset = Math.round(Math.cos(rotation)*diam);
drawLine(left-leftOffset,top-topOffset,left+leftOffset,top+topOffset,height,color);
}
function drawDiamond(left,top,width,height,color)
{
var halfWidth = width/2;
var halfHeight = height/2;
var pvertices = new Float32Array(8);
pvertices[0] = left;
pvertices[1] = top-halfHeight;
pvertices[2] = left-halfWidth;
pvertices[3] = top;
pvertices[4] = left+halfWidth;
pvertices[5] = top;
pvertices[6] = left;
pvertices[7] = top+halfHeight;
drawPolygon(pvertices,color);
}
function drawTriang(left,top,width,height,rotation,color)
{
var halfWidth = width/2;
var halfHeight = height/2;
var pvertices = new Float32Array(6);
pvertices[0] = 0;
pvertices[1] = 0-halfHeight;
pvertices[2] = 0-halfWidth;
pvertices[3] = 0+halfHeight;
pvertices[4] = 0+halfWidth;
pvertices[5] = 0+halfHeight;
var j = 0;
for (i=0;i<3;i++)
{
var tempX = pvertices[j];
var tempY = pvertices[j+1];
pvertices[j] = (Math.cos(rotation)*tempX)-(Math.sin(rotation)*tempY)
pvertices[j] = Math.round(pvertices[j]+left);
j++;
pvertices[j] = (Math.sin(rotation)*tempX)+(Math.cos(rotation)*tempY)
pvertices[j] = Math.round(pvertices[j]+top);
j++;
}
drawPolygon(pvertices,color);
}
function drawCircle(left,top,width,color){drawCircleDim(left,top,width,width,color)};
function drawCircleDim(left,top,width,height,color){
left = Math.round(left);
top = Math.round(top);
width = Math.round(width);
height = Math.round(height);
var w = Math.round(width/2);
var h = Math.round(height/2);
var numSections;
if(width>height)numSections = width*2;
else numSections = height*2;
if(numSections>33)numSections = 33;
if(numSections<10)numSections = 10;
var delta_theta = 2.0 * Math.PI / numSections
var theta = 0
if(circleCoords[w][h]==undefined)
{
//alert("make circle "+r);
circleCoords[w][h] = new Array(numSections);
circleCoords[w][h] = new Array(numSections);
for (i = 0; i < numSections ; i++) {
circleCoords[w][h][i] = new Array(2);
x = (w * Math.cos(theta));
y = (h * Math.sin(theta));
x = Math.round(x*1000)/1000
y = Math.round(y*1000)/1000
circleCoords[w][h][i][1] = x;
circleCoords[w][h][i][0] = y;
theta += delta_theta
}
circleCoords[w][h].sort(compareXValue);
for(var i = 0;i<numSections-1;i++)
{
if(circleCoords[w][h][i][0] == circleCoords[w][h][i+1][0] && circleCoords[w][h][i][1]<circleCoords[w][h][i+1][1])
{
temp = circleCoords[w][h][i];
circleCoords[w][h][i] = circleCoords[w][h][i+1];
circleCoords[w][h][i+1] = temp;
}
}
}
var j = 0;
var pvertices = new Float32Array(numSections*2);
for (i=0;i<numSections;i++)
{
pvertices[j] = circleCoords[w][h][i][1]+left;
j++;
pvertices[j] = circleCoords[w][h][i][0]+top;
j++;
}
drawPolygon(pvertices,color);
}
function drawLineArrow(left1,top1,left2,top2,width,color)
{
var opp = top1-top2;
var adj = left1-left2;
var angle = Math.atan(opp/adj)+Math.PI/2;
if(left1>left2 )angle+=Math.PI;
drawLine(left1,top1,left2,top2,width,color);
var triLeft = left1-Math.round(adj/2);
var triTop = top1-Math.round(opp/2);
drawTriang(triLeft,triTop,20,20,angle,color);
}
function stringPixelLength(string)
{
var code;
var width = 0;
for(i=0;i<string.length;i++)
{
code = string.charCodeAt(i)-32;
width += hersheyFont[code][1];
}
return width;
}
function printChar(left,top,character,color,thickness,size)
{
var code = character.charCodeAt(0)-32;
var verticesNeeded = hersheyFont[code][0];
var width = hersheyFont[code][1];
var lef1;
var top1;
var left2;
var top2;
var j = 0;
var i = 2;
var fHeight = 10*size;
while(i<(verticesNeeded*2)+2)
{
j++;
left1 = hersheyFont[code][i]*size+left;
top1 = (fHeight-hersheyFont[code][i+1]*size)+top;
if(hersheyFont[code][i] != -1 && hersheyFont[code][i+1] != -1)
{
if(i>2 && hersheyFont[code][i-1] != -1 && hersheyFont[code][i-2] != -1)
{
drawLine(left2,top2,left1,top1,thickness,color);
}
if(hersheyFont[code][i+2] != -1 && hersheyFont[code][i+3] != -1)
{
left2 = hersheyFont[code][i+2]*size+left;
top2 = (fHeight-hersheyFont[code][i+3]*size)+top;
drawLine(left1,top1,left2,top2,thickness,color);
}
i+=4;
}
else
{
i+=2;
}
}
return width*size;
}
function printString(left,top,string,color,thickness,size)
{
var wordArray = string.split(" ");
var numWords = wordArray.length;
var length = (stringPixelLength(string)/2)*size;
var offset = -length;
for(i=0;i<string.length;i++)
{
offset += printChar(left+offset,top,string[i],color,thickness,size);
}
}
//Styling functions
function getColor(index)
{
var temp = new Array(4);
temp = [colors[index][0],colors[index][1],colors[index][2],1.0]
return temp;
}
function flowTerminator(left,top,width,height,color,strokeSize,strokeColor)
{
var sOff = strokeSize*2;
flowTerminatorNoStroke(left,top,width,height,strokeColor);
flowTerminatorNoStroke(left,top,width-sOff,height-sOff,color);
}
function flowTerminatorNoStroke(left,top,width,height,color)
{
var cWidth = height;
var cOff = (width/2)-(cWidth/2);
drawCircle(left-cOff,top,cWidth,color);
drawCircle(left+cOff,top,cWidth,color);
drawSquare(left,top,cOff*2,height,0,color);
}
function flowProcess(left,top,width,height,color,strokeSize,strokeColor)
{
var sOff = strokeSize*2;
drawSquare(left,top,width,height,0,strokeColor);
drawSquare(left,top,width-sOff,height-sOff,0,color);
}
function diamondStrokeAlgorithm(width, height, strokeSize)
{
var angle1 = Math.atan(height/width);
var angle2 = Math.PI/2 - angle1;
var opp = strokeSize*Math.sin(angle2);
var width1Sq = (strokeSize*strokeSize)-(opp*opp);
var width1 = Math.sqrt(width1Sq);
var width2 = opp/(Math.tan(angle1));
var fWidth = (width1+width2)*2;
return fWidth;
}
function flowDecision(left,top,width,height,color,strokeSize,strokeColor)
{
var wOff = diamondStrokeAlgorithm(width/2, height/2, strokeSize);
var hOff = diamondStrokeAlgorithm(height/2, width/2, strokeSize);
drawDiamond(left,top,width,height,strokeColor);
drawDiamond(left,top,width-wOff,height-hOff,color);
}
// BLACK 0
// WHITE 1
// RED 2
// GREEN 3
// BLUE 4
// YELLOW 5
// PINK 6
// GREY 7
function drawEdge(left1,top1, left2,top2,style){
switch(style){
case 100: // FLOW CHART
// Draw line with Arrow at end
drawLineArrow(left1,top1,left2,top2,2,getColor(0));
break;
case -100:
// Draw line with Arrow at end - HIGHLIGHTED
drawLineArrow(left1,top1,left2,top2,2,getColor(6));
break;
case -10:
drawLine(left1,top1,left2,top2,2,getColor(6));
break;
default:
//Default edge style: black line
drawLine(left1,top1,left2,top2,2,getColor(0));
}
}
function drawVertex(left,top,width,height,style,text,c1,c2,c3)
{
var flowStrokeHighColor = getColor(5);
var flowStrokeColor = getColor(0);
var flowColor = getColor(7);
var flowStrokeSize = 2;
var flowTextColor = getColor(0);
var customColor = [c1,c2,c3,1.0];
switch(style){
case 100: // (100 - 199) FLOW CHART SYMBOLS
// Terminator, start stop
flowTerminator(left,top,width,height,flowColor,flowStrokeSize,flowStrokeColor);
printString(left,top,text,flowTextColor,2,0.75);
break;
case -100:
// Terminator, start stop - HIGHLIGHTED
flowTerminator(left,top,width,height,flowColor,flowStrokeSize,flowStrokeHighColor);
printString(left,top,text,flowTextColor,2,0.75);
break;
case 101:
// Process, process or action step
flowProcess(left,top,width,height,flowColor,flowStrokeSize,flowStrokeColor);
printString(left,top,text,flowTextColor,2,0.75);
break;
case -101:
// Process, process or action step - HIGHLIGHTED
flowProcess(left,top,width,height,flowColor,flowStrokeSize,flowStrokeHighColor);
printString(left,top,text,flowTextColor,2,0.75);
break;
case 102:
// Decision, question or branch
flowDecision(left,top,width,height,flowColor,flowStrokeSize,flowStrokeColor);
printString(left,top,text,flowTextColor,2,0.75);
break;
case -102:
// Decision, question or branch - HIGHLIGHTED
flowDecision(left,top,width,height,flowColor,flowStrokeSize,flowStrokeHighColor);
printString(left,top,text,flowTextColor,2,0.75);
break;
case 5:
// Circle
var sOff = flowStrokeSize*2;
drawCircleDim(left,top,width,height,flowStrokeColor);
drawCircleDim(left,top,width-sOff,height-sOff,customColor);
printString(left,top,text,flowTextColor,2,0.75);
break;
case -5:
// Circle
var sOff = flowStrokeSize*2;
drawCircleDim(left,top,width,height,flowStrokeHighColor);
drawCircleDim(left,top,width-sOff,height-sOff,customColor);
printString(left,top,text,flowTextColor,2,0.75);
break;
case 1:
// Smiley Face
drawCircle(left,top,width,5);
drawCircle(left,top,width*0.7,0);
drawCircle(left,top,width*0.5,5);
drawSquare(left,top,width*0.7,width*0.2,0,5);
drawSquare(left,top-width*0.1,width*0.70,width*0.2,0,5);
drawSquare(left,top-width*0.2,width*0.60,width*0.2,0,5);
drawSquare(left,top-width*0.3,width*0.40,width*0.1,0,5);
drawCircle(left-(width*0.20),top-(width*0.2),width*0.2,0);
drawCircle(left+(width*0.20),top-(width*0.2),width*0.2,0);
break;
case 2:
// Bart Simpson
drawSquare(left,top,width*0.9,width*1.1,0,0);
drawSquare(left,top,width*0.85,width*1.05,0,5);
drawSquare(left-width*0.27,top+width*0.2,width*0.35,width*1.2,0,0);
drawSquare(left-width*0.27,top+width*0.2,width*0.31,width*1.16,0,5);
drawCircle(left+width*0.15,top+width*0.45,width*0.6,0);
drawCircle(left+width*0.15,top+width*0.45,width*0.545,5);
drawSquare(left,top+width*0.27,width*0.85,width*0.5,0,5);
drawSquare(left-width*0.31,top-width*0.55,width*0.2,width*0.2,(Math.PI/4),0)
drawSquare(left-width*0.31,top-width*0.55,width*0.16,width*0.16,(Math.PI/4),5)
drawSquare(left-width*0.06,top-width*0.55,width*0.2,width*0.2,(Math.PI/4),0)
drawSquare(left-width*0.06,top-width*0.55,width*0.16,width*0.16,(Math.PI/4),5)
drawSquare(left+width*0.19,top-width*0.55,width*0.2,width*0.2,(Math.PI/4),0)
drawSquare(left+width*0.19,top-width*0.55,width*0.16,width*0.16,(Math.PI/4),5)
drawSquare(left+width*0.32,top-width*0.55,width*0.2,width*0.2,(Math.PI/4),0)
drawSquare(left+width*0.32,top-width*0.55,width*0.16,width*0.16,(Math.PI/4),5)
drawSquare(left,top-width*0.3,width*0.85,width*0.5,0,5);
drawSquare(left,top-width*0.23,width*0.85,width*0.5,0,5);
drawSquare(left-width*0.15,top+width*0.53,width*0.15,width*0.02,-(Math.PI/5),0)
drawCircle(left+width*0.3,top-width*0.1,width*0.4,0);
drawCircle(left+width*0.3,top-width*0.1,width*0.35,1);
drawCircle(left+width*0.3,top+width*0.1,width*0.2,0);
drawCircle(left+width*0.3,top+width*0.1,width*0.15,5);
drawSquare(left+width*0.2,top+width*0.1,width*0.2,width*0.2,0,0);
drawSquare(left+width*0.2,top+width*0.1,width*0.2,width*0.15,0,5);
drawCircle(left+width*0.05,top-width*0.1,width*0.4,0);
drawCircle(left+width*0.05,top-width*0.1,width*0.35,1);
drawCircle(left+width*0.3,top-width*0.1,width*0.05,0);
drawCircle(left+width*0.05,top-width*0.1,width*0.05,0);
break;
case -10:
drawCircleDim(left,top,width,height,6);
break;
default:
// Default vertex style: black circle
drawCircleDim(left,top,width,height,0);
}
}
function drawGraph() {
setupGL();
for(var i=0;i<edgeNumber;i++)
{
var left1 = parseInt(edgeArray[i][0]);
var top1 = parseInt(edgeArray[i][1]);
var left2 = parseInt(edgeArray[i][2]);
var top2 = parseInt(edgeArray[i][3]);
var style = parseInt(edgeArray[i][4]);
drawEdge( left1,top1,left2,top2,style);
}
for(var i=0;i<verticeNumber;i++)
{
var left = parseInt(verticeArray[i][0]);
var top = parseInt(verticeArray[i][1]);
var width = parseInt(verticeArray[i][2]);
var height = parseInt(verticeArray[i][3]);
var style = parseInt(verticeArray[i][4]);
var text = verticeArray[i][5];
var c1 = verticeArray[i][6];
var c2 = verticeArray[i][7];
var c3 = verticeArray[i][8];
drawVertex(left,top,width,height,style,text,c1,c2,c3);
}
}
drawGraph();
}-*/;
private static native int setupJSNI()/*-{
$wnd.edgeNumber = 0;
$wnd.verticeNumber = 0;
$wnd.edgeArray = new Array(1000);
for(i=0;i<edgeArray.length;i++)edgeArray[i] = new Array(5);
$wnd.verticeArray = new Array(1000);
for(i=0;i<verticeArray.length;i++)verticeArray[i] = new Array(9);
}-*/;
private static native int addEdge(double startX,double startY,double endX,double endY,int style)/*-{
edgeArray[edgeNumber][0] = parseInt(startX);
edgeArray[edgeNumber][1] = parseInt(startY);
edgeArray[edgeNumber][2] = parseInt(endX);
edgeArray[edgeNumber][3] = parseInt(endY);
edgeArray[edgeNumber][4] = parseInt(style);
edgeNumber++;
}-*/;
private static native int addVertice(double centreX,double centreY,double width,double height,int style,String label,double c1,double c2,double c3)/*-{
verticeArray[verticeNumber][0] = parseInt(centreX);
verticeArray[verticeNumber][1] = parseInt(centreY);
verticeArray[verticeNumber][2] = parseInt(width);
verticeArray[verticeNumber][3] = parseInt(height);
verticeArray[verticeNumber][4] = parseInt(style);
verticeArray[verticeNumber][5] = label;
verticeArray[verticeNumber][6] = c1;
verticeArray[verticeNumber][7] = c1;
verticeArray[verticeNumber][8] = c1;
verticeNumber++;
}-*/;
private static native int webglCheck()/*-{
if (typeof Float32Array != "undefined")return 1;
return 0;
}-*/;
public void renderGraph(GWTCanvas canvas, Collection<EdgeDrawable> edges,
Collection<VertexDrawable> vertices) {
// Do a (kind of reliable) check for webgl
if (webglCheck() == 1) { // Can do WebGL
// At the moment coordinates are passed to JavaScript as comma
// separated strings // This will most probably change in the
// future.
setupJSNI();
String edgesString = "";
String veticesString = "";
String separator = ",";
String label = "";
int vertexStyle;
int edgeStyle;
for (EdgeDrawable thisEdge : edges) {
double startX = (thisEdge.getStartX() + offsetX)*zoom;
double startY = (thisEdge.getStartY() + offsetY)*zoom;
double endX = (thisEdge.getEndX() + offsetX)*zoom;
double endY = (thisEdge.getEndY() + offsetY)*zoom;
//edgeStyle = thisEdge.getStyle();
edgeStyle = 100;
if(thisEdge.isHilighted())edgeStyle = -100;
addEdge(startX,startY,endX,endY,edgeStyle);
}
for (VertexDrawable thisVertex : vertices) {
double centreX = (thisVertex.getCenterX() + offsetX)*zoom;
double centreY = (thisVertex.getCenterY() + offsetY)*zoom;
double width = (0.5 * thisVertex.getWidth())*zoom;
double height = (0.5 * thisVertex.getHeight())*zoom;
vertexStyle = thisVertex.getStyle();
switch (vertexStyle) {
case VertexDrawable.STROKED_TERM_STYLE:
vertexStyle = 100;
break;
case VertexDrawable.STROKED_SQUARE_STYLE:
vertexStyle = 101;
break;
case VertexDrawable.STROKED_DIAMOND_STYLE:
vertexStyle = 102;
break;
default:
vertexStyle = 100;
break;
}
label = thisVertex.getLabel();
int[] customColor = {0,0,0};
if(thisVertex.getStyle() == VertexDrawable.COLORED_FILLED_CIRCLE)
{
vertexStyle = 5;
customColor = thisVertex.getColor();
}
if(thisVertex.isHilighted())vertexStyle = -vertexStyle;
addVertice(centreX,centreY,width,height,vertexStyle,label,customColor[0],customColor[1],customColor[2]);
}
// JSNI method used to draw webGL graph version
drawGraph3D();
}
else {
// Cant do webGL so draw on 2d Canvas
renderGraph2d(canvas, edges, vertices);
}
}
public void renderGraph2d(GWTCanvas canvas, Collection<EdgeDrawable> edges,
Collection<VertexDrawable> vertices) {
canvas.setLineWidth(1);
canvas.setStrokeStyle(Color.BLACK);
canvas.setFillStyle(Color.BLACK);
canvas.setFillStyle(Color.WHITE);
canvas.fillRect(0, 0, 2000, 2000);
canvas.setFillStyle(Color.BLACK);
drawGraph(edges, vertices, canvas);
}
// Draws a single vertex, currently only draws circular nodes
private void drawVertex(VertexDrawable vertex, GWTCanvas canvas) {
double centreX = (vertex.getLeft() + 0.5 * vertex.getWidth() + offsetX) * zoom;
double centreY = (vertex.getTop() + 0.5 * vertex.getHeight() + offsetY) * zoom;
double radius = (0.25 * vertex.getWidth()) * zoom;
canvas.moveTo(centreX, centreY);
canvas.beginPath();
canvas.arc(centreX, centreY, radius, 0, 360, false);
canvas.closePath();
canvas.stroke();
canvas.fill();
}
// Draws a line from coordinates to other coordinates
private void drawEdge(EdgeDrawable edge, GWTCanvas canvas) {
double startX = (edge.getStartX() + offsetX)*zoom;
double startY = (edge.getStartY() + offsetY)*zoom;
double endX = (edge.getEndX() + offsetX)*zoom;
double endY = (edge.getEndY() + offsetY)*zoom;
canvas.beginPath();
canvas.moveTo(startX, startY);
canvas.lineTo(endX, endY);
canvas.closePath();
canvas.stroke();
}
// Takes collections of edges and vertices and draws a graph on a specified
// canvas.
private void drawGraph(Collection<EdgeDrawable> edges,
Collection<VertexDrawable> vertices, GWTCanvas canvas) {
for (EdgeDrawable thisEdge : edges) {
drawEdge(thisEdge, canvas);
}
for (VertexDrawable thisVertex : vertices) {
drawVertex(thisVertex, canvas);
}
}
// set offset in the event of a pan
public void setOffset(int x, int y) {
offsetX = x;
offsetY = y;
}
// getters for offsets
public int getOffsetX() {
return offsetX;
}
public int getOffsetY() {
return offsetY;
}
//set zoom
public void setZoom(double z) {
zoom = z;
}
public double getZoom(){
return zoom;
}
}
| private static native void drawGraph3D() /*-{
var circleCoords = new Array(1000);
for(i=0;i<circleCoords.length;i++)circleCoords[i] = new Array(1000);
var gl;
var shaderProgram;
var mvMatrix;
var mvMatrixStack = [];
var colors = [[0.0, 0.0, 0.0], // BLACK 0
[1.0, 1.0, 1.0], // WHITE 1
[1.0, 0.0, 0.0], // RED 2
[0.0, 1.0, 0.0], // GREEN 3
[0.0, 0.0, 1.0], // BLUE 4
[1.0, 1.0, 0.0], // YELLOW 5
[1.0, 0.317, 1.0], // PINK 6
[0.5, 0.5, 0.5], // GREY 7
];
var hersheyFont=[
[0,16,//Ascii32
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[8,10,//Ascii33
5,21,5,7,-1,-1,5,2,4,1,5,0,6,1,5,2,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[5,16,//Ascii34
4,21,4,14,-1,-1,12,21,12,14,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[11,21,//Ascii35
11,25,4,-7,-1,-1,17,25,10,-7,-1,-1,4,12,18,12,-1,-1,3,6,17,6,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[26,20,//Ascii36
8,25,8,-4,-1,-1,12,25,12,-4,-1,-1,17,18,15,20,12,21,8,21,5,20,3,
18,3,16,4,14,5,13,7,12,13,10,15,9,16,8,17,6,17,3,15,1,12,0,
8,0,5,1,3,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[31,24,//Ascii37
21,21,3,0,-1,-1,8,21,10,19,10,17,9,15,7,14,5,14,3,16,3,18,4,
20,6,21,8,21,10,20,13,19,16,19,19,20,21,21,-1,-1,17,7,15,6,14,4,
14,2,16,0,18,0,20,1,21,3,21,5,19,7,17,7,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[34,26,//Ascii38
23,12,23,13,22,14,21,14,20,13,19,11,17,6,15,3,13,1,11,0,7,0,5,
1,4,2,3,4,3,6,4,8,5,9,12,13,13,14,14,16,14,18,13,20,11,21,
9,20,8,18,8,16,9,13,11,10,16,3,18,1,20,0,22,0,23,1,23,2,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[7,10,//Ascii39
5,19,4,20,5,21,6,20,6,18,5,16,4,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[10,14,//Ascii40
11,25,9,23,7,20,5,16,4,11,4,7,5,2,7,-2,9,-5,11,-7,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[10,14,//Ascii41
3,25,5,23,7,20,9,16,10,11,10,7,9,2,7,-2,5,-5,3,-7,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[8,16,//Ascii42
8,21,8,9,-1,-1,3,18,13,12,-1,-1,13,18,3,12,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[5,26,//Ascii43
13,18,13,0,-1,-1,4,9,22,9,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[8,10,//Ascii44
6,1,5,0,4,1,5,2,6,1,6,-1,5,-3,4,-4,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[2,26,//Ascii45
4,9,22,9,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[5,10,//Ascii46
5,2,4,1,5,0,6,1,5,2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[2,22,//Ascii47
20,25,2,-7,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[17,20,//Ascii48
9,21,6,20,4,17,3,12,3,9,4,4,6,1,9,0,11,0,14,1,16,4,17,
9,17,12,16,17,14,20,11,21,9,21,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[4,20,//Ascii49
6,17,8,18,11,21,11,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[14,20,//Ascii50
4,16,4,17,5,19,6,20,8,21,12,21,14,20,15,19,16,17,16,15,15,13,13,
10,3,0,17,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[15,20,//Ascii51
5,21,16,21,10,13,13,13,15,12,16,11,17,8,17,6,16,3,14,1,11,0,8,
0,5,1,4,2,3,4,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[6,20,//Ascii52
13,21,3,7,18,7,-1,-1,13,21,13,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[17,20,//Ascii53
15,21,5,21,4,12,5,13,8,14,11,14,14,13,16,11,17,8,17,6,16,3,14,
1,11,0,8,0,5,1,4,2,3,4,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[23,20,//Ascii54
16,18,15,20,12,21,10,21,7,20,5,17,4,12,4,7,5,3,7,1,10,0,11,
0,14,1,16,3,17,6,17,7,16,10,14,12,11,13,10,13,7,12,5,10,4,7,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[5,20,//Ascii55
17,21,7,0,-1,-1,3,21,17,21,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[29,20,//Ascii56
8,21,5,20,4,18,4,16,5,14,7,13,11,12,14,11,16,9,17,7,17,4,16,
2,15,1,12,0,8,0,5,1,4,2,3,4,3,7,4,9,6,11,9,12,13,13,
15,14,16,16,16,18,15,20,12,21,8,21,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[23,20,//Ascii57
16,14,15,11,13,9,10,8,9,8,6,9,4,11,3,14,3,15,4,18,6,20,9,
21,10,21,13,20,15,18,16,14,16,9,15,4,13,1,10,0,8,0,5,1,4,3,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[11,10,//Ascii58
5,14,4,13,5,12,6,13,5,14,-1,-1,5,2,4,1,5,0,6,1,5,2,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[14,10,//Ascii59
5,14,4,13,5,12,6,13,5,14,-1,-1,6,1,5,0,4,1,5,2,6,1,6,
-1,5,-3,4,-4,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[3,24,//Ascii60
20,18,4,9,20,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[5,26,//Ascii61
4,12,22,12,-1,-1,4,6,22,6,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[3,24,//Ascii62
4,18,20,9,4,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[20,18,//Ascii63
3,16,3,17,4,19,5,20,7,21,11,21,13,20,14,19,15,17,15,15,14,13,13,
12,9,10,9,7,-1,-1,9,2,8,1,9,0,10,1,9,2,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[55,27,//Ascii64
18,13,17,15,15,16,12,16,10,15,9,14,8,11,8,8,9,6,11,5,14,5,16,
6,17,8,-1,-1,12,16,10,14,9,11,9,8,10,6,11,5,-1,-1,18,16,17,8,
17,6,19,5,21,5,23,7,24,10,24,12,23,15,22,17,20,19,18,20,15,21,12,
21,9,20,7,19,5,17,4,15,3,12,3,9,4,6,5,4,7,2,9,1,12,0,
15,0,18,1,20,2,21,3,-1,-1,19,16,18,8,18,6,19,5,],
[8,18,//Ascii65
9,21,1,0,-1,-1,9,21,17,0,-1,-1,4,7,14,7,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[23,21,//Ascii66
4,21,4,0,-1,-1,4,21,13,21,16,20,17,19,18,17,18,15,17,13,16,12,13,
11,-1,-1,4,11,13,11,16,10,17,9,18,7,18,4,17,2,16,1,13,0,4,0,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[18,21,//Ascii67
18,16,17,18,15,20,13,21,9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,
3,7,1,9,0,13,0,15,1,17,3,18,5,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[15,21,//Ascii68
4,21,4,0,-1,-1,4,21,11,21,14,20,16,18,17,16,18,13,18,8,17,5,16,
3,14,1,11,0,4,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[11,19,//Ascii69
4,21,4,0,-1,-1,4,21,17,21,-1,-1,4,11,12,11,-1,-1,4,0,17,0,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[8,18,//Ascii70
4,21,4,0,-1,-1,4,21,17,21,-1,-1,4,11,12,11,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[22,21,//Ascii71
18,16,17,18,15,20,13,21,9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,
3,7,1,9,0,13,0,15,1,17,3,18,5,18,8,-1,-1,13,8,18,8,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[8,22,//Ascii72
4,21,4,0,-1,-1,18,21,18,0,-1,-1,4,11,18,11,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[2,8,//Ascii73
4,21,4,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[10,16,//Ascii74
12,21,12,5,11,2,10,1,8,0,6,0,4,1,3,2,2,5,2,7,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[8,21,//Ascii75
4,21,4,0,-1,-1,18,21,4,7,-1,-1,9,12,18,0,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[5,17,//Ascii76
4,21,4,0,-1,-1,4,0,16,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[11,24,//Ascii77
4,21,4,0,-1,-1,4,21,12,0,-1,-1,20,21,12,0,-1,-1,20,21,20,0,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[8,22,//Ascii78
4,21,4,0,-1,-1,4,21,18,0,-1,-1,18,21,18,0,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[21,22,//Ascii79
9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,
1,17,3,18,5,19,8,19,13,18,16,17,18,15,20,13,21,9,21,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[13,21,//Ascii80
4,21,4,0,-1,-1,4,21,13,21,16,20,17,19,18,17,18,14,17,12,16,11,13,
10,4,10,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[24,22,//Ascii81
9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,
1,17,3,18,5,19,8,19,13,18,16,17,18,15,20,13,21,9,21,-1,-1,12,4,
18,-2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[16,21,//Ascii82
4,21,4,0,-1,-1,4,21,13,21,16,20,17,19,18,17,18,15,17,13,16,12,13,
11,4,11,-1,-1,11,11,18,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[20,20,//Ascii83
17,18,15,20,12,21,8,21,5,20,3,18,3,16,4,14,5,13,7,12,13,10,15,
9,16,8,17,6,17,3,15,1,12,0,8,0,5,1,3,3,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[5,16,//Ascii84
8,21,8,0,-1,-1,1,21,15,21,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[10,22,//Ascii85
4,21,4,6,5,3,7,1,10,0,12,0,15,1,17,3,18,6,18,21,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[5,18,//Ascii86
1,21,9,0,-1,-1,17,21,9,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[11,24,//Ascii87
2,21,7,0,-1,-1,12,21,7,0,-1,-1,12,21,17,0,-1,-1,22,21,17,0,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[5,20,//Ascii88
3,21,17,0,-1,-1,17,21,3,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[6,18,//Ascii89
1,21,9,11,9,0,-1,-1,17,21,9,11,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[8,20,//Ascii90
17,21,3,0,-1,-1,3,21,17,21,-1,-1,3,0,17,0,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[11,14,//Ascii91
4,25,4,-7,-1,-1,5,25,5,-7,-1,-1,4,25,11,25,-1,-1,4,-7,11,-7,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[2,14,//Ascii92
0,21,14,-3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[11,14,//Ascii93
9,25,9,-7,-1,-1,10,25,10,-7,-1,-1,3,25,10,25,-1,-1,3,-7,10,-7,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[10,16,//Ascii94
6,15,8,18,10,15,-1,-1,3,12,8,17,13,12,-1,-1,8,17,8,0,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[2,16,//Ascii95
0,-2,16,-2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[7,10,//Ascii96
6,21,5,20,4,18,4,16,5,15,6,16,5,17,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[17,19,//Ascii97
15,14,15,0,-1,-1,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,
3,6,1,8,0,11,0,13,1,15,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[17,19,//Ascii98
4,21,4,0,-1,-1,4,11,6,13,8,14,11,14,13,13,15,11,16,8,16,6,15,
3,13,1,11,0,8,0,6,1,4,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[14,18,//Ascii99
15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,
0,13,1,15,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[17,19,//Ascii100
15,21,15,0,-1,-1,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,
3,6,1,8,0,11,0,13,1,15,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[17,18,//Ascii101
3,8,15,8,15,10,14,12,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,
3,6,1,8,0,11,0,13,1,15,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[8,12,//Ascii102
10,21,8,21,6,20,5,17,5,0,-1,-1,2,14,9,14,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[22,19,//Ascii103
15,14,15,-2,14,-5,13,-6,11,-7,8,-7,6,-6,-1,-1,15,11,13,13,11,14,8,
14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[10,19,//Ascii104
4,21,4,0,-1,-1,4,10,7,13,9,14,12,14,14,13,15,10,15,0,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[8,8,//Ascii105
3,21,4,20,5,21,4,22,3,21,-1,-1,4,14,4,0,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[11,10,//Ascii106
5,21,6,20,7,21,6,22,5,21,-1,-1,6,14,6,-3,5,-6,3,-7,1,-7,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[8,17,//Ascii107
4,21,4,0,-1,-1,14,14,4,4,-1,-1,8,8,15,0,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[2,8,//Ascii108
4,21,4,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[18,30,//Ascii109
4,14,4,0,-1,-1,4,10,7,13,9,14,12,14,14,13,15,10,15,0,-1,-1,15,
10,18,13,20,14,23,14,25,13,26,10,26,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[10,19,//Ascii110
4,14,4,0,-1,-1,4,10,7,13,9,14,12,14,14,13,15,10,15,0,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[17,19,//Ascii111
8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3,16,
6,16,8,15,11,13,13,11,14,8,14,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[17,19,//Ascii112
4,14,4,-7,-1,-1,4,11,6,13,8,14,11,14,13,13,15,11,16,8,16,6,15,
3,13,1,11,0,8,0,6,1,4,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[17,19,//Ascii113
15,14,15,-7,-1,-1,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,
3,6,1,8,0,11,0,13,1,15,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[8,13,//Ascii114
4,14,4,0,-1,-1,4,8,5,11,7,13,9,14,12,14,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[17,17,//Ascii115
14,11,13,13,10,14,7,14,4,13,3,11,4,9,6,8,11,7,13,6,14,4,14,
3,13,1,10,0,7,0,4,1,3,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[8,12,//Ascii116
5,21,5,4,6,1,8,0,10,0,-1,-1,2,14,9,14,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[10,19,//Ascii117
4,14,4,4,5,1,7,0,10,0,12,1,15,4,-1,-1,15,14,15,0,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[5,16,//Ascii118
2,14,8,0,-1,-1,14,14,8,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[11,22,//Ascii119
3,14,7,0,-1,-1,11,14,7,0,-1,-1,11,14,15,0,-1,-1,19,14,15,0,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[5,17,//Ascii120
3,14,14,0,-1,-1,14,14,3,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[9,16,//Ascii121
2,14,8,0,-1,-1,14,14,8,0,6,-4,4,-6,2,-7,1,-7,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[8,17,//Ascii122
14,14,3,0,-1,-1,3,14,14,14,-1,-1,3,0,14,0,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[39,14,//Ascii123
9,25,7,24,6,23,5,21,5,19,6,17,7,16,8,14,8,12,6,10,-1,-1,7,
24,6,22,6,20,7,18,8,17,9,15,9,13,8,11,4,9,8,7,9,5,9,3,
8,1,7,0,6,-2,6,-4,7,-6,-1,-1,6,8,8,6,8,4,7,2,6,1,5,
-1,5,-3,6,-5,7,-6,9,-7,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[2,8,//Ascii124
4,25,4,-7,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[39,14,//Ascii125
5,25,7,24,8,23,9,21,9,19,8,17,7,16,6,14,6,12,8,10,-1,-1,7,
24,8,22,8,20,7,18,6,17,5,15,5,13,6,11,10,9,6,7,5,5,5,3,
6,1,7,0,8,-2,8,-4,7,-6,-1,-1,8,8,6,6,6,4,7,2,8,1,9,
-1,9,-3,8,-5,7,-6,5,-7,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,],
[23,24,//Ascii126
3,6,3,8,4,11,6,12,8,12,10,11,14,8,16,7,18,7,20,8,21,10,-1,
-1,3,8,4,10,6,11,8,11,10,10,14,7,16,6,18,6,20,7,21,10,21,12,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,]
];
// Sylvester.js Libary
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('9 17={3i:\'0.1.3\',16:1e-6};l v(){}v.23={e:l(i){8(i<1||i>7.4.q)?w:7.4[i-1]},2R:l(){8 7.4.q},1u:l(){8 F.1x(7.2u(7))},24:l(a){9 n=7.4.q;9 V=a.4||a;o(n!=V.q){8 1L}J{o(F.13(7.4[n-1]-V[n-1])>17.16){8 1L}}H(--n);8 2x},1q:l(){8 v.u(7.4)},1b:l(a){9 b=[];7.28(l(x,i){b.19(a(x,i))});8 v.u(b)},28:l(a){9 n=7.4.q,k=n,i;J{i=k-n;a(7.4[i],i+1)}H(--n)},2q:l(){9 r=7.1u();o(r===0){8 7.1q()}8 7.1b(l(x){8 x/r})},1C:l(a){9 V=a.4||a;9 n=7.4.q,k=n,i;o(n!=V.q){8 w}9 b=0,1D=0,1F=0;7.28(l(x,i){b+=x*V[i-1];1D+=x*x;1F+=V[i-1]*V[i-1]});1D=F.1x(1D);1F=F.1x(1F);o(1D*1F===0){8 w}9 c=b/(1D*1F);o(c<-1){c=-1}o(c>1){c=1}8 F.37(c)},1m:l(a){9 b=7.1C(a);8(b===w)?w:(b<=17.16)},34:l(a){9 b=7.1C(a);8(b===w)?w:(F.13(b-F.1A)<=17.16)},2k:l(a){9 b=7.2u(a);8(b===w)?w:(F.13(b)<=17.16)},2j:l(a){9 V=a.4||a;o(7.4.q!=V.q){8 w}8 7.1b(l(x,i){8 x+V[i-1]})},2C:l(a){9 V=a.4||a;o(7.4.q!=V.q){8 w}8 7.1b(l(x,i){8 x-V[i-1]})},22:l(k){8 7.1b(l(x){8 x*k})},x:l(k){8 7.22(k)},2u:l(a){9 V=a.4||a;9 i,2g=0,n=7.4.q;o(n!=V.q){8 w}J{2g+=7.4[n-1]*V[n-1]}H(--n);8 2g},2f:l(a){9 B=a.4||a;o(7.4.q!=3||B.q!=3){8 w}9 A=7.4;8 v.u([(A[1]*B[2])-(A[2]*B[1]),(A[2]*B[0])-(A[0]*B[2]),(A[0]*B[1])-(A[1]*B[0])])},2A:l(){9 m=0,n=7.4.q,k=n,i;J{i=k-n;o(F.13(7.4[i])>F.13(m)){m=7.4[i]}}H(--n);8 m},2Z:l(x){9 a=w,n=7.4.q,k=n,i;J{i=k-n;o(a===w&&7.4[i]==x){a=i+1}}H(--n);8 a},3g:l(){8 S.2X(7.4)},2d:l(){8 7.1b(l(x){8 F.2d(x)})},2V:l(x){8 7.1b(l(y){8(F.13(y-x)<=17.16)?x:y})},1o:l(a){o(a.K){8 a.1o(7)}9 V=a.4||a;o(V.q!=7.4.q){8 w}9 b=0,2b;7.28(l(x,i){2b=x-V[i-1];b+=2b*2b});8 F.1x(b)},3a:l(a){8 a.1h(7)},2T:l(a){8 a.1h(7)},1V:l(t,a){9 V,R,x,y,z;2S(7.4.q){27 2:V=a.4||a;o(V.q!=2){8 w}R=S.1R(t).4;x=7.4[0]-V[0];y=7.4[1]-V[1];8 v.u([V[0]+R[0][0]*x+R[0][1]*y,V[1]+R[1][0]*x+R[1][1]*y]);1I;27 3:o(!a.U){8 w}9 C=a.1r(7).4;R=S.1R(t,a.U).4;x=7.4[0]-C[0];y=7.4[1]-C[1];z=7.4[2]-C[2];8 v.u([C[0]+R[0][0]*x+R[0][1]*y+R[0][2]*z,C[1]+R[1][0]*x+R[1][1]*y+R[1][2]*z,C[2]+R[2][0]*x+R[2][1]*y+R[2][2]*z]);1I;2P:8 w}},1t:l(a){o(a.K){9 P=7.4.2O();9 C=a.1r(P).4;8 v.u([C[0]+(C[0]-P[0]),C[1]+(C[1]-P[1]),C[2]+(C[2]-(P[2]||0))])}1d{9 Q=a.4||a;o(7.4.q!=Q.q){8 w}8 7.1b(l(x,i){8 Q[i-1]+(Q[i-1]-x)})}},1N:l(){9 V=7.1q();2S(V.4.q){27 3:1I;27 2:V.4.19(0);1I;2P:8 w}8 V},2n:l(){8\'[\'+7.4.2K(\', \')+\']\'},26:l(a){7.4=(a.4||a).2O();8 7}};v.u=l(a){9 V=25 v();8 V.26(a)};v.i=v.u([1,0,0]);v.j=v.u([0,1,0]);v.k=v.u([0,0,1]);v.2J=l(n){9 a=[];J{a.19(F.2F())}H(--n);8 v.u(a)};v.1j=l(n){9 a=[];J{a.19(0)}H(--n);8 v.u(a)};l S(){}S.23={e:l(i,j){o(i<1||i>7.4.q||j<1||j>7.4[0].q){8 w}8 7.4[i-1][j-1]},33:l(i){o(i>7.4.q){8 w}8 v.u(7.4[i-1])},2E:l(j){o(j>7.4[0].q){8 w}9 a=[],n=7.4.q,k=n,i;J{i=k-n;a.19(7.4[i][j-1])}H(--n);8 v.u(a)},2R:l(){8{2D:7.4.q,1p:7.4[0].q}},2D:l(){8 7.4.q},1p:l(){8 7.4[0].q},24:l(a){9 M=a.4||a;o(1g(M[0][0])==\'1f\'){M=S.u(M).4}o(7.4.q!=M.q||7.4[0].q!=M[0].q){8 1L}9 b=7.4.q,15=b,i,G,10=7.4[0].q,j;J{i=15-b;G=10;J{j=10-G;o(F.13(7.4[i][j]-M[i][j])>17.16){8 1L}}H(--G)}H(--b);8 2x},1q:l(){8 S.u(7.4)},1b:l(a){9 b=[],12=7.4.q,15=12,i,G,10=7.4[0].q,j;J{i=15-12;G=10;b[i]=[];J{j=10-G;b[i][j]=a(7.4[i][j],i+1,j+1)}H(--G)}H(--12);8 S.u(b)},2i:l(a){9 M=a.4||a;o(1g(M[0][0])==\'1f\'){M=S.u(M).4}8(7.4.q==M.q&&7.4[0].q==M[0].q)},2j:l(a){9 M=a.4||a;o(1g(M[0][0])==\'1f\'){M=S.u(M).4}o(!7.2i(M)){8 w}8 7.1b(l(x,i,j){8 x+M[i-1][j-1]})},2C:l(a){9 M=a.4||a;o(1g(M[0][0])==\'1f\'){M=S.u(M).4}o(!7.2i(M)){8 w}8 7.1b(l(x,i,j){8 x-M[i-1][j-1]})},2B:l(a){9 M=a.4||a;o(1g(M[0][0])==\'1f\'){M=S.u(M).4}8(7.4[0].q==M.q)},22:l(a){o(!a.4){8 7.1b(l(x){8 x*a})}9 b=a.1u?2x:1L;9 M=a.4||a;o(1g(M[0][0])==\'1f\'){M=S.u(M).4}o(!7.2B(M)){8 w}9 d=7.4.q,15=d,i,G,10=M[0].q,j;9 e=7.4[0].q,4=[],21,20,c;J{i=15-d;4[i]=[];G=10;J{j=10-G;21=0;20=e;J{c=e-20;21+=7.4[i][c]*M[c][j]}H(--20);4[i][j]=21}H(--G)}H(--d);9 M=S.u(4);8 b?M.2E(1):M},x:l(a){8 7.22(a)},32:l(a,b,c,d){9 e=[],12=c,i,G,j;9 f=7.4.q,1p=7.4[0].q;J{i=c-12;e[i]=[];G=d;J{j=d-G;e[i][j]=7.4[(a+i-1)%f][(b+j-1)%1p]}H(--G)}H(--12);8 S.u(e)},31:l(){9 a=7.4.q,1p=7.4[0].q;9 b=[],12=1p,i,G,j;J{i=1p-12;b[i]=[];G=a;J{j=a-G;b[i][j]=7.4[j][i]}H(--G)}H(--12);8 S.u(b)},1y:l(){8(7.4.q==7.4[0].q)},2A:l(){9 m=0,12=7.4.q,15=12,i,G,10=7.4[0].q,j;J{i=15-12;G=10;J{j=10-G;o(F.13(7.4[i][j])>F.13(m)){m=7.4[i][j]}}H(--G)}H(--12);8 m},2Z:l(x){9 a=w,12=7.4.q,15=12,i,G,10=7.4[0].q,j;J{i=15-12;G=10;J{j=10-G;o(7.4[i][j]==x){8{i:i+1,j:j+1}}}H(--G)}H(--12);8 w},30:l(){o(!7.1y){8 w}9 a=[],n=7.4.q,k=n,i;J{i=k-n;a.19(7.4[i][i])}H(--n);8 v.u(a)},1K:l(){9 M=7.1q(),1c;9 n=7.4.q,k=n,i,1s,1n=7.4[0].q,p;J{i=k-n;o(M.4[i][i]==0){2e(j=i+1;j<k;j++){o(M.4[j][i]!=0){1c=[];1s=1n;J{p=1n-1s;1c.19(M.4[i][p]+M.4[j][p])}H(--1s);M.4[i]=1c;1I}}}o(M.4[i][i]!=0){2e(j=i+1;j<k;j++){9 a=M.4[j][i]/M.4[i][i];1c=[];1s=1n;J{p=1n-1s;1c.19(p<=i?0:M.4[j][p]-M.4[i][p]*a)}H(--1s);M.4[j]=1c}}}H(--n);8 M},3h:l(){8 7.1K()},2z:l(){o(!7.1y()){8 w}9 M=7.1K();9 a=M.4[0][0],n=M.4.q-1,k=n,i;J{i=k-n+1;a=a*M.4[i][i]}H(--n);8 a},3f:l(){8 7.2z()},2y:l(){8(7.1y()&&7.2z()===0)},2Y:l(){o(!7.1y()){8 w}9 a=7.4[0][0],n=7.4.q-1,k=n,i;J{i=k-n+1;a+=7.4[i][i]}H(--n);8 a},3e:l(){8 7.2Y()},1Y:l(){9 M=7.1K(),1Y=0;9 a=7.4.q,15=a,i,G,10=7.4[0].q,j;J{i=15-a;G=10;J{j=10-G;o(F.13(M.4[i][j])>17.16){1Y++;1I}}H(--G)}H(--a);8 1Y},3d:l(){8 7.1Y()},2W:l(a){9 M=a.4||a;o(1g(M[0][0])==\'1f\'){M=S.u(M).4}9 T=7.1q(),1p=T.4[0].q;9 b=T.4.q,15=b,i,G,10=M[0].q,j;o(b!=M.q){8 w}J{i=15-b;G=10;J{j=10-G;T.4[i][1p+j]=M[i][j]}H(--G)}H(--b);8 T},2w:l(){o(!7.1y()||7.2y()){8 w}9 a=7.4.q,15=a,i,j;9 M=7.2W(S.I(a)).1K();9 b,1n=M.4[0].q,p,1c,2v;9 c=[],2c;J{i=a-1;1c=[];b=1n;c[i]=[];2v=M.4[i][i];J{p=1n-b;2c=M.4[i][p]/2v;1c.19(2c);o(p>=15){c[i].19(2c)}}H(--b);M.4[i]=1c;2e(j=0;j<i;j++){1c=[];b=1n;J{p=1n-b;1c.19(M.4[j][p]-M.4[i][p]*M.4[j][i])}H(--b);M.4[j]=1c}}H(--a);8 S.u(c)},3c:l(){8 7.2w()},2d:l(){8 7.1b(l(x){8 F.2d(x)})},2V:l(x){8 7.1b(l(p){8(F.13(p-x)<=17.16)?x:p})},2n:l(){9 a=[];9 n=7.4.q,k=n,i;J{i=k-n;a.19(v.u(7.4[i]).2n())}H(--n);8 a.2K(\'\\n\')},26:l(a){9 i,4=a.4||a;o(1g(4[0][0])!=\'1f\'){9 b=4.q,15=b,G,10,j;7.4=[];J{i=15-b;G=4[i].q;10=G;7.4[i]=[];J{j=10-G;7.4[i][j]=4[i][j]}H(--G)}H(--b);8 7}9 n=4.q,k=n;7.4=[];J{i=k-n;7.4.19([4[i]])}H(--n);8 7}};S.u=l(a){9 M=25 S();8 M.26(a)};S.I=l(n){9 a=[],k=n,i,G,j;J{i=k-n;a[i]=[];G=k;J{j=k-G;a[i][j]=(i==j)?1:0}H(--G)}H(--n);8 S.u(a)};S.2X=l(a){9 n=a.q,k=n,i;9 M=S.I(n);J{i=k-n;M.4[i][i]=a[i]}H(--n);8 M};S.1R=l(b,a){o(!a){8 S.u([[F.1H(b),-F.1G(b)],[F.1G(b),F.1H(b)]])}9 d=a.1q();o(d.4.q!=3){8 w}9 e=d.1u();9 x=d.4[0]/e,y=d.4[1]/e,z=d.4[2]/e;9 s=F.1G(b),c=F.1H(b),t=1-c;8 S.u([[t*x*x+c,t*x*y-s*z,t*x*z+s*y],[t*x*y+s*z,t*y*y+c,t*y*z-s*x],[t*x*z-s*y,t*y*z+s*x,t*z*z+c]])};S.3b=l(t){9 c=F.1H(t),s=F.1G(t);8 S.u([[1,0,0],[0,c,-s],[0,s,c]])};S.39=l(t){9 c=F.1H(t),s=F.1G(t);8 S.u([[c,0,s],[0,1,0],[-s,0,c]])};S.38=l(t){9 c=F.1H(t),s=F.1G(t);8 S.u([[c,-s,0],[s,c,0],[0,0,1]])};S.2J=l(n,m){8 S.1j(n,m).1b(l(){8 F.2F()})};S.1j=l(n,m){9 a=[],12=n,i,G,j;J{i=n-12;a[i]=[];G=m;J{j=m-G;a[i][j]=0}H(--G)}H(--12);8 S.u(a)};l 14(){}14.23={24:l(a){8(7.1m(a)&&7.1h(a.K))},1q:l(){8 14.u(7.K,7.U)},2U:l(a){9 V=a.4||a;8 14.u([7.K.4[0]+V[0],7.K.4[1]+V[1],7.K.4[2]+(V[2]||0)],7.U)},1m:l(a){o(a.W){8 a.1m(7)}9 b=7.U.1C(a.U);8(F.13(b)<=17.16||F.13(b-F.1A)<=17.16)},1o:l(a){o(a.W){8 a.1o(7)}o(a.U){o(7.1m(a)){8 7.1o(a.K)}9 N=7.U.2f(a.U).2q().4;9 A=7.K.4,B=a.K.4;8 F.13((A[0]-B[0])*N[0]+(A[1]-B[1])*N[1]+(A[2]-B[2])*N[2])}1d{9 P=a.4||a;9 A=7.K.4,D=7.U.4;9 b=P[0]-A[0],2a=P[1]-A[1],29=(P[2]||0)-A[2];9 c=F.1x(b*b+2a*2a+29*29);o(c===0)8 0;9 d=(b*D[0]+2a*D[1]+29*D[2])/c;9 e=1-d*d;8 F.13(c*F.1x(e<0?0:e))}},1h:l(a){9 b=7.1o(a);8(b!==w&&b<=17.16)},2T:l(a){8 a.1h(7)},1v:l(a){o(a.W){8 a.1v(7)}8(!7.1m(a)&&7.1o(a)<=17.16)},1U:l(a){o(a.W){8 a.1U(7)}o(!7.1v(a)){8 w}9 P=7.K.4,X=7.U.4,Q=a.K.4,Y=a.U.4;9 b=X[0],1z=X[1],1B=X[2],1T=Y[0],1S=Y[1],1M=Y[2];9 c=P[0]-Q[0],2s=P[1]-Q[1],2r=P[2]-Q[2];9 d=-b*c-1z*2s-1B*2r;9 e=1T*c+1S*2s+1M*2r;9 f=b*b+1z*1z+1B*1B;9 g=1T*1T+1S*1S+1M*1M;9 h=b*1T+1z*1S+1B*1M;9 k=(d*g/f+h*e)/(g-h*h);8 v.u([P[0]+k*b,P[1]+k*1z,P[2]+k*1B])},1r:l(a){o(a.U){o(7.1v(a)){8 7.1U(a)}o(7.1m(a)){8 w}9 D=7.U.4,E=a.U.4;9 b=D[0],1l=D[1],1k=D[2],1P=E[0],1O=E[1],1Q=E[2];9 x=(1k*1P-b*1Q),y=(b*1O-1l*1P),z=(1l*1Q-1k*1O);9 N=v.u([x*1Q-y*1O,y*1P-z*1Q,z*1O-x*1P]);9 P=11.u(a.K,N);8 P.1U(7)}1d{9 P=a.4||a;o(7.1h(P)){8 v.u(P)}9 A=7.K.4,D=7.U.4;9 b=D[0],1l=D[1],1k=D[2],1w=A[0],18=A[1],1a=A[2];9 x=b*(P[1]-18)-1l*(P[0]-1w),y=1l*((P[2]||0)-1a)-1k*(P[1]-18),z=1k*(P[0]-1w)-b*((P[2]||0)-1a);9 V=v.u([1l*x-1k*z,1k*y-b*x,b*z-1l*y]);9 k=7.1o(P)/V.1u();8 v.u([P[0]+V.4[0]*k,P[1]+V.4[1]*k,(P[2]||0)+V.4[2]*k])}},1V:l(t,a){o(1g(a.U)==\'1f\'){a=14.u(a.1N(),v.k)}9 R=S.1R(t,a.U).4;9 C=a.1r(7.K).4;9 A=7.K.4,D=7.U.4;9 b=C[0],1E=C[1],1J=C[2],1w=A[0],18=A[1],1a=A[2];9 x=1w-b,y=18-1E,z=1a-1J;8 14.u([b+R[0][0]*x+R[0][1]*y+R[0][2]*z,1E+R[1][0]*x+R[1][1]*y+R[1][2]*z,1J+R[2][0]*x+R[2][1]*y+R[2][2]*z],[R[0][0]*D[0]+R[0][1]*D[1]+R[0][2]*D[2],R[1][0]*D[0]+R[1][1]*D[1]+R[1][2]*D[2],R[2][0]*D[0]+R[2][1]*D[1]+R[2][2]*D[2]])},1t:l(a){o(a.W){9 A=7.K.4,D=7.U.4;9 b=A[0],18=A[1],1a=A[2],2N=D[0],1l=D[1],1k=D[2];9 c=7.K.1t(a).4;9 d=b+2N,2h=18+1l,2o=1a+1k;9 Q=a.1r([d,2h,2o]).4;9 e=[Q[0]+(Q[0]-d)-c[0],Q[1]+(Q[1]-2h)-c[1],Q[2]+(Q[2]-2o)-c[2]];8 14.u(c,e)}1d o(a.U){8 7.1V(F.1A,a)}1d{9 P=a.4||a;8 14.u(7.K.1t([P[0],P[1],(P[2]||0)]),7.U)}},1Z:l(a,b){a=v.u(a);b=v.u(b);o(a.4.q==2){a.4.19(0)}o(b.4.q==2){b.4.19(0)}o(a.4.q>3||b.4.q>3){8 w}9 c=b.1u();o(c===0){8 w}7.K=a;7.U=v.u([b.4[0]/c,b.4[1]/c,b.4[2]/c]);8 7}};14.u=l(a,b){9 L=25 14();8 L.1Z(a,b)};14.X=14.u(v.1j(3),v.i);14.Y=14.u(v.1j(3),v.j);14.Z=14.u(v.1j(3),v.k);l 11(){}11.23={24:l(a){8(7.1h(a.K)&&7.1m(a))},1q:l(){8 11.u(7.K,7.W)},2U:l(a){9 V=a.4||a;8 11.u([7.K.4[0]+V[0],7.K.4[1]+V[1],7.K.4[2]+(V[2]||0)],7.W)},1m:l(a){9 b;o(a.W){b=7.W.1C(a.W);8(F.13(b)<=17.16||F.13(F.1A-b)<=17.16)}1d o(a.U){8 7.W.2k(a.U)}8 w},2k:l(a){9 b=7.W.1C(a.W);8(F.13(F.1A/2-b)<=17.16)},1o:l(a){o(7.1v(a)||7.1h(a)){8 0}o(a.K){9 A=7.K.4,B=a.K.4,N=7.W.4;8 F.13((A[0]-B[0])*N[0]+(A[1]-B[1])*N[1]+(A[2]-B[2])*N[2])}1d{9 P=a.4||a;9 A=7.K.4,N=7.W.4;8 F.13((A[0]-P[0])*N[0]+(A[1]-P[1])*N[1]+(A[2]-(P[2]||0))*N[2])}},1h:l(a){o(a.W){8 w}o(a.U){8(7.1h(a.K)&&7.1h(a.K.2j(a.U)))}1d{9 P=a.4||a;9 A=7.K.4,N=7.W.4;9 b=F.13(N[0]*(A[0]-P[0])+N[1]*(A[1]-P[1])+N[2]*(A[2]-(P[2]||0)));8(b<=17.16)}},1v:l(a){o(1g(a.U)==\'1f\'&&1g(a.W)==\'1f\'){8 w}8!7.1m(a)},1U:l(a){o(!7.1v(a)){8 w}o(a.U){9 A=a.K.4,D=a.U.4,P=7.K.4,N=7.W.4;9 b=(N[0]*(P[0]-A[0])+N[1]*(P[1]-A[1])+N[2]*(P[2]-A[2]))/(N[0]*D[0]+N[1]*D[1]+N[2]*D[2]);8 v.u([A[0]+D[0]*b,A[1]+D[1]*b,A[2]+D[2]*b])}1d o(a.W){9 c=7.W.2f(a.W).2q();9 N=7.W.4,A=7.K.4,O=a.W.4,B=a.K.4;9 d=S.1j(2,2),i=0;H(d.2y()){i++;d=S.u([[N[i%3],N[(i+1)%3]],[O[i%3],O[(i+1)%3]]])}9 e=d.2w().4;9 x=N[0]*A[0]+N[1]*A[1]+N[2]*A[2];9 y=O[0]*B[0]+O[1]*B[1]+O[2]*B[2];9 f=[e[0][0]*x+e[0][1]*y,e[1][0]*x+e[1][1]*y];9 g=[];2e(9 j=1;j<=3;j++){g.19((i==j)?0:f[(j+(5-i)%3)%3])}8 14.u(g,c)}},1r:l(a){9 P=a.4||a;9 A=7.K.4,N=7.W.4;9 b=(A[0]-P[0])*N[0]+(A[1]-P[1])*N[1]+(A[2]-(P[2]||0))*N[2];8 v.u([P[0]+N[0]*b,P[1]+N[1]*b,(P[2]||0)+N[2]*b])},1V:l(t,a){9 R=S.1R(t,a.U).4;9 C=a.1r(7.K).4;9 A=7.K.4,N=7.W.4;9 b=C[0],1E=C[1],1J=C[2],1w=A[0],18=A[1],1a=A[2];9 x=1w-b,y=18-1E,z=1a-1J;8 11.u([b+R[0][0]*x+R[0][1]*y+R[0][2]*z,1E+R[1][0]*x+R[1][1]*y+R[1][2]*z,1J+R[2][0]*x+R[2][1]*y+R[2][2]*z],[R[0][0]*N[0]+R[0][1]*N[1]+R[0][2]*N[2],R[1][0]*N[0]+R[1][1]*N[1]+R[1][2]*N[2],R[2][0]*N[0]+R[2][1]*N[1]+R[2][2]*N[2]])},1t:l(a){o(a.W){9 A=7.K.4,N=7.W.4;9 b=A[0],18=A[1],1a=A[2],2M=N[0],2L=N[1],2Q=N[2];9 c=7.K.1t(a).4;9 d=b+2M,2p=18+2L,2m=1a+2Q;9 Q=a.1r([d,2p,2m]).4;9 e=[Q[0]+(Q[0]-d)-c[0],Q[1]+(Q[1]-2p)-c[1],Q[2]+(Q[2]-2m)-c[2]];8 11.u(c,e)}1d o(a.U){8 7.1V(F.1A,a)}1d{9 P=a.4||a;8 11.u(7.K.1t([P[0],P[1],(P[2]||0)]),7.W)}},1Z:l(a,b,c){a=v.u(a);a=a.1N();o(a===w){8 w}b=v.u(b);b=b.1N();o(b===w){8 w}o(1g(c)==\'1f\'){c=w}1d{c=v.u(c);c=c.1N();o(c===w){8 w}}9 d=a.4[0],18=a.4[1],1a=a.4[2];9 e=b.4[0],1W=b.4[1],1X=b.4[2];9 f,1i;o(c!==w){9 g=c.4[0],2l=c.4[1],2t=c.4[2];f=v.u([(1W-18)*(2t-1a)-(1X-1a)*(2l-18),(1X-1a)*(g-d)-(e-d)*(2t-1a),(e-d)*(2l-18)-(1W-18)*(g-d)]);1i=f.1u();o(1i===0){8 w}f=v.u([f.4[0]/1i,f.4[1]/1i,f.4[2]/1i])}1d{1i=F.1x(e*e+1W*1W+1X*1X);o(1i===0){8 w}f=v.u([b.4[0]/1i,b.4[1]/1i,b.4[2]/1i])}7.K=a;7.W=f;8 7}};11.u=l(a,b,c){9 P=25 11();8 P.1Z(a,b,c)};11.2I=11.u(v.1j(3),v.k);11.2H=11.u(v.1j(3),v.i);11.2G=11.u(v.1j(3),v.j);11.36=11.2I;11.35=11.2H;11.3j=11.2G;9 $V=v.u;9 $M=S.u;9 $L=14.u;9 $P=11.u;',62,206,'||||elements|||this|return|var||||||||||||function|||if||length||||create|Vector|null|||||||||Math|nj|while||do|anchor||||||||Matrix||direction||normal||||kj|Plane|ni|abs|Line|ki|precision|Sylvester|A2|push|A3|map|els|else||undefined|typeof|contains|mod|Zero|D3|D2|isParallelTo|kp|distanceFrom|cols|dup|pointClosestTo|np|reflectionIn|modulus|intersects|A1|sqrt|isSquare|X2|PI|X3|angleFrom|mod1|C2|mod2|sin|cos|break|C3|toRightTriangular|false|Y3|to3D|E2|E1|E3|Rotation|Y2|Y1|intersectionWith|rotate|v12|v13|rank|setVectors|nc|sum|multiply|prototype|eql|new|setElements|case|each|PA3|PA2|part|new_element|round|for|cross|product|AD2|isSameSizeAs|add|isPerpendicularTo|v22|AN3|inspect|AD3|AN2|toUnitVector|PsubQ3|PsubQ2|v23|dot|divisor|inverse|true|isSingular|determinant|max|canMultiplyFromLeft|subtract|rows|col|random|ZX|YZ|XY|Random|join|N2|N1|D1|slice|default|N3|dimensions|switch|liesIn|translate|snapTo|augment|Diagonal|trace|indexOf|diagonal|transpose|minor|row|isAntiparallelTo|ZY|YX|acos|RotationZ|RotationY|liesOn|RotationX|inv|rk|tr|det|toDiagonalMatrix|toUpperTriangular|version|XZ'.split('|'),0,{}))
// gtUtils.js Libary
Matrix.Translation = function (v)
{
if (v.elements.length == 2) {
var r = Matrix.I(3);
r.elements[2][0] = v.elements[0];
r.elements[2][1] = v.elements[1];
return r;
}
if (v.elements.length == 3) {
var r = Matrix.I(4);
r.elements[0][3] = v.elements[0];
r.elements[1][3] = v.elements[1];
r.elements[2][3] = v.elements[2];
return r;
}
throw "Invalid length for Translation";
}
Matrix.prototype.flatten = function ()
{
var result = [];
if (this.elements.length == 0)
return [];
for (var j = 0; j < this.elements[0].length; j++)
for (var i = 0; i < this.elements.length; i++)
result.push(this.elements[i][j]);
return result;
}
Matrix.prototype.ensure4x4 = function()
{
if (this.elements.length == 4 &&
this.elements[0].length == 4)
return this;
if (this.elements.length > 4 ||
this.elements[0].length > 4)
return null;
for (var i = 0; i < this.elements.length; i++) {
for (var j = this.elements[i].length; j < 4; j++) {
if (i == j)
this.elements[i].push(1);
else
this.elements[i].push(0);
}
}
for (var i = this.elements.length; i < 4; i++) {
if (i == 0)
this.elements.push([1, 0, 0, 0]);
else if (i == 1)
this.elements.push([0, 1, 0, 0]);
else if (i == 2)
this.elements.push([0, 0, 1, 0]);
else if (i == 3)
this.elements.push([0, 0, 0, 1]);
}
return this;
};
Matrix.prototype.make3x3 = function()
{
if (this.elements.length != 4 ||
this.elements[0].length != 4)
return null;
return Matrix.create([[this.elements[0][0], this.elements[0][1], this.elements[0][2]],
[this.elements[1][0], this.elements[1][1], this.elements[1][2]],
[this.elements[2][0], this.elements[2][1], this.elements[2][2]]]);
};
Vector.prototype.flatten = function ()
{
return this.elements;
};
function mht(m) {
var s = "";
if (m.length == 16) {
for (var i = 0; i < 4; i++) {
s += "<span style='font-family: monospace'>[" + m[i*4+0].toFixed(4) + "," + m[i*4+1].toFixed(4) + "," + m[i*4+2].toFixed(4) + "," + m[i*4+3].toFixed(4) + "]</span><br>";
}
} else if (m.length == 9) {
for (var i = 0; i < 3; i++) {
s += "<span style='font-family: monospace'>[" + m[i*3+0].toFixed(4) + "," + m[i*3+1].toFixed(4) + "," + m[i*3+2].toFixed(4) + "]</font><br>";
}
} else {
return m.toString();
}
return s;
}
function makeLookAt(ex, ey, ez,
cx, cy, cz,
ux, uy, uz)
{
var eye = $V([ex, ey, ez]);
var center = $V([cx, cy, cz]);
var up = $V([ux, uy, uz]);
var mag;
var z = eye.subtract(center).toUnitVector();
var x = up.cross(z).toUnitVector();
var y = z.cross(x).toUnitVector();
var m = $M([[x.e(1), x.e(2), x.e(3), 0],
[y.e(1), y.e(2), y.e(3), 0],
[z.e(1), z.e(2), z.e(3), 0],
[0, 0, 0, 1]]);
var t = $M([[1, 0, 0, -ex],
[0, 1, 0, -ey],
[0, 0, 1, -ez],
[0, 0, 0, 1]]);
return m.x(t);
}
function makePerspective(fovy, aspect, znear, zfar)
{
var ymax = znear * Math.tan(fovy * Math.PI / 360.0);
var ymin = -ymax;
var xmin = ymin * aspect;
var xmax = ymax * aspect;
return makeFrustum(xmin, xmax, ymin, ymax, znear, zfar);
}
function makeFrustum(left, right,
bottom, top,
znear, zfar)
{
var X = 2*znear/(right-left);
var Y = 2*znear/(top-bottom);
var A = (right+left)/(right-left);
var B = (top+bottom)/(top-bottom);
var C = -(zfar+znear)/(zfar-znear);
var D = -2*zfar*znear/(zfar-znear);
return $M([[X, 0, A, 0],
[0, Y, B, 0],
[0, 0, C, D],
[0, 0, -1, 0]]);
}
function makeOrtho(left, right, bottom, top, znear, zfar)
{
var tx = - (right + left) / (right - left);
var ty = - (top + bottom) / (top - bottom);
var tz = - (zfar + znear) / (zfar - znear);
return $M([[2 / (right - left), 0, 0, tx],
[0, 2 / (top - bottom), 0, ty],
[0, 0, -2 / (zfar - znear), tz],
[0, 0, 0, 1]]);
}
// End of Libaries
function initGL(canvas) {
try {
gl = canvas.getContext("experimental-webgl");
gl.viewportWidth = canvas.width;
gl.viewportHeight = canvas.height;
} catch(e) {
}
if (!gl) {
alert("Could not initialise WebGL");
}
}
function getShader(gl, id) {
var shaderScript = document.getElementById(id);
if (!shaderScript) {
return null;
}
var str = "";
var k = shaderScript.firstChild;
while (k) {
if (k.nodeType == 3) {
str += k.textContent;
}
k = k.nextSibling;
}
var shader;
if (shaderScript.type == "x-shader/x-fragment") {
shader = gl.createShader(gl.FRAGMENT_SHADER);
} else if (shaderScript.type == "x-shader/x-vertex") {
shader = gl.createShader(gl.VERTEX_SHADER);
} else {
return null;
}
gl.shaderSource(shader, str);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
alert(gl.getShaderInfoLog(shader));
return null;
}
return shader;
}
function initShaders() {
var fragmentShader = getShader(gl, "shader-fs");
var vertexShader = getShader(gl, "shader-vs");
shaderProgram = gl.createProgram();
gl.attachShader(shaderProgram, vertexShader);
gl.attachShader(shaderProgram, fragmentShader);
gl.linkProgram(shaderProgram);
if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
alert("Could not initialise shaders");
}
gl.useProgram(shaderProgram);
shaderProgram.vertexPositionAttribute
= gl.getAttribLocation(shaderProgram, "aVertexPosition");
gl.enableVertexAttribArray(shaderProgram.vertexPositionAttribute);
shaderProgram.vertexColorAttribute
= gl.getAttribLocation(shaderProgram, "aVertexColor");
gl.enableVertexAttribArray(shaderProgram.vertexColorAttribute);
shaderProgram.pMatrixUniform
= gl.getUniformLocation(shaderProgram, "uPMatrix");
shaderProgram.mvMatrixUniform
= gl.getUniformLocation(shaderProgram, "uMVMatrix");
}
function mvPushMatrix(m) {
if (m) {
mvMatrixStack.push(m.dup());
mvMatrix = m.dup();
} else {
mvMatrixStack.push(mvMatrix.dup());
}
}
function mvPopMatrix() {
if (mvMatrixStack.length == 0) {
throw "Invalid popMatrix!";
}
mvMatrix = mvMatrixStack.pop();
return mvMatrix;
}
function loadIdentity() {
mvMatrix = Matrix.I(4);
}
function multMatrix(m) {
mvMatrix = mvMatrix.x(m);
}
function mvTranslate(v) {
var m = Matrix.Translation($V([v[0], v[1], v[2]])).ensure4x4();
multMatrix(m);
}
function mvRotate(ang, v) {
var arad = ang * Math.PI / 180.0;
var m = Matrix.Rotation(arad, $V([v[0], v[1], v[2]])).ensure4x4();
multMatrix(m);
}
var pMatrix;
function perspective(fovy, aspect, znear, zfar) {
pMatrix = makePerspective(fovy, aspect, znear, zfar);
}
function setMatrixUniforms() {
gl.uniformMatrix4fv(shaderProgram.pMatrixUniform,
false, new Float32Array(pMatrix.flatten()));
gl.uniformMatrix4fv(shaderProgram.mvMatrixUniform,
false, new Float32Array(mvMatrix.flatten()));
}
function compareXValue(array1, array2)
{
var value1 = array1[0];
var value2 = array2[0];
if (value1 > value2) return 1;
if (value1 < value2) return -1;
return 0;
}
function setupShaders(){
var headID = document.getElementsByTagName("head")[0];
var fsScript = document.createElement('script');
fsScript.id="shader-fs";
fsScript.type = 'x-shader/x-fragment';
fsScript.text = "#ifdef GL_ES\n\
precision highp float;\n\
#endif\n\
varying vec4 vColor;\n\
void main(void) {\n\
gl_FragColor = vColor;\n\
}";
var vsScript = document.createElement('script');
vsScript.id="shader-vs";
vsScript.type = 'x-shader/x-vertex';
vsScript.text = "attribute vec3 aVertexPosition;\n\
attribute vec4 aVertexColor;\n\
\n\
uniform mat4 uMVMatrix;\n\
uniform mat4 uPMatrix;\n\
\n\
varying vec4 vColor;\n\
\n\
void main(void) {\n\
gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);\n\
vColor = aVertexColor;\n\
}";
headID.appendChild(vsScript);
headID.appendChild(fsScript);
initShaders();
}
function setupCanvas(){
canvas1 = document.getElementsByTagName("canvas")[1];
canvas1.style.position = "absolute";
canvas1.style.zIndex = 10;
canvas1.style.opacity = 0.5;
canvas = document.getElementsByTagName("canvas")[0];
canvas.style.zIndex = 0;
initGL(canvas);
}
function setupGL(){
setupCanvas();
setupShaders();
gl.clearColor(1.0, 1.0, 1.0, 1.0);
gl.clearDepth(1.0);
gl.enable(gl.DEPTH_TEST);
gl.depthFunc(gl.LEQUAL);
gl.viewport(0, 0, gl.viewportWidth, gl.viewportHeight);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
perspective(45, gl.viewportWidth / gl.viewportHeight, 0.1, 100.0);
loadIdentity();
var uTop = 2.478;
var uLeft = -uTop;
mvTranslate([uLeft,uTop, -10.0])
mvPushMatrix();
}
// Drawing functions
function drawPolygon(pixelVertices,color)
{
var factor;
var glWidth = 4.92;
var vertices = new Float32Array(1000);
var polygonColors = new Float32Array(1000);
var vl = 0;
if(canvas.width>=canvas.height) factor = glWidth/canvas.height;
else factor = glWidth/canvas.width;
for(var i=0;i<pixelVertices.length;i++){
pixelVertices[i] = (pixelVertices[i])*factor;
if (i%2){
vertices[vl] = -pixelVertices[i];
vl++;
vertices[vl] = (4.0);
}
else
{
vertices[vl] = (pixelVertices[i]);
}
vl++;
}
vertexPositionBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vertexPositionBuffer);
gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
vertexPositionBuffer.itemSize = 3;
vertexPositionBuffer.numItems = vl / 3.0;
vertexColorBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vertexColorBuffer);
for(var i=0;i<(vl / 3.0)*4;i+=4){
polygonColors[i] = color[0];
polygonColors[i+1] = color[1];
polygonColors[i+2] = color[2];
polygonColors[i+3] = color[3];
}
gl.bufferData(gl.ARRAY_BUFFER, polygonColors, gl.STATIC_DRAW);
vertexColorBuffer.itemSize = 4;
vertexColorBuffer.numItems = vl / 3.0;
gl.bindBuffer(gl.ARRAY_BUFFER, vertexPositionBuffer);
gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute,
vertexPositionBuffer.itemSize, gl.FLOAT, false, 0, 0);
gl.bindBuffer(gl.ARRAY_BUFFER, vertexColorBuffer);
gl.vertexAttribPointer(shaderProgram.vertexColorAttribute,
vertexColorBuffer.itemSize, gl.FLOAT, false, 0, 0);
setMatrixUniforms();
gl.drawArrays(gl.TRIANGLE_STRIP, 0, vl / 3.0);
}
function drawLine(left1,top1,left2,top2,width,color)
{
if(top1 <= top2){
var temp1 = left1;
var temp2 = top1;
left1 = left2;
top1 = top2;
left2 = temp1;
top2 = temp2;
}
var length = Math.sqrt(((top2-top1)*(top2-top1))+((left2-left1)*(left2-left1)));
var vHeight = top1-top2;
var hWidth = left1-left2;
var deg = 180/Math.PI;
var angle = Math.atan(vHeight/hWidth);
var angle2 = ((Math.PI/2)-angle);
var height2 = Math.sin(angle2)*(width/2);
var width2 = Math.sqrt(((width/2)*(width/2))-(height2*height2));
if(angle*deg<0)
{
var topRightX = left1-(width2);
var topRightY = top1-height2;
var topLeftX = left1+(width2);
var topLeftY = top1+height2;
var bottomRightX = left2-(width2);
var bottomRightY = top2-height2;
var bottomLeftX = left2+(width2);
var bottomLeftY = top2+height2;
}
else
{
var topRightX = left1-(width2);
var topRightY = top1+height2;
var topLeftX = left1+(width2);
var topLeftY = top1-height2;
var bottomRightX = left2-(width2);
var bottomRightY = top2+height2;
var bottomLeftX = left2+(width2);
var bottomLeftY = top2-height2;
}
var pvertices = new Float32Array([
topRightX, topRightY,
topLeftX, topLeftY,
bottomRightX, bottomRightY,
bottomLeftX, bottomLeftY
]);
drawPolygon(pvertices,color);
}
function drawSquare(left,top,width,height,rotation,color){drawSquareComplex(left,top,width,height,rotation,height,width,color);}
function drawSquareComplex(left,top,width,height,rotation,vHeight,hWidth,color){
var diam = width/2;
var topOffset = Math.round(Math.sin(rotation)*diam);
var leftOffset = Math.round(Math.cos(rotation)*diam);
drawLine(left-leftOffset,top-topOffset,left+leftOffset,top+topOffset,height,color);
}
function drawDiamond(left,top,width,height,color)
{
var halfWidth = width/2;
var halfHeight = height/2;
var pvertices = new Float32Array(8);
pvertices[0] = left;
pvertices[1] = top-halfHeight;
pvertices[2] = left-halfWidth;
pvertices[3] = top;
pvertices[4] = left+halfWidth;
pvertices[5] = top;
pvertices[6] = left;
pvertices[7] = top+halfHeight;
drawPolygon(pvertices,color);
}
function drawTriang(left,top,width,height,rotation,color)
{
var halfWidth = width/2;
var halfHeight = height/2;
var pvertices = new Float32Array(6);
pvertices[0] = 0;
pvertices[1] = 0-halfHeight;
pvertices[2] = 0-halfWidth;
pvertices[3] = 0+halfHeight;
pvertices[4] = 0+halfWidth;
pvertices[5] = 0+halfHeight;
var j = 0;
for (i=0;i<3;i++)
{
var tempX = pvertices[j];
var tempY = pvertices[j+1];
pvertices[j] = (Math.cos(rotation)*tempX)-(Math.sin(rotation)*tempY)
pvertices[j] = Math.round(pvertices[j]+left);
j++;
pvertices[j] = (Math.sin(rotation)*tempX)+(Math.cos(rotation)*tempY)
pvertices[j] = Math.round(pvertices[j]+top);
j++;
}
drawPolygon(pvertices,color);
}
function drawCircle(left,top,width,color){drawCircleDim(left,top,width,width,color)};
function drawCircleDim(left,top,width,height,color){
left = Math.round(left);
top = Math.round(top);
width = Math.round(width);
height = Math.round(height);
var w = Math.round(width/2);
var h = Math.round(height/2);
var numSections;
if(width>height)numSections = width*2;
else numSections = height*2;
if(numSections>33)numSections = 33;
if(numSections<10)numSections = 10;
var delta_theta = 2.0 * Math.PI / numSections
var theta = 0
if(circleCoords[w][h]==undefined)
{
//alert("make circle "+r);
circleCoords[w][h] = new Array(numSections);
circleCoords[w][h] = new Array(numSections);
for (i = 0; i < numSections ; i++) {
circleCoords[w][h][i] = new Array(2);
x = (w * Math.cos(theta));
y = (h * Math.sin(theta));
x = Math.round(x*1000)/1000
y = Math.round(y*1000)/1000
circleCoords[w][h][i][1] = x;
circleCoords[w][h][i][0] = y;
theta += delta_theta
}
circleCoords[w][h].sort(compareXValue);
for(var i = 0;i<numSections-1;i++)
{
if(circleCoords[w][h][i][0] == circleCoords[w][h][i+1][0] && circleCoords[w][h][i][1]<circleCoords[w][h][i+1][1])
{
temp = circleCoords[w][h][i];
circleCoords[w][h][i] = circleCoords[w][h][i+1];
circleCoords[w][h][i+1] = temp;
}
}
}
var j = 0;
var pvertices = new Float32Array(numSections*2);
for (i=0;i<numSections;i++)
{
pvertices[j] = circleCoords[w][h][i][1]+left;
j++;
pvertices[j] = circleCoords[w][h][i][0]+top;
j++;
}
drawPolygon(pvertices,color);
}
function drawLineArrow(left1,top1,left2,top2,width,color)
{
var opp = top1-top2;
var adj = left1-left2;
var angle = Math.atan(opp/adj)+Math.PI/2;
if(left1>left2 )angle+=Math.PI;
drawLine(left1,top1,left2,top2,width,color);
var triLeft = left1-Math.round(adj/2);
var triTop = top1-Math.round(opp/2);
drawTriang(triLeft,triTop,20,20,angle,color);
}
function stringPixelLength(string)
{
var code;
var width = 0;
for(i=0;i<string.length;i++)
{
code = string.charCodeAt(i)-32;
width += hersheyFont[code][1];
}
return width;
}
function printChar(left,top,character,color,thickness,size)
{
var code = character.charCodeAt(0)-32;
var verticesNeeded = hersheyFont[code][0];
var width = hersheyFont[code][1];
var lef1;
var top1;
var left2;
var top2;
var j = 0;
var i = 2;
var fHeight = 10*size;
while(i<(verticesNeeded*2)+2)
{
j++;
left1 = hersheyFont[code][i]*size+left;
top1 = (fHeight-hersheyFont[code][i+1]*size)+top;
if(hersheyFont[code][i] != -1 && hersheyFont[code][i+1] != -1)
{
if(i>2 && hersheyFont[code][i-1] != -1 && hersheyFont[code][i-2] != -1)
{
drawLine(left2,top2,left1,top1,thickness,color);
}
if(hersheyFont[code][i+2] != -1 && hersheyFont[code][i+3] != -1)
{
left2 = hersheyFont[code][i+2]*size+left;
top2 = (fHeight-hersheyFont[code][i+3]*size)+top;
drawLine(left1,top1,left2,top2,thickness,color);
}
i+=4;
}
else
{
i+=2;
}
}
return width*size;
}
function printString(left,top,string,color,thickness,size)
{
var wordArray = string.split(" ");
var numWords = wordArray.length;
var length = (stringPixelLength(string)/2)*size;
var offset = -length;
for(i=0;i<string.length;i++)
{
offset += printChar(left+offset,top,string[i],color,thickness,size);
}
}
//Styling functions
function getColor(index)
{
var temp = new Array(4);
temp = [colors[index][0],colors[index][1],colors[index][2],1.0]
return temp;
}
function flowTerminator(left,top,width,height,color,strokeSize,strokeColor)
{
var sOff = strokeSize*2;
flowTerminatorNoStroke(left,top,width,height,strokeColor);
flowTerminatorNoStroke(left,top,width-sOff,height-sOff,color);
}
function flowTerminatorNoStroke(left,top,width,height,color)
{
var cWidth = height;
var cOff = (width/2)-(cWidth/2);
drawCircle(left-cOff,top,cWidth,color);
drawCircle(left+cOff,top,cWidth,color);
drawSquare(left,top,cOff*2,height,0,color);
}
function flowProcess(left,top,width,height,color,strokeSize,strokeColor)
{
var sOff = strokeSize*2;
drawSquare(left,top,width,height,0,strokeColor);
drawSquare(left,top,width-sOff,height-sOff,0,color);
}
function diamondStrokeAlgorithm(width, height, strokeSize)
{
var angle1 = Math.atan(height/width);
var angle2 = Math.PI/2 - angle1;
var opp = strokeSize*Math.sin(angle2);
var width1Sq = (strokeSize*strokeSize)-(opp*opp);
var width1 = Math.sqrt(width1Sq);
var width2 = opp/(Math.tan(angle1));
var fWidth = (width1+width2)*2;
return fWidth;
}
function flowDecision(left,top,width,height,color,strokeSize,strokeColor)
{
var wOff = diamondStrokeAlgorithm(width/2, height/2, strokeSize);
var hOff = diamondStrokeAlgorithm(height/2, width/2, strokeSize);
drawDiamond(left,top,width,height,strokeColor);
drawDiamond(left,top,width-wOff,height-hOff,color);
}
// BLACK 0
// WHITE 1
// RED 2
// GREEN 3
// BLUE 4
// YELLOW 5
// PINK 6
// GREY 7
function drawEdge(left1,top1, left2,top2,style){
switch(style){
case 100: // FLOW CHART
// Draw line with Arrow at end
drawLineArrow(left1,top1,left2,top2,2,getColor(0));
break;
case -100:
// Draw line with Arrow at end - HIGHLIGHTED
drawLineArrow(left1,top1,left2,top2,2,getColor(6));
break;
case -10:
drawLine(left1,top1,left2,top2,2,getColor(6));
break;
default:
//Default edge style: black line
drawLine(left1,top1,left2,top2,2,getColor(0));
}
}
function drawVertex(left,top,width,height,style,text,c1,c2,c3)
{
var flowStrokeHighColor = getColor(5);
var flowStrokeColor = getColor(0);
var flowColor = getColor(7);
var flowStrokeSize = 2;
var flowTextColor = getColor(0);
var customColor = [c1,c2,c3,1.0];
switch(style){
case 100: // (100 - 199) FLOW CHART SYMBOLS
// Terminator, start stop
flowTerminator(left,top,width,height,flowColor,flowStrokeSize,flowStrokeColor);
printString(left,top,text,flowTextColor,2,0.75);
break;
case -100:
// Terminator, start stop - HIGHLIGHTED
flowTerminator(left,top,width,height,flowColor,flowStrokeSize,flowStrokeHighColor);
printString(left,top,text,flowTextColor,2,0.75);
break;
case 101:
// Process, process or action step
flowProcess(left,top,width,height,flowColor,flowStrokeSize,flowStrokeColor);
printString(left,top,text,flowTextColor,2,0.75);
break;
case -101:
// Process, process or action step - HIGHLIGHTED
flowProcess(left,top,width,height,flowColor,flowStrokeSize,flowStrokeHighColor);
printString(left,top,text,flowTextColor,2,0.75);
break;
case 102:
// Decision, question or branch
flowDecision(left,top,width,height,flowColor,flowStrokeSize,flowStrokeColor);
printString(left,top,text,flowTextColor,2,0.75);
break;
case -102:
// Decision, question or branch - HIGHLIGHTED
flowDecision(left,top,width,height,flowColor,flowStrokeSize,flowStrokeHighColor);
printString(left,top,text,flowTextColor,2,0.75);
break;
case 5:
// Circle
var sOff = flowStrokeSize*2;
drawCircleDim(left,top,width,height,flowStrokeColor);
drawCircleDim(left,top,width-sOff,height-sOff,customColor);
printString(left,top,text,flowTextColor,2,0.75);
break;
case -5:
// Circle
var sOff = flowStrokeSize*2;
drawCircleDim(left,top,width,height,flowStrokeHighColor);
drawCircleDim(left,top,width-sOff,height-sOff,customColor);
printString(left,top,text,flowTextColor,2,0.75);
break;
case 1:
// Smiley Face
drawCircle(left,top,width,5);
drawCircle(left,top,width*0.7,0);
drawCircle(left,top,width*0.5,5);
drawSquare(left,top,width*0.7,width*0.2,0,5);
drawSquare(left,top-width*0.1,width*0.70,width*0.2,0,5);
drawSquare(left,top-width*0.2,width*0.60,width*0.2,0,5);
drawSquare(left,top-width*0.3,width*0.40,width*0.1,0,5);
drawCircle(left-(width*0.20),top-(width*0.2),width*0.2,0);
drawCircle(left+(width*0.20),top-(width*0.2),width*0.2,0);
break;
case 2:
// Bart Simpson
drawSquare(left,top,width*0.9,width*1.1,0,0);
drawSquare(left,top,width*0.85,width*1.05,0,5);
drawSquare(left-width*0.27,top+width*0.2,width*0.35,width*1.2,0,0);
drawSquare(left-width*0.27,top+width*0.2,width*0.31,width*1.16,0,5);
drawCircle(left+width*0.15,top+width*0.45,width*0.6,0);
drawCircle(left+width*0.15,top+width*0.45,width*0.545,5);
drawSquare(left,top+width*0.27,width*0.85,width*0.5,0,5);
drawSquare(left-width*0.31,top-width*0.55,width*0.2,width*0.2,(Math.PI/4),0)
drawSquare(left-width*0.31,top-width*0.55,width*0.16,width*0.16,(Math.PI/4),5)
drawSquare(left-width*0.06,top-width*0.55,width*0.2,width*0.2,(Math.PI/4),0)
drawSquare(left-width*0.06,top-width*0.55,width*0.16,width*0.16,(Math.PI/4),5)
drawSquare(left+width*0.19,top-width*0.55,width*0.2,width*0.2,(Math.PI/4),0)
drawSquare(left+width*0.19,top-width*0.55,width*0.16,width*0.16,(Math.PI/4),5)
drawSquare(left+width*0.32,top-width*0.55,width*0.2,width*0.2,(Math.PI/4),0)
drawSquare(left+width*0.32,top-width*0.55,width*0.16,width*0.16,(Math.PI/4),5)
drawSquare(left,top-width*0.3,width*0.85,width*0.5,0,5);
drawSquare(left,top-width*0.23,width*0.85,width*0.5,0,5);
drawSquare(left-width*0.15,top+width*0.53,width*0.15,width*0.02,-(Math.PI/5),0)
drawCircle(left+width*0.3,top-width*0.1,width*0.4,0);
drawCircle(left+width*0.3,top-width*0.1,width*0.35,1);
drawCircle(left+width*0.3,top+width*0.1,width*0.2,0);
drawCircle(left+width*0.3,top+width*0.1,width*0.15,5);
drawSquare(left+width*0.2,top+width*0.1,width*0.2,width*0.2,0,0);
drawSquare(left+width*0.2,top+width*0.1,width*0.2,width*0.15,0,5);
drawCircle(left+width*0.05,top-width*0.1,width*0.4,0);
drawCircle(left+width*0.05,top-width*0.1,width*0.35,1);
drawCircle(left+width*0.3,top-width*0.1,width*0.05,0);
drawCircle(left+width*0.05,top-width*0.1,width*0.05,0);
break;
case -10:
drawCircleDim(left,top,width,height,6);
break;
default:
// Default vertex style: black circle
drawCircleDim(left,top,width,height,0);
}
}
function drawGraph() {
setupGL();
for(var i=0;i<edgeNumber;i++)
{
var left1 = parseInt(edgeArray[i][0]);
var top1 = parseInt(edgeArray[i][1]);
var left2 = parseInt(edgeArray[i][2]);
var top2 = parseInt(edgeArray[i][3]);
var style = parseInt(edgeArray[i][4]);
drawEdge( left1,top1,left2,top2,style);
}
for(var i=0;i<verticeNumber;i++)
{
var left = parseInt(verticeArray[i][0]);
var top = parseInt(verticeArray[i][1]);
var width = parseInt(verticeArray[i][2]);
var height = parseInt(verticeArray[i][3]);
var style = parseInt(verticeArray[i][4]);
var text = verticeArray[i][5];
var c1 = verticeArray[i][6];
var c2 = verticeArray[i][7];
var c3 = verticeArray[i][8];
drawVertex(left,top,width,height,style,text,c1,c2,c3);
}
}
drawGraph();
}-*/;
private static native int setupJSNI()/*-{
$wnd.edgeNumber = 0;
$wnd.verticeNumber = 0;
$wnd.edgeArray = new Array(1000);
for(i=0;i<edgeArray.length;i++)edgeArray[i] = new Array(5);
$wnd.verticeArray = new Array(1000);
for(i=0;i<verticeArray.length;i++)verticeArray[i] = new Array(9);
}-*/;
private static native int addEdge(double startX,double startY,double endX,double endY,int style)/*-{
edgeArray[edgeNumber][0] = parseInt(startX);
edgeArray[edgeNumber][1] = parseInt(startY);
edgeArray[edgeNumber][2] = parseInt(endX);
edgeArray[edgeNumber][3] = parseInt(endY);
edgeArray[edgeNumber][4] = parseInt(style);
edgeNumber++;
}-*/;
private static native int addVertice(double centreX,double centreY,double width,double height,int style,String label,double c1,double c2,double c3)/*-{
verticeArray[verticeNumber][0] = parseInt(centreX);
verticeArray[verticeNumber][1] = parseInt(centreY);
verticeArray[verticeNumber][2] = parseInt(width);
verticeArray[verticeNumber][3] = parseInt(height);
verticeArray[verticeNumber][4] = parseInt(style);
verticeArray[verticeNumber][5] = label;
verticeArray[verticeNumber][6] = c1;
verticeArray[verticeNumber][7] = c1;
verticeArray[verticeNumber][8] = c1;
verticeNumber++;
}-*/;
private static native int webglCheck()/*-{
if (typeof Float32Array != "undefined")return 1;
return 0;
}-*/;
public void renderGraph(GWTCanvas canvas, Collection<EdgeDrawable> edges,
Collection<VertexDrawable> vertices) {
// Do a (kind of reliable) check for webgl
if (webglCheck() == 1) { // Can do WebGL
// At the moment coordinates are passed to JavaScript as comma
// separated strings // This will most probably change in the
// future.
setupJSNI();
String edgesString = "";
String veticesString = "";
String separator = ",";
String label = "";
int vertexStyle;
int edgeStyle;
for (EdgeDrawable thisEdge : edges) {
double startX = (thisEdge.getStartX() + offsetX)*zoom;
double startY = (thisEdge.getStartY() + offsetY)*zoom;
double endX = (thisEdge.getEndX() + offsetX)*zoom;
double endY = (thisEdge.getEndY() + offsetY)*zoom;
//edgeStyle = thisEdge.getStyle();
edgeStyle = 100;
if(thisEdge.isHilighted())edgeStyle = -100;
addEdge(startX,startY,endX,endY,edgeStyle);
}
for (VertexDrawable thisVertex : vertices) {
double centreX = (thisVertex.getCenterX() + offsetX)*zoom;
double centreY = (thisVertex.getCenterY() + offsetY)*zoom;
double width = (0.5 * thisVertex.getWidth())*zoom;
double height = (0.5 * thisVertex.getHeight())*zoom;
vertexStyle = thisVertex.getStyle();
switch (vertexStyle) {
case VertexDrawable.STROKED_TERM_STYLE:
vertexStyle = 100;
break;
case VertexDrawable.STROKED_SQUARE_STYLE:
vertexStyle = 101;
break;
case VertexDrawable.STROKED_DIAMOND_STYLE:
vertexStyle = 102;
break;
default:
vertexStyle = 100;
break;
}
label = thisVertex.getLabel();
int[] customColor = {0,0,0};
if(thisVertex.getStyle() == VertexDrawable.COLORED_FILLED_CIRCLE)
{
vertexStyle = 5;
customColor = thisVertex.getColor();
}
if(thisVertex.isHilighted())vertexStyle = -vertexStyle;
runJavascript("alert("+vertexStyle+")");
addVertice(centreX,centreY,width,height,vertexStyle,label,customColor[0],customColor[1],customColor[2]);
}
// JSNI method used to draw webGL graph version
drawGraph3D();
}
else {
// Cant do webGL so draw on 2d Canvas
renderGraph2d(canvas, edges, vertices);
}
}
public void renderGraph2d(GWTCanvas canvas, Collection<EdgeDrawable> edges,
Collection<VertexDrawable> vertices) {
canvas.setLineWidth(1);
canvas.setStrokeStyle(Color.BLACK);
canvas.setFillStyle(Color.BLACK);
canvas.setFillStyle(Color.WHITE);
canvas.fillRect(0, 0, 2000, 2000);
canvas.setFillStyle(Color.BLACK);
drawGraph(edges, vertices, canvas);
}
// Draws a single vertex, currently only draws circular nodes
private void drawVertex(VertexDrawable vertex, GWTCanvas canvas) {
double centreX = (vertex.getLeft() + 0.5 * vertex.getWidth() + offsetX) * zoom;
double centreY = (vertex.getTop() + 0.5 * vertex.getHeight() + offsetY) * zoom;
double radius = (0.25 * vertex.getWidth()) * zoom;
canvas.moveTo(centreX, centreY);
canvas.beginPath();
canvas.arc(centreX, centreY, radius, 0, 360, false);
canvas.closePath();
canvas.stroke();
canvas.fill();
}
// Draws a line from coordinates to other coordinates
private void drawEdge(EdgeDrawable edge, GWTCanvas canvas) {
double startX = (edge.getStartX() + offsetX)*zoom;
double startY = (edge.getStartY() + offsetY)*zoom;
double endX = (edge.getEndX() + offsetX)*zoom;
double endY = (edge.getEndY() + offsetY)*zoom;
canvas.beginPath();
canvas.moveTo(startX, startY);
canvas.lineTo(endX, endY);
canvas.closePath();
canvas.stroke();
}
// Takes collections of edges and vertices and draws a graph on a specified
// canvas.
private void drawGraph(Collection<EdgeDrawable> edges,
Collection<VertexDrawable> vertices, GWTCanvas canvas) {
for (EdgeDrawable thisEdge : edges) {
drawEdge(thisEdge, canvas);
}
for (VertexDrawable thisVertex : vertices) {
drawVertex(thisVertex, canvas);
}
}
// set offset in the event of a pan
public void setOffset(int x, int y) {
offsetX = x;
offsetY = y;
}
// getters for offsets
public int getOffsetX() {
return offsetX;
}
public int getOffsetY() {
return offsetY;
}
//set zoom
public void setZoom(double z) {
zoom = z;
}
public double getZoom(){
return zoom;
}
}
|
diff --git a/net.sourceforge.eclipseccase/src/net/sourceforge/eclipseccase/ClearCaseProvider.java b/net.sourceforge.eclipseccase/src/net/sourceforge/eclipseccase/ClearCaseProvider.java
index e8e13c9..d5eba39 100644
--- a/net.sourceforge.eclipseccase/src/net/sourceforge/eclipseccase/ClearCaseProvider.java
+++ b/net.sourceforge.eclipseccase/src/net/sourceforge/eclipseccase/ClearCaseProvider.java
@@ -1,2414 +1,2414 @@
/*******************************************************************************
* Copyright (c) 2002, 2004 eclipse-ccase.sourceforge.net.
* 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:
* Matthew Conway - initial API and implementation
* IBM Corporation - concepts and ideas from Eclipse
* Gunnar Wagenknecht - new features, enhancements and bug fixes
*******************************************************************************/
package net.sourceforge.eclipseccase;
import java.io.File;
import java.text.MessageFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.sourceforge.clearcase.ClearCase;
import net.sourceforge.clearcase.ClearCaseCLIImpl;
import net.sourceforge.clearcase.ClearCaseElementState;
import net.sourceforge.clearcase.ClearCaseException;
import net.sourceforge.clearcase.ClearCaseInterface;
import net.sourceforge.clearcase.events.OperationListener;
import net.sourceforge.eclipseccase.ClearCasePreferences;
import org.eclipse.core.resources.*;
import org.eclipse.core.resources.team.FileModificationValidator;
import org.eclipse.core.resources.team.IMoveDeleteHook;
import org.eclipse.core.runtime.*;
import org.eclipse.team.core.RepositoryProvider;
import org.eclipse.team.core.Team;
import org.eclipse.team.core.TeamException;
import org.eclipse.ui.PlatformUI;
/**
* The ClearCase repository provider. Layer to clearcase java api.
*/
public class ClearCaseProvider extends RepositoryProvider {
/** trace id */
private static final String TRACE_ID_IS_IGNORED = "ClearCaseProvider#isIgnored"; //$NON-NLS-1$
private static Map<String, String> viewLookupTable = new Hashtable<String, String>(
200);
private static Map<String, IContainer> viewAccessLookupTable = new Hashtable<String, IContainer>(
30);
private static Map<String, Boolean> snapshotViewLookupTable = new Hashtable<String, Boolean>(
30);
UncheckOutOperation UNCHECK_OUT = new UncheckOutOperation();
CheckInOperation CHECK_IN = new CheckInOperation();
CheckOutOperation CHECKOUT = new CheckOutOperation();
UnHijackOperation UNHIJACK = new UnHijackOperation();
AddOperation ADD = new AddOperation();
RefreshStateOperation REFRESH_STATE = new RefreshStateOperation();
CheckoutUnreservedOperation CO_UNRESERVED = new CheckoutUnreservedOperation();
CheckoutReservedOperation CO_RESERVED = new CheckoutReservedOperation();
private final IMoveDeleteHook moveHandler = new MoveHandler(this);
private String comment = ""; //$NON-NLS-1$
public static final String ID = "net.sourceforge.eclipseccase.ClearcaseProvider"; //$NON-NLS-1$
private static final String TRACE_ID = "ClearCaseProvider"; //$NON-NLS-1$
public static final Status OK_STATUS = new Status(IStatus.OK, ID,
TeamException.OK, "OK", null); //$NON-NLS-1$
public static final Status FAILED_STATUS = new Status(IStatus.ERROR, ID,
TeamException.UNABLE, "FAILED", null); //$NON-NLS-1$
public static final IStatus CANCEL_STATUS = Status.CANCEL_STATUS;
public static final String SNAIL = "@";
public static final String NO_ACTIVITY = "No activity in view";
public static final String UNRESERVED = "unreserved";
public static final String RESERVED = "reserved";
// is used to keep track of which views that has a file checked out when
// doing a move.
public static final ArrayList<String> checkedOutInOtherView = new ArrayList<String>();
boolean refreshResources = true;
private OperationListener opListener = null;
private boolean isTest = false;
public ClearCaseProvider() {
super();
}
UpdateOperation UPDATE = new UpdateOperation();
DeleteOperation DELETE = new DeleteOperation();
/**
* Checks if the monitor has been canceled.
*
* @param monitor
*/
protected static void checkCanceled(IProgressMonitor monitor) {
if (null != monitor && monitor.isCanceled())
throw new OperationCanceledException();
}
/*
* (non-Javadoc)
*
* @see org.eclipse.team.core.RepositoryProvider#configureProject()
*/
@Override
public void configureProject() throws CoreException {
// configureProject
}
/*
* (non-Javadoc)
*
* @see org.eclipse.team.core.RepositoryProvider#getID()
*/
@Override
public String getID() {
return ID;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.core.resources.IProjectNature#deconfigure()
*/
public void deconfigure() throws CoreException {
// deconfigure
}
public static ClearCaseProvider getClearCaseProvider(IResource resource) {
if (null == resource)
return null;
IProject project = resource.getProject();
if (null == project)
return null;
RepositoryProvider provider = RepositoryProvider.getProvider(project);
if (provider instanceof ClearCaseProvider) {
// FIXME Achim: Whats this next line for?
((ClearCaseProvider) provider).opListener = null;
return (ClearCaseProvider) provider;
} else
return null;
}
/*
* @see SimpleAccessOperations#get(IResource[], int, IProgressMonitor)
*/
public void get(IResource[] resources, int depth, IProgressMonitor progress)
throws TeamException {
execute(UPDATE, resources, depth, progress);
}
/*
* @see SimpleAccessOperations#checkout(IResource[], int, IProgressMonitor)
*/
public void checkout(IResource[] resources, int depth,
IProgressMonitor progress) throws TeamException {
try {
execute(CHECKOUT, resources, depth, progress);
} finally {
setComment("");
}
}
public void unhijack(IResource[] resources, int depth,
IProgressMonitor progress) throws TeamException {
try {
execute(UNHIJACK, resources, depth, progress);
} finally {
setComment("");
}
}
/**
* Invalidates the state cache of all specified resources.
*
* @param resourceToRefresh
* @param monitor
* @throws CoreException
*/
public void refreshRecursive(IResource resourceToRefresh,
IProgressMonitor monitor) throws CoreException {
try {
monitor.beginTask("Refreshing " + resourceToRefresh.getName(), 50);
final List<IResource> toRefresh = new ArrayList<IResource>(80);
monitor.subTask("collecting members");
resourceToRefresh.accept(new IResourceVisitor() {
public boolean visit(IResource resource) throws CoreException {
if (!Team.isIgnoredHint(resource)) {
toRefresh.add(resource);
}
return true;
}
});
monitor.worked(30);
monitor.subTask("scheduling updates");
if (!toRefresh.isEmpty()) {
StateCacheFactory.getInstance().refreshStateAsyncHighPriority(
toRefresh.toArray(new IResource[toRefresh.size()]),
monitor);
}
monitor.worked(10);
} finally {
monitor.done();
}
}
public void refreshRecursive(IResource[] resources, IProgressMonitor monitor) {
StateCacheFactory.getInstance().refreshStateAsyncHighPriority(
resources, monitor);
}
/**
* Invalidates the state of the specified resource and only of the specified
* resource, not recursive
*
* @param resource
*/
public void refresh(IResource resource) {
StateCacheFactory.getInstance().get(resource).updateAsync(true);
}
/*
* @see SimpleAccessOperations#checkin(IResource[], int, IProgressMonitor)
*/
public void checkin(IResource[] resources, int depth,
IProgressMonitor progressMonitor) throws TeamException {
try {
execute(CHECK_IN, resources, depth, progressMonitor);
} finally {
setComment("");
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.team.core.RepositoryProvider#getRuleFactory()
*/
@Override
public IResourceRuleFactory getRuleFactory() {
return new ClearCaseResourceRuleFactory();
}
/**
* @see SimpleAccessOperations#uncheckout(IResource[], int,
* IProgressMonitor)
*/
public void uncheckout(IResource[] resources, int depth,
IProgressMonitor progress) throws TeamException {
execute(UNCHECK_OUT, resources, depth, progress);
}
/**
* @see SimpleAccessOperations#delete(IResource[], IProgressMonitor)
*/
public void delete(IResource[] resources, IProgressMonitor progress)
throws TeamException {
try {
execute(DELETE, resources, IResource.DEPTH_INFINITE, progress);
} finally {
setComment("");
}
}
public void add(IResource[] resources, int depth, IProgressMonitor progress)
throws TeamException {
try {
execute(ADD, resources, depth, progress);
} finally {
setComment("");
}
}
public void unreserved(IResource[] resources, int depth,
IProgressMonitor progress) throws TeamException {
try {
execute(CO_UNRESERVED, resources, depth, progress);
} finally {
setComment("");
}
}
public void reserved(IResource[] resources, int depth,
IProgressMonitor progress) throws TeamException {
try {
execute(CO_RESERVED, resources, depth, progress);
} finally {
setComment("");
}
}
/*
* @see SimpleAccessOperations#moved(IPath, IResource, IProgressMonitor)
*/
public void moved(IPath source, IResource target, IProgressMonitor progress)
throws TeamException {
// moved
}
/**
* @see SimpleAccessOperations#isCheckedOut(IResource)
*/
public boolean isCheckedOut(IResource resource) {
return StateCacheFactory.getInstance().get(resource).isCheckedOut();
}
/**
* Indicates if the specified resource is contained in a Snapshot view.
*
* @param resource
* @return
*/
public boolean isSnapShot(IResource resource) {
return StateCacheFactory.getInstance().get(resource).isSnapShot();
}
public boolean isHijacked(IResource resource) {
return StateCacheFactory.getInstance().get(resource).isHijacked();
}
public boolean isUnknownState(IResource resource) {
return StateCacheFactory.getInstance().isUninitialized(resource);
}
/**
* @see SimpleAccessOperations#isClearCaseElement(IResource)
*/
public boolean isClearCaseElement(IResource resource) {
return StateCacheFactory.getInstance().get(resource)
.isClearCaseElement();
}
/*
* @see SimpleAccessOperations#isDirty(IResource)
*/
public boolean isDirty(IResource resource) {
return StateCacheFactory.getInstance().get(resource).isDirty();
}
public String getVersion(IResource resource) {
return StateCacheFactory.getInstance().get(resource).getVersion();
}
public String getPredecessorVersion(IResource resource) {
return StateCacheFactory.getInstance().get(resource)
.getPredecessorVersion();
}
public void showVersionTree(String element, File workingDir) {
ClearCasePlugin.getEngine().showVersionTree(element, workingDir);
}
public void showFindMerge(File workingDir) {
ClearCasePlugin.getEngine().showFindMerge(workingDir);
}
public String[] loadBrancheList(File workingDir) {
return ClearCasePlugin.getEngine().loadBrancheList(workingDir);
}
public String[] searchFilesInBranch(String branchName, File workingDir,
OperationListener listener) {
return ClearCasePlugin.getEngine().searchFilesInBranch(branchName,
workingDir, listener);
}
public void update(String element, int flags, boolean workingDir) {
ClearCasePlugin.getEngine().update(element, flags, workingDir);
}
public void compareWithPredecessor(String element) {
ClearCasePlugin.getEngine().compareWithPredecessor(element);
}
public void describeVersionGUI(String element) {
ClearCasePlugin.getEngine().describeVersionGUI(element);
}
public String[] describe(String element, int flag, String format) {
return ClearCasePlugin.getEngine().describe(element, flag, format);
}
public void compareWithVersion(String element1, String element2) {
ClearCasePlugin.getEngine().compareWithVersion(element1, element2);
}
/**
* Parsers single/multiple line/-s of output. Type.java Predecessor:
* /main/dev/0 View:eraonel_w12b2 Status: unreserved
*
* @param element
* @return
*/
public boolean isCheckedOutInAnyView(String element) {
//UCM we do not need to know of another stream co.
if(ClearCasePreferences.isUCM()){
return false;
}
boolean isCheckedoutInOtherView = false;
checkedOutInOtherView.clear();
HashMap<Integer, String> args = new HashMap<Integer, String>();
args
.put(Integer.valueOf(ClearCase.FORMAT),
"%En\tPredecessor: %[version_predecessor]p\tView: %Tf\tStatus: %Rf\n");
String[] output = ClearCasePlugin.getEngine().findCheckouts(
ClearCase.FORMAT, args, new String[] { element });
// Check if line ends with these keywords.
Pattern pattern = Pattern.compile(".*View:\\s(.*)\\sStatus:.*");
if (output.length > 0 ) {
// we have file checked-out in other view.
isCheckedoutInOtherView = true;
for (int i = 0; i < output.length; i++) {
String line = output[i];
Matcher matcher = pattern.matcher(line);
if (matcher.find()) {
// Adding information to user.Filter out current view.
String view = matcher.group(1);
if (!view.equals(getViewName(element))) {
checkedOutInOtherView.add(view);
}
}
}
}
return isCheckedoutInOtherView;
}
public static String getViewName(IResource resource) {
if (resource == null || resource.getProject() == null)
return "";
// assume that a complete project is inside one view
String path;
try {
path = resource.getProject().getLocation().toOSString();
} catch (NullPointerException e) {
return "";
}
String res = viewLookupTable.get(path);
if (res == null || res.length() == 0) {
// use the originally given resource for the cleartool query
if (!(resource instanceof IContainer)) {
resource = resource.getParent();
}
res = getViewName(resource.getLocation().toOSString());
if (res.length() > 0) {
viewLookupTable.put(path, res);
viewAccessLookupTable.put(res, (IContainer) resource);
}
}
return res;
}
public static IContainer getViewFolder(final String viewname) {
IContainer res = viewAccessLookupTable.get(viewname);
if (res == null) {
// TODO: search for a directory in view
} else if (!res.isAccessible()) {
// TODO: search for a new directory in view
}
return res;
}
public static String getViewName(final String path) {
String res = viewLookupTable.get(path);
if (res == null) {
res = ClearCasePlugin.getEngine().getViewName(path);
viewLookupTable.put(path, res);
}
return res;
}
public static String[] getUsedViewNames() {
Set<String> views = new HashSet<String>();
for (String v : viewLookupTable.values()) {
views.add(v);
}
return views.toArray(new String[views.size()]);
}
/**
* Returns the view type of the view containing the resource.
*
* @param resource
* The resource inside a view.
* @return "dynamic" or "snapshot"
*/
public static String getViewType(IResource resource) {
return isSnapshotView(getViewName(resource)) ? ClearCaseInterface.VIEW_TYPE_SNAPSHOT
: ClearCaseInterface.VIEW_TYPE_DYNAMIC;
}
public static boolean isSnapshotView(final String viewName) {
Boolean res = snapshotViewLookupTable.get(viewName);
if (res == null) {
if (viewName.length() == 0) {
// special case, can happen after queries in non-view
// directories
res = false;
} else {
// standard case, we have a viewname, ask CC for the type
String viewtype = ClearCasePlugin.getEngine().getViewType(
viewName);
res = viewtype.equals(ClearCaseInterface.VIEW_TYPE_SNAPSHOT);
}
snapshotViewLookupTable.put(viewName, res);
}
return res;
}
/**
* Returns the root of the view. An empty view root indicates a dynamic
* view.
*
* @param resource
* @return
*/
public String getViewRoot(IResource resource) throws TeamException {
return ClearCasePlugin.getEngine().getViewLocation(
);
}
/**
* Returns the name of the vob that contains the specified element
*
* @param resource
* @return
*/
public String getVobName(IResource resource) throws TeamException {
String viewRoot = getViewRoot(resource);
IPath viewLocation = new Path(viewRoot);
IPath resourceLocation = resource.getLocation();
// ignore device when dealing with dynamic views
if (viewRoot.length() == 0) {
viewLocation = viewLocation.setDevice(resourceLocation.getDevice());
}
if (viewLocation.isPrefixOf(resourceLocation)) {
IPath vobLocation = resourceLocation
.removeFirstSegments(viewLocation.segmentCount());
if (!ClearCasePlugin.isWindows() && vobLocation.segmentCount() > 0) {
// on unix vobs are prefixed with directory named "/vobs"
vobLocation = vobLocation.removeFirstSegments(1);
}
if (vobLocation.segmentCount() > 0)
return vobLocation.segment(0);
}
return "none";
}
/**
* Returns the vob relative path of the specified element
*
* @param resource
* @return the vob relativ path (maybe <code>null</code> if outside vob)
*/
public String getVobRelativPath(IResource resource) throws TeamException {
String viewRoot = getViewRoot(resource);
IPath viewLocation = new Path(viewRoot).setDevice(null); // ignore
// device
IPath resourceLocation = resource.getLocation().setDevice(null); // ignore
// devices
if (viewLocation.isPrefixOf(resourceLocation)) {
IPath vobLocation = resourceLocation
.removeFirstSegments(viewLocation.segmentCount());
if (!ClearCasePlugin.isWindows() && vobLocation.segmentCount() > 0) {
// on unix vobs are prefixed with directory named "/vobs"
vobLocation = vobLocation.removeFirstSegments(1);
}
if (vobLocation.segmentCount() > 0)
return vobLocation.removeFirstSegments(1).makeRelative()
.toString();
}
return null;
}
// FIXME: We need to handle exceptions.
public boolean setActivity(String activitySelector, String viewName) {
ClearCaseElementState[] cces = ClearCasePlugin.getEngine().setActivity(
ClearCase.VIEW, activitySelector, viewName);
if (cces == null) {
System.out.println("ERROR: Could not set activity: "
+ activitySelector + " Got null response.");
return false;
}
if (cces[0].state == ClearCase.ACTIVITY_SET) {
return true;
} else {
return false;
}
}
/**
* Returns a list of actvities. Makes a new request each time and does not
* cache.
*
* @param viewName
* @return
*/
public ArrayList<String> listMyActivities() {
String[] output = ClearCasePlugin.getEngine().getActivity(
ClearCase.CVIEW | ClearCase.ME | ClearCase.SHORT, null);
if (output.length > 0) {
return new ArrayList<String>(Arrays.asList(output));
}
return new ArrayList<String>(Arrays
.asList(new String[] { NO_ACTIVITY }));
}
public ArrayList<String> listAllActivities() {
String[] output = ClearCasePlugin.getEngine().getActivity(
ClearCase.CVIEW | ClearCase.SHORT, null);
return new ArrayList<String>(Arrays.asList(output));
}
/**
*
* @return
*/
public boolean activityAssociated(String viewName) {
HashMap<Integer, String> args = new HashMap<Integer, String>();
args.put(Integer.valueOf(ClearCase.VIEW), viewName);
String[] output = ClearCasePlugin.getEngine().getActivity(
ClearCase.VIEW | ClearCase.SHORT, args);
if (output.length > 0) {
if (ClearCasePlugin.DEBUG_PROVIDER) {
ClearCasePlugin.trace(TRACE_ID,
"Activity " + output[0] + " is associated!"); //$NON-NLS-1$
}
return true;
}
return false;
}
/**
* Get name of set activity in current view.
*
* @return
*/
public String getCurrentActivity() {
String result = "";
String[] output = ClearCasePlugin.getEngine().getActivity(
ClearCase.SHORT | ClearCase.CACT, null);
if (output == null | output.length == 0) {
return result;
}
if (output[0] != null && output[0].length() > 0) {
return output[0];
}
return result;
}
public ClearCaseElementState createActivity(String headline,
String activitySelector, String path) throws ClearCaseException {
ClearCaseElementState[] cces = ClearCasePlugin.getEngine().mkActivity(
ClearCase.HEADLINE | ClearCase.FORCE | ClearCase.NSET,
headline, activitySelector, path);
if (cces != null) {
return cces[0];
} else {
return null;
}
}
// public String getStream(String viewName) {
// return ClearCasePlugin.getEngine().getStream(
// ClearCase.SHORT | ClearCase.VIEW, viewName);
// }
public String getCurrentStream() {
String result = "";
String[] output = ClearCasePlugin.getEngine().getStream(
ClearCase.SHORT, null);
if (output != null && output.length > 0) {
result = output[0];
}
return result;
}
/**
* Extract pvob tag. (Unix) activity:<activity_name>@/vobs/$pvob or
* /vob/$pvob (Windows) activity:<activity_name@\$pvob
*
* @param activitySelector
* @return pVobTag $pvob
*/
public String getPvobTag(String activitySelector) {
int index = activitySelector.indexOf(SNAIL) + 1;
String path = activitySelector.substring(index).trim();
return path.substring(0);
}
/**
* getStream() returns an array but contains one or no element.If we have
* actvities in stream we have one element.
* activity:<activityId>@/vobs/$pvob,activity:<activityId>@/vobs/$pvob,
* activity: ... All activities are on one line.
*
* @return array of activities or an empty array.
*/
public String[] getActivitySelectors(String view) {
String[] result = new String[] {};
HashMap<Integer, String> args = new HashMap<Integer, String>();
args.put(Integer.valueOf(ClearCase.FORMAT), "%[activities]CXp");
args.put(Integer.valueOf(ClearCase.VIEW), view);
String[] output = ClearCasePlugin.getEngine().getStream(
ClearCase.FORMAT | ClearCase.VIEW, args);
if (output != null && output.length == 1) {
result = output[0].split(", ");
}
return result;
}
/**
* Before the move operation we check if parent directories are checked out.
* We use that after the move has been performed in clearcase to set
* directories state (co/ci) as prior to move operation. If checkout is need
* then it is performed within the java clearcase package. The checkin is
* however performed within this method since we know the state prior to
* move operation and there is no need to send this information to the
* clearcase package. So an evetual checkin will be performed in this
* method.
*
* @param source
* @param destination
* @param monitor
* @return result status of the operation.
*/
public IStatus move(IResource source, IResource destination,
IProgressMonitor monitor) {
int returnCode = 1;// Used in messge dialog.
try {
monitor.beginTask("Moving " + source.getFullPath() + " to "
+ destination.getFullPath(), 100);
// Sanity check - can't move something that is not part of clearcase
if (!isClearCaseElement(source))
return new Status(
IStatus.ERROR,
ID,
TeamException.NO_REMOTE_RESOURCE,
MessageFormat
.format(
"Resource \"{0}\" is not under source control!",
new Object[] { source.getFullPath()
.toString() }), null);
IStatus result = OK_STATUS;
ClearCaseElementState[] state = null;
if (isCheckedOutInAnyView(source.getLocation().toOSString())) {
StringBuffer sb = new StringBuffer();
for (String view : checkedOutInOtherView) {
sb.append(view + "\t");
}
// Open message dialog and ask if we want to continue.
returnCode = showMessageDialog(
"File Checkedout in Other View ",
"File checkedout in the following views: "
+ sb.toString()+"\n"
+ " Do you still want to move, "
+ source.getName() + "?");
if(returnCode != 0){
return cancelCheckout(source,monitor, opListener);
}
}
if (ClearCasePreferences.isAutoCheckinParentAfterMoveAllowed()) {
state = ClearCasePlugin.getEngine()
.move(
source.getLocation().toOSString(),
destination.getLocation().toOSString(),
getComment(),
ClearCase.FORCE | ClearCase.CHECKIN
| getCheckoutType(), opListener);
} else {
state = ClearCasePlugin.getEngine().move(
source.getLocation().toOSString(),
destination.getLocation().toOSString(), getComment(),
ClearCase.FORCE | getCheckoutType(), opListener);
}
StateCacheFactory.getInstance().remove(source);
updateState(source.getParent(), IResource.DEPTH_ZERO,
new SubProgressMonitor(monitor, 10));
updateState(destination.getParent(), IResource.DEPTH_ZERO,
new SubProgressMonitor(monitor, 10));
updateState(destination, IResource.DEPTH_INFINITE,
new SubProgressMonitor(monitor, 10));
if (!state[0].isMoved())
return new Status(IStatus.ERROR, ID, TeamException.UNABLE,
"Could not move element: "
// + ccStatus.message
, null);
return result;
} finally {
setComment("");
monitor.done();
}
}
public IStatus checkoutParent(IResource resource, IProgressMonitor monitor) {
try {
monitor.beginTask("Checking out "
+ resource.getParent().getFullPath().toString(), 10);
IStatus result = OK_STATUS;
String parent = null;
// IProject's parent is the workspace directory, we want the
// filesystem
// parent if the workspace is not itself in clearcase
boolean flag = resource instanceof IProject
&& !isClearCaseElement(resource.getParent());
if (flag) {
parent = resource.getLocation().toFile().getParent().toString();
} else {
parent = resource.getParent().getLocation().toOSString();
}
monitor.worked(2);
ClearCaseElementState elementState = ClearCasePlugin.getEngine()
.getElementState(parent);
if (!elementState.isElement()) {
result = new Status(IStatus.ERROR, ID, TeamException.UNABLE,
"Could not find a parent that is a clearcase element",
null);
return result;
}
monitor.worked(2);
if (!elementState.isCheckedOut() && !elementState.isLink()) {
String[] element = { parent };
ClearCaseElementState[] elementState2 = ClearCasePlugin
.getEngine().checkout(element, getComment(),
getCheckoutType(), opListener);
monitor.worked(4);
if (!flag) {
updateState(resource.getParent(), IResource.DEPTH_ZERO,
new SubProgressMonitor(monitor, 10));
}
if (elementState2 == null) {
// TODO: Handle ccStatus.message.
result = new Status(IStatus.ERROR, ID,
TeamException.UNABLE,
"Could not check out parent: " + "ccStatus", null);
}
}
return result;
} finally {
monitor.done();
}
}
// Notifies decorator that state has changed for an element
public void updateState(IResource resource, int depth,
IProgressMonitor monitor) {
try {
monitor.beginTask("Refreshing " + resource.getFullPath(), 20);
if (!refreshResources) {
StateCacheFactory.getInstance().removeSingle(resource);
monitor.worked(10);
} else {
resource.refreshLocal(depth,
new SubProgressMonitor(monitor, 10));
}
if (resource.exists()) {
doUpdateState(resource, depth, new SubProgressMonitor(monitor,
10));
} else {
StateCacheFactory.getInstance().refreshStateAsyncHighPriority(
new IResource[] { resource }, null);
}
} catch (CoreException ex) {
ClearCasePlugin.log(IStatus.ERROR,
"Error refreshing ClearCase state: " + ex.getMessage(), ex);
} finally {
monitor.done();
}
}
private IStatus doUpdateState(IResource resource, int depth,
IProgressMonitor progressMonitor) {
IStatus result = execute(REFRESH_STATE, resource, depth,
progressMonitor);
return result;
}
/**
* @see RepositoryProvider#getMoveDeleteHook()
*/
@Override
public IMoveDeleteHook getMoveDeleteHook() {
return moveHandler;
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.team.core.RepositoryProvider#getFileModificationValidator2()
*/
@Override
public FileModificationValidator getFileModificationValidator2() {
return ClearCasePlugin.getDefault().getClearCaseModificationHandler();
}
/**
* Gets the comment.
*
* @return Returns a String
*/
public String getComment() {
return comment;
}
/**
* Sets the comment.
*
* @param comment
* The comment to set
*/
public void setComment(String comment) {
// escape comment if enabled
// if (comment.trim().length() > 0 && ClearCasePlugin.isCommentEscape())
// comment = ClearCaseUtil.getEscaped(comment);
this.comment = comment;
}
// Out of sheer laziness, I appropriated the following code from the team
// provider example =)
private static final class RefreshStateOperation implements
IRecursiveOperation {
@SuppressWarnings("deprecation")
public IStatus visit(IResource resource, IProgressMonitor monitor) {
try {
checkCanceled(monitor);
monitor.beginTask("Refreshing State " + resource.getFullPath(),
10);
// probably overkill/expensive to do it here - should do it
// on a
// case by case basis for each method that actually changes
// state
StateCache cache = StateCacheFactory.getInstance()
.get(resource);
if (!cache.isSymbolicLink()) {
// force update immediately. For symlinks, the symlink
// target has to be updated first, see below
cache.doUpdate();
}
// check if a symbolic link target is also in our workspace
if (cache.isSymbolicLink()
&& null != cache.getSymbolicLinkTarget()) {
File target = new File(cache.getSymbolicLinkTarget());
if (!target.isAbsolute()) {
target = null != cache.getPath() ? new File(cache
.getPath()).getParentFile() : null;
if (null != target) {
target = new File(target, cache
.getSymbolicLinkTarget());
}
}
if (null != target && target.exists()) {
IPath targetLocation = new Path(target
.getAbsolutePath());
IResource[] resources = null;
if (target.isDirectory()) {
resources = ResourcesPlugin.getWorkspace()
.getRoot().findContainersForLocation(
targetLocation);
} else {
resources = ResourcesPlugin.getWorkspace()
.getRoot().findFilesForLocation(
targetLocation);
}
if (null != resources) {
for (int i = 0; i < resources.length; i++) {
IResource foundResource = resources[i];
ClearCaseProvider provider = ClearCaseProvider
.getClearCaseProvider(foundResource);
if (null != provider) {
StateCacheFactory.getInstance().get(
foundResource).updateAsync(false);
// after the target is updated, we must
// update the
// symlink itself again :-(
cache.updateAsync(false);
}
}
}
}
}
return OK_STATUS;
} finally {
monitor.done();
}
}
}
private final class AddOperation implements IRecursiveOperation {
ArrayList<IResource> privateElement = new ArrayList<IResource>();
ArrayList<IResource> parentToCheckin = new ArrayList<IResource>();
public IStatus visit(IResource resource, IProgressMonitor monitor) {
try {
monitor.beginTask(
"Adding " + resource.getFullPath().toString(), 100);
IStatus result = OK_STATUS;
// Sanity check - can't add something that already is under VC
if (isClearCaseElement(resource))
// return status with severity OK
return new Status(
IStatus.OK,
ID,
TeamException.UNABLE,
MessageFormat
.format(
"Resource \"{0}\" is already under source control!",
new Object[] { resource
.getFullPath().toString() }),
null);
result = findPrivateElements(resource, monitor);
if (result.isOK()) {
Collections.reverse(privateElement);
for (Object element : privateElement) {
IResource myResource = (IResource) element;
if (myResource.getType() == IResource.FOLDER) {
result = makeFolderElement(myResource, monitor);
} else if (myResource.getType() == IResource.FILE) {
result = makeFileElement(myResource, monitor);
}
}
}
// Add operation checks out parent directory. Change state to
// checked-out. No resource changed event is sent since this is
// implicitly done by
// add.
IResource directory = resource.getParent();
try {
directory.refreshLocal(IResource.DEPTH_ZERO,
new SubProgressMonitor(monitor, 10));
updateState(directory, IResource.DEPTH_ZERO,
new SubProgressMonitor(monitor, 10));
} catch (CoreException e) {
System.out.println("We got an exception!");
e.printStackTrace();
result = new Status(IStatus.ERROR, ID,
TeamException.UNABLE, "Add failed: " + "Exception"
+ e.getMessage(), null);
}
// Add check recursive checkin of files.
if (ClearCasePreferences.isAddWithCheckin()
&& result == OK_STATUS) {
try {
for (Object element : privateElement) {
IResource res = (IResource) element;
IResource folder = res.getParent();
if (!parentToCheckin.contains(folder)) {
parentToCheckin.add(folder);
}
if (isCheckedOut(res)) {
checkin(new IResource[] { res },
IResource.DEPTH_ZERO,
new SubProgressMonitor(monitor, 10));
}
}
for (IResource parent : parentToCheckin) {
if (isCheckedOut(parent)) {
checkin(new IResource[] { parent },
IResource.DEPTH_ZERO,
new SubProgressMonitor(monitor, 10));
}
}
} catch (TeamException e) {
result = new Status(IStatus.ERROR, ID,
TeamException.UNABLE,
"Checkin of resource failed: " + "Exception"
+ e.getMessage(), null);
}
}
monitor.worked(40);
return result;
} finally {
monitor.done();
privateElement.clear();
parentToCheckin.clear();
}
}
/**
* Recursively from bottom of file path to top until clearcase element
* is found.
*
* @param resource
* @param monitor
* @return
*/
private IStatus findPrivateElements(IResource resource,
IProgressMonitor monitor) {
IStatus result = OK_STATUS;
IResource parent = resource.getParent();
// When resource is a project, try checkout its parent, and if
// that fails,
// then neither project nor workspace is in clearcase.
if (isClearCaseElement(parent)) {
privateElement.add(resource);
updateState(parent, IResource.DEPTH_ZERO,
new SubProgressMonitor(monitor, 10));// make sure state
// for parent is
// correct.
if (!isCheckedOut(parent)) {
ClearCaseElementState[] state = ClearCasePlugin.getEngine()
.checkout(
new String[] { parent.getLocation()
.toOSString() }, getComment(),
ClearCase.NONE, opListener);
if (state[0].isCheckedOut()) {
updateState(parent, IResource.DEPTH_ZERO,
new SubProgressMonitor(monitor, 10));
}
}
} else if (resource instanceof IProject
&& !(isClearCaseElement(resource))) {
// We reached project top and it is not a cc element.
result = new Status(IStatus.ERROR, ID, TeamException.UNABLE,
"Add failed: " + "project folder " + resource.getName()
+ " is not an element is not an cc element",
null);
} else {
privateElement.add(resource);
findPrivateElements(parent, new SubProgressMonitor(monitor, 10));
}
return result;
}
}
private Status makeFileElement(IResource resource, IProgressMonitor monitor) {
Status result = OK_STATUS;
ClearCaseElementState state = ClearCasePlugin
.getEngine()
.add(
resource.getLocation().toOSString(),
false,
getComment(),
ClearCase.PTIME
| (ClearCasePreferences.isUseMasterForAdd() ? ClearCase.MASTER
: ClearCase.NONE), opListener);
if (state.isElement()) {
// Do nothing!
} else {
result = new Status(IStatus.ERROR, ID, TeamException.UNABLE,
"Add failed: " + "Could not add element"
+ resource.getName(), null);
}
try {
resource.refreshLocal(IResource.DEPTH_ZERO, new SubProgressMonitor(
monitor, 10));
} catch (CoreException e) {
System.out.println("We got an exception!");
e.printStackTrace();
result = new Status(IStatus.ERROR, ID, TeamException.UNABLE,
"Add failed: " + "Exception" + e.getMessage(), null);
}
updateState(resource, IResource.DEPTH_ZERO, new SubProgressMonitor(
monitor, 10));
if (result.isOK()) {
result = forceSetChgrp(resource);
}
return result;
}
private Status makeFolderElement(IResource resource,
IProgressMonitor monitor) {
File dir = new File(resource.getLocation().toOSString());
File tmpDir = new File(dir.getParentFile(), dir.getName() + ".tmp");
Status result = OK_STATUS;
try {
// rename target dir to <name>.tmp since clearcase cannot make
// an directory element out of an existing view private one.
if (!dir.renameTo(tmpDir)) {
result = new Status(IStatus.ERROR, ID, TeamException.UNABLE,
"Add failed: " + "Could not rename " + dir.getPath()
+ " to " + tmpDir.getPath()
+ resource.getName(), null);
}
// Now time to create the original directory in
// clearcase.
ClearCaseElementState state = ClearCasePlugin.getEngine().add(
resource.getLocation().toOSString(),
true,
getComment(),
ClearCasePreferences.isUseMasterForAdd() ? ClearCase.MASTER
: ClearCase.NONE, opListener);
if (!state.isElement()) {
result = new Status(IStatus.ERROR, ID, TeamException.UNABLE,
"Add failed: " + "Could not add element"
+ resource.getName(), null);
}
// Now move back the content of <name>.tmp to cc created one.
if (!moveDirRec(tmpDir, dir)) {
result = new Status(IStatus.ERROR, ID, TeamException.UNABLE,
"Could not move back the content of " + dir.getPath()
+ " as part of adding it to Clearcase:\n"
+ "Its old content is in " + tmpDir.getName()
+ ". Please move it back manually", null);
}
if (result.isOK()) {
result = forceSetChgrp(resource);
}
// Now move back the content of tmp to original.
// To avoid CoreException do a refreshLocal(). Does
// not recognize the cc created resource directory.
resource.refreshLocal(IResource.DEPTH_ZERO, new SubProgressMonitor(
monitor, 10));
updateState(resource, IResource.DEPTH_ZERO, new SubProgressMonitor(
monitor, 10));
} catch (CoreException ce) {
System.out.println("We got an exception!");
ce.printStackTrace();
result = new Status(IStatus.ERROR, ID, TeamException.UNABLE,
"Add failed: " + "Exception" + ce.getMessage(), null);
}
return result;
}
private Status forceSetChgrp(IResource resource) {
Status result = OK_STATUS;
String group = ClearCasePreferences.getClearCasePrimaryGroup().trim();
if (group.length() > 0) {
try {
ClearCasePlugin.getEngine().setGroup(
resource.getLocation().toOSString(), group, opListener);
} catch (Exception e) {
result = new Status(IStatus.ERROR, ID, TeamException.UNABLE,
"Chgrp failed: " + "Could not change group element "
+ resource.getName() + "\n" + e.getMessage(),
null);
}
}
return result;
}
private final class UncheckOutOperation implements IRecursiveOperation {
public IStatus visit(final IResource resource,
final IProgressMonitor monitor) {
try {
monitor.beginTask("Uncheckout " + resource.getFullPath(), 100);
StateCache cache = getCache(resource);
final StateCache targetElement = getFinalTargetElement(cache);
// Sanity check - can't process something that is not part of
// clearcase
if (targetElement == null
|| !targetElement.isClearCaseElement())
return new Status(
IStatus.WARNING,
ID,
TeamException.NO_REMOTE_RESOURCE,
MessageFormat
.format(
"Resource \"{0}\" is not a ClearCase element!",
new Object[] { resource
.getFullPath().toString() }),
null);
// Sanity check - can't uncheckout something that is not checked
// out
if (!targetElement.isCheckedOut())
// return severity OK
return new Status(IStatus.OK, ID,
TeamException.NOT_CHECKED_OUT,
MessageFormat.format(
"Resource \"{0}\" is not checked out!",
new Object[] { targetElement.getPath() }),
null);
IStatus result = OK_STATUS;
// Yes continue checking out.
int flags = ClearCase.RECURSIVE;
if (ClearCasePreferences.isKeepChangesAfterUncheckout()) {
flags |= ClearCase.KEEP;
}
ClearCasePlugin.getEngine().uncheckout(
new String[] { targetElement.getPath() }, flags,
opListener);
monitor.worked(40);
updateState(resource, IResource.DEPTH_ZERO,
new SubProgressMonitor(monitor, 10));
// if (!status.status) {
// result = new Status(IStatus.ERROR, ID,
// TeamException.UNABLE, "Uncheckout failed: "
// + status.message, null);
// }
return result;
} finally {
monitor.done();
}
}
}
private final class DeleteOperation implements IIterativeOperation {
public IStatus visit(IResource resource, int depth,
IProgressMonitor monitor) {
try {
monitor.beginTask("Deleting " + resource.getFullPath(), 100);
// Sanity check - can't delete something that is not part of
// clearcase
if (!isClearCaseElement(resource))
return new Status(
IStatus.ERROR,
ID,
TeamException.NO_REMOTE_RESOURCE,
MessageFormat
.format(
"Resource \"{0}\" is not a ClearCase element!",
new Object[] { resource
.getFullPath().toString() }),
null);
IStatus result = checkoutParent(resource,
new SubProgressMonitor(monitor, 10));
if (result.isOK()) {
ClearCasePlugin.getEngine()
.delete(
new String[] { resource.getLocation()
.toOSString() }, getComment(),
ClearCase.RECURSIVE | ClearCase.KEEP,
opListener);
monitor.worked(40);
updateState(resource, IResource.DEPTH_INFINITE,
new SubProgressMonitor(monitor, 10));
// if (!status.status) {
// result = new Status(IStatus.ERROR, ID,
// TeamException.UNABLE, "Delete failed: "
// + status.message, null);
// }
}
return result;
} finally {
monitor.done();
}
}
}
protected final class CheckInOperation implements IRecursiveOperation {
public IStatus visit(IResource resource, IProgressMonitor monitor) {
try {
int returnCode = 1;// Used in messge dialog.
monitor.beginTask("Checkin in " + resource.getFullPath(), 100);
StateCache cache = getCache(resource);
final StateCache targetElement = getFinalTargetElement(cache);
IStatus result = OK_STATUS;
// Sanity check - can't check in something that is not part of
// clearcase
if (targetElement == null
|| !targetElement.isClearCaseElement())
return new Status(
IStatus.WARNING,
ID,
TeamException.NO_REMOTE_RESOURCE,
MessageFormat
.format(
"Resource \"{0}\" is not a ClearCase element!",
new Object[] { resource
.getFullPath().toString() }),
null);
// Sanity check - can't checkin something that is not checked
// out
if (!targetElement.isCheckedOut())
// return status with severity OK
return new Status(IStatus.OK, ID,
TeamException.NOT_CHECKED_OUT,
MessageFormat.format(
"Resource \"{0}\" is not checked out!",
new Object[] { targetElement.getPath() }),
null);
if (ClearCasePreferences.isCheckinIdenticalAllowed()) {
ClearCasePlugin.getEngine().checkin(
new String[] { targetElement.getPath() },
getComment(),
ClearCase.PTIME | ClearCase.IDENTICAL, opListener);
} else {
try {
ClearCasePlugin.getEngine().checkin(
new String[] { targetElement.getPath() },
getComment(), ClearCase.PTIME, opListener);
} catch (ClearCaseException cce) {
// check error
switch (cce.getErrorCode()) {
case ClearCase.ERROR_PREDECESSOR_IS_IDENTICAL:
result = new Status(
IStatus.ERROR,
ID,
TeamException.NOT_CHECKED_IN,
MessageFormat
.format(
Messages
.getString("ClearCasePlugin.error.checkin.identicalPredecessor"),
new Object[] { cce
.getElements() }),
null);
break;
case ClearCase.ERROR_ELEMENT_HAS_CHECKOUTS:
result = new Status(
IStatus.ERROR,
ID,
TeamException.NOT_CHECKED_IN,
MessageFormat
.format(
Messages
.getString("ClearCasePlugin.error.checkin.elementHasCheckouts"),
new Object[] { cce
.getElements() }),
null);
break;
case ClearCase.ERROR_MOST_RECENT_NOT_PREDECESSOR_OF_THIS_VERSION:
// Only support for: To merge the latest version
// with your checkout
// getVersion --> \branch\CHECKEDOUT.
String branchName = getBranchName(getVersion(resource));
String latestVersion = resource.getLocation()
.toOSString()
+ "@@" + branchName + "LATEST";
ClearCaseElementState myState = ClearCasePlugin
.getEngine().merge(targetElement.getPath(),
- new String[] { latestVersion },
+ new String[] { latestVersion },null,
ClearCase.GRAPHICAL);
if (myState.isMerged()) {
returnCode = showMessageDialog("Checkin",
"Do you want to checkin the merged result?");
if (returnCode == 0) {
// Yes continue checkin
ClearCasePlugin.getEngine().checkin(
new String[] { targetElement
.getPath() }, getComment(),
ClearCase.PTIME, opListener);
}
} else {
result = new Status(
IStatus.ERROR,
ID,
TeamException.CONFLICT,
MessageFormat
.format(
Messages
.getString("ClearCasePlugin.error.checkin.mergeLatestProblem"),
new Object[] { cce
.getElements() }),
null);
}
break;
default:
result = new Status(
IStatus.ERROR,
ID,
TeamException.NOT_CHECKED_IN,
MessageFormat
.format(
Messages
.getString("ClearCasePlugin.error.checkin.unknown"),
new Object[] { cce
.getElements() }),
null);
break;
}
}
}
monitor.worked(40);
updateState(resource, IResource.DEPTH_ZERO,
new SubProgressMonitor(monitor, 10));
return result;
} finally {
monitor.done();
}
}
}
private final class CheckOutOperation implements IRecursiveOperation {
public IStatus visit(final IResource resource,
final IProgressMonitor monitor) {
try {
int returnCode = 1;// Used for message dialogs.
monitor
.beginTask("Checking out " + resource.getFullPath(),
100);
StateCache cache = getCache(resource);
final StateCache targetElement = getFinalTargetElement(cache);
// Sanity check - can't checkout something that is not part of
// clearcase
if (targetElement == null
|| !targetElement.isClearCaseElement())
return new Status(
IStatus.WARNING,
ID,
TeamException.NO_REMOTE_RESOURCE,
MessageFormat
.format(
"Resource \"{0}\" is not a ClearCase element!",
new Object[] { resource
.getFullPath().toString() }),
null);
// Sanity check - can't checkout something that is already
// checked out
if (targetElement.isCheckedOut())
// return status with severity OK
return new Status(IStatus.OK, ID,
TeamException.NOT_CHECKED_IN, MessageFormat.format(
"Resource \"{0}\" is already checked out!",
new Object[] { targetElement.getPath() }),
null);
IStatus result = OK_STATUS;
// update if necessary
if (ClearCasePreferences.isCheckoutLatest()
&& targetElement.isSnapShot()) {
monitor.subTask("Updating " + targetElement.getPath());
update(resource.getFullPath().toOSString(), 0, false);
}
monitor.worked(20);
// only checkout if update was successful
if (result == OK_STATUS) {
monitor.subTask("Checking out " + targetElement.getPath());
try {
ClearCasePlugin
.getEngine()
.checkout(
new String[] { targetElement.getPath() },
getComment(),
getCheckoutType()
| ClearCase.PTIME
| (targetElement.isHijacked() ? ClearCase.HIJACKED
: ClearCase.NONE)|(ClearCasePreferences.isUseMasterForAdd() ? ClearCase.NMASTER
: ClearCase.NONE),
opListener);
} catch (ClearCaseException cce) {
switch (cce.getErrorCode()) {
case ClearCase.ERROR_ELEMENT_HAS_CHECKOUTS:
returnCode = showMessageDialog("Checkout",
"Resource already checked-out reserved.\nDo you want to check-out unreserved?");
if (returnCode == 0) {
// Yes continue checking out but
// unreserved.
ClearCasePlugin.getEngine()
.checkout(
new String[] { targetElement
.getPath() },
getComment(),
ClearCase.UNRESERVED
| ClearCase.PTIME|(ClearCasePreferences.isUseMasterForAdd() ? ClearCase.NMASTER: ClearCase.NONE),
opListener);
monitor.worked(40);
updateState(resource, IResource.DEPTH_ZERO,
new SubProgressMonitor(monitor, 10));
}
break;
case ClearCase.ERROR_BRANCH_IS_MASTERED_BY_REPLICA:
returnCode = showMessageDialog(
"Checkout",
"Resource could not be checked out since not your replica.\nDo you want change mastership?");
changeMastershipSequence(returnCode, targetElement,
opListener);
monitor.worked(40);
updateState(resource, IResource.DEPTH_ZERO,
new SubProgressMonitor(monitor, 10));
break;
default:
result = new Status(
IStatus.ERROR,
ID,
TeamException.UNABLE,
MessageFormat
.format(
Messages
.getString("ClearCasePlugin.error.checkin.unknown"),
new Object[] { cce
.getElements() }),
null);
break;
}
}
}
monitor.worked(20);
// update state of target element first (if symlink)
if (!targetElement.equals(cache)) {
targetElement.doUpdate();
}
// update state
updateState(resource, IResource.DEPTH_ZERO,
new SubProgressMonitor(monitor, 10));
return result;
} finally {
monitor.done();
}
}
}
private final class UnHijackOperation implements IRecursiveOperation {
public IStatus visit(final IResource resource,
final IProgressMonitor monitor) {
try {
monitor.beginTask("Checkin out " + resource.getFullPath(), 100);
// Sanity check - can't checkout something that is not part of
// clearcase
if (!isHijacked(resource))
return new Status(
IStatus.WARNING,
ID,
TeamException.NOT_AUTHORIZED,
MessageFormat
.format(
"Resource \"{0}\" is not a Hijacked ClearCase element!",
new Object[] { resource
.getFullPath().toString() }),
null);
IStatus result = OK_STATUS;
try {
/* remove existing xx.keep file */
File keep = new File(resource.getLocation().toOSString()
+ ".keep");
if (keep.exists()) {
keep.delete();
}
/* rename existing xx.keep file */
keep = new File(resource.getLocation().toOSString());
if (keep.exists()) {
keep.renameTo(new File(resource.getLocation()
.toOSString()
+ ".keep"));
}
} catch (Exception e) {
result = FAILED_STATUS;
}
monitor.worked(20);
if (result == OK_STATUS) {
// update if necessary
if (ClearCasePreferences.isCheckoutLatest()
&& isSnapShot(resource)) {
monitor.subTask("Updating " + resource.getName());
update(resource.getLocation().toOSString(),
ClearCase.GRAPHICAL, false);
}
}
monitor.worked(20);
// update state
updateState(resource.getParent(), IResource.DEPTH_ONE,
new SubProgressMonitor(monitor, 10));
return result;
} finally {
monitor.done();
}
}
}
private final class UpdateOperation implements IIterativeOperation {
public IStatus visit(IResource resource, int depth,
IProgressMonitor monitor) {
try {
monitor.beginTask("Updating " + resource.getFullPath(), 100);
// Sanity check - can't update something that is not part of
// clearcase
if (!isClearCaseElement(resource))
return new Status(
IStatus.ERROR,
ID,
TeamException.NO_REMOTE_RESOURCE,
MessageFormat
.format(
"Resource \"{0}\" is not a ClearCase element!",
new Object[] { resource
.getFullPath().toString() }),
null);
IStatus result = OK_STATUS;
String element = resource.getLocation().toOSString();
ClearCasePlugin.getEngine().update(element, 0, false);
monitor.worked(40);
updateState(resource, IResource.DEPTH_INFINITE,
new SubProgressMonitor(monitor, 10));
return result;
} finally {
monitor.done();
}
}
}
private final class CheckoutUnreservedOperation implements
IIterativeOperation {
public IStatus visit(IResource resource, int depth,
IProgressMonitor monitor) {
try {
monitor.beginTask("Changing checkout to unreserved "
+ resource.getFullPath(), 100);
// Sanity check - can't update something that is not part of
// clearcase
if (!isClearCaseElement(resource))
return new Status(
IStatus.ERROR,
ID,
TeamException.NO_REMOTE_RESOURCE,
MessageFormat
.format(
"Resource \"{0}\" is not a ClearCase element!",
new Object[] { resource
.getFullPath().toString() }),
null);
IStatus result = OK_STATUS;
String element = resource.getLocation().toOSString();
ClearCasePlugin.getEngine().unreserved(
new String[] { element }, null, 0, opListener);
monitor.worked(40);
updateState(resource, IResource.DEPTH_INFINITE,
new SubProgressMonitor(monitor, 10));
return result;
} finally {
monitor.done();
}
}
}
private final class CheckoutReservedOperation implements
IIterativeOperation {
public IStatus visit(IResource resource, int depth,
IProgressMonitor monitor) {
try {
monitor.beginTask("Changing checkout to reserved "
+ resource.getFullPath(), 100);
// Sanity check - can't update something that is not part of
// clearcase
if (!isClearCaseElement(resource))
return new Status(
IStatus.ERROR,
ID,
TeamException.NO_REMOTE_RESOURCE,
MessageFormat
.format(
"Resource \"{0}\" is not a ClearCase element!",
new Object[] { resource
.getFullPath().toString() }),
null);
IStatus result = OK_STATUS;
String element = resource.getLocation().toOSString();
ClearCasePlugin.getEngine().reserved(new String[] { element },
null, 0, opListener);
monitor.worked(40);
updateState(resource, IResource.DEPTH_INFINITE,
new SubProgressMonitor(monitor, 10));
return result;
} finally {
monitor.done();
}
}
}
/**
* These interfaces are to operations that can be performed on the array of
* resources, and on all resources identified by the depth parameter.
*
* @see execute(IOperation, IResource[], int, IProgressMonitor)
*/
public static interface IOperation {
// empty
}
public static interface IIterativeOperation extends IOperation {
public IStatus visit(IResource resource, int depth,
IProgressMonitor progress);
}
public static interface IRecursiveOperation extends IOperation {
public IStatus visit(IResource resource, IProgressMonitor progress);
}
/**
* Perform the given operation on the array of resources, each to the
* specified depth. Throw an exception if a problem ocurs, otherwise remain
* silent.
*/
protected void execute(IOperation operation, IResource[] resources,
int depth, IProgressMonitor progress) throws TeamException {
if (null == progress) {
progress = new NullProgressMonitor();
}
// Create an array to hold the status for each resource.
MultiStatus multiStatus = new MultiStatus(getID(), TeamException.OK,
"OK", null);
// For each resource in the local resources array until we have errors.
try {
progress.beginTask("Processing", 1000 * resources.length);
for (int i = 0; i < resources.length
&& !multiStatus.matches(IStatus.ERROR); i++) {
progress.subTask(resources[i].getFullPath().toString());
if (!isIgnored(resources[i])) {
if (operation instanceof IRecursiveOperation) {
multiStatus.merge(execute(
(IRecursiveOperation) operation, resources[i],
depth, new SubProgressMonitor(progress, 1000)));
} else {
multiStatus
.merge(((IIterativeOperation) operation).visit(
resources[i], depth,
new SubProgressMonitor(progress, 1000)));
}
} else {
progress.worked(1000);
}
}
// Finally, if any problems occurred, throw the exeption with all
// the statuses,
// but if there were no problems exit silently.
if (!multiStatus.isOK()) {
String message = multiStatus.matches(IStatus.ERROR) ? "There were errors that prevent the requested operation from finishing successfully."
: "The requested operation finished with warnings.";
throw new TeamException(new MultiStatus(
multiStatus.getPlugin(), multiStatus.getCode(),
multiStatus.getChildren(), message, multiStatus
.getException()));
}
// Cause all the resource changes to be broadcast to listeners.
// TeamPlugin.getManager().broadcastResourceStateChanges(resources);
} finally {
progress.done();
}
}
/**
* Perform the given operation on a resource to the given depth.
*/
protected IStatus execute(IRecursiveOperation operation,
IResource resource, int depth, IProgressMonitor progress) {
if (null == progress) {
progress = new NullProgressMonitor();
}
try {
progress.beginTask("Processing", 1000);
// Visit the given resource first.
IStatus status = operation.visit(resource, new SubProgressMonitor(
progress, 200));
// If the resource is a file then the depth parameter is irrelevant.
if (resource.getType() == IResource.FILE)
return status;
// If we are not considering any members of the container then we
// are done.
if (depth == IResource.DEPTH_ZERO)
return status;
// If the operation was unsuccessful, do not attempt to go deep.
if (status.matches(IStatus.ERROR)) // if (!status.isOK())
return status;
// if operation was cancaled, do not go deep
if (CANCEL_STATUS == status)
return OK_STATUS;
// If the container has no children then we are done.
IResource[] members = getMembers(resource);
if (members.length == 0)
return status;
// There are children and we are going deep, the response will be a
// multi-status.
MultiStatus multiStatus = new MultiStatus(status.getPlugin(),
status.getCode(), status.getMessage(), status
.getException());
// The next level will be one less than the current level...
int childDepth = (depth == IResource.DEPTH_ONE) ? IResource.DEPTH_ZERO
: IResource.DEPTH_INFINITE;
// Collect the responses in the multistatus (use merge to flatten
// the tree).
int ticks = 800 / members.length;
for (int i = 0; i < members.length
&& !multiStatus.matches(IStatus.ERROR); i++) {
progress.subTask(members[i].getFullPath().toString());
if (!isIgnored(members[i])) {
multiStatus
.merge(execute(operation, members[i], childDepth,
new SubProgressMonitor(progress, ticks)));
} else {
progress.worked(ticks);
}
}
// correct the MultiStatus message
if (!multiStatus.isOK()) {
/*
* Remember: the multi status was created with "OK" as message!
* This is not meaningful anymore. We have to correct it.
*/
String message = multiStatus.matches(IStatus.ERROR) ? "There were errors that prevent the requested operation from finishing successfully."
: "The requested operation finished with warnings.";
multiStatus = new MultiStatus(multiStatus.getPlugin(),
multiStatus.getCode(), multiStatus.getChildren(),
message, multiStatus.getException());
}
return multiStatus;
} finally {
progress.done();
}
}
protected IResource[] getMembers(IResource resource) {
if (resource.getType() != IResource.FILE) {
try {
return ((IContainer) resource).members();
} catch (CoreException exception) {
exception.printStackTrace();
throw new RuntimeException();
}
} // end-if
else
return new IResource[0];
}
/**
* @see org.eclipse.team.core.RepositoryProvider#canHandleLinkedResources()
*/
@Override
public boolean canHandleLinkedResources() {
return true;
}
@Override
public boolean canHandleLinkedResourceURI() {
return true;
}
/**
* Used to prevent co of resources like .project, .cproject ..
*
* @param resource
* @return
*/
public boolean isPreventCheckout(IResource resource) {
String list_csv = ClearCasePreferences.isPreventCheckOut().trim()
.replaceAll(" ", "");
String[] preventCoElements = null;
if (list_csv != null && list_csv.length() > 0) {
if (!list_csv.endsWith(",")) {
preventCoElements = list_csv.split(",");
} else {
// no list just one file.
preventCoElements = new String[] { list_csv };
}
for (String element : preventCoElements) {
if (resource.getName().equals(element)) {
return true;
}
}
}
return false;
}
/**
* Indicates if a resource is ignored and not handled.
* <p>
* Resources are never ignored, if they have a remote resource.
* </p>
*
* @param resource
* @return
*/
public boolean isIgnored(IResource resource) {
// // ignore eclipse linked resource
// if (resource.isLinked()) {
// if (ClearCasePlugin.DEBUG_PROVIDER_IGNORED_RESOURCES) {
// ClearCasePlugin.trace(TRACE_ID_IS_IGNORED,
// "linked resource: " + resource); //$NON-NLS-1$
// }
// return true;
// }
// never ignore handled resources
if (isClearCaseElement(resource))
return false;
// never ignore workspace root
IResource parent = resource.getParent();
if (null == parent)
return false;
// check the global ignores from Team (includes derived resources)
if (Team.isIgnoredHint(resource)) {
if (ClearCasePlugin.DEBUG_PROVIDER_IGNORED_RESOURCES) {
ClearCasePlugin.trace(TRACE_ID_IS_IGNORED,
"ignore hint from team plug-in: " + resource); //$NON-NLS-1$
}
return true;
}
// never ignore uninitialized resources
if (isUnknownState(resource))
return false;
// ignore resources outside view
if (!isInsideView(resource)) {
if (ClearCasePlugin.DEBUG_PROVIDER_IGNORED_RESOURCES) {
ClearCasePlugin.trace(TRACE_ID_IS_IGNORED,
"outside view: " + resource); //$NON-NLS-1$
}
return true;
}
// bug 904248: do not ignore if parent is a linked resource
if (parent.isLinked())
return false;
// check the parent, if the parent is ignored
// then this resource is ignored also
return isIgnored(parent);
}
/**
* @param resource
* @return
*/
public boolean isSymbolicLink(IResource resource) {
return StateCacheFactory.getInstance().get(resource).isSymbolicLink();
}
/**
* @param resource
* @return
*/
public boolean isSymbolicLinkTargetValid(IResource resource) {
return StateCacheFactory.getInstance().get(resource)
.isSymbolicLinkTargetValid();
}
/**
* @param resource
* @return
*/
public String getSymbolicLinkTarget(IResource resource) {
return StateCacheFactory.getInstance().get(resource)
.getSymbolicLinkTarget();
}
/**
* Indicates if the specified resource is edited (checked out) by someone
* else.
*
* @param childResource
* @return <code>true</code> if the specified resource is edited (checked
* out) by someone else, <code>false</code> otherwise
*/
public boolean isEdited(IResource resource) {
return StateCacheFactory.getInstance().get(resource).isEdited();
}
/**
* Indicates if the specified resource is a view root directory containing
* vobs.
*
* @param resource
* @return <code>true</code> if the specified resource is a view root
* directory
*/
public boolean isViewRoot(IResource resource) {
/*
* todo: we need a better check for the view root; this only supports
* structures where a project is the view directory containing the vobs
*/
return null != resource && resource.getType() == IResource.PROJECT
&& !isClearCaseElement(resource);
}
/**
* Indicates if the specified resource is a vob root directory.
*
* @param resource
* @return <code>true</code> if the specified resource is a vob root
* directory
*/
public boolean isVobRoot(IResource resource) {
/*
* todo: we need a better check for the vob root; this only supports
* structures where a project is the view directory containing the vobs
*/
// return resource.getType() == IResource.FOLDER && !resource.isLinked()
// && isViewRoot(resource.getParent());
return false;
}
/**
* Indicates if the specified resource is inside a view directory.
*
* @param resource
* @return <code>true</code> if the specified resource is a view directory
*/
public boolean isInsideView(IResource resource) {
return StateCacheFactory.getInstance().get(resource).isInsideView();
}
/**
* Get the StateCache for an element
*
* @param resource
* @return the corresponding StateCache
*/
public StateCache getCache(IResource resource) {
return StateCacheFactory.getInstance().get(resource);
}
/**
* Ensures the specified resource is initialized.
*
* @param resource
*/
public void ensureInitialized(IResource resource) {
StateCacheFactory.getInstance().ensureInitialized(resource);
}
/**
*
* Helper method that retrieves the branch name. Handles both win and unix
* versions.
*
* @param version
* @return
*/
private String getBranchName(String version) {
int firstBackSlash = 0;
int lastBackSlash = 0;
if (version.startsWith("\\")) {
// Win32
firstBackSlash = version.indexOf("\\");
lastBackSlash = version.lastIndexOf("\\");
} else {
// Unix
firstBackSlash = version.indexOf("/");
lastBackSlash = version.lastIndexOf("/");
}
return version.substring(firstBackSlash, lastBackSlash + 1);
}
private int getCheckoutType() {
if (ClearCasePreferences.isReservedCheckoutsAlways())
return ClearCase.RESERVED;
else if (ClearCasePreferences.isReservedCheckoutsIfPossible())
return ClearCase.RESERVED_IF_POSSIBLE;
else
return ClearCase.UNRESERVED;
}
public void setOperationListener(OperationListener opListener) {
this.opListener = opListener;
}
/**
* For a given element, calculates the final CC element that a checkout/in
* operation can act on. If the given cache points to a regular file or
* directory element, it is returned verbatim. If it is a symlink, we try to
* resolve the symlink to the final element and return a StateCache for
* that.
*
* @param cache
* a valid StateCache which maybe points to a symlink
* @return the final CC element, no symlink. If the symlink can't be
* resolved in CC null is returned
*/
@SuppressWarnings("deprecation")
public StateCache getFinalTargetElement(StateCache cache) {
if (!cache.isSymbolicLink() || null == cache.getSymbolicLinkTarget())
return cache;
File target = new File(cache.getSymbolicLinkTarget());
if (!target.isAbsolute()) {
target = null != cache.getPath() ? new File(cache.getPath())
.getParentFile() : null;
if (null != target) {
target = new File(target, cache.getSymbolicLinkTarget());
}
}
if (null != target && target.exists()) {
IPath targetLocation = new Path(target.getAbsolutePath());
IResource[] resources = null;
if (target.isDirectory()) {
resources = ResourcesPlugin.getWorkspace().getRoot()
.findContainersForLocation(targetLocation);
} else {
resources = ResourcesPlugin.getWorkspace().getRoot()
.findFilesForLocation(targetLocation);
}
if (null != resources) {
for (int i = 0; i < resources.length; i++) {
IResource foundResource = resources[i];
ClearCaseProvider provider = ClearCaseProvider
.getClearCaseProvider(foundResource);
if (null != provider)
return StateCacheFactory.getInstance().get(
foundResource);
}
}
}
return null;
}
// FIXME: eraonel 20100503 move this to other file.
public static boolean moveDirRec(File fromDir, File toDir) {
if (!toDir.exists()) {
return fromDir.renameTo(toDir);
}
File[] files = fromDir.listFiles();
if (files == null) {
return false;
}
boolean success = true;
for (int i = 0; i < files.length; i++) {
File fromFile = files[i];
File toFile = new File(toDir, fromFile.getName());
success = success && fromFile.renameTo(toFile);
}
fromDir.delete();
return success;
}
/**
* Shows a message dialog where user can select: Yes=0 No=1 Cancel=2
*
* @param operationType
* @param msg
* @return result
*/
private int showMessageDialog(String operationType, String msg) {
DialogMessageRunnable dm = new DialogMessageRunnable(operationType, msg);
PlatformUI.getWorkbench().getDisplay().syncExec(dm);
return dm.getResult();
}
/**
* Request mastership and then checkout sequence.
*
* @param returnCode
* @param targetElement
* @param opListener
*/
private void changeMastershipSequence(int returnCode,
StateCache targetElement, OperationListener opListener) {
if (returnCode == 0) {
// Request mastership
ClearCaseElementState[] cces = ClearCasePlugin
.getEngine()
.requestMastership(targetElement.getPath(), getComment(), 0);
if (cces[0].state == ClearCase.MASTERSHIP_CHANGED) {
// Now possible to checkout.
ClearCasePlugin.getEngine().checkout(
new String[] { targetElement.getPath() },
getComment(),
getCheckoutType() | ClearCase.PTIME
| ClearCase.UNRESERVED | ClearCase.NMASTER,
opListener);
}
}
}
public void copyVersionIntoSnapShot(String destinationPath,
String versionToCopy) {
HashMap<Integer, String> args = new HashMap<Integer, String>();
args.put(Integer.valueOf(ClearCase.TO), destinationPath);
ClearCasePlugin.getEngine().get(ClearCase.TO, args, versionToCopy);
}
/**
* Method is used for a rename refactoring when the file to be renamed have been checkedout.
* When the file is checked out in another view and the user don't want to proceed we cancel checkout
* and return fail status. This is due to undo operation is not working.
* @param resource
* @param monitor
* @param opListener
* @return
*/
private IStatus cancelCheckout(IResource resource,IProgressMonitor monitor,OperationListener opListener){
//uncheckout since we do not want to checkout.
ClearCasePlugin.getEngine().uncheckout(new String[] { resource.getLocation().toOSString() }, ClearCase.NONE, opListener);
updateState(resource, IResource.DEPTH_ZERO,
new SubProgressMonitor(monitor, 10));
return new Status(
IStatus.ERROR,
ID,
TeamException.CONFLICT,
MessageFormat
.format(
"Cancelled move operation for \"{0}\"!",
new Object[] { resource.getFullPath()
.toString() }), null);
}
}
| true | true | public IStatus visit(IResource resource, IProgressMonitor monitor) {
try {
int returnCode = 1;// Used in messge dialog.
monitor.beginTask("Checkin in " + resource.getFullPath(), 100);
StateCache cache = getCache(resource);
final StateCache targetElement = getFinalTargetElement(cache);
IStatus result = OK_STATUS;
// Sanity check - can't check in something that is not part of
// clearcase
if (targetElement == null
|| !targetElement.isClearCaseElement())
return new Status(
IStatus.WARNING,
ID,
TeamException.NO_REMOTE_RESOURCE,
MessageFormat
.format(
"Resource \"{0}\" is not a ClearCase element!",
new Object[] { resource
.getFullPath().toString() }),
null);
// Sanity check - can't checkin something that is not checked
// out
if (!targetElement.isCheckedOut())
// return status with severity OK
return new Status(IStatus.OK, ID,
TeamException.NOT_CHECKED_OUT,
MessageFormat.format(
"Resource \"{0}\" is not checked out!",
new Object[] { targetElement.getPath() }),
null);
if (ClearCasePreferences.isCheckinIdenticalAllowed()) {
ClearCasePlugin.getEngine().checkin(
new String[] { targetElement.getPath() },
getComment(),
ClearCase.PTIME | ClearCase.IDENTICAL, opListener);
} else {
try {
ClearCasePlugin.getEngine().checkin(
new String[] { targetElement.getPath() },
getComment(), ClearCase.PTIME, opListener);
} catch (ClearCaseException cce) {
// check error
switch (cce.getErrorCode()) {
case ClearCase.ERROR_PREDECESSOR_IS_IDENTICAL:
result = new Status(
IStatus.ERROR,
ID,
TeamException.NOT_CHECKED_IN,
MessageFormat
.format(
Messages
.getString("ClearCasePlugin.error.checkin.identicalPredecessor"),
new Object[] { cce
.getElements() }),
null);
break;
case ClearCase.ERROR_ELEMENT_HAS_CHECKOUTS:
result = new Status(
IStatus.ERROR,
ID,
TeamException.NOT_CHECKED_IN,
MessageFormat
.format(
Messages
.getString("ClearCasePlugin.error.checkin.elementHasCheckouts"),
new Object[] { cce
.getElements() }),
null);
break;
case ClearCase.ERROR_MOST_RECENT_NOT_PREDECESSOR_OF_THIS_VERSION:
// Only support for: To merge the latest version
// with your checkout
// getVersion --> \branch\CHECKEDOUT.
String branchName = getBranchName(getVersion(resource));
String latestVersion = resource.getLocation()
.toOSString()
+ "@@" + branchName + "LATEST";
ClearCaseElementState myState = ClearCasePlugin
.getEngine().merge(targetElement.getPath(),
new String[] { latestVersion },
ClearCase.GRAPHICAL);
if (myState.isMerged()) {
returnCode = showMessageDialog("Checkin",
"Do you want to checkin the merged result?");
if (returnCode == 0) {
// Yes continue checkin
ClearCasePlugin.getEngine().checkin(
new String[] { targetElement
.getPath() }, getComment(),
ClearCase.PTIME, opListener);
}
} else {
result = new Status(
IStatus.ERROR,
ID,
TeamException.CONFLICT,
MessageFormat
.format(
Messages
.getString("ClearCasePlugin.error.checkin.mergeLatestProblem"),
new Object[] { cce
.getElements() }),
null);
}
break;
default:
result = new Status(
IStatus.ERROR,
ID,
TeamException.NOT_CHECKED_IN,
MessageFormat
.format(
Messages
.getString("ClearCasePlugin.error.checkin.unknown"),
new Object[] { cce
.getElements() }),
null);
break;
}
}
}
monitor.worked(40);
updateState(resource, IResource.DEPTH_ZERO,
new SubProgressMonitor(monitor, 10));
return result;
} finally {
monitor.done();
}
}
| public IStatus visit(IResource resource, IProgressMonitor monitor) {
try {
int returnCode = 1;// Used in messge dialog.
monitor.beginTask("Checkin in " + resource.getFullPath(), 100);
StateCache cache = getCache(resource);
final StateCache targetElement = getFinalTargetElement(cache);
IStatus result = OK_STATUS;
// Sanity check - can't check in something that is not part of
// clearcase
if (targetElement == null
|| !targetElement.isClearCaseElement())
return new Status(
IStatus.WARNING,
ID,
TeamException.NO_REMOTE_RESOURCE,
MessageFormat
.format(
"Resource \"{0}\" is not a ClearCase element!",
new Object[] { resource
.getFullPath().toString() }),
null);
// Sanity check - can't checkin something that is not checked
// out
if (!targetElement.isCheckedOut())
// return status with severity OK
return new Status(IStatus.OK, ID,
TeamException.NOT_CHECKED_OUT,
MessageFormat.format(
"Resource \"{0}\" is not checked out!",
new Object[] { targetElement.getPath() }),
null);
if (ClearCasePreferences.isCheckinIdenticalAllowed()) {
ClearCasePlugin.getEngine().checkin(
new String[] { targetElement.getPath() },
getComment(),
ClearCase.PTIME | ClearCase.IDENTICAL, opListener);
} else {
try {
ClearCasePlugin.getEngine().checkin(
new String[] { targetElement.getPath() },
getComment(), ClearCase.PTIME, opListener);
} catch (ClearCaseException cce) {
// check error
switch (cce.getErrorCode()) {
case ClearCase.ERROR_PREDECESSOR_IS_IDENTICAL:
result = new Status(
IStatus.ERROR,
ID,
TeamException.NOT_CHECKED_IN,
MessageFormat
.format(
Messages
.getString("ClearCasePlugin.error.checkin.identicalPredecessor"),
new Object[] { cce
.getElements() }),
null);
break;
case ClearCase.ERROR_ELEMENT_HAS_CHECKOUTS:
result = new Status(
IStatus.ERROR,
ID,
TeamException.NOT_CHECKED_IN,
MessageFormat
.format(
Messages
.getString("ClearCasePlugin.error.checkin.elementHasCheckouts"),
new Object[] { cce
.getElements() }),
null);
break;
case ClearCase.ERROR_MOST_RECENT_NOT_PREDECESSOR_OF_THIS_VERSION:
// Only support for: To merge the latest version
// with your checkout
// getVersion --> \branch\CHECKEDOUT.
String branchName = getBranchName(getVersion(resource));
String latestVersion = resource.getLocation()
.toOSString()
+ "@@" + branchName + "LATEST";
ClearCaseElementState myState = ClearCasePlugin
.getEngine().merge(targetElement.getPath(),
new String[] { latestVersion },null,
ClearCase.GRAPHICAL);
if (myState.isMerged()) {
returnCode = showMessageDialog("Checkin",
"Do you want to checkin the merged result?");
if (returnCode == 0) {
// Yes continue checkin
ClearCasePlugin.getEngine().checkin(
new String[] { targetElement
.getPath() }, getComment(),
ClearCase.PTIME, opListener);
}
} else {
result = new Status(
IStatus.ERROR,
ID,
TeamException.CONFLICT,
MessageFormat
.format(
Messages
.getString("ClearCasePlugin.error.checkin.mergeLatestProblem"),
new Object[] { cce
.getElements() }),
null);
}
break;
default:
result = new Status(
IStatus.ERROR,
ID,
TeamException.NOT_CHECKED_IN,
MessageFormat
.format(
Messages
.getString("ClearCasePlugin.error.checkin.unknown"),
new Object[] { cce
.getElements() }),
null);
break;
}
}
}
monitor.worked(40);
updateState(resource, IResource.DEPTH_ZERO,
new SubProgressMonitor(monitor, 10));
return result;
} finally {
monitor.done();
}
}
|
diff --git a/src/test/java/com/huskycode/jpaquery/DependenciesDefinitionTest.java b/src/test/java/com/huskycode/jpaquery/DependenciesDefinitionTest.java
index db5e930..ece0a53 100644
--- a/src/test/java/com/huskycode/jpaquery/DependenciesDefinitionTest.java
+++ b/src/test/java/com/huskycode/jpaquery/DependenciesDefinitionTest.java
@@ -1,29 +1,29 @@
package com.huskycode.jpaquery;
import com.huskycode.jpaquery.DependenciesDefinition;
import com.huskycode.jpaquery.link.Link;
import org.hamcrest.CoreMatchers;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
import javax.persistence.metamodel.SingularAttribute;
/**
* @author Varokas Panusuwan
*/
public class DependenciesDefinitionTest {
@Test
public void shouldBeAbleToDefineDependenciesByLinks() {
SingularAttribute pointA = Mockito.mock(SingularAttribute.class);
SingularAttribute pointB = Mockito.mock(SingularAttribute.class);
- Link anyLink = Link.from(pointA).to(pointB);
+ Link anyLink = Link.from(Object.class, pointA).to(Object.class, pointB);
DependenciesDefinition deps =
DependenciesDefinition.fromLinks(new Link[] { anyLink });
Assert.assertThat(deps.getLinks().length, CoreMatchers.is(1));
Assert.assertThat(deps.getLinks()[0],
CoreMatchers.is(CoreMatchers.sameInstance(anyLink)));
}
}
| true | true | public void shouldBeAbleToDefineDependenciesByLinks() {
SingularAttribute pointA = Mockito.mock(SingularAttribute.class);
SingularAttribute pointB = Mockito.mock(SingularAttribute.class);
Link anyLink = Link.from(pointA).to(pointB);
DependenciesDefinition deps =
DependenciesDefinition.fromLinks(new Link[] { anyLink });
Assert.assertThat(deps.getLinks().length, CoreMatchers.is(1));
Assert.assertThat(deps.getLinks()[0],
CoreMatchers.is(CoreMatchers.sameInstance(anyLink)));
}
| public void shouldBeAbleToDefineDependenciesByLinks() {
SingularAttribute pointA = Mockito.mock(SingularAttribute.class);
SingularAttribute pointB = Mockito.mock(SingularAttribute.class);
Link anyLink = Link.from(Object.class, pointA).to(Object.class, pointB);
DependenciesDefinition deps =
DependenciesDefinition.fromLinks(new Link[] { anyLink });
Assert.assertThat(deps.getLinks().length, CoreMatchers.is(1));
Assert.assertThat(deps.getLinks()[0],
CoreMatchers.is(CoreMatchers.sameInstance(anyLink)));
}
|
diff --git a/core/src/main/java/org/infinispan/marshall/jboss/ConstantObjectTable.java b/core/src/main/java/org/infinispan/marshall/jboss/ConstantObjectTable.java
index 5d8a3682cc..aebf651fc2 100644
--- a/core/src/main/java/org/infinispan/marshall/jboss/ConstantObjectTable.java
+++ b/core/src/main/java/org/infinispan/marshall/jboss/ConstantObjectTable.java
@@ -1,263 +1,269 @@
/*
* JBoss, Home of Professional Open Source.
* Copyright 2009, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.infinispan.marshall.jboss;
import org.infinispan.CacheException;
import org.infinispan.atomic.AtomicHashMap;
import org.infinispan.atomic.AtomicHashMapDelta;
import org.infinispan.atomic.ClearOperation;
import org.infinispan.atomic.PutOperation;
import org.infinispan.atomic.RemoveOperation;
import org.infinispan.commands.RemoteCommandFactory;
import org.infinispan.commands.control.LockControlCommand;
import org.infinispan.commands.control.RehashControlCommand;
import org.infinispan.commands.control.StateTransferControlCommand;
import org.infinispan.commands.read.GetKeyValueCommand;
import org.infinispan.commands.remote.ClusteredGetCommand;
import org.infinispan.commands.remote.MultipleRpcCommand;
import org.infinispan.commands.remote.SingleRpcCommand;
import org.infinispan.commands.tx.CommitCommand;
import org.infinispan.commands.tx.PrepareCommand;
import org.infinispan.commands.tx.RollbackCommand;
import org.infinispan.commands.write.ClearCommand;
import org.infinispan.commands.write.InvalidateCommand;
import org.infinispan.commands.write.InvalidateL1Command;
import org.infinispan.commands.write.PutKeyValueCommand;
import org.infinispan.commands.write.PutMapCommand;
import org.infinispan.commands.write.RemoveCommand;
import org.infinispan.commands.write.ReplaceCommand;
import org.infinispan.container.entries.ImmortalCacheEntry;
import org.infinispan.container.entries.ImmortalCacheValue;
import org.infinispan.container.entries.MortalCacheEntry;
import org.infinispan.container.entries.MortalCacheValue;
import org.infinispan.container.entries.TransientCacheEntry;
import org.infinispan.container.entries.TransientCacheValue;
import org.infinispan.container.entries.TransientMortalCacheEntry;
import org.infinispan.container.entries.TransientMortalCacheValue;
import org.infinispan.distribution.DefaultConsistentHash;
import org.infinispan.distribution.UnionConsistentHash;
import org.infinispan.loaders.bucket.Bucket;
import org.infinispan.marshall.Externalizer;
import org.infinispan.marshall.Marshallable;
import org.infinispan.marshall.MarshalledValue;
import org.infinispan.marshall.exts.ArrayListExternalizer;
import org.infinispan.marshall.exts.LinkedListExternalizer;
import org.infinispan.marshall.exts.MapExternalizer;
import org.infinispan.marshall.exts.ReplicableCommandExternalizer;
import org.infinispan.marshall.exts.SetExternalizer;
import org.infinispan.marshall.exts.SingletonListExternalizer;
import org.infinispan.remoting.responses.ExceptionResponse;
import org.infinispan.remoting.responses.ExtendedResponse;
import org.infinispan.remoting.responses.RequestIgnoredResponse;
import org.infinispan.remoting.responses.SuccessfulResponse;
import org.infinispan.remoting.responses.UnsuccessfulResponse;
import org.infinispan.remoting.transport.jgroups.JGroupsAddress;
import org.infinispan.transaction.xa.DeadlockDetectingGlobalTransaction;
import org.infinispan.transaction.xa.GlobalTransaction;
import org.infinispan.util.FastCopyHashMap;
import org.infinispan.util.ReflectionUtil;
import org.infinispan.util.Util;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import org.jboss.marshalling.Marshaller;
import org.jboss.marshalling.ObjectTable;
import org.jboss.marshalling.Unmarshaller;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
/**
* Constant ObjectTable that marshalls constant instances regardless of whether these are generic objects such as
* UnsuccessfulResponse.INSTANCE, or home grown Externalizer implementations. In both cases, this is a hugely efficient
* way of sending around constant singleton objects.
*
* @author Galder Zamarreño
* @since 4.0
*/
public class ConstantObjectTable implements ObjectTable {
private static final Log log = LogFactory.getLog(ConstantObjectTable.class);
private static final Map<String, String> JDK_EXTERNALIZERS = new HashMap<String, String>();
static final Set<String> MARSHALLABLES = new HashSet<String>();
static {
JDK_EXTERNALIZERS.put(ArrayList.class.getName(), ArrayListExternalizer.class.getName());
JDK_EXTERNALIZERS.put(LinkedList.class.getName(), LinkedListExternalizer.class.getName());
JDK_EXTERNALIZERS.put(HashMap.class.getName(), MapExternalizer.class.getName());
JDK_EXTERNALIZERS.put(TreeMap.class.getName(), MapExternalizer.class.getName());
JDK_EXTERNALIZERS.put(HashSet.class.getName(), SetExternalizer.class.getName());
JDK_EXTERNALIZERS.put(TreeSet.class.getName(), SetExternalizer.class.getName());
JDK_EXTERNALIZERS.put("java.util.Collections$SingletonList", SingletonListExternalizer.class.getName());
MARSHALLABLES.add(GlobalTransaction.class.getName());
MARSHALLABLES.add(DeadlockDetectingGlobalTransaction.class.getName());
MARSHALLABLES.add(JGroupsAddress.class.getName());
MARSHALLABLES.add("org.infinispan.util.Immutables$ImmutableMapWrapper");
MARSHALLABLES.add(MarshalledValue.class.getName());
MARSHALLABLES.add(FastCopyHashMap.class.getName());
MARSHALLABLES.add("org.infinispan.transaction.TransactionLog$LogEntry");
MARSHALLABLES.add(ExtendedResponse.class.getName());
MARSHALLABLES.add(SuccessfulResponse.class.getName());
MARSHALLABLES.add(ExceptionResponse.class.getName());
MARSHALLABLES.add(RequestIgnoredResponse.class.getName());
MARSHALLABLES.add(UnsuccessfulResponse.class.getName());
MARSHALLABLES.add(StateTransferControlCommand.class.getName());
MARSHALLABLES.add(ClusteredGetCommand.class.getName());
MARSHALLABLES.add(MultipleRpcCommand.class.getName());
MARSHALLABLES.add(SingleRpcCommand.class.getName());
MARSHALLABLES.add(GetKeyValueCommand.class.getName());
MARSHALLABLES.add(PutKeyValueCommand.class.getName());
MARSHALLABLES.add(RemoveCommand.class.getName());
MARSHALLABLES.add(InvalidateCommand.class.getName());
MARSHALLABLES.add(ReplaceCommand.class.getName());
MARSHALLABLES.add(ClearCommand.class.getName());
MARSHALLABLES.add(PutMapCommand.class.getName());
MARSHALLABLES.add(PrepareCommand.class.getName());
MARSHALLABLES.add(CommitCommand.class.getName());
MARSHALLABLES.add(RollbackCommand.class.getName());
MARSHALLABLES.add(InvalidateL1Command.class.getName());
MARSHALLABLES.add(LockControlCommand.class.getName());
MARSHALLABLES.add(RehashControlCommand.class.getName());
MARSHALLABLES.add(ImmortalCacheEntry.class.getName());
MARSHALLABLES.add(MortalCacheEntry.class.getName());
MARSHALLABLES.add(TransientCacheEntry.class.getName());
MARSHALLABLES.add(TransientMortalCacheEntry.class.getName());
MARSHALLABLES.add(ImmortalCacheValue.class.getName());
MARSHALLABLES.add(MortalCacheValue.class.getName());
MARSHALLABLES.add(TransientCacheValue.class.getName());
MARSHALLABLES.add(TransientMortalCacheValue.class.getName());
MARSHALLABLES.add(AtomicHashMap.class.getName());
MARSHALLABLES.add(Bucket.class.getName());
MARSHALLABLES.add("org.infinispan.tree.NodeKey");
MARSHALLABLES.add("org.infinispan.tree.Fqn");
MARSHALLABLES.add(AtomicHashMapDelta.class.getName());
MARSHALLABLES.add(PutOperation.class.getName());
MARSHALLABLES.add(RemoveOperation.class.getName());
MARSHALLABLES.add(ClearOperation.class.getName());
MARSHALLABLES.add(DefaultConsistentHash.class.getName());
MARSHALLABLES.add(UnionConsistentHash.class.getName());
}
/**
* Contains mapping of classes to their corresponding Externalizer classes via ExternalizerAdapter instances.
*/
private final Map<Class<?>, ExternalizerAdapter> writers = new IdentityHashMap<Class<?>, ExternalizerAdapter>();
/**
* Contains mapping of ids to their corresponding Externalizer classes via ExternalizerAdapter instances.
*/
private final Map<Integer, ExternalizerAdapter> readers = new HashMap<Integer, ExternalizerAdapter>();
public void start(RemoteCommandFactory cmdFactory, org.infinispan.marshall.Marshaller ispnMarshaller) {
HashSet<Integer> ids = new HashSet<Integer>();
- try {
for (Map.Entry<String, String> entry : JDK_EXTERNALIZERS.entrySet()) {
try {
Class clazz = Util.loadClass(entry.getKey());
- Externalizer ext = (Externalizer) Util.getInstance(entry.getValue());
+ Externalizer ext = null;
+ try {
+ ext = (Externalizer) Util.getInstance(entry.getValue());
+ } catch (Exception e) {
+ throw new CacheException("Could not instantiate entry: " + entry,e);
+ }
Marshallable marshallable = ReflectionUtil.getAnnotation(ext.getClass(), Marshallable.class);
int id = marshallable.id();
ids.add(id);
ExternalizerAdapter adapter = new ExternalizerAdapter(id, ext);
writers.put(clazz, adapter);
readers.put(id, adapter);
} catch (ClassNotFoundException e) {
if (log.isDebugEnabled())
log.debug("Unable to load class (ignore if class belonging to a module not in use): {0}", e.getMessage());
}
}
for (String marshallableClass : MARSHALLABLES) {
try {
Class clazz = Util.loadClass(marshallableClass);
Marshallable marshallable = ReflectionUtil.getAnnotation(clazz, Marshallable.class);
if (marshallable != null && !marshallable.externalizer().equals(Externalizer.class)) {
int id = marshallable.id();
- Externalizer ext = Util.getInstance(marshallable.externalizer());
+ Externalizer ext = null;
+ try {
+ ext = Util.getInstance(marshallable.externalizer());
+ } catch (Exception e) {
+ throw new CacheException("Could not instantiate the externalizer: " + marshallable.externalizer(), e);
+ }
if (!ids.add(id))
throw new CacheException("Duplicate id found! id=" + id + " in " + ext.getClass().getName() + " is shared by another marshallable class.");
if (ext instanceof ReplicableCommandExternalizer) {
((ReplicableCommandExternalizer) ext).inject(cmdFactory);
}
if (ext instanceof MarshalledValue.Externalizer) {
((MarshalledValue.Externalizer) ext).inject(ispnMarshaller);
}
ExternalizerAdapter adapter = new ExternalizerAdapter(id, ext);
writers.put(clazz, adapter);
readers.put(id, adapter);
}
} catch (ClassNotFoundException e) {
if (log.isDebugEnabled())
log.debug("Unable to load class (ignore if class belonging to a module not in use): {0}", e.getMessage());
}
}
- } catch (Exception e) {
- throw new CacheException("Unable to instantiate Externalizer class", e);
- }
}
public void stop() {
writers.clear();
readers.clear();
}
public Writer getObjectWriter(Object o) throws IOException {
return writers.get(o.getClass());
}
public Object readObject(Unmarshaller input) throws IOException, ClassNotFoundException {
ExternalizerAdapter adapter = (ExternalizerAdapter) readers.get(input.readUnsignedByte());
return adapter.readObject(input);
}
static class ExternalizerAdapter implements Writer {
final int id;
final Externalizer externalizer;
ExternalizerAdapter(int id, Externalizer externalizer) {
this.id = id;
this.externalizer = externalizer;
}
public Object readObject(Unmarshaller input) throws IOException, ClassNotFoundException {
return externalizer.readObject(input);
}
public void writeObject(Marshaller output, Object object) throws IOException {
output.write(id);
externalizer.writeObject(output, object);
}
}
}
| false | true | public void start(RemoteCommandFactory cmdFactory, org.infinispan.marshall.Marshaller ispnMarshaller) {
HashSet<Integer> ids = new HashSet<Integer>();
try {
for (Map.Entry<String, String> entry : JDK_EXTERNALIZERS.entrySet()) {
try {
Class clazz = Util.loadClass(entry.getKey());
Externalizer ext = (Externalizer) Util.getInstance(entry.getValue());
Marshallable marshallable = ReflectionUtil.getAnnotation(ext.getClass(), Marshallable.class);
int id = marshallable.id();
ids.add(id);
ExternalizerAdapter adapter = new ExternalizerAdapter(id, ext);
writers.put(clazz, adapter);
readers.put(id, adapter);
} catch (ClassNotFoundException e) {
if (log.isDebugEnabled())
log.debug("Unable to load class (ignore if class belonging to a module not in use): {0}", e.getMessage());
}
}
for (String marshallableClass : MARSHALLABLES) {
try {
Class clazz = Util.loadClass(marshallableClass);
Marshallable marshallable = ReflectionUtil.getAnnotation(clazz, Marshallable.class);
if (marshallable != null && !marshallable.externalizer().equals(Externalizer.class)) {
int id = marshallable.id();
Externalizer ext = Util.getInstance(marshallable.externalizer());
if (!ids.add(id))
throw new CacheException("Duplicate id found! id=" + id + " in " + ext.getClass().getName() + " is shared by another marshallable class.");
if (ext instanceof ReplicableCommandExternalizer) {
((ReplicableCommandExternalizer) ext).inject(cmdFactory);
}
if (ext instanceof MarshalledValue.Externalizer) {
((MarshalledValue.Externalizer) ext).inject(ispnMarshaller);
}
ExternalizerAdapter adapter = new ExternalizerAdapter(id, ext);
writers.put(clazz, adapter);
readers.put(id, adapter);
}
} catch (ClassNotFoundException e) {
if (log.isDebugEnabled())
log.debug("Unable to load class (ignore if class belonging to a module not in use): {0}", e.getMessage());
}
}
} catch (Exception e) {
throw new CacheException("Unable to instantiate Externalizer class", e);
}
}
| public void start(RemoteCommandFactory cmdFactory, org.infinispan.marshall.Marshaller ispnMarshaller) {
HashSet<Integer> ids = new HashSet<Integer>();
for (Map.Entry<String, String> entry : JDK_EXTERNALIZERS.entrySet()) {
try {
Class clazz = Util.loadClass(entry.getKey());
Externalizer ext = null;
try {
ext = (Externalizer) Util.getInstance(entry.getValue());
} catch (Exception e) {
throw new CacheException("Could not instantiate entry: " + entry,e);
}
Marshallable marshallable = ReflectionUtil.getAnnotation(ext.getClass(), Marshallable.class);
int id = marshallable.id();
ids.add(id);
ExternalizerAdapter adapter = new ExternalizerAdapter(id, ext);
writers.put(clazz, adapter);
readers.put(id, adapter);
} catch (ClassNotFoundException e) {
if (log.isDebugEnabled())
log.debug("Unable to load class (ignore if class belonging to a module not in use): {0}", e.getMessage());
}
}
for (String marshallableClass : MARSHALLABLES) {
try {
Class clazz = Util.loadClass(marshallableClass);
Marshallable marshallable = ReflectionUtil.getAnnotation(clazz, Marshallable.class);
if (marshallable != null && !marshallable.externalizer().equals(Externalizer.class)) {
int id = marshallable.id();
Externalizer ext = null;
try {
ext = Util.getInstance(marshallable.externalizer());
} catch (Exception e) {
throw new CacheException("Could not instantiate the externalizer: " + marshallable.externalizer(), e);
}
if (!ids.add(id))
throw new CacheException("Duplicate id found! id=" + id + " in " + ext.getClass().getName() + " is shared by another marshallable class.");
if (ext instanceof ReplicableCommandExternalizer) {
((ReplicableCommandExternalizer) ext).inject(cmdFactory);
}
if (ext instanceof MarshalledValue.Externalizer) {
((MarshalledValue.Externalizer) ext).inject(ispnMarshaller);
}
ExternalizerAdapter adapter = new ExternalizerAdapter(id, ext);
writers.put(clazz, adapter);
readers.put(id, adapter);
}
} catch (ClassNotFoundException e) {
if (log.isDebugEnabled())
log.debug("Unable to load class (ignore if class belonging to a module not in use): {0}", e.getMessage());
}
}
}
|
diff --git a/baixing_quanleimu/src/com/baixing/activity/CameraActivity.java b/baixing_quanleimu/src/com/baixing/activity/CameraActivity.java
index 1e1dd638..f1a68dc4 100644
--- a/baixing_quanleimu/src/com/baixing/activity/CameraActivity.java
+++ b/baixing_quanleimu/src/com/baixing/activity/CameraActivity.java
@@ -1,830 +1,830 @@
package com.baixing.activity;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.CameraInfo;
import android.hardware.Camera.PictureCallback;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build.VERSION;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.util.Pair;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.baixing.broadcast.CommonIntentAction;
import com.baixing.data.GlobalDataManager;
import com.baixing.entity.BXLocation;
import com.baixing.entity.BXThumbnail;
import com.baixing.tracking.TrackConfig;
import com.baixing.tracking.Tracker;
import com.baixing.util.BitmapUtils;
import com.baixing.util.Util;
import com.baixing.util.post.ImageUploader;
import com.baixing.util.post.ImageUploader.Callback;
import com.baixing.view.CameraPreview;
import com.quanleimu.activity.R;
/**
*
* @author liuchong
*
*/
public class CameraActivity extends Activity implements OnClickListener, SensorEventListener {
public static final String TAG = "CAMPREV";
private static final int REQ_PICK_GALLERY = 1;
private static final int MAX_IMG_COUNT = 6;
private SensorManager sensorMgr;
private Sensor sensor;
private CameraPreview mPreview;
Camera mCamera;
private boolean isInitialized = false;
boolean isFrontCam; //If current camera is facing or front camera.
boolean isLandscapeMode;
// int cameraCurrentlyLocked;
Orien currentOrien = Orien.DEFAULT;
SensorEvent lastSensorEvent;
private ArrayList<BXThumbnail> originalList = new ArrayList<BXThumbnail>();
private ArrayList<BXThumbnail> deleteList = new ArrayList<BXThumbnail>();
private ArrayList<BXThumbnail> imageList = new ArrayList<BXThumbnail>();
private List<UploadingCallback> callbacks = new ArrayList<UploadingCallback>();
// private ArrayList<String> imagePaths = new ArrayList<String>();
private OnDeleteListener deleteListener;
/*
* Internal message.
*/
private static final int MSG_PIC_TAKEN = 0;
private static final int MSG_SAVE_DONE = 1;
private static final int MSG_ORIENTATION_CHANGE = 2;
private static final int MSG_UPDATE_THUMBNAILS = 3;
private static final int MSG_UPLOADING_STATUS_UPDATE = 4;
// private static final int MSG_FINISH_ME = 5;
private static final int MSG_PAUSE_ME = 6;
private static final int MSG_INIT_CAME = 7;
private static final int MSG_CANCEL_STORE_PIC = 8;
private static final int MSG_RESUME_ME = 9;
private static final int MSG_TAKEPIC_DELAY = 10;
/*
* Internal message parameters: image uploading status.
*/
private static final int STATE_UPLOADING = 1;
private static final int STATE_FAIL = 2;
private static final int STATE_DONE = 3;
private Handler handler;
public static enum Orien {
DEFAULT("DEFAULT",0),
TOP_UP("TOP_UP", 90),
RIGHT_UP("RIGHT_UP", 0),
BOTTOM_UP("BOTTOM_UP", 270),
LEFT_UP("LEFT_UP", 180);
String des = "";
int orientationDegree;
private Orien(String des, int degree) {
this.des = des;
this.orientationDegree = degree;
}
}
private void updateCapState() {
boolean enable = imageList.size() < MAX_IMG_COUNT;
findViewById(R.id.cap).setEnabled(enable);
findViewById(R.id.pick_gallery).setEnabled(enable);
}
class InternalHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch(msg.what) {
case MSG_TAKEPIC_DELAY:
{
BooleanWrapper bW = (BooleanWrapper) msg.obj;
- if (!bW.isTrue) {
+ if (!bW.isTrue && mCamera != null) {
mCamera.takePicture(null, null, mPicture);
}
break;
}
case MSG_PAUSE_ME:
{
isInitialized = false;
sensorMgr.unregisterListener(CameraActivity.this);
ViewGroup cameraP = (ViewGroup) findViewById(R.id.camera_parent);
if (mPreview != null) {
cameraP.removeView(mPreview);
}
if (mCamera != null) {
mPreview.setCamera(null);
mCamera.release();
mCamera = null;
}
break;
}
case MSG_CANCEL_STORE_PIC: {
updateCapState();
if (isInitialized) {
mCamera.startPreview();
}
break;
}
case MSG_INIT_CAME : {
ViewGroup cameraP = (ViewGroup) findViewById(R.id.camera_parent);
if (mPreview != null) {
cameraP.removeView(mPreview);
}
initializeCamera();
TextView txt = (TextView) findViewById(R.id.cam_not_available_tip);
txt.setVisibility(mCamera == null ? View.VISIBLE : View.GONE);
if (mCamera != null) {
mPreview = new CameraPreview(CameraActivity.this);
cameraP.addView(mPreview, LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
mPreview.setCamera(mCamera);
}
isInitialized = true;
updateCapState();
break;
}
case MSG_RESUME_ME:{
// Profiler.markStart("sensorRegister");
if (sensor != null) {
sensorMgr.registerListener(CameraActivity.this, sensor, SensorManager.SENSOR_DELAY_NORMAL);
}
// Profiler.markEnd("sensorRegister");
break;
}
case MSG_PIC_TAKEN:
if (isInitialized) {
mCamera.startPreview();
}
break;
case MSG_SAVE_DONE:
BXThumbnail newPicPair = (BXThumbnail) msg.obj;
if (newPicPair != null) {
ImageUploader.getInstance().startUpload(newPicPair.getLocalPath(), newPicPair.getThumbnail(), null);
boolean succed = appendResultImage(newPicPair);
if (succed) {
addImageUri(newPicPair);
}
} else {
Toast.makeText(CameraActivity.this, "获取照片失败", Toast.LENGTH_SHORT).show();
}
findViewById(R.id.cap).setEnabled(true);
break;
case MSG_ORIENTATION_CHANGE:
if (isInitialized) {
autoFocusWhenOrienChange();
}
break;
case MSG_UPDATE_THUMBNAILS:
if (imageList != null && imageList.size() > 0) {
for (BXThumbnail t : imageList) {
appendResultImage(t);
}
}
else {
Toast.makeText(CameraActivity.this, R.string.tip_camera_before_post, Toast.LENGTH_LONG).show();
}
break;
case MSG_UPLOADING_STATUS_UPDATE:
Pair<Bitmap, ImageView> p = (Pair<Bitmap, ImageView>) msg.obj;
if (p.second != null) {
switch (msg.arg1) {
case STATE_UPLOADING:
((View) p.second.getParent()).findViewById(R.id.loading_status).setVisibility(View.VISIBLE);
p.second.setImageBitmap(p.first);
break;
case STATE_FAIL:
((View) p.second.getParent()).findViewById(R.id.loading_status).setVisibility(View.GONE);
p.second.setImageResource(R.drawable.icon_load_fail);
break;
case STATE_DONE:
((View) p.second.getParent()).findViewById(R.id.loading_status).setVisibility(View.GONE);
p.second.setImageBitmap(p.first);
break;
}
}
break;
}
}
}
private ArrayList<String> getLocalUrls() {
ArrayList<String> list = new ArrayList<String>();
for (BXThumbnail t : imageList) {
list.add(t.getLocalPath());
}
return list;
}
private void addImageUri(BXThumbnail p) {
imageList.add(p);
updateCapState();
if (imageList.size() == MAX_IMG_COUNT) {
finishTakenPic();
}
}
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_BACK)
{
cancelTakenPic();
}
else{
return super.onKeyDown(keyCode, event);
}
return true;
}
private void cancelTakenPic() {
onCancelEdit();
int resultCode = getIntent().getExtras().getInt(CommonIntentAction.EXTRA_COMMON_FINISH_CODE, Activity.RESULT_CANCELED);
Intent backIntent = (Intent) getIntent().getExtras().get(CommonIntentAction.EXTRA_COMMON_INTENT);//new Intent(this, QuanleimuMainActivity.class);
Bundle bundle = new Bundle();
bundle.putBoolean(CommonIntentAction.EXTRA_COMMON_IS_THIRD_PARTY, true);
bundle.putInt(CommonIntentAction.EXTRA_COMMON_REQUST_CODE, getIntent().getExtras().getInt(CommonIntentAction.EXTRA_COMMON_REQUST_CODE));
bundle.putInt(CommonIntentAction.EXTRA_COMMON_RESULT_CODE, resultCode);
backIntent.putExtras(bundle);
backIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
this.startActivity(backIntent);
this.finish();
}
private void finishTakenPic() {
//Cancel the delete list.
for (BXThumbnail t : deleteList) {
ImageUploader.getInstance().cancel(t.getLocalPath());
}
Intent backIntent = (Intent) getIntent().getExtras().get(CommonIntentAction.EXTRA_COMMON_INTENT);//new Intent(this, QuanleimuMainActivity.class);
Bundle bundle = new Bundle();
bundle.putBoolean(CommonIntentAction.EXTRA_COMMON_IS_THIRD_PARTY, true);
bundle.putInt(CommonIntentAction.EXTRA_COMMON_REQUST_CODE, getIntent().getExtras().getInt(CommonIntentAction.EXTRA_COMMON_REQUST_CODE));
bundle.putInt(CommonIntentAction.EXTRA_COMMON_RESULT_CODE, RESULT_OK);
Intent data = new Intent();
data.putStringArrayListExtra(CommonIntentAction.EXTRA_IMAGE_LIST, getLocalUrls());
bundle.putParcelable(CommonIntentAction.EXTRA_COMMON_DATA, data);
backIntent.putExtras(bundle);
backIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
this.startActivity(backIntent);
// handler.sendEmptyMessageDelayed(MSG_FINISH_ME, 50);
this.finish();
}
private void deleteImageUri(BXThumbnail t) {
imageList.remove(t);
deleteList.add(t);
updateCapState();
}
private ViewGroup findFirstBlankImage(ViewGroup root) {
final int count = root.getChildCount();
for (int i=0; i<count; i++) {
ViewGroup child = (ViewGroup) root.getChildAt(i);
if (child.getTag() == null) {
return child;
}
}
return null;
}
private boolean appendResultImage(BXThumbnail thumbnail) {
if (thumbnail == null) {
return false;
}
ViewGroup vp = (ViewGroup) this.findViewById(R.id.result_parent);
ViewGroup imageRoot = findFirstBlankImage(vp);
if (imageRoot == null) {
return false; // you should nerver encounter this case.
}
imageRoot.setTag(thumbnail.getLocalPath());
final View deleteCmd = imageRoot.findViewById(R.id.delete_preview);
deleteCmd.setVisibility(View.VISIBLE);
deleteCmd.setOnClickListener(deleteListener);
deleteCmd.setTag(thumbnail);
View deleteBtn = imageRoot.findViewById(R.id.delete_btn);
deleteBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
deleteCmd.performClick();
}
});
try
{
ImageView img = (ImageView) imageRoot.findViewById(R.id.result_image);
if (thumbnail.getThumbnail() != null) {
img.setImageBitmap(thumbnail.getThumbnail());
}
UploadingCallback cbk = new UploadingCallback(img);
callbacks.add(cbk);
ImageUploader.getInstance().registerCallback(thumbnail.getLocalPath(), cbk);
TextView nextLabel = (TextView) findViewById(R.id.right_btn_txt);
nextLabel.setText("完成");
return true;
}
catch (Throwable t) {
Log.d(TAG, "error when add image view " + imageRoot);
}
return false;
}
class UploadingCallback implements ImageUploader.Callback {
WeakReference<ImageView> viewRef;
UploadingCallback(ImageView v) {
viewRef = new WeakReference<ImageView>(v);
}
@Override
public void onUploadDone(String imagePath, String serverUrl,
Bitmap thumbnail) {
notifyHandler(STATE_DONE, imagePath, thumbnail);
}
@Override
public void onUploading(String imagePath, Bitmap thumbnail) {
notifyHandler(STATE_UPLOADING, imagePath, thumbnail);
}
@Override
public void onUploadFail(String imagePath, Bitmap thumbnail) {
notifyHandler(STATE_FAIL, imagePath, thumbnail);
}
private void notifyHandler(int status, String imagePath, Bitmap thumbnail) {
Log.d(TAG, "image status update to : " + status);
if (thumbnail != null) { //Update thumbnail.
for (BXThumbnail t : imageList) {
if (imagePath.equals(t.getLocalPath())) {
t.setThumbnail(thumbnail);
}
}
}
ImageView img = viewRef.get();
if (img != null && handler != null) { //When activity is destroyed, handler will be null.
Message msg = handler.obtainMessage();
msg.what = MSG_UPLOADING_STATUS_UPDATE;
msg.arg1 = status;
msg.obj = new Pair<Bitmap, ImageView>(thumbnail, viewRef.get());
handler.sendMessage(msg);
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Profiler.markStart("cameOnCreate");
handler = new InternalHandler(); //Make sure handler instance is created on main thread.
if (VERSION.SDK_INT <= 10) {
isLandscapeMode = true;
this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setContentView(R.layout.image_selector_land);
}
else
{
setContentView(R.layout.image_selector);
}
//Take picture action.
findViewById(R.id.cap).setOnClickListener(this);
findViewById(R.id.finish_cap).setOnClickListener(this);
findViewById(R.id.cap).setEnabled(false);//Do not let user take pitcure before initialize.
if (this.getIntent().hasExtra(CommonIntentAction.EXTRA_FINISH_ACTION_LABEL)) {
TextView nextLabel = (TextView) findViewById(R.id.right_btn_txt);
nextLabel.setText(getIntent().getStringExtra(CommonIntentAction.EXTRA_FINISH_ACTION_LABEL));
}
//Sensor to update current orientation.
sensorMgr = (SensorManager) this.getSystemService(Context.SENSOR_SERVICE);
sensor = sensorMgr.getDefaultSensor(Sensor.TYPE_ORIENTATION);
deleteListener = new OnDeleteListener();
findViewById(R.id.pick_gallery).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent goIntent = new Intent(Intent.ACTION_GET_CONTENT);
goIntent.addCategory(Intent.CATEGORY_OPENABLE);
goIntent.setType("image/*");
startActivityForResult(goIntent, REQ_PICK_GALLERY);
}
});
ImageUploader.getInstance().attachActivity(this); //Attach activity.
if (this.getIntent().hasExtra(CommonIntentAction.EXTRA_IMAGE_LIST)) {
ArrayList<String> list = this.getIntent().getStringArrayListExtra(CommonIntentAction.EXTRA_IMAGE_LIST);
this.getIntent().removeExtra(CommonIntentAction.EXTRA_IMAGE_LIST);
this.imageList.clear();
this.originalList.clear();
for (String p : list) {
this.originalList.add(BXThumbnail.createThumbnail(p, null));
}
this.imageList.addAll(originalList);
}
handler.sendEmptyMessageDelayed(MSG_UPDATE_THUMBNAILS, 500);
// Profiler.markEnd("cameOnCreate");
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
ArrayList<String> imgKeys = new ArrayList<String>();
if (imageList != null) {
for (BXThumbnail t : imageList) {
imgKeys.add(t.getLocalPath());
}
}
outState.putStringArrayList(CommonIntentAction.EXTRA_IMAGE_LIST, imgKeys);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
ArrayList<String> imgKeys = savedInstanceState.getStringArrayList(CommonIntentAction.EXTRA_IMAGE_LIST);
if (imgKeys != null) {
this.imageList.clear();
this.originalList.clear();
for (String p : imgKeys) {
this.originalList.add(BXThumbnail.createThumbnail(p, null));
}
this.imageList.addAll(originalList);
}
super.onRestoreInstanceState(savedInstanceState);
}
protected void onDestroy() {
// this.handler = null; //Do not handle action any more.
for (Callback callback : this.callbacks) {
ImageUploader.getInstance().removeCallback(callback);
}
this.callbacks.clear();
super.onDestroy();
Log.d(TAG, "cam destroyed!");
}
@SuppressLint("NewApi")
public void initializeCamera(){
// Profiler.markStart("initializeCame");
Camera c = null;
try {
c = Camera.open(); // attempt to get a Camera instance, this will open the default facing camera if there is any.
isFrontCam = false;
}
catch (Exception e){
// Camera is not available (in use or does not exist)
Log.d("CAM", "fail to open cam " + e.getMessage());
}
if (c == null) { //For devices which only have front camera.
try {
c = Camera.open(0);
CameraInfo info = new CameraInfo();
Camera.getCameraInfo(0, info);
isFrontCam = info.facing == CameraInfo.CAMERA_FACING_FRONT;
}
catch (Throwable t) {
Log.w(TAG, "Open camera failed.");
}
}
mCamera = c;
if (mCamera != null && this.getIntent().hasExtra("location")) {
BXLocation loc = (BXLocation) this.getIntent().getSerializableExtra("location");
mCamera.getParameters().setGpsLatitude(loc.fLat);
mCamera.getParameters().setGpsLongitude(loc.fLon);
}
// Profiler.markEnd("initializeCame");
// return c; // returns null if camera is unavailable
}
@Override
protected void onPause() {
handler.sendEmptyMessage(MSG_PAUSE_ME);
Log.d(TAG, "cam paused");
super.onPause();
}
@Override
protected void onResume() {
GlobalDataManager.getInstance().setLastActiveActivity(this.getClass());
Tracker.getInstance().pv(TrackConfig.TrackMobile.PV.CAMERA).end();
// Profiler.markStart("cameOnResume");
super.onResume();
handler.sendEmptyMessage(MSG_INIT_CAME);
handler.sendEmptyMessageDelayed(MSG_RESUME_ME, 500);//Do not block the main thread.
// Profiler.markEnd("cameOnResume");
}
//An indicator to indicate if user.
private void autoFocusWhenOrienChange() {
try {
if (mCamera != null) {
mCamera.autoFocus(new Camera.AutoFocusCallback() {
public void onAutoFocus(boolean success, Camera camera) {
//Do nothing.
}
});
}
}
catch (Throwable t) {
Log.d(TAG, "error occur when do autofocus.");
}
}
private PictureCallback mPicture = new PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera) {
if (!Util.isExternalStorageWriteable()) {
Toast.makeText(CameraActivity.this, "请检查SD卡状态", Toast.LENGTH_SHORT).show();
handler.sendEmptyMessage(MSG_CANCEL_STORE_PIC);
return;
}
postAppendPhoto(data);
handler.sendEmptyMessage(MSG_PIC_TAKEN);
}
};
@Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.cap:
takePic();
break;
case R.id.finish_cap:
finishTakenPic();
break;
}
}
private void onCancelEdit() {
for (BXThumbnail t : imageList ) {
if (originalList.indexOf(t) == -1) {
ImageUploader.getInstance().cancel(t.getLocalPath());
}
}
}
public void takePic() {
Log.w(TAG, "click to take pic " + System.currentTimeMillis());
View capV = findViewById(R.id.cap);
capV.setEnabled(false);
final BooleanWrapper bWrapper = new BooleanWrapper();
mCamera.autoFocus(new AutoFocusCallback() {
@Override
public void onAutoFocus(boolean focused, Camera cam) {
bWrapper.isTrue = true;
mCamera.takePicture(null, null, mPicture);
mCamera.cancelAutoFocus(); //Avoid deprecate auto-focus notification.
}
});
//For some device, auto focus never return for unknown reason.
Message msg = handler.obtainMessage(MSG_TAKEPIC_DELAY, bWrapper);
handler.sendMessageDelayed(msg, 2000);
}
@Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
if (sensorEvent.sensor.getType() == Sensor.TYPE_ORIENTATION) {
lastSensorEvent = sensorEvent;
float pitch = sensorEvent.values[1];
float roll = sensorEvent.values[2];
Orien newOrien = updateOrien(pitch, roll);
if (newOrien != null && currentOrien != newOrien) {
Log.w(TAG, "orientation changed from " + currentOrien.des + " to " + newOrien.des);
currentOrien = newOrien;
handler.sendEmptyMessage(MSG_ORIENTATION_CHANGE);
}
}
}
private Orien updateOrien(float pitch, float roll) {
if ((pitch < -45 && pitch > -135) ||
(roll >= -15 && roll <= 15 && pitch >= -45 && pitch <= 0)) { //When roll is very small, most likely phone is top up.Do not consider bottom up case because no body will do that.
return Orien.TOP_UP;
}
if (pitch > 45 && pitch < 135) {
return Orien.BOTTOM_UP;
}
if (roll > 45) {
return Orien.RIGHT_UP;
}
if (roll < -45 ||
(roll > -45 && roll < 0 && (pitch > -15 && pitch < 15))) { //When pitch is very small and roll is negative.
return Orien.LEFT_UP;
}
return Orien.DEFAULT;
}
class OnDeleteListener implements View.OnClickListener {
@Override
public void onClick(View v) {
ViewGroup vp = (ViewGroup) v.getParent();//(ViewGroup) findViewById(R.id.result_parent);
// vp.removeView((View) v.getParent());
vp.setTag(null);
ImageView img = (ImageView) vp.findViewById(R.id.result_image);
img.setImageResource(R.drawable.bg_transparent);
BXThumbnail thumbnail = (BXThumbnail) v.getTag();
deleteImageUri(thumbnail);
v.setVisibility(View.INVISIBLE);
//Append this view to the tail of the child list.
ViewGroup imgContainer = (ViewGroup) vp.getParent();
imgContainer.removeView(vp);
imgContainer.addView(vp);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQ_PICK_GALLERY && resultCode == RESULT_OK) {
postAppendData(data);
}
}
private String getRealPathFromURI(Uri contentUri) {
return BitmapUtils.getRealPathFromURI(this, contentUri);
}
private BXThumbnail findFromList(String path, List<BXThumbnail> list, boolean deleteIt) {
BXThumbnail t = null;
for (BXThumbnail tt : list) {
if (tt.getLocalPath().equals(path)) {
t = tt;
break;
}
}
if (t != null && deleteIt) {
list.remove(t);
}
return t;
}
private void postAppendData(Intent data) {
AsyncTask<Uri, Integer, BXThumbnail> task = new AsyncTask<Uri, Integer, BXThumbnail>() {
@Override
protected BXThumbnail doInBackground(Uri... params) {
String path = getRealPathFromURI(params[0]);
BXThumbnail tb = findFromList(path, deleteList, true);
if (tb == null) {
tb = BitmapUtils.copyAndCreateThrmbnail(path, CameraActivity.this);
}
return tb;
}
@Override
protected void onPostExecute(BXThumbnail result) {
Message msg = handler.obtainMessage(MSG_SAVE_DONE, result);
handler.sendMessage(msg);
}
};
task.execute(data.getData());
}
private void postAppendPhoto(byte[] cameraData) {
AsyncTask<byte[], Integer, BXThumbnail> task = new AsyncTask<byte[], Integer, BXThumbnail>() {
@Override
protected BXThumbnail doInBackground(byte[]... params) {
return BitmapUtils.saveAndCreateThumbnail(params[0], currentOrien.orientationDegree, CameraActivity.this, isFrontCam);
}
@Override
protected void onPostExecute(BXThumbnail result) {
boolean full = (MAX_IMG_COUNT -1) == imageList.size();
Message msg = handler.obtainMessage(MSG_SAVE_DONE, result);
handler.sendMessage(msg);
if (!full) {
Toast.makeText(CameraActivity.this, "再来一张吧,你还能再添加" + (MAX_IMG_COUNT-imageList.size() -1) + "张", Toast.LENGTH_SHORT).show();
}
}
};
task.execute(cameraData);
}
protected void finalize() {
try {
if (mCamera != null) {
mCamera.release();
}
} catch (Throwable t) {
Log.d(TAG, "close camera failed when finalize this class.");
}
try {
super.finalize();
} catch (Throwable e) {
e.printStackTrace();
}
Log.d(TAG, "came finalize");
}
private class BooleanWrapper {
boolean isTrue;
}
}
| true | true | public void handleMessage(Message msg) {
switch(msg.what) {
case MSG_TAKEPIC_DELAY:
{
BooleanWrapper bW = (BooleanWrapper) msg.obj;
if (!bW.isTrue) {
mCamera.takePicture(null, null, mPicture);
}
break;
}
case MSG_PAUSE_ME:
{
isInitialized = false;
sensorMgr.unregisterListener(CameraActivity.this);
ViewGroup cameraP = (ViewGroup) findViewById(R.id.camera_parent);
if (mPreview != null) {
cameraP.removeView(mPreview);
}
if (mCamera != null) {
mPreview.setCamera(null);
mCamera.release();
mCamera = null;
}
break;
}
case MSG_CANCEL_STORE_PIC: {
updateCapState();
if (isInitialized) {
mCamera.startPreview();
}
break;
}
case MSG_INIT_CAME : {
ViewGroup cameraP = (ViewGroup) findViewById(R.id.camera_parent);
if (mPreview != null) {
cameraP.removeView(mPreview);
}
initializeCamera();
TextView txt = (TextView) findViewById(R.id.cam_not_available_tip);
txt.setVisibility(mCamera == null ? View.VISIBLE : View.GONE);
if (mCamera != null) {
mPreview = new CameraPreview(CameraActivity.this);
cameraP.addView(mPreview, LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
mPreview.setCamera(mCamera);
}
isInitialized = true;
updateCapState();
break;
}
case MSG_RESUME_ME:{
// Profiler.markStart("sensorRegister");
if (sensor != null) {
sensorMgr.registerListener(CameraActivity.this, sensor, SensorManager.SENSOR_DELAY_NORMAL);
}
// Profiler.markEnd("sensorRegister");
break;
}
case MSG_PIC_TAKEN:
if (isInitialized) {
mCamera.startPreview();
}
break;
case MSG_SAVE_DONE:
BXThumbnail newPicPair = (BXThumbnail) msg.obj;
if (newPicPair != null) {
ImageUploader.getInstance().startUpload(newPicPair.getLocalPath(), newPicPair.getThumbnail(), null);
boolean succed = appendResultImage(newPicPair);
if (succed) {
addImageUri(newPicPair);
}
} else {
Toast.makeText(CameraActivity.this, "获取照片失败", Toast.LENGTH_SHORT).show();
}
findViewById(R.id.cap).setEnabled(true);
break;
case MSG_ORIENTATION_CHANGE:
if (isInitialized) {
autoFocusWhenOrienChange();
}
break;
case MSG_UPDATE_THUMBNAILS:
if (imageList != null && imageList.size() > 0) {
for (BXThumbnail t : imageList) {
appendResultImage(t);
}
}
else {
Toast.makeText(CameraActivity.this, R.string.tip_camera_before_post, Toast.LENGTH_LONG).show();
}
break;
case MSG_UPLOADING_STATUS_UPDATE:
Pair<Bitmap, ImageView> p = (Pair<Bitmap, ImageView>) msg.obj;
if (p.second != null) {
switch (msg.arg1) {
case STATE_UPLOADING:
((View) p.second.getParent()).findViewById(R.id.loading_status).setVisibility(View.VISIBLE);
p.second.setImageBitmap(p.first);
break;
case STATE_FAIL:
((View) p.second.getParent()).findViewById(R.id.loading_status).setVisibility(View.GONE);
p.second.setImageResource(R.drawable.icon_load_fail);
break;
case STATE_DONE:
((View) p.second.getParent()).findViewById(R.id.loading_status).setVisibility(View.GONE);
p.second.setImageBitmap(p.first);
break;
}
}
break;
}
}
| public void handleMessage(Message msg) {
switch(msg.what) {
case MSG_TAKEPIC_DELAY:
{
BooleanWrapper bW = (BooleanWrapper) msg.obj;
if (!bW.isTrue && mCamera != null) {
mCamera.takePicture(null, null, mPicture);
}
break;
}
case MSG_PAUSE_ME:
{
isInitialized = false;
sensorMgr.unregisterListener(CameraActivity.this);
ViewGroup cameraP = (ViewGroup) findViewById(R.id.camera_parent);
if (mPreview != null) {
cameraP.removeView(mPreview);
}
if (mCamera != null) {
mPreview.setCamera(null);
mCamera.release();
mCamera = null;
}
break;
}
case MSG_CANCEL_STORE_PIC: {
updateCapState();
if (isInitialized) {
mCamera.startPreview();
}
break;
}
case MSG_INIT_CAME : {
ViewGroup cameraP = (ViewGroup) findViewById(R.id.camera_parent);
if (mPreview != null) {
cameraP.removeView(mPreview);
}
initializeCamera();
TextView txt = (TextView) findViewById(R.id.cam_not_available_tip);
txt.setVisibility(mCamera == null ? View.VISIBLE : View.GONE);
if (mCamera != null) {
mPreview = new CameraPreview(CameraActivity.this);
cameraP.addView(mPreview, LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
mPreview.setCamera(mCamera);
}
isInitialized = true;
updateCapState();
break;
}
case MSG_RESUME_ME:{
// Profiler.markStart("sensorRegister");
if (sensor != null) {
sensorMgr.registerListener(CameraActivity.this, sensor, SensorManager.SENSOR_DELAY_NORMAL);
}
// Profiler.markEnd("sensorRegister");
break;
}
case MSG_PIC_TAKEN:
if (isInitialized) {
mCamera.startPreview();
}
break;
case MSG_SAVE_DONE:
BXThumbnail newPicPair = (BXThumbnail) msg.obj;
if (newPicPair != null) {
ImageUploader.getInstance().startUpload(newPicPair.getLocalPath(), newPicPair.getThumbnail(), null);
boolean succed = appendResultImage(newPicPair);
if (succed) {
addImageUri(newPicPair);
}
} else {
Toast.makeText(CameraActivity.this, "获取照片失败", Toast.LENGTH_SHORT).show();
}
findViewById(R.id.cap).setEnabled(true);
break;
case MSG_ORIENTATION_CHANGE:
if (isInitialized) {
autoFocusWhenOrienChange();
}
break;
case MSG_UPDATE_THUMBNAILS:
if (imageList != null && imageList.size() > 0) {
for (BXThumbnail t : imageList) {
appendResultImage(t);
}
}
else {
Toast.makeText(CameraActivity.this, R.string.tip_camera_before_post, Toast.LENGTH_LONG).show();
}
break;
case MSG_UPLOADING_STATUS_UPDATE:
Pair<Bitmap, ImageView> p = (Pair<Bitmap, ImageView>) msg.obj;
if (p.second != null) {
switch (msg.arg1) {
case STATE_UPLOADING:
((View) p.second.getParent()).findViewById(R.id.loading_status).setVisibility(View.VISIBLE);
p.second.setImageBitmap(p.first);
break;
case STATE_FAIL:
((View) p.second.getParent()).findViewById(R.id.loading_status).setVisibility(View.GONE);
p.second.setImageResource(R.drawable.icon_load_fail);
break;
case STATE_DONE:
((View) p.second.getParent()).findViewById(R.id.loading_status).setVisibility(View.GONE);
p.second.setImageBitmap(p.first);
break;
}
}
break;
}
}
|
diff --git a/galapagos/Biotope.java b/galapagos/Biotope.java
index b3ddf76..4acbde4 100644
--- a/galapagos/Biotope.java
+++ b/galapagos/Biotope.java
@@ -1,382 +1,382 @@
package galapagos;
import java.util.*;
import java.lang.*;
public class Biotope extends Observable {
public final int width, height;
private final double breedingProbability;
private final int maxHitpoints, initialHitpoints, hitpointsPerRound;
private final int minMaxAge, maxMaxAge;
private final int finchesPerBehavior;
private int round;
public final World<GalapagosFinch> world;
private final TreeMap<String,Statistics> statisticsTree;
private final List<Behavior> finchBehaviors;
private final static int HelpedGotHelpValue = 3;
private final static int HelpedDidntGetHelpValue = 0;
private final static int DidntHelpGotHelpValue = 5;
private final static int DidntHelpDidntGetHelpValue = 1;
private ArrayList<Boolean> engagedFinches;
/**
* Create a Biotope object with some sensible default environment
* values.
*
* @param behaviors A list of behavior objects that will be cloned
* to create the actual behaviors for the finches.
*/
public Biotope (List<Behavior> behaviors) {
this(100, 100, 1.00/3.00, 12, 7, 3, 10, 13, 40, behaviors);
}
/**
* Create a Biotope object with the environment values specified
* by the arguments.
*
* @param width The width of the simulated game world in
* cells. Each cell can hold a single finch.
* @param height The height of the simulated game world in
* cells. Each cell can hold a single finch.
* @param breedingProbability The chance each finch has to create
* offspring each round.
* @param maxHitpoints The maximum number of hit points finches
* can attain through being claned.
* @param initialHitpoints The number of hit points a new finch
* will have.
* @param hitpointsPerRound The number of hit points a finch will
* loose each round.
* @param minMaxAge The lower bound on the randomly determined
* maximum age of finches in rounds.
* @param maxMaxAge The upper bound on the randomly determined
* maximum age of finches in rounds.
* @param finchesPerBehavior The number of finches that will
* initially be created for each behavior.
* @param behaviors A list of behavior objects that will be cloned
* to create the actual behaviors for the finches.
*
* @require 0 < width
* @require 0 < height
* @require 0.0 <= breedingProbability <= 1.0
* @require 0 < initialHitpoints <= maxHitpoints
* @require 0 <= hitPointsPerRound
* @require 1 < minMaxAge <= maxMaxAge
* @require 0 <= finchesPerBehavior
*/
public Biotope (int width, int height, double breedingProbability, int maxHitpoints,
int initialHitpoints, int hitpointsPerRound, int minMaxAge, int maxMaxAge,
int finchesPerBehavior, List<Behavior> behaviors) {
assert (0.0 <= breedingProbability && breedingProbability <= 1.0)
: "breedingProbability must be between 0 and 1, inclusive.";
assert (0 < initialHitpoints)
: "initialHitpoints must be greater than zero.";
- assert (initialHitpoints < maxHitpoints)
+ assert (initialHitpoints <= maxHitpoints)
: "maxHitpoints must be greater than initialHitpoints.";
assert (0 <= hitpointsPerRound)
: "hitPointsPerRound must be greater than zero.";
assert (0 < minMaxAge)
: "The lower bound on the maximum age must be greater than zero";
assert (minMaxAge <= maxMaxAge)
: "The upper bound on the maximum age must be greater than the lower bound.";
assert (0 <= finchesPerBehavior)
: "At least one finch per behavior must be specified.";
this.width = width;
this.height = height;
this.breedingProbability = breedingProbability;
this.maxHitpoints = maxHitpoints;
this.initialHitpoints = initialHitpoints;
this.hitpointsPerRound = hitpointsPerRound;
this.minMaxAge = minMaxAge;
this.maxMaxAge = maxMaxAge;
this.finchesPerBehavior = finchesPerBehavior;
this.finchBehaviors = behaviors;
world = new World<GalapagosFinch>(width, height);
statisticsTree = new TreeMap<String,Statistics>();
engagedFinches = new ArrayList<Boolean>(width * height);
for (int i = 0; i < width * height; i++)
engagedFinches.add(false);
addStartFinches();
}
/**
* Add the initial finches using the values for finchesPerBehavior
* and the list of behaviors.
*/
private void addStartFinches()
{
Iterator<World<GalapagosFinch>.Place> worldIterator = world.randomIterator();
for (Iterator<Behavior> bIterator = finchBehaviors.iterator();
bIterator.hasNext();)
{
Behavior b = bIterator.next();
statisticsTree.put(b.toString(),new Statistics());
for (int i = 0;i < finchesPerBehavior && worldIterator.hasNext();i++)
{
World<GalapagosFinch>.Place p = worldIterator.next();
placeFinch(p,b,false);
}
}
}
/**
* Place a new finch of the provided behavior at the given place.
*
* @param p Where the new finch will be put in the world.
* @param b A behavior object that will be cloned to get the
* behavior for the new finch.
* @param born If true, the finch is considered to be new-born,
* affecting statistics, and making sure that it will not breed
* until the next round.
*
* @ensure p.getElement() == null
*/
private void placeFinch (World<GalapagosFinch>.Place p, Behavior b, Boolean born) {
Statistics stat = statisticsTree.get(b.toString());
stat.incPopulation();
GalapagosFinch finch = new GalapagosFinch(initialHitpoints,
maxHitpoints,
randomMaxAge(),
b.clone());
if (born)
stat.incBorn();
else
finch.makeOlder();
p.setElement(finch);
}
/**
* Put a new finch in the world at position x, y. The finch will
* have the provided behavior, and it will overwrite any already
* existing finch at the position.
*/
public void putFinch (int x, int y, Behavior b) {
World.Place p = world.getAt(x, y);
// If we have a finch here already, subtract it from the total
// population of that type.
if (p.getElement() != null) {
Statistics s = statisticsTree.get(((GalapagosFinch)p.getElement()).behavior().toString());
s.decPopulation();
}
placeFinch(p, b, false);
setChanged();
notifyObservers();
}
/**
* Return a random age for a new finch, based on maxMaxAge and
* minMaxAge.
*
* @ensure minMaxAge < randomMaxAge() < maxMaxAge;
*/
private int randomMaxAge () {
return minMaxAge + (int)(Math.random() * (maxMaxAge - minMaxAge));
}
/**
* Run a single round in the simulation, consisting of updating
* statistics, randomly creating offspring, arrange meetings
* between finches, age and possibly kill finches and notify any
* observers.
*/
public void runRound () {
for (Statistics stat : statisticsTree.values())
stat.newRound();
breed();
makeMeetings();
grimReaper();
round++;
setChanged();
notifyObservers();
}
/**
* Let some of the finches breed, if possible (a finch needs an
* empty neighbour place to breed).
*/
private void breed () {
for (Iterator<World<GalapagosFinch>.Place> i = world.randomIterator(); i.hasNext();) {
World<GalapagosFinch>.Place place = i.next();
GalapagosFinch finch = place.getElement();
if (finch != null && finch.age() > 0 && Math.random() <= breedingProbability) {
List<World<GalapagosFinch>.Place> neighbours = place.emptyNeighbours();
if (!neighbours.isEmpty())
placeFinch(neighbours.get(0), finch.behavior().clone(), true);
}
}
}
/**
* Sets up random meetings between the finches of the world.
*/
private void makeMeetings() {
clearEngagementKnowledge();
for (Iterator i = world.randomIterator(); i.hasNext(); ) {
World<GalapagosFinch>.Place place = (World.Place) i.next();
if(place.getElement() != null && !isEngaged(place))
makeMeeting(place);
}
}
/**
* Engages the finch at the specified place with one of its neighbours (if any).
* And makes them meet eachother.
* @require place.getElement() != null && !isEngaged(place)
* @ensure isEngaged(place)
* @param place the place holding the unengaged finch
*/
private void makeMeeting(World<GalapagosFinch>.Place place) {
assert (place.getElement() != null) : "Can't engage a null-finch";
assert (!isEngaged(place)) : "The finch is already engaged";
List<World<GalapagosFinch>.Place> filledNeighbours = place.filledNeighbours();
for (World<GalapagosFinch>.Place p : filledNeighbours)
if (!isEngaged(p)) {
engage(p);
engage(place);
meet(place.getElement(), p.getElement());
return;
}
}
/**
* Clear the information about which finches have already met this
* round.
*/
private void clearEngagementKnowledge() {
for (int i = 0; i < engagedFinches.size(); i++)
engagedFinches.set(i, false);
}
/**
* Register the fact that the finch at place has been involved in
* a meeting this round.
*
* @require place.getElement() != null
*/
private void engage(World.Place place) {
assert place.getElement() != null
: "Cannot register an empty place as having participated in a meeting.";
engagedFinches.set(place.xPosition() * height + place.yPosition(), true);
}
/**
* Return true if place has already been engaged in a meeting.
*/
private boolean isEngaged(World.Place place) {
return engagedFinches.get(place.xPosition() * height + place.yPosition());
}
/**
* Perform a meeting between two finches, letting them act on each
* other and inform them of the other finch's action. The actions
* will be performed in parallel, not sequentially, so there is no
* bias towards providing one finch or the other with information
* about what the other finch has done.
*/
private void meet(GalapagosFinch finch1, GalapagosFinch finch2) {
//let both finches decide if they won't to help the other finch
Action finch1Action = finch1.decide(finch2);
Action finch2Action = finch2.decide(finch1);
finch1.changeHitpoints(getMeetingResult(finch1Action, finch2Action));
finch2.changeHitpoints(getMeetingResult(finch2Action, finch1Action));
//tell the finches what was done to them (so they eventually can learn)
finch1.response(finch2, finch2Action);
finch2.response(finch1, finch1Action);
}
/**
* Get the hit point increase value for performing finch1Action
* while having finch2Action performed on you.
*/
private int getMeetingResult(Action finch1Action, Action finch2Action) {
if (finch1Action == Action.CLEANING) {
if (finch2Action == Action.CLEANING) {
return HelpedGotHelpValue;
}
else if (finch2Action == Action.IGNORING) {
return HelpedDidntGetHelpValue;
}
} else if (finch1Action == Action.IGNORING) {
if (finch2Action == Action.CLEANING) {
return DidntHelpGotHelpValue;
}
else if (finch2Action == Action.IGNORING) {
return DidntHelpDidntGetHelpValue;
}
}
throw new Error("Unhandled Action combination");
}
/**
* Decrease the hitpoints of all finches by hitpointsPerRound, and
* find dead finches and remove them from world, and store the
* changes in statisticsTree.
*/
private void grimReaper () {
for (World<GalapagosFinch>.Place p : world) if (p.getElement() != null) {
GalapagosFinch f = p.getElement();
f.changeHitpoints(-hitpointsPerRound);
f.makeOlder();
FinchStatus newStatus = f.status();
if (newStatus != FinchStatus.ALIVE) {
Statistics s = statisticsTree.get(f.behavior().toString());
if (newStatus == FinchStatus.DEAD_AGE)
s.incDeadByAge();
else s.incDeadByTicks();
s.decPopulation();
p.setElement(null);
}
}
}
/**
* Return the statistics for the behavior with the specified name.
*
* @require behavior must be the name of a known Behavior.
*/
public Statistics statistics(String behavior) {
assert(statisticsTree.containsKey(behavior))
: "Asked to retrieve statistics for unknown behavior.";
return statisticsTree.get(behavior.toString());
}
/**
* Get the current round number.
*
* @ensure 0 < round()
*/
public int round () {
return round;
}
/**
* Return an iterator for walking through the places of the world
* of this Biotope object.
*/
public Iterator<World<GalapagosFinch>.Place> worldIterator () {
return world.iterator();
}
/**
* Get a list of all the behaviors in the Biotope.
*/
public List<Behavior> behaviors () {
return finchBehaviors;
}
/**
* Notify the observers of the Biotope.
*/
public void doNotifyObservers () {
setChanged();
notifyObservers();
}
}
| true | true | public Biotope (int width, int height, double breedingProbability, int maxHitpoints,
int initialHitpoints, int hitpointsPerRound, int minMaxAge, int maxMaxAge,
int finchesPerBehavior, List<Behavior> behaviors) {
assert (0.0 <= breedingProbability && breedingProbability <= 1.0)
: "breedingProbability must be between 0 and 1, inclusive.";
assert (0 < initialHitpoints)
: "initialHitpoints must be greater than zero.";
assert (initialHitpoints < maxHitpoints)
: "maxHitpoints must be greater than initialHitpoints.";
assert (0 <= hitpointsPerRound)
: "hitPointsPerRound must be greater than zero.";
assert (0 < minMaxAge)
: "The lower bound on the maximum age must be greater than zero";
assert (minMaxAge <= maxMaxAge)
: "The upper bound on the maximum age must be greater than the lower bound.";
assert (0 <= finchesPerBehavior)
: "At least one finch per behavior must be specified.";
this.width = width;
this.height = height;
this.breedingProbability = breedingProbability;
this.maxHitpoints = maxHitpoints;
this.initialHitpoints = initialHitpoints;
this.hitpointsPerRound = hitpointsPerRound;
this.minMaxAge = minMaxAge;
this.maxMaxAge = maxMaxAge;
this.finchesPerBehavior = finchesPerBehavior;
this.finchBehaviors = behaviors;
world = new World<GalapagosFinch>(width, height);
statisticsTree = new TreeMap<String,Statistics>();
engagedFinches = new ArrayList<Boolean>(width * height);
for (int i = 0; i < width * height; i++)
engagedFinches.add(false);
addStartFinches();
}
| public Biotope (int width, int height, double breedingProbability, int maxHitpoints,
int initialHitpoints, int hitpointsPerRound, int minMaxAge, int maxMaxAge,
int finchesPerBehavior, List<Behavior> behaviors) {
assert (0.0 <= breedingProbability && breedingProbability <= 1.0)
: "breedingProbability must be between 0 and 1, inclusive.";
assert (0 < initialHitpoints)
: "initialHitpoints must be greater than zero.";
assert (initialHitpoints <= maxHitpoints)
: "maxHitpoints must be greater than initialHitpoints.";
assert (0 <= hitpointsPerRound)
: "hitPointsPerRound must be greater than zero.";
assert (0 < minMaxAge)
: "The lower bound on the maximum age must be greater than zero";
assert (minMaxAge <= maxMaxAge)
: "The upper bound on the maximum age must be greater than the lower bound.";
assert (0 <= finchesPerBehavior)
: "At least one finch per behavior must be specified.";
this.width = width;
this.height = height;
this.breedingProbability = breedingProbability;
this.maxHitpoints = maxHitpoints;
this.initialHitpoints = initialHitpoints;
this.hitpointsPerRound = hitpointsPerRound;
this.minMaxAge = minMaxAge;
this.maxMaxAge = maxMaxAge;
this.finchesPerBehavior = finchesPerBehavior;
this.finchBehaviors = behaviors;
world = new World<GalapagosFinch>(width, height);
statisticsTree = new TreeMap<String,Statistics>();
engagedFinches = new ArrayList<Boolean>(width * height);
for (int i = 0; i < width * height; i++)
engagedFinches.add(false);
addStartFinches();
}
|
diff --git a/src/org/nosco/ant/ClassGenerator.java b/src/org/nosco/ant/ClassGenerator.java
index 2382fe2..cb2a035 100644
--- a/src/org/nosco/ant/ClassGenerator.java
+++ b/src/org/nosco/ant/ClassGenerator.java
@@ -1,734 +1,732 @@
package org.nosco.ant;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Blob;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.nosco.json.JSONArray;
import org.nosco.json.JSONException;
import org.nosco.json.JSONObject;
import org.nosco.util.Misc;
import org.nosco.util.RSArgsParser;
class ClassGenerator {
private static RSArgsParser argsParser = new RSArgsParser(new HashMap<String,Boolean>() {{
put("package", true);
put("metadata", true);
put("dir", true);
put("strip-prefixes", true);
put("strip-suffixes", true);
}}, new HashMap<String,String>() {{
put("p", "package");
put("m", "metadata");
put("d", "dir");
}}, new HashMap<String,String>() {{
put("package", "noscodb");
put("dir", "gensrc");
put("metadata", "schema.json");
put("fakefks", "fake_fks.json");
}});
private final String pkg;
private final String dir;
private String[] stripPrefixes;
private String[] stripSuffixes;
public ClassGenerator(String dir, String pkg, String[] stripPrefixes, String[] stripSuffixes) {
this.dir = dir;
this.pkg = pkg;
this.stripPrefixes = stripPrefixes.clone();
this.stripSuffixes = stripSuffixes.clone();
}
private static class FK {
String name = null;
String[] reffing = null;
String[] reffed = null;
Map<String,String> columns = new LinkedHashMap<String,String>();
}
public static void main(String[] args) throws IOException, JSONException {
Map<String, String> params = argsParser.parse(args);
String dir = params.get("dir");
//recursiveDelete(new File(dir));
String pkg = params.get("package");
String[] stripPrefixes = {};
if (params.get("strip-prefixes") != null) stripPrefixes = params.get("strip-prefixes").split(",");
String[] stripSuffixes = {};
if (params.get("strip-suffixes") != null) stripSuffixes = params.get("strip-suffixes").split(",");
String metadataFile = params.get("metadata");
String fakefksFile = params.get("fakefks");
go(dir, pkg, stripPrefixes, stripSuffixes, metadataFile, fakefksFile, null, null);
}
public static void go(String dir, String pkg, String[] stripPrefixes,
String[] stripSuffixes, String metadataFile, String fakefksFile, String dataSource,
String callbackPackage) throws IOException, JSONException {
BufferedReader br = new BufferedReader(new FileReader(metadataFile));
StringBuffer sb = new StringBuffer();
String s = null;
while ((s=br.readLine())!=null) sb.append(s).append('\n');
JSONObject metadata = new JSONObject(sb.toString());
JSONObject fakeFKs = new JSONObject();
File fakeFKsFile = new File(fakefksFile);
if (fakeFKsFile.exists()) {
br = new BufferedReader(new FileReader(fakeFKsFile));
sb = new StringBuffer();
s = null;
while ((s=br.readLine())!=null) sb.append(s).append('\n');
fakeFKs = new JSONObject(sb.toString());
}
ClassGenerator generator = new ClassGenerator(dir, pkg, stripPrefixes, stripSuffixes);
JSONObject schemas = metadata.getJSONObject("schemas");
JSONObject foreignKeys = metadata.getJSONObject("foreign_keys");
String dataSourceName = DataSourceGenerator.getDataSourceName(dataSource);
for (String schema : schemas.keySet()) {
JSONObject tables = schemas.getJSONObject(schema);
for (String table : tables.keySet()) {
// skip these junk mssql tables
if(table.startsWith("syncobj_")) continue;
JSONObject columns = tables.getJSONObject(table);
JSONArray pks = getJSONArray(metadata, "primary_keys", schema, table);
List<FK> fks = new ArrayList<FK>();
List<FK> fksIn = new ArrayList<FK>();
for (String constraint_name : foreignKeys.keySet()) {
JSONObject fkmd = foreignKeys.getJSONObject(constraint_name);
splitFK(schema, table, fks, fksIn, constraint_name, fkmd);
}
for (String constraint_name : fakeFKs.keySet()) {
JSONObject fkmd = fakeFKs.getJSONObject(constraint_name);
splitFK(schema, table, fks, fksIn, constraint_name, fkmd);
}
generator.generate(schema, table, columns, pks, fks, fksIn, dataSourceName,
callbackPackage);
}
}
}
private static void splitFK(String schema, String table, List<FK> fks, List<FK> fksIn,
String constraint_name, JSONObject fkmd) throws JSONException {
FK fk = new FK();
fk.name = constraint_name;
String[] reffing = {fkmd.getJSONArray("reffing").getString(0),
fkmd.getJSONArray("reffing").getString(1)};
fk.reffing = reffing;
String[] reffed = {fkmd.getJSONArray("reffed").getString(0),
fkmd.getJSONArray("reffed").getString(1)};
fk.reffed = reffed;
JSONObject cols = fkmd.getJSONObject("columns");
for (String key : cols.keySet()) {
fk.columns.put(key, cols.getString(key));
}
if (schema.equals(fk.reffing[0]) && table.equals(fk.reffing[1])) {
fks.add(fk);
}
if (schema.equals(fk.reffed[0]) && table.equals(fk.reffed[1])) {
fksIn.add(fk);
}
}
private static JSONObject getJSONObject(JSONObject o, String... path) throws JSONException {
for (String s : path) {
if (o==null) return null;
if (o.has(s)) o = o.optJSONObject(s);
else return null;
}
return o;
}
private static JSONArray getJSONArray(Object o, String... path) throws JSONException {
for (String s : path) {
if (o==null) return null;
if (o instanceof JSONObject && ((JSONObject)o).has(s)) {
o = ((JSONObject)o).opt(s);
} else return null;
}
if (o instanceof JSONArray) return (JSONArray) o;
else return null;
}
private static void recursiveDelete(File file) {
if (file==null) return;
for (File f : file.listFiles()) {
if (f.isDirectory()) recursiveDelete(f);
else f.delete();
}
file.delete();
}
private static String getFieldName(String column) {
return column.replace(' ', '_')
.replace("%", "_PERCENT")
.replace("-", "_DASH_")
.toUpperCase();
}
private static String getFieldName(Collection<String> columns) {
StringBuffer sb = new StringBuffer();
int i = 1;
for (String column : columns) {
sb.append(column.replace(' ', '_').toUpperCase());
if (++i < columns.size()) sb.append("__");
}
return sb.toString();
}
private void generate(String schema, String table, JSONObject columns, JSONArray pks,
List<FK> fks, List<FK> fksIn, String dataSourceName, String callbackPackage)
throws IOException, JSONException {
String className = genTableClassName(table);
Set<String> pkSet = new HashSet<String>();
if (pks == null) pks = new JSONArray();
for (int i=0; i<pks.length(); ++i) {
pkSet.add(pks.getString(i));
}
int fieldCount = columns.keySet().size();
String pkgDir = Misc.join("/", pkg.split("[.]"));
new File(Misc.join("/", dir, pkgDir, schema)).mkdirs();
File file = new File(Misc.join("/", dir, pkgDir, schema, className+".java"));
System.out.println("writing: "+ file.getAbsolutePath());
BufferedWriter br = new BufferedWriter(new FileWriter(file));
br.write("package "+ pkg +"."+ schema +";\n\n");
br.write("import java.lang.reflect.Method;\n");
br.write("import java.lang.reflect.InvocationTargetException;\n");
br.write("import java.sql.SQLException;\n");
br.write("import java.util.Map;\n\n");
br.write("import java.util.HashMap;\n\n");
br.write("import org.nosco.Field;\n");
br.write("import org.nosco.Query;\n");
br.write("import org.nosco.QueryFactory;\n");
br.write("import org.nosco.Table;\n");
br.write("\n");
br.write("public class "+ className +" extends Table {\n\n");
// write field constants
int index = 0;
for (String column : columns.keySet()) {
br.write("\tpublic static final Field<");
br.write(getFieldType(columns.getString(column)).getName());
br.write("> "+ getFieldName(column));
br.write(" = new Field<"+ getFieldType(columns.getString(column)).getName());
br.write(">("+ index +", "+ className +".class, \""+ column);
br.write("\", "+ getFieldType(columns.getString(column)).getName() +".class");
br.write(");\n");
++index;
}
br.write("\n");
// write primary keys
br.write("\tpublic static Field.PK PK = new Field.PK(");
for (int i=0; i<pks.length(); ++i) {
br.write(pks.getString(i).toUpperCase());
if (i<pks.length()-1) br.write(", ");
}
br.write(");\n");
br.write("\tpublic org.nosco.Field.PK PK() { return PK; }\n\n");
// write foreign keys
for (FK fk : fks) {
String referencedTable = fk.reffed[1];
String referencedTableClassName = genTableClassName(referencedTable);
if (!schema.equals(fk.reffed[0])) {
referencedTableClassName = pkg +"."+ fk.reffed[0] +"."+ referencedTableClassName;
}
String fkName = genFKName(fk.columns.keySet(), referencedTable);
br.write("\tpublic static final Field.FK FK_"+ fkName);
br.write(" = new Field.FK("+ index +", "+ className +".class, ");
br.write(referencedTableClassName +".class");
for (Entry<String, String> e : fk.columns.entrySet()) {
br.write(", "+ e.getKey().toUpperCase());
}
for (Entry<String, String> e : fk.columns.entrySet()) {
br.write(", "+ referencedTableClassName +".");
br.write(e.getValue().toUpperCase());
}
br.write(");\n");
++index;
}
br.write("\n");
// write field value references
for (String column : columns.keySet()) {
br.write("\tprivate "+ getFieldType(columns.getString(column)).getName());
br.write(" "+ getInstanceFieldName(column) + " = null;\n");
}
br.write("\n");
// write constructors
br.write("\tpublic "+ className +"() {}\n\n");
br.write("\t@SuppressWarnings(\"rawtypes\")\n");
br.write("\tprotected "+ className +"(Field[] fields, Object[] objects, int start, int end) {\n");
br.write("\t\tif (fields.length != objects.length)\n\t\t\tthrow new IllegalArgumentException(");
br.write("\"fields.length != objects.length => \"+ fields.length +\" != \"+ objects.length");
br.write(" +\"\");\n");
br.write("\t\tfor (int i=start; i<end; ++i) {\n");
for (String column : columns.keySet()) {
br.write("\t\t\tif (fields[i]=="+ getFieldName(column) +") {\n");
br.write("\t\t\t\t"+ getInstanceFieldName(column) +" = (");
br.write(getFieldType(columns.getString(column)).getName());
br.write(") objects[i];\n");
br.write("\t\t\t\t__NOSCO_FETCHED_VALUES.set("+ getFieldName(column) +".INDEX);\n");
br.write("\t\t\t\tcontinue;\n");
br.write("\t\t\t}\n");
}
br.write("\t\t}\n\t}\n\n");
// write abstract method impls
br.write("\tpublic String SCHEMA_NAME() {\n\t\treturn \""+ schema +"\";\n\t}\n\n");
br.write("\tpublic String TABLE_NAME() {\n\t\treturn \""+ table +"\";\n\t}\n\n");
br.write("\t@SuppressWarnings(\"rawtypes\")\n");
br.write("\tpublic Field[] FIELDS() {\n\t\tField[] fields = {");
for (String column : columns.keySet()) {
br.write(getFieldName(column)+",");
}
br.write("};\n\t\treturn fields;\n\t}\n\n");
br.write("\t@SuppressWarnings(\"rawtypes\")\n");
br.write("\tpublic Field.FK[] FKS() {\n\t\tField.FK[] fields = {");
for (FK fk : fks) {
String referencedTable = fk.reffed[1];
// if (!schema.equals(fk.reffed[0])) {
// referencedTable = fk.reffed[0] +"_"+ referencedTable;
// }
br.write("FK_" + genFKName(fk.columns.keySet(), referencedTable) + ",");
}
br.write("};\n\t\treturn fields;\n\t}\n\n");
//br.write("\tpublic Field[] GET_PRIMARY_KEY_FIELDS() {\n\t\tField[] fields = {");
//for (int i=0; i<pks.length(); ++i) {
// br.write(pks.getString(i).toUpperCase()+",");
//}
//br.write("};\n\t\treturn fields;\n\t}\n\n");
br.write("\tpublic static final Query<"+ className +"> ALL = QueryFactory.IT.getQuery("
+ className +".class).use("+ pkg +"."+ dataSourceName +"."+ schema.toUpperCase() +");\n\n");
// write toString
br.write("\t public String toString() {\n");
br.write("\t\treturn \"["+ className);
for (int i=0; i<pks.length(); ++i) {
String pk = pks.getString(i);
br.write(" "+ pk+":");
br.write("\"+"+ getInstanceFieldName(pk));
br.write("+\"");
}
br.write("]\";\n");
br.write("\t}\n\n");
// write getters and setters
for (String column : columns.keySet()) {
//boolean skipColumn = false;
//for (FK fk : fks) {
// if (fk.columns.containsKey(column)) skipColumn = true;
//}
//if (skipColumn) continue;
String cls = getFieldType(columns.getString(column)).getName();
br.write("\tpublic "+ cls +" get"+ getInstanceMethodName(column) +"() {\n");
br.write("\t\tif (!__NOSCO_FETCHED_VALUES.get("+ getFieldName(column) +".INDEX)) {\n");
br.write("\t\t\t"+ getInstanceFieldName(column) +" = ALL.onlyFields(");
br.write(getFieldName(column)+")");
for (String pk : pkSet) {
br.write(".where("+ getFieldName(pk) +".eq("+ getInstanceFieldName(pk) +"))");
}
br.write(".getTheOnly().get"+ getInstanceMethodName(column) +"();\n");
br.write("\t\t\t__NOSCO_FETCHED_VALUES.set("+ getFieldName(column) +".INDEX);\n");
br.write("\t\t}\n");
br.write("\t\treturn "+ getInstanceFieldName(column) +";\n\t}\n\n");
//if (!pkSet.contains(column)) {
br.write("\tpublic "+ className +" set"+ getInstanceMethodName(column));
br.write("("+ cls +" v) {\n");
br.write("\t\t"+ getInstanceFieldName(column) +" = v;\n");
br.write("\t\tif (__NOSCO_UPDATED_VALUES == null) __NOSCO_UPDATED_VALUES = new java.util.BitSet();\n");
br.write("\t\t__NOSCO_UPDATED_VALUES.set("+ getFieldName(column) +".INDEX);\n");
br.write("\t\treturn this;\n");
br.write("\t}\n\n");
//}
}
// write getters and setters for FKs
for (FK fk : fks) {
String referencedSchema = fk.reffed[0];
String referencedTable = fk.reffed[1];
//String referencedColumn = referenced.getString(2);
String referencedTableClassName = genTableClassName(referencedTable);
if (!schema.equals(fk.reffed[0])) {
referencedTableClassName = pkg +"."+ fk.reffed[0] +"."+ referencedTableClassName;
}
String methodName = genFKMethodName(fk.columns.keySet(), referencedTable);
String cachedObjectName = "_NOSCO_FK_"+ underscoreToCamelCase(fk.columns.keySet(), false);
br.write("\tprivate "+ referencedTableClassName +" "+ cachedObjectName +" = null;\n\n");
br.write("\tpublic "+ referencedTableClassName +" get"+ methodName +"() {\n");
br.write("\t\tif (!__NOSCO_FETCHED_VALUES.get(FK_"+ genFKName(fk.columns.keySet(), referencedTable) +".INDEX)) {\n");
br.write("\t\t\t"+ cachedObjectName +" = "+ referencedTableClassName +".ALL");
br.write(".where("+ referencedTableClassName +"."+ getFieldName(fk.columns.values()) +".eq("+ underscoreToCamelCase(fk.columns.keySet(), false) +"))");
br.write(".getTheOnly();\n");
br.write("\t\t\t__NOSCO_FETCHED_VALUES.set(FK_"+ genFKName(fk.columns.keySet(), referencedTable) +".INDEX);\n");
br.write("\t\t}\n");
br.write("\t\treturn "+ cachedObjectName +";\n\t}\n\n");
br.write("\tpublic "+ className +" set"+ methodName +"("+ referencedTableClassName +" v) {\n");
//br.write(" v) {\n\t\tPUT_VALUE(");
br.write("\t\t"+ underscoreToCamelCase(fk.columns.keySet(), false) +" = v.get"+ underscoreToCamelCase(fk.columns.values(), true) +"();\n");
br.write("\t\tif (__NOSCO_UPDATED_VALUES == null) __NOSCO_UPDATED_VALUES = new java.util.BitSet();\n");
br.write("\t\t__NOSCO_UPDATED_VALUES.set("+ getFieldName(fk.columns.keySet()) +".INDEX);\n");
br.write("\t\t"+ cachedObjectName +" = v;\n");
br.write("\t\t__NOSCO_UPDATED_VALUES.set(FK_"+ genFKName(fk.columns.keySet(), referencedTable) +".INDEX);\n");
br.write("\t\treturn this;\n");
br.write("\n\t}\n\n");
}
// write SET_FK
br.write("\tprotected void SET_FK(Field.FK field, Object v) {\n");
br.write("\t\tif (false);\n");
for (FK fk : fks) {
String cachedObjectName = "_NOSCO_FK_"+ underscoreToCamelCase(fk.columns.keySet(), false);
String referencedTable = fk.reffed[1];
String referencedTableClassName = genTableClassName(referencedTable);
if (!schema.equals(fk.reffed[0])) {
referencedTableClassName = pkg +"."+ fk.reffed[0] +"."+ referencedTableClassName;
}
br.write("\t\telse if (field == FK_"+ genFKName(fk.columns.keySet(), referencedTable) +") {\n");
br.write("\t\t\t"+ cachedObjectName +" = ("+ referencedTableClassName +") v;\n");
br.write("\t\t\t__NOSCO_FETCHED_VALUES.set(FK_"+ genFKName(fk.columns.keySet(), referencedTable) +".INDEX);\n");
br.write("\t\t}\n");
}
br.write("\t\telse {throw new RuntimeException(\"unknown FK\");}\n");
br.write("\t}\n\n");
for (FK fk : fksIn) {
String relatedSchema = fk.reffing[0];
String relatedTable = fk.reffing[1];
String relatedTableClassName = this.genTableClassName(relatedTable);
//String method = genFKMethodName(fk.columns.keySet(), relatedTableClassName);
String method = relatedTableClassName;
if (!schema.equals(fk.reffing[0])) {
relatedTableClassName = pkg +"."+ fk.reffing[0] +"."+ relatedTableClassName;
}
for (String s : fk.columns.keySet()) method += "_" + s;
method = getInstanceMethodName(method);
br.write("\tpublic Query<"+ relatedTableClassName +"> get"+ method +"Set() ");
br.write("{\n\t\treturn "+ relatedTableClassName +".ALL");
for (Entry<String, String> e : fk.columns.entrySet()) {
String relatedColumn = e.getKey();
String column = e.getValue();
br.write(".where("+ relatedTableClassName +"."+ getFieldName(relatedColumn) +".eq(get"+ getInstanceMethodName(column) +"()))");
}
br.write(";\n\t}\n\n");
}
// write save function
br.write("\t@SuppressWarnings(\"rawtypes\")\n");
br.write("\tpublic boolean save() throws SQLException {\n");
br.write("\t\tif (!dirty()) return false;\n");
br.write("\t\tQuery<"+ className +"> query = ALL");
for (String pk : pkSet) {
br.write(".where("+ getFieldName(pk) +".eq("+ getInstanceFieldName(pk) +"))");
}
br.write(";\n");
if (!pkSet.isEmpty()) {
br.write("\t\tif (");
List<String> pkList = new ArrayList<String>(pkSet);
for (int i=0; i<pkList.size(); ++i) {
br.write(getInstanceFieldName(pkList.get(i)) +" == null");
if (i<pkList.size()-1) br.write(" || ");
}
br.write(") {\n");
br.write("} else {\n");
br.write("\t\t\tif (__NOSCO_CALLBACK_UPDATE_PRE!=null) "
+ "try { __NOSCO_CALLBACK_UPDATE_PRE.invoke(null, this); }"
+ "catch (IllegalAccessException e) { e.printStackTrace(); } "
+ "catch (InvocationTargetException e) { e.printStackTrace(); }\n");
br.write("\t\t}\n");
}
br.write("\t\tMap<Field<?>,Object> updates = new HashMap<Field<?>,Object>();\n");
for (String column : columns.keySet()) {
br.write("\t\tif (__NOSCO_UPDATED_VALUES.get("+ getFieldName(column) +".INDEX)) {\n");
br.write("\t\t\tupdates.put("+ getFieldName(column) +", "+ getInstanceFieldName(column) +");\n");
br.write("\t\t}\n");
}
br.write("\t\tquery = query.set(updates);\n");
if (pkSet.isEmpty()) {
br.write("\t\t\tquery.insert();\n\t\treturn true;\n");
} else {
br.write("\t\tif (");
List<String> pkList = new ArrayList<String>(pkSet);
for (int i=0; i<pkList.size(); ++i) {
br.write(getInstanceFieldName(pkList.get(i)) +" == null");
if (i<pkList.size()-1) br.write(" || ");
}
br.write(") {\n");
br.write("\t\t\t"+ getInstanceFieldName(pkList.get(0)) +" = (");
br.write(getFieldType(columns.getString(pkList.get(0))).getName() +") query.insert();\n");
br.write("\t\t\treturn true;\n\t\t} else {\n");
br.write("\t\t\tint count = query.update();\n");
br.write("\t\t\tif (__NOSCO_CALLBACK_UPDATE_POST!=null) "
+ "try { __NOSCO_CALLBACK_UPDATE_POST.invoke(null, this); }"
+ "catch (IllegalAccessException e) { e.printStackTrace(); } "
+ "catch (InvocationTargetException e) { e.printStackTrace(); }\n");
br.write("\t\t\treturn count==1;\n");
br.write("\t\t}\n");
}
br.write("\t}\n");
// write update function
br.write("\t@SuppressWarnings(\"rawtypes\")\n");
br.write("\tpublic boolean update() throws SQLException {\n");
br.write("\t\tif (!dirty()) return false;\n");
br.write("\t\tQuery<"+ className +"> query = ALL");
for (String pk : pkSet) {
br.write(".where("+ getFieldName(pk) +".eq("+ getInstanceFieldName(pk) +"))");
}
br.write(";\n");
br.write("\t\tif (__NOSCO_CALLBACK_UPDATE_PRE!=null) "
+ "try { __NOSCO_CALLBACK_UPDATE_PRE.invoke(null, this); }"
+ "catch (IllegalAccessException e) { e.printStackTrace(); } "
+ "catch (InvocationTargetException e) { e.printStackTrace(); }\n");
br.write("\t\tMap<Field<?>,Object> updates = new HashMap<Field<?>,Object>();\n");
for (String column : columns.keySet()) {
br.write("\t\tif (__NOSCO_UPDATED_VALUES.get("+ getFieldName(column) +".INDEX)) {\n");
br.write("\t\t\tupdates.put("+ getFieldName(column) +", "+ getInstanceFieldName(column) +");\n");
br.write("\t\t}\n");
}
br.write("\t\tquery = query.set(updates);\n");
br.write("\t\tint count = query.update();\n");
br.write("\t\tif (__NOSCO_CALLBACK_UPDATE_POST!=null) "
+ "try { __NOSCO_CALLBACK_UPDATE_POST.invoke(null, this); }"
+ "catch (IllegalAccessException e) { e.printStackTrace(); } "
+ "catch (InvocationTargetException e) { e.printStackTrace(); }\n");
br.write("\t\treturn count==1;\n");
br.write("\t}\n");
// write insert function
br.write("\t@SuppressWarnings(\"rawtypes\")\n");
br.write("\tpublic boolean insert() throws SQLException {\n");
br.write("\t\tif (!dirty()) return false;\n");
br.write("\t\tQuery<"+ className +"> query = ALL");
for (String pk : pkSet) {
br.write(".where("+ getFieldName(pk) +".eq("+ getInstanceFieldName(pk) +"))");
}
br.write(";\n");
if (!pkSet.isEmpty()) {
br.write("\t\tif (__NOSCO_CALLBACK_INSERT_PRE!=null) "
+ "try { __NOSCO_CALLBACK_INSERT_PRE.invoke(null, this); }"
+ "catch (IllegalAccessException e) { e.printStackTrace(); } "
+ "catch (InvocationTargetException e) { e.printStackTrace(); }\n");
}
br.write("\t\tMap<Field<?>,Object> updates = new HashMap<Field<?>,Object>();\n");
for (String column : columns.keySet()) {
- br.write("\t\tif (__NOSCO_UPDATED_VALUES.get("+ getFieldName(column) +".INDEX)) {\n");
- br.write("\t\t\tupdates.put("+ getFieldName(column) +", "+ getInstanceFieldName(column) +");\n");
- br.write("\t\t}\n");
+ br.write("\t\tupdates.put("+ getFieldName(column) +", "+ getInstanceFieldName(column) +");\n");
}
br.write("\t\tquery = query.set(updates);\n");
br.write("\t\t\tquery.insert();\n");
br.write("\t\t\tif (__NOSCO_CALLBACK_INSERT_POST!=null) "
+ "try { __NOSCO_CALLBACK_INSERT_POST.invoke(null, this); }"
+ "catch (IllegalAccessException e) { e.printStackTrace(); } "
+ "catch (InvocationTargetException e) { e.printStackTrace(); }\n");
br.write("\t\t\treturn true;\n");
br.write("\t}\n");
// write callbacks
br.write("\tprivate static Method __NOSCO_CALLBACK_INSERT_PRE = null;\n");
br.write("\tprivate static Method __NOSCO_CALLBACK_INSERT_POST = null;\n");
br.write("\tprivate static Method __NOSCO_CALLBACK_UPDATE_PRE = null;\n");
br.write("\tprivate static Method __NOSCO_CALLBACK_UPDATE_POST = null;\n");
br.write("\tstatic {\n");
br.write("\t\ttry {\n\t\t\t __NOSCO_CALLBACK_INSERT_PRE = Class.forName(\""+ callbackPackage
+"."+ schema +"."+ className +"CB\").getMethod(\"preInsert\", "
+ className +".class);\n\t\t} catch (Exception e) { /* ignore */ }\n");
br.write("\t\ttry {\n\t\t\t __NOSCO_CALLBACK_INSERT_POST = Class.forName(\""+ callbackPackage
+"."+ schema +"."+ className +"CB\").getMethod(\"postInsert\", "
+ className +".class);\n\t\t} catch (Exception e) { /* ignore */ }\n");
br.write("\t\ttry {\n\t\t\t __NOSCO_CALLBACK_UPDATE_PRE = Class.forName(\""+ callbackPackage
+"."+ schema +"."+ className +"CB\").getMethod(\"preUpdate\", "
+ className +".class);\n\t\t} catch (Exception e) { /* ignore */ }\n");
br.write("\t\ttry {\n\t\t\t __NOSCO_CALLBACK_UPDATE_POST = Class.forName(\""+ callbackPackage
+"."+ schema +"."+ className +"CB\").getMethod(\"postUpdate\", "
+ className +".class);\n\t\t} catch (Exception e) { /* ignore */ }\n");
br.write("\t\t\n");
br.write("\t\t\n");
//callbackPackage;
br.write("\t}\n");
// end class
br.write("}\n");
br.close();
}
private static String getInstanceFieldName(String column) {
if ("class".equals(column)) column = "JAVA_KEYWORD_class";
if ("for".equals(column)) column = "JAVA_KEYWORD_for";
column = column.replace("-", "_DASH_");
return underscoreToCamelCase(column, false);
}
private static String getInstanceMethodName(String column) {
if ("class".equals(column)) column = "JAVA_KEYWORD_class";
column = column.replace("-", "_DASH_");
return underscoreToCamelCase(column, true);
}
private String genFKName(Set<String> columns, String referencedTable) {
for(String column : columns) {
column = column.toUpperCase();
referencedTable = referencedTable.toUpperCase();
if (column.endsWith("_ID")) column = column.substring(0,column.length()-3);
if (referencedTable.startsWith(column)) {
return dePlural(referencedTable).toUpperCase();
} else {
return dePlural(column +"_"+ referencedTable).toUpperCase();
}
}
return null;
}
private String genFKMethodName(Set<String> columns, String referencedTable) {
return this.underscoreToCamelCase(columns, true)+"FK";
//return genTableClassName(genFKName(columns, referencedTable));
}
private String genTableClassName(String table) {
for (String prefix : stripPrefixes) {
if (table.startsWith(prefix)) {
table = table.substring(prefix.length());
break;
}
}
/*for (String suffix : stripSuffixes) {
if (table.endsWith(suffix)) {
table = table.substring(0,table.length()-suffix.length());
break;
}
} //*/
return underscoreToCamelCase(dePlural(table), true);
}
private String dePlural(String s) {
s = s.toLowerCase();
if (s.endsWith("series"));
else if (s.endsWith("us"));
else if (s.endsWith("is"));
else if (s.endsWith("as"));
else if (s.endsWith("ies")) s = s.substring(0,s.length()-3)+"y";
else if (s.endsWith("s")) s = s.substring(0,s.length()-1);
return s;
}
private Class<? extends Object> getFieldType(String type) {
if ("varchar".equals(type)) return String.class;
if ("char".equals(type)) return Character.class;
if ("nvarchar".equals(type)) return String.class;
if ("nchar".equals(type)) return String.class;
if ("longtext".equals(type)) return String.class;
if ("text".equals(type)) return String.class;
if ("tinytext".equals(type)) return String.class;
if ("mediumtext".equals(type)) return String.class;
if ("ntext".equals(type)) return String.class;
if ("xml".equals(type)) return String.class;
if ("int".equals(type)) return Integer.class;
if ("mediumint".equals(type)) return Integer.class;
if ("smallint".equals(type)) return Integer.class;
if ("tinyint".equals(type)) return Integer.class;
if ("bigint".equals(type)) return Long.class;
if ("decimal".equals(type)) return Double.class;
if ("money".equals(type)) return Double.class;
if ("numeric".equals(type)) return Double.class;
if ("float".equals(type)) return Double.class;
if ("real".equals(type)) return Float.class;
if ("blob".equals(type)) return Blob.class;
if ("longblob".equals(type)) return Blob.class;
if ("datetime".equals(type)) return Timestamp.class;
if ("date".equals(type)) return Date.class;
if ("timestamp".equals(type)) return Timestamp.class;
if ("year".equals(type)) return Integer.class;
if ("enum".equals(type)) return Integer.class;
if ("set".equals(type)) return String.class;
if ("bit".equals(type)) return Boolean.class;
if ("binary".equals(type)) return java.sql.Blob.class;
if ("varbinary".equals(type)) return java.sql.Blob.class;
if ("sql_variant".equals(type)) return Object.class;
if ("smalldatetime".equals(type)) return Timestamp.class;
if ("uniqueidentifier".equals(type)) return String.class;
if ("image".equals(type)) return java.sql.Blob.class;
System.err.println("unknown field type: "+ type);
return null;
}
private static String underscoreToCamelCase(String s, boolean capitalizeFirstChar) {
if (s==null) return null;
if (s.length()==0) return s;
s = s.toLowerCase();
s = s.replace(' ', '_').replace("%", "_PERCENT");
char[] c = s.toCharArray();
if (capitalizeFirstChar) {
c[0] = Character.toUpperCase(c[0]);
}
for (int i=1; i<c.length; ++i) {
if (c[i-1]=='_') {
c[i] = Character.toUpperCase(c[i]);
}
}
return new String(c).replaceAll("_", "");
}
private static String underscoreToCamelCase(Collection<String> strings, boolean capitalizeFirstChar) {
StringBuffer sb = new StringBuffer();
for (String s : strings) {
sb.append(underscoreToCamelCase(s, capitalizeFirstChar));
capitalizeFirstChar = true;
}
return sb.toString();
}
}
| true | true | private void generate(String schema, String table, JSONObject columns, JSONArray pks,
List<FK> fks, List<FK> fksIn, String dataSourceName, String callbackPackage)
throws IOException, JSONException {
String className = genTableClassName(table);
Set<String> pkSet = new HashSet<String>();
if (pks == null) pks = new JSONArray();
for (int i=0; i<pks.length(); ++i) {
pkSet.add(pks.getString(i));
}
int fieldCount = columns.keySet().size();
String pkgDir = Misc.join("/", pkg.split("[.]"));
new File(Misc.join("/", dir, pkgDir, schema)).mkdirs();
File file = new File(Misc.join("/", dir, pkgDir, schema, className+".java"));
System.out.println("writing: "+ file.getAbsolutePath());
BufferedWriter br = new BufferedWriter(new FileWriter(file));
br.write("package "+ pkg +"."+ schema +";\n\n");
br.write("import java.lang.reflect.Method;\n");
br.write("import java.lang.reflect.InvocationTargetException;\n");
br.write("import java.sql.SQLException;\n");
br.write("import java.util.Map;\n\n");
br.write("import java.util.HashMap;\n\n");
br.write("import org.nosco.Field;\n");
br.write("import org.nosco.Query;\n");
br.write("import org.nosco.QueryFactory;\n");
br.write("import org.nosco.Table;\n");
br.write("\n");
br.write("public class "+ className +" extends Table {\n\n");
// write field constants
int index = 0;
for (String column : columns.keySet()) {
br.write("\tpublic static final Field<");
br.write(getFieldType(columns.getString(column)).getName());
br.write("> "+ getFieldName(column));
br.write(" = new Field<"+ getFieldType(columns.getString(column)).getName());
br.write(">("+ index +", "+ className +".class, \""+ column);
br.write("\", "+ getFieldType(columns.getString(column)).getName() +".class");
br.write(");\n");
++index;
}
br.write("\n");
// write primary keys
br.write("\tpublic static Field.PK PK = new Field.PK(");
for (int i=0; i<pks.length(); ++i) {
br.write(pks.getString(i).toUpperCase());
if (i<pks.length()-1) br.write(", ");
}
br.write(");\n");
br.write("\tpublic org.nosco.Field.PK PK() { return PK; }\n\n");
// write foreign keys
for (FK fk : fks) {
String referencedTable = fk.reffed[1];
String referencedTableClassName = genTableClassName(referencedTable);
if (!schema.equals(fk.reffed[0])) {
referencedTableClassName = pkg +"."+ fk.reffed[0] +"."+ referencedTableClassName;
}
String fkName = genFKName(fk.columns.keySet(), referencedTable);
br.write("\tpublic static final Field.FK FK_"+ fkName);
br.write(" = new Field.FK("+ index +", "+ className +".class, ");
br.write(referencedTableClassName +".class");
for (Entry<String, String> e : fk.columns.entrySet()) {
br.write(", "+ e.getKey().toUpperCase());
}
for (Entry<String, String> e : fk.columns.entrySet()) {
br.write(", "+ referencedTableClassName +".");
br.write(e.getValue().toUpperCase());
}
br.write(");\n");
++index;
}
br.write("\n");
// write field value references
for (String column : columns.keySet()) {
br.write("\tprivate "+ getFieldType(columns.getString(column)).getName());
br.write(" "+ getInstanceFieldName(column) + " = null;\n");
}
br.write("\n");
// write constructors
br.write("\tpublic "+ className +"() {}\n\n");
br.write("\t@SuppressWarnings(\"rawtypes\")\n");
br.write("\tprotected "+ className +"(Field[] fields, Object[] objects, int start, int end) {\n");
br.write("\t\tif (fields.length != objects.length)\n\t\t\tthrow new IllegalArgumentException(");
br.write("\"fields.length != objects.length => \"+ fields.length +\" != \"+ objects.length");
br.write(" +\"\");\n");
br.write("\t\tfor (int i=start; i<end; ++i) {\n");
for (String column : columns.keySet()) {
br.write("\t\t\tif (fields[i]=="+ getFieldName(column) +") {\n");
br.write("\t\t\t\t"+ getInstanceFieldName(column) +" = (");
br.write(getFieldType(columns.getString(column)).getName());
br.write(") objects[i];\n");
br.write("\t\t\t\t__NOSCO_FETCHED_VALUES.set("+ getFieldName(column) +".INDEX);\n");
br.write("\t\t\t\tcontinue;\n");
br.write("\t\t\t}\n");
}
br.write("\t\t}\n\t}\n\n");
// write abstract method impls
br.write("\tpublic String SCHEMA_NAME() {\n\t\treturn \""+ schema +"\";\n\t}\n\n");
br.write("\tpublic String TABLE_NAME() {\n\t\treturn \""+ table +"\";\n\t}\n\n");
br.write("\t@SuppressWarnings(\"rawtypes\")\n");
br.write("\tpublic Field[] FIELDS() {\n\t\tField[] fields = {");
for (String column : columns.keySet()) {
br.write(getFieldName(column)+",");
}
br.write("};\n\t\treturn fields;\n\t}\n\n");
br.write("\t@SuppressWarnings(\"rawtypes\")\n");
br.write("\tpublic Field.FK[] FKS() {\n\t\tField.FK[] fields = {");
for (FK fk : fks) {
String referencedTable = fk.reffed[1];
// if (!schema.equals(fk.reffed[0])) {
// referencedTable = fk.reffed[0] +"_"+ referencedTable;
// }
br.write("FK_" + genFKName(fk.columns.keySet(), referencedTable) + ",");
}
br.write("};\n\t\treturn fields;\n\t}\n\n");
//br.write("\tpublic Field[] GET_PRIMARY_KEY_FIELDS() {\n\t\tField[] fields = {");
//for (int i=0; i<pks.length(); ++i) {
// br.write(pks.getString(i).toUpperCase()+",");
//}
//br.write("};\n\t\treturn fields;\n\t}\n\n");
br.write("\tpublic static final Query<"+ className +"> ALL = QueryFactory.IT.getQuery("
+ className +".class).use("+ pkg +"."+ dataSourceName +"."+ schema.toUpperCase() +");\n\n");
// write toString
br.write("\t public String toString() {\n");
br.write("\t\treturn \"["+ className);
for (int i=0; i<pks.length(); ++i) {
String pk = pks.getString(i);
br.write(" "+ pk+":");
br.write("\"+"+ getInstanceFieldName(pk));
br.write("+\"");
}
br.write("]\";\n");
br.write("\t}\n\n");
// write getters and setters
for (String column : columns.keySet()) {
//boolean skipColumn = false;
//for (FK fk : fks) {
// if (fk.columns.containsKey(column)) skipColumn = true;
//}
//if (skipColumn) continue;
String cls = getFieldType(columns.getString(column)).getName();
br.write("\tpublic "+ cls +" get"+ getInstanceMethodName(column) +"() {\n");
br.write("\t\tif (!__NOSCO_FETCHED_VALUES.get("+ getFieldName(column) +".INDEX)) {\n");
br.write("\t\t\t"+ getInstanceFieldName(column) +" = ALL.onlyFields(");
br.write(getFieldName(column)+")");
for (String pk : pkSet) {
br.write(".where("+ getFieldName(pk) +".eq("+ getInstanceFieldName(pk) +"))");
}
br.write(".getTheOnly().get"+ getInstanceMethodName(column) +"();\n");
br.write("\t\t\t__NOSCO_FETCHED_VALUES.set("+ getFieldName(column) +".INDEX);\n");
br.write("\t\t}\n");
br.write("\t\treturn "+ getInstanceFieldName(column) +";\n\t}\n\n");
//if (!pkSet.contains(column)) {
br.write("\tpublic "+ className +" set"+ getInstanceMethodName(column));
br.write("("+ cls +" v) {\n");
br.write("\t\t"+ getInstanceFieldName(column) +" = v;\n");
br.write("\t\tif (__NOSCO_UPDATED_VALUES == null) __NOSCO_UPDATED_VALUES = new java.util.BitSet();\n");
br.write("\t\t__NOSCO_UPDATED_VALUES.set("+ getFieldName(column) +".INDEX);\n");
br.write("\t\treturn this;\n");
br.write("\t}\n\n");
//}
}
// write getters and setters for FKs
for (FK fk : fks) {
String referencedSchema = fk.reffed[0];
String referencedTable = fk.reffed[1];
//String referencedColumn = referenced.getString(2);
String referencedTableClassName = genTableClassName(referencedTable);
if (!schema.equals(fk.reffed[0])) {
referencedTableClassName = pkg +"."+ fk.reffed[0] +"."+ referencedTableClassName;
}
String methodName = genFKMethodName(fk.columns.keySet(), referencedTable);
String cachedObjectName = "_NOSCO_FK_"+ underscoreToCamelCase(fk.columns.keySet(), false);
br.write("\tprivate "+ referencedTableClassName +" "+ cachedObjectName +" = null;\n\n");
br.write("\tpublic "+ referencedTableClassName +" get"+ methodName +"() {\n");
br.write("\t\tif (!__NOSCO_FETCHED_VALUES.get(FK_"+ genFKName(fk.columns.keySet(), referencedTable) +".INDEX)) {\n");
br.write("\t\t\t"+ cachedObjectName +" = "+ referencedTableClassName +".ALL");
br.write(".where("+ referencedTableClassName +"."+ getFieldName(fk.columns.values()) +".eq("+ underscoreToCamelCase(fk.columns.keySet(), false) +"))");
br.write(".getTheOnly();\n");
br.write("\t\t\t__NOSCO_FETCHED_VALUES.set(FK_"+ genFKName(fk.columns.keySet(), referencedTable) +".INDEX);\n");
br.write("\t\t}\n");
br.write("\t\treturn "+ cachedObjectName +";\n\t}\n\n");
br.write("\tpublic "+ className +" set"+ methodName +"("+ referencedTableClassName +" v) {\n");
//br.write(" v) {\n\t\tPUT_VALUE(");
br.write("\t\t"+ underscoreToCamelCase(fk.columns.keySet(), false) +" = v.get"+ underscoreToCamelCase(fk.columns.values(), true) +"();\n");
br.write("\t\tif (__NOSCO_UPDATED_VALUES == null) __NOSCO_UPDATED_VALUES = new java.util.BitSet();\n");
br.write("\t\t__NOSCO_UPDATED_VALUES.set("+ getFieldName(fk.columns.keySet()) +".INDEX);\n");
br.write("\t\t"+ cachedObjectName +" = v;\n");
br.write("\t\t__NOSCO_UPDATED_VALUES.set(FK_"+ genFKName(fk.columns.keySet(), referencedTable) +".INDEX);\n");
br.write("\t\treturn this;\n");
br.write("\n\t}\n\n");
}
// write SET_FK
br.write("\tprotected void SET_FK(Field.FK field, Object v) {\n");
br.write("\t\tif (false);\n");
for (FK fk : fks) {
String cachedObjectName = "_NOSCO_FK_"+ underscoreToCamelCase(fk.columns.keySet(), false);
String referencedTable = fk.reffed[1];
String referencedTableClassName = genTableClassName(referencedTable);
if (!schema.equals(fk.reffed[0])) {
referencedTableClassName = pkg +"."+ fk.reffed[0] +"."+ referencedTableClassName;
}
br.write("\t\telse if (field == FK_"+ genFKName(fk.columns.keySet(), referencedTable) +") {\n");
br.write("\t\t\t"+ cachedObjectName +" = ("+ referencedTableClassName +") v;\n");
br.write("\t\t\t__NOSCO_FETCHED_VALUES.set(FK_"+ genFKName(fk.columns.keySet(), referencedTable) +".INDEX);\n");
br.write("\t\t}\n");
}
br.write("\t\telse {throw new RuntimeException(\"unknown FK\");}\n");
br.write("\t}\n\n");
for (FK fk : fksIn) {
String relatedSchema = fk.reffing[0];
String relatedTable = fk.reffing[1];
String relatedTableClassName = this.genTableClassName(relatedTable);
//String method = genFKMethodName(fk.columns.keySet(), relatedTableClassName);
String method = relatedTableClassName;
if (!schema.equals(fk.reffing[0])) {
relatedTableClassName = pkg +"."+ fk.reffing[0] +"."+ relatedTableClassName;
}
for (String s : fk.columns.keySet()) method += "_" + s;
method = getInstanceMethodName(method);
br.write("\tpublic Query<"+ relatedTableClassName +"> get"+ method +"Set() ");
br.write("{\n\t\treturn "+ relatedTableClassName +".ALL");
for (Entry<String, String> e : fk.columns.entrySet()) {
String relatedColumn = e.getKey();
String column = e.getValue();
br.write(".where("+ relatedTableClassName +"."+ getFieldName(relatedColumn) +".eq(get"+ getInstanceMethodName(column) +"()))");
}
br.write(";\n\t}\n\n");
}
// write save function
br.write("\t@SuppressWarnings(\"rawtypes\")\n");
br.write("\tpublic boolean save() throws SQLException {\n");
br.write("\t\tif (!dirty()) return false;\n");
br.write("\t\tQuery<"+ className +"> query = ALL");
for (String pk : pkSet) {
br.write(".where("+ getFieldName(pk) +".eq("+ getInstanceFieldName(pk) +"))");
}
br.write(";\n");
if (!pkSet.isEmpty()) {
br.write("\t\tif (");
List<String> pkList = new ArrayList<String>(pkSet);
for (int i=0; i<pkList.size(); ++i) {
br.write(getInstanceFieldName(pkList.get(i)) +" == null");
if (i<pkList.size()-1) br.write(" || ");
}
br.write(") {\n");
br.write("} else {\n");
br.write("\t\t\tif (__NOSCO_CALLBACK_UPDATE_PRE!=null) "
+ "try { __NOSCO_CALLBACK_UPDATE_PRE.invoke(null, this); }"
+ "catch (IllegalAccessException e) { e.printStackTrace(); } "
+ "catch (InvocationTargetException e) { e.printStackTrace(); }\n");
br.write("\t\t}\n");
}
br.write("\t\tMap<Field<?>,Object> updates = new HashMap<Field<?>,Object>();\n");
for (String column : columns.keySet()) {
br.write("\t\tif (__NOSCO_UPDATED_VALUES.get("+ getFieldName(column) +".INDEX)) {\n");
br.write("\t\t\tupdates.put("+ getFieldName(column) +", "+ getInstanceFieldName(column) +");\n");
br.write("\t\t}\n");
}
br.write("\t\tquery = query.set(updates);\n");
if (pkSet.isEmpty()) {
br.write("\t\t\tquery.insert();\n\t\treturn true;\n");
} else {
br.write("\t\tif (");
List<String> pkList = new ArrayList<String>(pkSet);
for (int i=0; i<pkList.size(); ++i) {
br.write(getInstanceFieldName(pkList.get(i)) +" == null");
if (i<pkList.size()-1) br.write(" || ");
}
br.write(") {\n");
br.write("\t\t\t"+ getInstanceFieldName(pkList.get(0)) +" = (");
br.write(getFieldType(columns.getString(pkList.get(0))).getName() +") query.insert();\n");
br.write("\t\t\treturn true;\n\t\t} else {\n");
br.write("\t\t\tint count = query.update();\n");
br.write("\t\t\tif (__NOSCO_CALLBACK_UPDATE_POST!=null) "
+ "try { __NOSCO_CALLBACK_UPDATE_POST.invoke(null, this); }"
+ "catch (IllegalAccessException e) { e.printStackTrace(); } "
+ "catch (InvocationTargetException e) { e.printStackTrace(); }\n");
br.write("\t\t\treturn count==1;\n");
br.write("\t\t}\n");
}
br.write("\t}\n");
// write update function
br.write("\t@SuppressWarnings(\"rawtypes\")\n");
br.write("\tpublic boolean update() throws SQLException {\n");
br.write("\t\tif (!dirty()) return false;\n");
br.write("\t\tQuery<"+ className +"> query = ALL");
for (String pk : pkSet) {
br.write(".where("+ getFieldName(pk) +".eq("+ getInstanceFieldName(pk) +"))");
}
br.write(";\n");
br.write("\t\tif (__NOSCO_CALLBACK_UPDATE_PRE!=null) "
+ "try { __NOSCO_CALLBACK_UPDATE_PRE.invoke(null, this); }"
+ "catch (IllegalAccessException e) { e.printStackTrace(); } "
+ "catch (InvocationTargetException e) { e.printStackTrace(); }\n");
br.write("\t\tMap<Field<?>,Object> updates = new HashMap<Field<?>,Object>();\n");
for (String column : columns.keySet()) {
br.write("\t\tif (__NOSCO_UPDATED_VALUES.get("+ getFieldName(column) +".INDEX)) {\n");
br.write("\t\t\tupdates.put("+ getFieldName(column) +", "+ getInstanceFieldName(column) +");\n");
br.write("\t\t}\n");
}
br.write("\t\tquery = query.set(updates);\n");
br.write("\t\tint count = query.update();\n");
br.write("\t\tif (__NOSCO_CALLBACK_UPDATE_POST!=null) "
+ "try { __NOSCO_CALLBACK_UPDATE_POST.invoke(null, this); }"
+ "catch (IllegalAccessException e) { e.printStackTrace(); } "
+ "catch (InvocationTargetException e) { e.printStackTrace(); }\n");
br.write("\t\treturn count==1;\n");
br.write("\t}\n");
// write insert function
br.write("\t@SuppressWarnings(\"rawtypes\")\n");
br.write("\tpublic boolean insert() throws SQLException {\n");
br.write("\t\tif (!dirty()) return false;\n");
br.write("\t\tQuery<"+ className +"> query = ALL");
for (String pk : pkSet) {
br.write(".where("+ getFieldName(pk) +".eq("+ getInstanceFieldName(pk) +"))");
}
br.write(";\n");
if (!pkSet.isEmpty()) {
br.write("\t\tif (__NOSCO_CALLBACK_INSERT_PRE!=null) "
+ "try { __NOSCO_CALLBACK_INSERT_PRE.invoke(null, this); }"
+ "catch (IllegalAccessException e) { e.printStackTrace(); } "
+ "catch (InvocationTargetException e) { e.printStackTrace(); }\n");
}
br.write("\t\tMap<Field<?>,Object> updates = new HashMap<Field<?>,Object>();\n");
for (String column : columns.keySet()) {
br.write("\t\tif (__NOSCO_UPDATED_VALUES.get("+ getFieldName(column) +".INDEX)) {\n");
br.write("\t\t\tupdates.put("+ getFieldName(column) +", "+ getInstanceFieldName(column) +");\n");
br.write("\t\t}\n");
}
br.write("\t\tquery = query.set(updates);\n");
br.write("\t\t\tquery.insert();\n");
br.write("\t\t\tif (__NOSCO_CALLBACK_INSERT_POST!=null) "
+ "try { __NOSCO_CALLBACK_INSERT_POST.invoke(null, this); }"
+ "catch (IllegalAccessException e) { e.printStackTrace(); } "
+ "catch (InvocationTargetException e) { e.printStackTrace(); }\n");
br.write("\t\t\treturn true;\n");
br.write("\t}\n");
// write callbacks
br.write("\tprivate static Method __NOSCO_CALLBACK_INSERT_PRE = null;\n");
br.write("\tprivate static Method __NOSCO_CALLBACK_INSERT_POST = null;\n");
br.write("\tprivate static Method __NOSCO_CALLBACK_UPDATE_PRE = null;\n");
br.write("\tprivate static Method __NOSCO_CALLBACK_UPDATE_POST = null;\n");
br.write("\tstatic {\n");
br.write("\t\ttry {\n\t\t\t __NOSCO_CALLBACK_INSERT_PRE = Class.forName(\""+ callbackPackage
+"."+ schema +"."+ className +"CB\").getMethod(\"preInsert\", "
+ className +".class);\n\t\t} catch (Exception e) { /* ignore */ }\n");
br.write("\t\ttry {\n\t\t\t __NOSCO_CALLBACK_INSERT_POST = Class.forName(\""+ callbackPackage
+"."+ schema +"."+ className +"CB\").getMethod(\"postInsert\", "
+ className +".class);\n\t\t} catch (Exception e) { /* ignore */ }\n");
br.write("\t\ttry {\n\t\t\t __NOSCO_CALLBACK_UPDATE_PRE = Class.forName(\""+ callbackPackage
+"."+ schema +"."+ className +"CB\").getMethod(\"preUpdate\", "
+ className +".class);\n\t\t} catch (Exception e) { /* ignore */ }\n");
br.write("\t\ttry {\n\t\t\t __NOSCO_CALLBACK_UPDATE_POST = Class.forName(\""+ callbackPackage
+"."+ schema +"."+ className +"CB\").getMethod(\"postUpdate\", "
+ className +".class);\n\t\t} catch (Exception e) { /* ignore */ }\n");
br.write("\t\t\n");
br.write("\t\t\n");
//callbackPackage;
br.write("\t}\n");
// end class
br.write("}\n");
br.close();
}
| private void generate(String schema, String table, JSONObject columns, JSONArray pks,
List<FK> fks, List<FK> fksIn, String dataSourceName, String callbackPackage)
throws IOException, JSONException {
String className = genTableClassName(table);
Set<String> pkSet = new HashSet<String>();
if (pks == null) pks = new JSONArray();
for (int i=0; i<pks.length(); ++i) {
pkSet.add(pks.getString(i));
}
int fieldCount = columns.keySet().size();
String pkgDir = Misc.join("/", pkg.split("[.]"));
new File(Misc.join("/", dir, pkgDir, schema)).mkdirs();
File file = new File(Misc.join("/", dir, pkgDir, schema, className+".java"));
System.out.println("writing: "+ file.getAbsolutePath());
BufferedWriter br = new BufferedWriter(new FileWriter(file));
br.write("package "+ pkg +"."+ schema +";\n\n");
br.write("import java.lang.reflect.Method;\n");
br.write("import java.lang.reflect.InvocationTargetException;\n");
br.write("import java.sql.SQLException;\n");
br.write("import java.util.Map;\n\n");
br.write("import java.util.HashMap;\n\n");
br.write("import org.nosco.Field;\n");
br.write("import org.nosco.Query;\n");
br.write("import org.nosco.QueryFactory;\n");
br.write("import org.nosco.Table;\n");
br.write("\n");
br.write("public class "+ className +" extends Table {\n\n");
// write field constants
int index = 0;
for (String column : columns.keySet()) {
br.write("\tpublic static final Field<");
br.write(getFieldType(columns.getString(column)).getName());
br.write("> "+ getFieldName(column));
br.write(" = new Field<"+ getFieldType(columns.getString(column)).getName());
br.write(">("+ index +", "+ className +".class, \""+ column);
br.write("\", "+ getFieldType(columns.getString(column)).getName() +".class");
br.write(");\n");
++index;
}
br.write("\n");
// write primary keys
br.write("\tpublic static Field.PK PK = new Field.PK(");
for (int i=0; i<pks.length(); ++i) {
br.write(pks.getString(i).toUpperCase());
if (i<pks.length()-1) br.write(", ");
}
br.write(");\n");
br.write("\tpublic org.nosco.Field.PK PK() { return PK; }\n\n");
// write foreign keys
for (FK fk : fks) {
String referencedTable = fk.reffed[1];
String referencedTableClassName = genTableClassName(referencedTable);
if (!schema.equals(fk.reffed[0])) {
referencedTableClassName = pkg +"."+ fk.reffed[0] +"."+ referencedTableClassName;
}
String fkName = genFKName(fk.columns.keySet(), referencedTable);
br.write("\tpublic static final Field.FK FK_"+ fkName);
br.write(" = new Field.FK("+ index +", "+ className +".class, ");
br.write(referencedTableClassName +".class");
for (Entry<String, String> e : fk.columns.entrySet()) {
br.write(", "+ e.getKey().toUpperCase());
}
for (Entry<String, String> e : fk.columns.entrySet()) {
br.write(", "+ referencedTableClassName +".");
br.write(e.getValue().toUpperCase());
}
br.write(");\n");
++index;
}
br.write("\n");
// write field value references
for (String column : columns.keySet()) {
br.write("\tprivate "+ getFieldType(columns.getString(column)).getName());
br.write(" "+ getInstanceFieldName(column) + " = null;\n");
}
br.write("\n");
// write constructors
br.write("\tpublic "+ className +"() {}\n\n");
br.write("\t@SuppressWarnings(\"rawtypes\")\n");
br.write("\tprotected "+ className +"(Field[] fields, Object[] objects, int start, int end) {\n");
br.write("\t\tif (fields.length != objects.length)\n\t\t\tthrow new IllegalArgumentException(");
br.write("\"fields.length != objects.length => \"+ fields.length +\" != \"+ objects.length");
br.write(" +\"\");\n");
br.write("\t\tfor (int i=start; i<end; ++i) {\n");
for (String column : columns.keySet()) {
br.write("\t\t\tif (fields[i]=="+ getFieldName(column) +") {\n");
br.write("\t\t\t\t"+ getInstanceFieldName(column) +" = (");
br.write(getFieldType(columns.getString(column)).getName());
br.write(") objects[i];\n");
br.write("\t\t\t\t__NOSCO_FETCHED_VALUES.set("+ getFieldName(column) +".INDEX);\n");
br.write("\t\t\t\tcontinue;\n");
br.write("\t\t\t}\n");
}
br.write("\t\t}\n\t}\n\n");
// write abstract method impls
br.write("\tpublic String SCHEMA_NAME() {\n\t\treturn \""+ schema +"\";\n\t}\n\n");
br.write("\tpublic String TABLE_NAME() {\n\t\treturn \""+ table +"\";\n\t}\n\n");
br.write("\t@SuppressWarnings(\"rawtypes\")\n");
br.write("\tpublic Field[] FIELDS() {\n\t\tField[] fields = {");
for (String column : columns.keySet()) {
br.write(getFieldName(column)+",");
}
br.write("};\n\t\treturn fields;\n\t}\n\n");
br.write("\t@SuppressWarnings(\"rawtypes\")\n");
br.write("\tpublic Field.FK[] FKS() {\n\t\tField.FK[] fields = {");
for (FK fk : fks) {
String referencedTable = fk.reffed[1];
// if (!schema.equals(fk.reffed[0])) {
// referencedTable = fk.reffed[0] +"_"+ referencedTable;
// }
br.write("FK_" + genFKName(fk.columns.keySet(), referencedTable) + ",");
}
br.write("};\n\t\treturn fields;\n\t}\n\n");
//br.write("\tpublic Field[] GET_PRIMARY_KEY_FIELDS() {\n\t\tField[] fields = {");
//for (int i=0; i<pks.length(); ++i) {
// br.write(pks.getString(i).toUpperCase()+",");
//}
//br.write("};\n\t\treturn fields;\n\t}\n\n");
br.write("\tpublic static final Query<"+ className +"> ALL = QueryFactory.IT.getQuery("
+ className +".class).use("+ pkg +"."+ dataSourceName +"."+ schema.toUpperCase() +");\n\n");
// write toString
br.write("\t public String toString() {\n");
br.write("\t\treturn \"["+ className);
for (int i=0; i<pks.length(); ++i) {
String pk = pks.getString(i);
br.write(" "+ pk+":");
br.write("\"+"+ getInstanceFieldName(pk));
br.write("+\"");
}
br.write("]\";\n");
br.write("\t}\n\n");
// write getters and setters
for (String column : columns.keySet()) {
//boolean skipColumn = false;
//for (FK fk : fks) {
// if (fk.columns.containsKey(column)) skipColumn = true;
//}
//if (skipColumn) continue;
String cls = getFieldType(columns.getString(column)).getName();
br.write("\tpublic "+ cls +" get"+ getInstanceMethodName(column) +"() {\n");
br.write("\t\tif (!__NOSCO_FETCHED_VALUES.get("+ getFieldName(column) +".INDEX)) {\n");
br.write("\t\t\t"+ getInstanceFieldName(column) +" = ALL.onlyFields(");
br.write(getFieldName(column)+")");
for (String pk : pkSet) {
br.write(".where("+ getFieldName(pk) +".eq("+ getInstanceFieldName(pk) +"))");
}
br.write(".getTheOnly().get"+ getInstanceMethodName(column) +"();\n");
br.write("\t\t\t__NOSCO_FETCHED_VALUES.set("+ getFieldName(column) +".INDEX);\n");
br.write("\t\t}\n");
br.write("\t\treturn "+ getInstanceFieldName(column) +";\n\t}\n\n");
//if (!pkSet.contains(column)) {
br.write("\tpublic "+ className +" set"+ getInstanceMethodName(column));
br.write("("+ cls +" v) {\n");
br.write("\t\t"+ getInstanceFieldName(column) +" = v;\n");
br.write("\t\tif (__NOSCO_UPDATED_VALUES == null) __NOSCO_UPDATED_VALUES = new java.util.BitSet();\n");
br.write("\t\t__NOSCO_UPDATED_VALUES.set("+ getFieldName(column) +".INDEX);\n");
br.write("\t\treturn this;\n");
br.write("\t}\n\n");
//}
}
// write getters and setters for FKs
for (FK fk : fks) {
String referencedSchema = fk.reffed[0];
String referencedTable = fk.reffed[1];
//String referencedColumn = referenced.getString(2);
String referencedTableClassName = genTableClassName(referencedTable);
if (!schema.equals(fk.reffed[0])) {
referencedTableClassName = pkg +"."+ fk.reffed[0] +"."+ referencedTableClassName;
}
String methodName = genFKMethodName(fk.columns.keySet(), referencedTable);
String cachedObjectName = "_NOSCO_FK_"+ underscoreToCamelCase(fk.columns.keySet(), false);
br.write("\tprivate "+ referencedTableClassName +" "+ cachedObjectName +" = null;\n\n");
br.write("\tpublic "+ referencedTableClassName +" get"+ methodName +"() {\n");
br.write("\t\tif (!__NOSCO_FETCHED_VALUES.get(FK_"+ genFKName(fk.columns.keySet(), referencedTable) +".INDEX)) {\n");
br.write("\t\t\t"+ cachedObjectName +" = "+ referencedTableClassName +".ALL");
br.write(".where("+ referencedTableClassName +"."+ getFieldName(fk.columns.values()) +".eq("+ underscoreToCamelCase(fk.columns.keySet(), false) +"))");
br.write(".getTheOnly();\n");
br.write("\t\t\t__NOSCO_FETCHED_VALUES.set(FK_"+ genFKName(fk.columns.keySet(), referencedTable) +".INDEX);\n");
br.write("\t\t}\n");
br.write("\t\treturn "+ cachedObjectName +";\n\t}\n\n");
br.write("\tpublic "+ className +" set"+ methodName +"("+ referencedTableClassName +" v) {\n");
//br.write(" v) {\n\t\tPUT_VALUE(");
br.write("\t\t"+ underscoreToCamelCase(fk.columns.keySet(), false) +" = v.get"+ underscoreToCamelCase(fk.columns.values(), true) +"();\n");
br.write("\t\tif (__NOSCO_UPDATED_VALUES == null) __NOSCO_UPDATED_VALUES = new java.util.BitSet();\n");
br.write("\t\t__NOSCO_UPDATED_VALUES.set("+ getFieldName(fk.columns.keySet()) +".INDEX);\n");
br.write("\t\t"+ cachedObjectName +" = v;\n");
br.write("\t\t__NOSCO_UPDATED_VALUES.set(FK_"+ genFKName(fk.columns.keySet(), referencedTable) +".INDEX);\n");
br.write("\t\treturn this;\n");
br.write("\n\t}\n\n");
}
// write SET_FK
br.write("\tprotected void SET_FK(Field.FK field, Object v) {\n");
br.write("\t\tif (false);\n");
for (FK fk : fks) {
String cachedObjectName = "_NOSCO_FK_"+ underscoreToCamelCase(fk.columns.keySet(), false);
String referencedTable = fk.reffed[1];
String referencedTableClassName = genTableClassName(referencedTable);
if (!schema.equals(fk.reffed[0])) {
referencedTableClassName = pkg +"."+ fk.reffed[0] +"."+ referencedTableClassName;
}
br.write("\t\telse if (field == FK_"+ genFKName(fk.columns.keySet(), referencedTable) +") {\n");
br.write("\t\t\t"+ cachedObjectName +" = ("+ referencedTableClassName +") v;\n");
br.write("\t\t\t__NOSCO_FETCHED_VALUES.set(FK_"+ genFKName(fk.columns.keySet(), referencedTable) +".INDEX);\n");
br.write("\t\t}\n");
}
br.write("\t\telse {throw new RuntimeException(\"unknown FK\");}\n");
br.write("\t}\n\n");
for (FK fk : fksIn) {
String relatedSchema = fk.reffing[0];
String relatedTable = fk.reffing[1];
String relatedTableClassName = this.genTableClassName(relatedTable);
//String method = genFKMethodName(fk.columns.keySet(), relatedTableClassName);
String method = relatedTableClassName;
if (!schema.equals(fk.reffing[0])) {
relatedTableClassName = pkg +"."+ fk.reffing[0] +"."+ relatedTableClassName;
}
for (String s : fk.columns.keySet()) method += "_" + s;
method = getInstanceMethodName(method);
br.write("\tpublic Query<"+ relatedTableClassName +"> get"+ method +"Set() ");
br.write("{\n\t\treturn "+ relatedTableClassName +".ALL");
for (Entry<String, String> e : fk.columns.entrySet()) {
String relatedColumn = e.getKey();
String column = e.getValue();
br.write(".where("+ relatedTableClassName +"."+ getFieldName(relatedColumn) +".eq(get"+ getInstanceMethodName(column) +"()))");
}
br.write(";\n\t}\n\n");
}
// write save function
br.write("\t@SuppressWarnings(\"rawtypes\")\n");
br.write("\tpublic boolean save() throws SQLException {\n");
br.write("\t\tif (!dirty()) return false;\n");
br.write("\t\tQuery<"+ className +"> query = ALL");
for (String pk : pkSet) {
br.write(".where("+ getFieldName(pk) +".eq("+ getInstanceFieldName(pk) +"))");
}
br.write(";\n");
if (!pkSet.isEmpty()) {
br.write("\t\tif (");
List<String> pkList = new ArrayList<String>(pkSet);
for (int i=0; i<pkList.size(); ++i) {
br.write(getInstanceFieldName(pkList.get(i)) +" == null");
if (i<pkList.size()-1) br.write(" || ");
}
br.write(") {\n");
br.write("} else {\n");
br.write("\t\t\tif (__NOSCO_CALLBACK_UPDATE_PRE!=null) "
+ "try { __NOSCO_CALLBACK_UPDATE_PRE.invoke(null, this); }"
+ "catch (IllegalAccessException e) { e.printStackTrace(); } "
+ "catch (InvocationTargetException e) { e.printStackTrace(); }\n");
br.write("\t\t}\n");
}
br.write("\t\tMap<Field<?>,Object> updates = new HashMap<Field<?>,Object>();\n");
for (String column : columns.keySet()) {
br.write("\t\tif (__NOSCO_UPDATED_VALUES.get("+ getFieldName(column) +".INDEX)) {\n");
br.write("\t\t\tupdates.put("+ getFieldName(column) +", "+ getInstanceFieldName(column) +");\n");
br.write("\t\t}\n");
}
br.write("\t\tquery = query.set(updates);\n");
if (pkSet.isEmpty()) {
br.write("\t\t\tquery.insert();\n\t\treturn true;\n");
} else {
br.write("\t\tif (");
List<String> pkList = new ArrayList<String>(pkSet);
for (int i=0; i<pkList.size(); ++i) {
br.write(getInstanceFieldName(pkList.get(i)) +" == null");
if (i<pkList.size()-1) br.write(" || ");
}
br.write(") {\n");
br.write("\t\t\t"+ getInstanceFieldName(pkList.get(0)) +" = (");
br.write(getFieldType(columns.getString(pkList.get(0))).getName() +") query.insert();\n");
br.write("\t\t\treturn true;\n\t\t} else {\n");
br.write("\t\t\tint count = query.update();\n");
br.write("\t\t\tif (__NOSCO_CALLBACK_UPDATE_POST!=null) "
+ "try { __NOSCO_CALLBACK_UPDATE_POST.invoke(null, this); }"
+ "catch (IllegalAccessException e) { e.printStackTrace(); } "
+ "catch (InvocationTargetException e) { e.printStackTrace(); }\n");
br.write("\t\t\treturn count==1;\n");
br.write("\t\t}\n");
}
br.write("\t}\n");
// write update function
br.write("\t@SuppressWarnings(\"rawtypes\")\n");
br.write("\tpublic boolean update() throws SQLException {\n");
br.write("\t\tif (!dirty()) return false;\n");
br.write("\t\tQuery<"+ className +"> query = ALL");
for (String pk : pkSet) {
br.write(".where("+ getFieldName(pk) +".eq("+ getInstanceFieldName(pk) +"))");
}
br.write(";\n");
br.write("\t\tif (__NOSCO_CALLBACK_UPDATE_PRE!=null) "
+ "try { __NOSCO_CALLBACK_UPDATE_PRE.invoke(null, this); }"
+ "catch (IllegalAccessException e) { e.printStackTrace(); } "
+ "catch (InvocationTargetException e) { e.printStackTrace(); }\n");
br.write("\t\tMap<Field<?>,Object> updates = new HashMap<Field<?>,Object>();\n");
for (String column : columns.keySet()) {
br.write("\t\tif (__NOSCO_UPDATED_VALUES.get("+ getFieldName(column) +".INDEX)) {\n");
br.write("\t\t\tupdates.put("+ getFieldName(column) +", "+ getInstanceFieldName(column) +");\n");
br.write("\t\t}\n");
}
br.write("\t\tquery = query.set(updates);\n");
br.write("\t\tint count = query.update();\n");
br.write("\t\tif (__NOSCO_CALLBACK_UPDATE_POST!=null) "
+ "try { __NOSCO_CALLBACK_UPDATE_POST.invoke(null, this); }"
+ "catch (IllegalAccessException e) { e.printStackTrace(); } "
+ "catch (InvocationTargetException e) { e.printStackTrace(); }\n");
br.write("\t\treturn count==1;\n");
br.write("\t}\n");
// write insert function
br.write("\t@SuppressWarnings(\"rawtypes\")\n");
br.write("\tpublic boolean insert() throws SQLException {\n");
br.write("\t\tif (!dirty()) return false;\n");
br.write("\t\tQuery<"+ className +"> query = ALL");
for (String pk : pkSet) {
br.write(".where("+ getFieldName(pk) +".eq("+ getInstanceFieldName(pk) +"))");
}
br.write(";\n");
if (!pkSet.isEmpty()) {
br.write("\t\tif (__NOSCO_CALLBACK_INSERT_PRE!=null) "
+ "try { __NOSCO_CALLBACK_INSERT_PRE.invoke(null, this); }"
+ "catch (IllegalAccessException e) { e.printStackTrace(); } "
+ "catch (InvocationTargetException e) { e.printStackTrace(); }\n");
}
br.write("\t\tMap<Field<?>,Object> updates = new HashMap<Field<?>,Object>();\n");
for (String column : columns.keySet()) {
br.write("\t\tupdates.put("+ getFieldName(column) +", "+ getInstanceFieldName(column) +");\n");
}
br.write("\t\tquery = query.set(updates);\n");
br.write("\t\t\tquery.insert();\n");
br.write("\t\t\tif (__NOSCO_CALLBACK_INSERT_POST!=null) "
+ "try { __NOSCO_CALLBACK_INSERT_POST.invoke(null, this); }"
+ "catch (IllegalAccessException e) { e.printStackTrace(); } "
+ "catch (InvocationTargetException e) { e.printStackTrace(); }\n");
br.write("\t\t\treturn true;\n");
br.write("\t}\n");
// write callbacks
br.write("\tprivate static Method __NOSCO_CALLBACK_INSERT_PRE = null;\n");
br.write("\tprivate static Method __NOSCO_CALLBACK_INSERT_POST = null;\n");
br.write("\tprivate static Method __NOSCO_CALLBACK_UPDATE_PRE = null;\n");
br.write("\tprivate static Method __NOSCO_CALLBACK_UPDATE_POST = null;\n");
br.write("\tstatic {\n");
br.write("\t\ttry {\n\t\t\t __NOSCO_CALLBACK_INSERT_PRE = Class.forName(\""+ callbackPackage
+"."+ schema +"."+ className +"CB\").getMethod(\"preInsert\", "
+ className +".class);\n\t\t} catch (Exception e) { /* ignore */ }\n");
br.write("\t\ttry {\n\t\t\t __NOSCO_CALLBACK_INSERT_POST = Class.forName(\""+ callbackPackage
+"."+ schema +"."+ className +"CB\").getMethod(\"postInsert\", "
+ className +".class);\n\t\t} catch (Exception e) { /* ignore */ }\n");
br.write("\t\ttry {\n\t\t\t __NOSCO_CALLBACK_UPDATE_PRE = Class.forName(\""+ callbackPackage
+"."+ schema +"."+ className +"CB\").getMethod(\"preUpdate\", "
+ className +".class);\n\t\t} catch (Exception e) { /* ignore */ }\n");
br.write("\t\ttry {\n\t\t\t __NOSCO_CALLBACK_UPDATE_POST = Class.forName(\""+ callbackPackage
+"."+ schema +"."+ className +"CB\").getMethod(\"postUpdate\", "
+ className +".class);\n\t\t} catch (Exception e) { /* ignore */ }\n");
br.write("\t\t\n");
br.write("\t\t\n");
//callbackPackage;
br.write("\t}\n");
// end class
br.write("}\n");
br.close();
}
|
diff --git a/src/main/java/mdettlaff/mobilemachine/controller/HomeController.java b/src/main/java/mdettlaff/mobilemachine/controller/HomeController.java
index ae7295b..ec83e7d 100644
--- a/src/main/java/mdettlaff/mobilemachine/controller/HomeController.java
+++ b/src/main/java/mdettlaff/mobilemachine/controller/HomeController.java
@@ -1,44 +1,43 @@
package mdettlaff.mobilemachine.controller;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import mdettlaff.mobilemachine.domain.SimplifiedWebpage;
import mdettlaff.mobilemachine.service.PageSimplifierService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class HomeController {
private final PageSimplifierService service;
@Autowired
public HomeController(PageSimplifierService service) {
this.service = service;
}
@RequestMapping
public String home() {
return "index";
}
@RequestMapping("/simplified")
public ModelAndView simplified(@RequestParam String url,
@RequestParam(required = false, defaultValue = "1") int page) throws IOException {
SimplifiedWebpage webpage = service.simplify(url);
Map<String, Object> model = new HashMap<String, Object>();
model.put("title", webpage.getTitle());
model.put("html", webpage.getPage(page));
- model.put("currentPage", page);
model.put("nextPage", page == webpage.getPageCount() ? null : page + 1);
model.put("pageCount", webpage.getPageCount());
model.put("url", url);
return new ModelAndView("simplified", model);
}
}
| true | true | public ModelAndView simplified(@RequestParam String url,
@RequestParam(required = false, defaultValue = "1") int page) throws IOException {
SimplifiedWebpage webpage = service.simplify(url);
Map<String, Object> model = new HashMap<String, Object>();
model.put("title", webpage.getTitle());
model.put("html", webpage.getPage(page));
model.put("currentPage", page);
model.put("nextPage", page == webpage.getPageCount() ? null : page + 1);
model.put("pageCount", webpage.getPageCount());
model.put("url", url);
return new ModelAndView("simplified", model);
}
| public ModelAndView simplified(@RequestParam String url,
@RequestParam(required = false, defaultValue = "1") int page) throws IOException {
SimplifiedWebpage webpage = service.simplify(url);
Map<String, Object> model = new HashMap<String, Object>();
model.put("title", webpage.getTitle());
model.put("html", webpage.getPage(page));
model.put("nextPage", page == webpage.getPageCount() ? null : page + 1);
model.put("pageCount", webpage.getPageCount());
model.put("url", url);
return new ModelAndView("simplified", model);
}
|
diff --git a/src/republicaEternityEventIII/republica/devteam/EternityCommandExecutor.java b/src/republicaEternityEventIII/republica/devteam/EternityCommandExecutor.java
index 69f09b6..c77c68d 100644
--- a/src/republicaEternityEventIII/republica/devteam/EternityCommandExecutor.java
+++ b/src/republicaEternityEventIII/republica/devteam/EternityCommandExecutor.java
@@ -1,135 +1,136 @@
package republicaEternityEventIII.republica.devteam;
import java.util.Random;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class EternityCommandExecutor implements CommandExecutor{
private String puppetmaster;
private Ziminiar ziminiar;
private EternityMain em;
private CommandSender lastCS;
private static EternityCommandExecutor INSTANCE = null;
public EternityCommandExecutor(EternityMain em) {
super();
if (INSTANCE != null) {
throw new RuntimeException("Instantiated multiple EternityCommandExecutors");
}
this.em = em;
INSTANCE = this;
}
public static void sendMessageToLastSender(String message) {
INSTANCE.lastCS.sendMessage(message);
}
@Override
public boolean onCommand(CommandSender cs, Command c, String l, String[] args) {
lastCS = cs;
if(c.getLabel().equalsIgnoreCase("Ziminiar")){
if(cs.isOp()){
if (args.length == 1) {
puppetmaster = args[0];
//Code to change player into Ziminiar here
ziminiar = new Ziminiar(getPlayerByNameOf(puppetmaster), em);
setZiminiarInMain(ziminiar);
return true;
}
}
}
if(c.getLabel().equalsIgnoreCase("nerf")){
if(cs.isOp()){
if (args.length == 1) {
String status = args[0];
Ziminiar.cooldownEnabled = Boolean.parseBoolean(status);
return true;
}
}
}
if (c.getLabel().equalsIgnoreCase("setResultsSign")) {
if (cs.isOp()) {
SignPunchingOMatic.change();
cs.sendMessage("Punch a sign to set it.");
}
}
if (c.getLabel().equalsIgnoreCase("TestSFX")) {
if (cs.isOp()) {
SoundEffectsManager.playSpawnSound(((Player) cs).getLocation());
return true;
}
}
if (c.getLabel().equalsIgnoreCase("AddTestData")) {
if (cs.isOp()) {
MagicalStorage.incrementPlayerScore(cs.getName(), 1337);
MagicalStorage.incrementPlayerScore("AnotherPlayer", 19);
MagicalStorage.incrementPlayerScore("OneMorePlayer", 21);
return true;
}
}
if (c.getLabel().equalsIgnoreCase("getBook")) {
if (cs.isOp()) {
EternityItems.loadResults();
((Player) cs).getInventory().addItem(EternityItems.getResultsBook());
return true;
}
}
if (c.getLabel().equalsIgnoreCase("saveResults")) {
if (cs.isOp()) {
EternityItems.saveResults();
return true;
}
}
if(c.getLabel().equalsIgnoreCase("Caesar")){
if(cs.isOp()){
cs.sendMessage("Books begin to fall!");
Random rand = new Random();
int temp = rand.nextInt(4);
+ int temp2;
Player[] players = em.getServer().getOnlinePlayers();
for(int i = 0; i < temp && i < players.length; i++){
- int temp2 = rand.nextInt(players.length) - 1;
+ temp2 = rand.nextInt(players.length) - 1;
Player player = players[temp2];
cs.sendMessage("A book was sent to "+ player.getDisplayName() + ".");
player.sendMessage(ChatColor.GREEN + "A book falls from the sky.");
Location l1 = player.getLocation();
l1.add(2, 5, 0);
player.getWorld().dropItemNaturally(l1, EternityItems.caesarBook());
}
return true;
}
}
return false;
}
private Player getPlayerByNameOf(String s){
return em.getPlayer(s);
}
private void setZiminiarInMain(Ziminiar zz){
passZiminiarToMain(zz);
em.ZiminiarPlayer(getPlayerByNameOf(puppetmaster));
}
private void passZiminiarToMain(Ziminiar zz){
em.ziminiarClass(zz);
}
}
| false | true | public boolean onCommand(CommandSender cs, Command c, String l, String[] args) {
lastCS = cs;
if(c.getLabel().equalsIgnoreCase("Ziminiar")){
if(cs.isOp()){
if (args.length == 1) {
puppetmaster = args[0];
//Code to change player into Ziminiar here
ziminiar = new Ziminiar(getPlayerByNameOf(puppetmaster), em);
setZiminiarInMain(ziminiar);
return true;
}
}
}
if(c.getLabel().equalsIgnoreCase("nerf")){
if(cs.isOp()){
if (args.length == 1) {
String status = args[0];
Ziminiar.cooldownEnabled = Boolean.parseBoolean(status);
return true;
}
}
}
if (c.getLabel().equalsIgnoreCase("setResultsSign")) {
if (cs.isOp()) {
SignPunchingOMatic.change();
cs.sendMessage("Punch a sign to set it.");
}
}
if (c.getLabel().equalsIgnoreCase("TestSFX")) {
if (cs.isOp()) {
SoundEffectsManager.playSpawnSound(((Player) cs).getLocation());
return true;
}
}
if (c.getLabel().equalsIgnoreCase("AddTestData")) {
if (cs.isOp()) {
MagicalStorage.incrementPlayerScore(cs.getName(), 1337);
MagicalStorage.incrementPlayerScore("AnotherPlayer", 19);
MagicalStorage.incrementPlayerScore("OneMorePlayer", 21);
return true;
}
}
if (c.getLabel().equalsIgnoreCase("getBook")) {
if (cs.isOp()) {
EternityItems.loadResults();
((Player) cs).getInventory().addItem(EternityItems.getResultsBook());
return true;
}
}
if (c.getLabel().equalsIgnoreCase("saveResults")) {
if (cs.isOp()) {
EternityItems.saveResults();
return true;
}
}
if(c.getLabel().equalsIgnoreCase("Caesar")){
if(cs.isOp()){
cs.sendMessage("Books begin to fall!");
Random rand = new Random();
int temp = rand.nextInt(4);
Player[] players = em.getServer().getOnlinePlayers();
for(int i = 0; i < temp && i < players.length; i++){
int temp2 = rand.nextInt(players.length) - 1;
Player player = players[temp2];
cs.sendMessage("A book was sent to "+ player.getDisplayName() + ".");
player.sendMessage(ChatColor.GREEN + "A book falls from the sky.");
Location l1 = player.getLocation();
l1.add(2, 5, 0);
player.getWorld().dropItemNaturally(l1, EternityItems.caesarBook());
}
return true;
}
}
return false;
}
| public boolean onCommand(CommandSender cs, Command c, String l, String[] args) {
lastCS = cs;
if(c.getLabel().equalsIgnoreCase("Ziminiar")){
if(cs.isOp()){
if (args.length == 1) {
puppetmaster = args[0];
//Code to change player into Ziminiar here
ziminiar = new Ziminiar(getPlayerByNameOf(puppetmaster), em);
setZiminiarInMain(ziminiar);
return true;
}
}
}
if(c.getLabel().equalsIgnoreCase("nerf")){
if(cs.isOp()){
if (args.length == 1) {
String status = args[0];
Ziminiar.cooldownEnabled = Boolean.parseBoolean(status);
return true;
}
}
}
if (c.getLabel().equalsIgnoreCase("setResultsSign")) {
if (cs.isOp()) {
SignPunchingOMatic.change();
cs.sendMessage("Punch a sign to set it.");
}
}
if (c.getLabel().equalsIgnoreCase("TestSFX")) {
if (cs.isOp()) {
SoundEffectsManager.playSpawnSound(((Player) cs).getLocation());
return true;
}
}
if (c.getLabel().equalsIgnoreCase("AddTestData")) {
if (cs.isOp()) {
MagicalStorage.incrementPlayerScore(cs.getName(), 1337);
MagicalStorage.incrementPlayerScore("AnotherPlayer", 19);
MagicalStorage.incrementPlayerScore("OneMorePlayer", 21);
return true;
}
}
if (c.getLabel().equalsIgnoreCase("getBook")) {
if (cs.isOp()) {
EternityItems.loadResults();
((Player) cs).getInventory().addItem(EternityItems.getResultsBook());
return true;
}
}
if (c.getLabel().equalsIgnoreCase("saveResults")) {
if (cs.isOp()) {
EternityItems.saveResults();
return true;
}
}
if(c.getLabel().equalsIgnoreCase("Caesar")){
if(cs.isOp()){
cs.sendMessage("Books begin to fall!");
Random rand = new Random();
int temp = rand.nextInt(4);
int temp2;
Player[] players = em.getServer().getOnlinePlayers();
for(int i = 0; i < temp && i < players.length; i++){
temp2 = rand.nextInt(players.length) - 1;
Player player = players[temp2];
cs.sendMessage("A book was sent to "+ player.getDisplayName() + ".");
player.sendMessage(ChatColor.GREEN + "A book falls from the sky.");
Location l1 = player.getLocation();
l1.add(2, 5, 0);
player.getWorld().dropItemNaturally(l1, EternityItems.caesarBook());
}
return true;
}
}
return false;
}
|
diff --git a/org/lateralgm/joshedit/JoshText.java b/org/lateralgm/joshedit/JoshText.java
index 7638010..b3ede30 100644
--- a/org/lateralgm/joshedit/JoshText.java
+++ b/org/lateralgm/joshedit/JoshText.java
@@ -1,3059 +1,3059 @@
/* Copyright (C) 2011 Josh Ventura <[email protected]>
* Copyright (C) 2011, 2012 IsmAvatar <[email protected]>
*
* This file is part of JoshEdit. JoshEdit is free software.
* You can use, modify, and distribute it under the terms of
* the GNU General Public License, version 3 or later. */
package org.lateralgm.joshedit;
import java.awt.AWTEvent;
import java.awt.Color;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Event;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.EventListener;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.JComponent;
import javax.swing.JViewport;
import javax.swing.KeyStroke;
import javax.swing.Scrollable;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.TransferHandler;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import org.lateralgm.joshedit.FindDialog.FindNavigator;
import org.lateralgm.joshedit.Selection.ST;
import org.lateralgm.joshedit.TokenMarker.TokenMarkerInfo;
/**
* The main component class; instantiate this, and you're good to go.
*/
public class JoshText extends JComponent implements Scrollable,ComponentListener,ClipboardOwner,
FocusListener
{
/** Make the compiler shut up. */
private static final long serialVersionUID = 1L;
/** Any settings which affect the behavior of this JoshText. */
public static class Settings
{
/** True if the tab character is used, false to use spaces */
public static boolean indentUseTabs = true;
/**
* The size with which tab characters are represented, in spaces
* (characters)
*/
public static int indentSizeInSpaces = 8;
/** The string which will be inserted into the code for indentation. */
public static String indentRepString = "\t";
/** True if backspace should clear indentation to tab marks */
public static boolean smartBackspace = true;
/** True if the caret's line is to be highlighted */
public static boolean highlight_line = true;
/** True if tabs should be represented visually. */
public static boolean renderTabs;
}
// Components
/** The code contained in this JoshText; an array of lines. */
Code code;
/** Information about what is selected. */
Selection sel;
/** Information about our caret position */
Caret caret;
/** The listener that will handle text drag-and-drop. */
DragListener dragger;
/** The TokenMarker that will be polled for character formatting. */
private TokenMarker marker;
/**
* All Highlighters which will be called to highlight their lines or
* characters.
*/
public ArrayList<Highlighter> highlighters = new ArrayList<Highlighter>();
// Dimensions
/** The width of the largest UTF-8 character our font contains. */
private int monoAdvance;
/** The height of the largest UTF-8 character our font contains. */
private int lineHeight;
/**
* The largest height above the base line of any UTF-8 character our font
* contains.
*/
private int lineAscent;
/** The distance we need to keep between the baselines of each line of text. */
private int lineLeading;
/** Our longest row, and how many other rows are this long */
private int maxRowSize; // This is the size of the longest row, not the
// index.
/**
* A queue of all messages that need displayed in our status bar.
* There will probably only be one item on this queue at a time.
*/
Queue<String> infoMessages = new LinkedList<String>();
/** Find and Replace Navigator; eg, QuickFind. */
public FindNavigator finder;
/**
* A Highlighter is a class that gets painted before the text
* so as to appear in the background of the characters.
*/
public static interface Highlighter
{
/**
* Called when it is time to render any and all backgrounds for this Highlighter.
*
* @param g
* The graphics object to paint to.
* @param i
* The insets of the canvas.
* @param gm
* The string and glyph metrics for this code.
* @param line_start
* The index of the first visible line.
* @param line_end
* The index of the last visible line.
*/
void paint(Graphics g, Insets i, CodeMetrics gm, int line_start, int line_end);
}
/**
* An interface for passing glyph and string metrics associated with this
* editor.
*/
public static interface CodeMetrics
{
/**
* Get the width of a particular string from its start to a given end
* position.
*
* @param str
* The string whose width will be returned.
* @param end
* The index of the last character to consider in calculating
* the width.
* @return The width of the given range of characters in the given
* string.
*/
int stringWidth(String str, int end);
/**
* Get the width of the line of code with a given index from its start
* to a given end position.
*
* @param line
* The index of the line whose width will be returned.
* @param end
* The index of the last character to consider in calculating
* the width.
* @return The width of the given range of characters in the given
* string.
*/
int lineWidth(int line, int end);
/**
* Get the width of each glyph rendered, which will be the width of the
* largest glyph in the UTF-8 character set.
*
* @return Returns the width each glyph is given.
*/
int glyphWidth();
/**
* @return Returns the height given to each line.
*/
int lineHeight();
}
/** Our own code metric information. */
CodeMetrics metrics = new CodeMetrics()
{
@Override
public int stringWidth(String l, int end)
{
end = Math.min(end,l.length());
int w = 0;
for (int i = 0; i < end; i++)
if (l.charAt(i) == '\t')
{
final int wf = monoAdvance * Settings.indentSizeInSpaces;
w = ((w + wf) / wf) * wf;
}
else
w += monoAdvance;
return w;
}
@Override
public int lineWidth(int y, int end)
{
return stringWidth(code.getsb(y).toString(),end);
}
@Override
public int glyphWidth()
{
return monoAdvance;
}
@Override
public int lineHeight()
{
return lineHeight;
}
};
/**
* Character "type", such as letter (1), whitespace (2), symbol (0), etc.
* Used for word selection and backspacing.
*/
public static final class ChType
{
/** This character is some generic symbol. */
public static final int NONE = 0;
/**
* This character is a word char, which includes underscores and
* numerals.
*/
public static final int WORD = 1;
/** This character is whitespace. */
public static final int WHITE = 2;
}
/** An array of character types by their ordinal. */
private static final char chType[] = new char[256];
static
{
for (int i = 0; i < 256; i++)
chType[i] = ChType.NONE;
for (int i = 'a'; i < 'z'; i++)
chType[i] = ChType.WORD;
for (int i = 'A'; i < 'Z'; i++)
chType[i] = ChType.WORD;
for (int i = '0'; i < '9'; i++)
chType[i] = ChType.WORD;
chType['_'] = ChType.WORD;
chType[' '] = ChType.WHITE;
chType['\t'] = ChType.WHITE;
chType['\r'] = ChType.WHITE;
chType['\n'] = ChType.WHITE;
}
/** Code completion syntax descriptor. */
SyntaxDesc myLang;
/** Default constructor; delegates to JoshText(String[]). */
public JoshText()
{
this(null);
}
/**
* Construct a new JoshText with some code given as a String[] of lines.
*
* @param lines
* An array of Strings; one String for each line.
*/
public JoshText(String[] lines)
{
// Drawing stuff
setPreferredSize(new Dimension(320,240));
setFont(new Font(Font.MONOSPACED,Font.PLAIN,12));
setBackground(Color.WHITE);
setForeground(Color.BLACK);
setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR));
setOpaque(true);
getInsets().left = 4;
setFocusable(true);
focusGained(null);
setFocusTraversalKeysEnabled(false);
setTransferHandler(new JoshTextTransferHandler());
mapActions();
// The mapping of keystrokes and action names
Bindings.readMappings(getInputMap());
// Events
enableEvents(AWTEvent.MOUSE_EVENT_MASK | AWTEvent.MOUSE_MOTION_EVENT_MASK
| AWTEvent.KEY_EVENT_MASK);
// Managing our code
code = new Code();
if (lines == null || lines.length == 0)
code.add(new StringBuilder());
else
for (String line : lines)
code.add(line);
FontMetrics fm = getFontMetrics(getFont());
lineAscent = fm.getAscent();
lineHeight = fm.getHeight();
lineLeading = fm.getLeading();
monoAdvance = fm.getWidths()['M'];
caret = new Caret(this);
sel = new Selection(code,this,caret);
dragger = new DragListener();
myLang = new SyntaxDesc();
myLang.set_language("Shitbag");
if (Settings.highlight_line) highlighters.add(new Highlighter()
{
@Override
public void paint(Graphics g, Insets i, CodeMetrics gm, int line_start, int line_end)
{
if (sel.row == caret.row)
{
Color rc = g.getColor();
g.setColor(new Color(230,240,255));
Rectangle clip = g.getClipBounds();
g.fillRect(i.left + clip.x,i.top + caret.row * gm.lineHeight(),clip.width,gm.lineHeight());
g.setColor(rc);
}
}
});
highlighters.add(sel);
BracketHighlighter bm = new BracketHighlighter();
highlighters.add(bm);
caret.addCaretListener(bm);
caret.addCaretListener(new CaretListener()
{
@Override
public void caretUpdate(CaretEvent e)
{
if (!mas.isRunning()) doShowCaret();
}
});
doCodeSize(true);
}
/**
* Set the contents of this editor from an array of strings.
*
* @param lines
* An array of Strings making up the code, with one String per
* line.
*/
public void setText(String[] lines)
{
code.clear();
if (lines == null || lines.length == 0)
code.add(new StringBuilder());
else
for (String line : lines)
code.add(line);
fireLineChange(0,code.size());
}
/**
* Get the text in this editor as a String[].
*
* @return Return the text in this editor as an array of strings,
* with one element in the array for each line.
*/
public String[] getLines()
{
String res[] = new String[code.size()];
for (int i = 0; i < code.size(); i++)
res[i] = code.get(i).sbuild.toString();
return res;
}
/**
* Get the number of lines in the current code..
*
* @return The number of lines in the current code.
*/
public int getLineCount()
{
return code.size();
}
/**
* Get the text in this editor as a String.
*
* @return Returns the text in this editor as a single string.
*/
public String getText()
{
StringBuilder res = new StringBuilder();
for (int i = 0; i < code.size(); i++)
res.append(code.get(i).sbuild.toString() + "\n");
return res.toString();
}
/**
* Basically like htmlSpecialChars in PHP.
*
* @param x The not HTML-ready string.
* @return The HTML-ready string.
*/
public static String htmlSpecialChars(String x)
{
if (x == null) return "";
x = x.replace("/","/").replace("\\","\");
x = x.replace("&","&").replace("\"",""");
x = x.replace("<","<").replace(">",">");
return x;
}
/**
* Export the current code as HTML.
*
* @return The contents of the editor, with tokens marked up in HTML.
*/
public String getHTML()
{
StringBuilder res = new StringBuilder(code.size() * 100);
for (int i = 0; i < code.size(); i++)
{
Line l = code.get(i);
StringBuilder lsb = l.sbuild;
int from = 0;
ArrayList<TokenMarkerInfo> tmall = marker.getStyles(l);
for (TokenMarkerInfo ti : tmall)
{
if (ti.startPos > from) res.append(htmlSpecialChars(lsb.substring(from,ti.startPos)));
if (ti.startPos < ti.endPos)
{
res.append("<span style=\"");
if ((ti.fontStyle & Font.BOLD) != 0) res.append("font-weight:bold;");
if ((ti.fontStyle & Font.ITALIC) != 0) res.append("font-style:italic;");
if (ti.color != null)
res.append("color:#" + Integer.toHexString(ti.color.getRGB()).substring(2) + ";");
res.append("\">");
res.append(htmlSpecialChars(lsb.substring(ti.startPos,ti.endPos)));
res.append("</span>");
}
from = ti.endPos;
}
res.append("\n");
}
return res.toString();
}
/**
* Applies a TokenMarker that will be polled for character formatting
*
* @param tm
* the TokenMarker to apply
*/
public void setTokenMarker(TokenMarker tm)
{
if (marker != null) removeLineChangeListener(marker);
marker = tm;
addLineChangeListener(marker);
fireLineChange(0,code.size());
}
// ==========================================================
// == Map action names to their implementations =============
// ==========================================================
/** Delete the current line, including the newline character. */
public AbstractAction aLineDel = new AbstractAction("LINEDEL")
{
private static final long serialVersionUID = 1L;
/** @see AbstractAction#actionPerformed(ActionEvent) */
@Override
public void actionPerformed(ActionEvent e)
{
// delete the line where the caret is
}
};
/** Duplicate the current line, placing the copy beneath this one. */
public AbstractAction aLineDup = new AbstractAction("LINEDUP")
{
private static final long serialVersionUID = 1L;
/** @see AbstractAction#actionPerformed(ActionEvent) */
@Override
public void actionPerformed(ActionEvent e)
{
UndoPatch up = new UndoPatch();
up.realize(up.startRow + sel.duplicate());
storeUndo(up,OPT.DUPLICATE);
}
};
/** Swap the currently selected lines, or this line and the line above it. */
public AbstractAction aLineSwap = new AbstractAction("LINESWAP")
{
private static final long serialVersionUID = 1L;
/** @see AbstractAction#actionPerformed(ActionEvent) */
@Override
public void actionPerformed(ActionEvent e)
{
if (caret.row == sel.row)
{
if (caret.row == 0) return;
UndoPatch up = new UndoPatch(caret.row - 1,caret.row);
StringBuilder swb = code.getsb(caret.row - 1);
code.get(caret.row - 1).sbuild = code.get(caret.row).sbuild;
code.get(caret.row).sbuild = swb;
up.realize(caret.row);
storeUndo(up,OPT.SWAP);
if (sel.type != ST.RECT) caret.col = line_offset_from(caret.row,caret.colw);
}
else
{
UndoPatch up = new UndoPatch();
int srow = Math.min(sel.row,caret.row), erow = Math.max(sel.row,caret.row);
StringBuilder swb = code.getsb(srow);
for (int i = srow; i < erow; i++)
code.get(i).sbuild = code.get(i + 1).sbuild;
code.get(erow).sbuild = swb;
up.realize(erow);
if (sel.type != ST.RECT) caret.col = line_offset_from(caret.row,caret.colw);
storeUndo(up,OPT.SWAP);
}
}
};
/** Un-swap the selected lines, or this line and the line below it. */
public AbstractAction aLineUnSwap = new AbstractAction("LINEUNSWAP")
{
private static final long serialVersionUID = 1L;
/** @see AbstractAction#actionPerformed(ActionEvent) */
@Override
public void actionPerformed(ActionEvent e)
{
if (caret.row == sel.row)
{
if (caret.row >= code.size() - 1) return;
UndoPatch up = new UndoPatch(caret.row,caret.row + 1);
StringBuilder swb = code.getsb(caret.row + 1);
code.get(caret.row + 1).sbuild = code.get(caret.row).sbuild;
code.get(caret.row).sbuild = swb;
up.realize(caret.row);
storeUndo(up,OPT.UNSWAP);
if (sel.type != ST.RECT) caret.col = line_offset_from(caret.row,caret.colw);
}
else
{
UndoPatch up = new UndoPatch();
int srow = Math.min(sel.row,caret.row), erow = Math.max(sel.row,caret.row);
StringBuilder swb = code.getsb(erow);
for (int i = erow; i > srow; i--)
code.get(i).sbuild = code.get(i - 1).sbuild;
code.get(srow).sbuild = swb;
up.realize(erow);
storeUndo(up,OPT.UNSWAP);
if (sel.type != ST.RECT) caret.col = line_offset_from(caret.row,caret.colw);
}
}
};
/**
* Select all: Place the caret at the end of the code,
* and start the selection from the beginning.
*/
public AbstractAction aSelAll = new AbstractAction("SELALL")
{
private static final long serialVersionUID = 1L;
/** @see AbstractAction#actionPerformed(ActionEvent) */
@Override
public void actionPerformed(ActionEvent e)
{
sel.row = sel.col = 0;
caret.row = code.size() - 1;
caret.col = code.getsb(caret.row).length();
sel.type = ST.NORM;
sel.selectionChanged();
}
};
/** Copy the contents of the selection to the clipboard. */
public AbstractAction aCopy = new AbstractAction("COPY")
{
private static final long serialVersionUID = 1L;
/** @see AbstractAction#actionPerformed(ActionEvent) */
@Override
public void actionPerformed(ActionEvent e)
{
sel.copy();
}
};
/**
* Cut the contents of the selection, removing them from
* the code and storing them in the clipboard.
*/
public AbstractAction aCut = new AbstractAction("CUT")
{
private static final long serialVersionUID = 1L;
/** @see AbstractAction#actionPerformed(ActionEvent) */
@Override
public void actionPerformed(ActionEvent e)
{
if (sel.isEmpty()) return;
sel.copy();
UndoPatch up = new UndoPatch();
sel.deleteSel();
up.realize(Math.max(caret.row,sel.row));
storeUndo(up,OPT.DELETE);
repaint();
}
};
/**
* Paste the clipboard into the code, overwriting the selection if there is
* one.
*/
public AbstractAction aPaste = new AbstractAction("PASTE")
{
private static final long serialVersionUID = 1L;
/** @see AbstractAction#actionPerformed(ActionEvent) */
@Override
public void actionPerformed(ActionEvent e)
{
UndoPatch up = new UndoPatch(Math.min(caret.row,sel.row),Math.max(
Math.max(caret.row,sel.row),
Math.min(code.size() - 1,Math.min(caret.row,sel.row) + sel.getPasteRipple() - 1)));
up.realize(sel.paste());
storeUndo(up,OPT.PASTE);
repaint();
}
};
/** Undo the most recent action. */
public AbstractAction aUndo = new AbstractAction("UNDO")
{
private static final long serialVersionUID = 1L;
/** @see AbstractAction#actionPerformed(ActionEvent) */
@Override
public void actionPerformed(ActionEvent e)
{
undo();
}
};
/** Redo the most recently undone action. */
public AbstractAction aRedo = new AbstractAction("REDO")
{
private static final long serialVersionUID = 1L;
/** @see AbstractAction#actionPerformed(ActionEvent) */
@Override
public void actionPerformed(ActionEvent e)
{
redo();
}
};
/** Display the find dialog. */
public AbstractAction aFind = new AbstractAction("FIND")
{
private static final long serialVersionUID = 1L;
/** @see AbstractAction#actionPerformed(ActionEvent) */
@Override
public void actionPerformed(ActionEvent e)
{
findDialog.setVisible(true);
}
};
/** Display the quick find dialog. */
public AbstractAction aQuickFind = new AbstractAction("QUICKFIND")
{
private static final long serialVersionUID = 1L;
/** @see AbstractAction#actionPerformed(ActionEvent) */
@Override
public void actionPerformed(ActionEvent e)
{
finder.present();
}
};
/** Decrease the indent for all selected lines. */
public AbstractAction aUnindent = new AbstractAction("UNINDENT")
{
private static final long serialVersionUID = 1L;
/** @see AbstractAction#actionPerformed(ActionEvent) */
@Override
public void actionPerformed(ActionEvent e)
{
UndoPatch up = new UndoPatch();
int erow;
for (int row = erow = Math.min(sel.row,caret.row); row <= sel.row || row <= caret.row; row++)
{
unindent(row);
erow = row;
}
up.realize(erow);
storeUndo(up,OPT.INDENT);
}
};
/** Map the AbstractActions declared in JoshText to keyboard hotkeys. */
private void mapActions()
{
ActionMap am = getActionMap();
Action acts[] = { aLineDel,aLineDup,aLineSwap,aLineUnSwap,aSelAll,aCopy,aCut,aPaste,aUndo,
aRedo,aFind,aQuickFind,aUnindent };
for (Action a : acts)
am.put(a.getValue(Action.NAME),a);
}
/** The global find dialog. */
FindDialog findDialog = FindDialog.getInstance();
/**
* Removes a unit of indentation from the beginning of a given row.
*
* @param row
* The index of the row to unindent.
*/
void unindent(int row)
{
StringBuilder sb = code.get(row).sbuild;
int wc = 0, cc = 0;
while (cc < sb.length() && Character.isWhitespace(sb.charAt(cc)))
{
if (sb.charAt(cc) == '\t')
{
wc = ((wc + Settings.indentSizeInSpaces) / Settings.indentSizeInSpaces)
* Settings.indentSizeInSpaces;
}
else
wc++;
cc++;
}
if (wc > 0)
{
int kspaces = ((wc - 1) / Settings.indentSizeInSpaces) * Settings.indentSizeInSpaces;
for (int atspaces = 0, lastspaces, i = 0; i < cc; i++)
{
lastspaces = atspaces;
if (sb.charAt(i) == '\t')
atspaces = ((atspaces + Settings.indentSizeInSpaces) / Settings.indentSizeInSpaces)
* Settings.indentSizeInSpaces;
else
atspaces++;
if (atspaces == kspaces)
{
if (sel.type != ST.RECT)
{
if (sel.row == row) sel.col -= cc - i - 1;
if (caret.row == row) caret.col -= cc - i - 1;
}
for (i++; i < cc; cc--)
sb.delete(i,i + 1);
break;
}
if (atspaces > kspaces)
{
if (sel.type != ST.RECT)
{
if (sel.row == row) sel.col -= cc - i;
if (caret.row == row) caret.col -= cc - i;
}
for (; i < cc; cc--)
sb.delete(i,i + 1);
for (i = lastspaces; i < kspaces; i++)
{
if (sel.row == row) sel.col++;
if (caret.row == row) caret.col++;
sb.insert(i," ");
}
break;
}
}
}
}
/** @see javax.swing.JComponent#addNotify() */
@Override
public void addNotify()
{
super.addNotify();
getParent().addComponentListener(this);
}
/**
* Converts a string to a KeyStroke. The string should be of the
* form <i>modifiers</i>+<i>shortcut</i> where <i>modifiers</i>
* is any combination of A for Alt, C for Control, S for Shift,
* G for AltGr, or M for Meta, and <i>shortcut</i> is either a
* single character or a keycode name from the <code>KeyEvent</code> class,
* without the <code>VK_</code> prefix.
*
* @param s
* A string description of the key stroke.
* @return The resulting composed KeyStroke.
* @throws IllegalArgumentException
* if the key cannot be parsed for some reason.
*/
public static KeyStroke key(String s) throws IllegalArgumentException
{
if (s == null) return null;
int index = s.indexOf('+');
String key = s.substring(index + 1);
if (key.length() == 0) throw new IllegalArgumentException("Invalid key stroke: " + s);
// Parse modifiers
int modifiers = 0;
if (index != -1)
{
for (int i = 0; i < index; i++)
{
switch (Character.toUpperCase(s.charAt(i)))
{
case 'A':
modifiers |= InputEvent.ALT_DOWN_MASK;
break;
case 'C':
modifiers |= InputEvent.CTRL_DOWN_MASK;
break;
case 'G':
modifiers |= InputEvent.ALT_GRAPH_MASK;
break;
case 'M':
modifiers |= InputEvent.META_DOWN_MASK;
break;
case 'S':
modifiers |= InputEvent.SHIFT_DOWN_MASK;
break;
}
}
}
// Handle basic ordinal (single character) key
if (key.length() == 1)
{
char ch = Character.toUpperCase(key.charAt(0));
if (modifiers == 0) return KeyStroke.getKeyStroke(ch);
return KeyStroke.getKeyStroke(ch,modifiers);
}
// Otherwise use Reflection to parse the key
int ch;
try
{
ch = KeyEvent.class.getField("VK_".concat(key)).getInt(null);
}
catch (Exception e)
{
throw new IllegalArgumentException("Invalid key stroke: " + s,e);
}
return KeyStroke.getKeyStroke(ch,modifiers);
}
/**
* Fit this component so that it can contain all code, but is not sized
* excessively.
*/
void fitToCode()
{
int insetY = lineLeading;
int w = (maxRowSize + 1) * monoAdvance + getInsets().left + 1; // extra
// char
// +
// pixel
// for
// overwrite
// caret
int h = code.size() * lineHeight + insetY;
setMinimumSize(new Dimension(w,h));
setMaximumSize(new Dimension(Integer.MAX_VALUE,Integer.MAX_VALUE));
fireResize();
repaint();
}
/**
* Calculate the size of the code, and optionally fit the window to it.
*
* @param rs
* Whether or not to resize the window to these new dimensions.
*/
void doCodeSize(boolean rs)
{
maxRowSize = 0;
for (int i = 0; i < code.size(); i++)
if (code.getsb(i).length() > maxRowSize) maxRowSize = code.getsb(i).length();
if (rs)
{
fitToCode();
}
}
/** Adjust the view such that it contains the caret. */
private void doShowCaret()
{
if (!(getParent() instanceof JViewport)) return;
JViewport p = ((JViewport) getParent());
Rectangle vr = p.getViewRect();
Rectangle cr = new Rectangle(caret.col * monoAdvance,caret.row * lineHeight,monoAdvance,
lineHeight);
Point rp = new Point(vr.x,vr.y);
if (cr.y + cr.height > vr.y + vr.height)
rp.y = cr.y + cr.height - vr.height;
else if (cr.y < vr.y) rp.y = Math.max(0,cr.y);
if (cr.x + cr.width > vr.x + vr.width)
rp.x = cr.x + cr.width - vr.width + 5 * monoAdvance;
else if (cr.x < vr.x) rp.x = Math.max(0,cr.x - 5 * monoAdvance);
if (rp.x != vr.x || rp.y != vr.y) p.setViewPosition(rp);
}
/**
* @param point The new mouse point.
*/
private void updateMouseAutoScroll(Point point)
{
// FIXME: This entire thing is some huge pile of fail.
// It scrolls too slowly and causes viewport issues.
if (!(getParent() instanceof JViewport)) return;
JViewport p = ((JViewport) getParent());
Rectangle vr = p.getViewRect();
Point rp = new Point(0,0);
if (point.x > vr.x + vr.width)
rp.x += Math.pow(3,Math.max(0,Math.log10(point.x - vr.x - vr.width) - 1));
if (point.x < vr.x) rp.x -= Math.pow(3,Math.max(0,Math.log10(vr.x - point.x) - 1));
if (point.y > vr.y + vr.height)
rp.y += Math.pow(5,Math.max(0,Math.log10(point.y - vr.y - vr.height) - 1));
if (point.y < vr.y) rp.y -= Math.pow(5,Math.max(0,Math.log10(vr.y - point.y) - 1));
rp.x = Math.max(0,Math.min(maxRowSize,rp.x));
rp.y = Math.max(0,Math.min(code.size() * lineHeight - vr.height,rp.y));
mas.p = p;
mas.rp = rp;
if (rp.x != 0 || rp.y != 0)
mas.start();
else
mas.stop();
}
/** Stop the auto-scroll mechanism. */
void removeMouseAutoScroll()
{
mas.stop();
}
/** Class for handling the auto scroll. */
class MouseAutoScroll
{
/** Rate Point. The velocity of the auto scroll. */
Point rp;
/** The viewport. */
JViewport p;
/** True if the autoscroll is active, false otherwise. */
private boolean running = false;
/** Default constructor. Creates a timer. */
MouseAutoScroll()
{
new Timer().scheduleAtFixedRate(doMouseAutoScroll,100,100);
}
/** Start the scroll mechanism. */
void start()
{
running = true;
}
/** Stop the scroll mechanism. */
void stop()
{
running = false;
}
/**
* Test if the scroll mechanism is active.
*
* @return Whether the scroll mechanism is active.
*/
boolean isRunning()
{
return running;
}
/** Our timer task callback */
TimerTask doMouseAutoScroll = new TimerTask()
{
@Override
public void run()
{
if (!running) return;
Point po = p.getViewPosition();
p.setViewPosition(new Point(po.x + rp.x * monoAdvance,po.y + rp.y * lineHeight));
// doShowCaret();
updateUI();
}
};
}
/** Our local auto scroll mechanism. */
private MouseAutoScroll mas = new MouseAutoScroll();
/**
* Get the width of a particular line up to a given position.
*
* @param l
* The index of the line in question.
* @param pos
* The number of characters from the start of the line to
* consider in the width.
* @return The width of the specified portion of the line with the given
* index.
*/
public int line_wid_at(int l, int pos)
{
return metrics.stringWidth(code.getsb(l).toString(),pos);
}
/**
* Returns the index of the last character in the line with the given index
* which fits in the given width.
*
* @param line
* The line to get the offset in.
* @param wid
* The width to be translated to a character index.
* @return Returns the given width, translated to a character index.
*/
public int line_offset_from(int line, int wid)
{
int ret;
String l = code.getsb(line).toString();
int w = 0, lw = 0;
for (ret = 0; ret < l.length() && w < wid; ret++)
{
lw = w;
if (l.charAt(ret) == '\t')
{
final int wf = monoAdvance * Settings.indentSizeInSpaces;
w = ((w + wf) / wf) * wf;
}
else
w += monoAdvance;
}
if (Math.abs(lw - wid) < Math.abs(w - wid)) return Math.min(l.length(),ret - 1);
return Math.min(l.length(),ret);
}
/**
* Takes the nth character in the line with the given line index
* and computes the column at which that character will be rendered.
*
* @param line
* The index of the line in question.
* @param n
* The index of the character whose column will be returned.
* @return The column number of the nth character on the line.
*/
public int index_to_column(int line, int n)
{
int col = 0;
StringBuilder l = code.getsb(line);
n = Math.min(n,l.length());
for (int i = 0; i < n; i++)
if (l.charAt(i) == '\t')
{
col += Settings.indentSizeInSpaces;
col /= Settings.indentSizeInSpaces;
col *= Settings.indentSizeInSpaces;
}
else
++col;
return col;
}
/**
* Takes a column number and a line with the given index, and returns the
* index of the character in that line which will render at that column.
* If the line does not reach the given column, then the length of the
* line is returned.
*
* @param line
* The line index in question.
* @param col
* The column the index of character at which will be returned.
* @return The index of the character in the given line that renders at the
* given column.
*/
public int column_to_index(int line, int col)
{
int ind = 0;
StringBuilder l = code.getsb(line);
for (int i = 0; i < col && ind < l.length(); ind++)
if (l.charAt(ind) == '\t')
{
i += Settings.indentSizeInSpaces;
i /= Settings.indentSizeInSpaces;
i *= Settings.indentSizeInSpaces;
}
else
++i;
return ind;
}
/**
* Takes a column number and a line with the given index, and returns the
* index of the character in that line which will render at that column.
* If the line does not reach the given column, the result is the sum of
* the length of the line and the number of columns between the column
* index of the end of the line and the given column. This means that the
* behavior is the same as it would be if the line were suffixed with an
* infinite number of spaces.
*
* @param line
* The line index in question.
* @param col
* The column the index of character at which will be returned.
* @return The index of the character in the given line that renders at the
* given column.
*/
public int column_to_index_unsafe(int line, int col)
{
int ind = 0;
StringBuilder l = code.getsb(line);
int i;
for (i = 0; i < col && ind < l.length(); ind++)
if (l.charAt(ind) == '\t')
{
i += Settings.indentSizeInSpaces;
i /= Settings.indentSizeInSpaces;
i *= Settings.indentSizeInSpaces;
}
else
++i;
ind += col - i;
return ind;
}
/**
* @param line
* The index of the line to check in.
* @param col
* The column to look at inside the line.
* @return Returns whether the given column in the line with the given
* index lies within a tab character.
*/
public boolean column_in_tab(int line, int col)
{
int ind = 0;
StringBuilder l = code.getsb(line);
int i;
for (i = 0; i < col && ind < l.length(); ind++)
{
if (l.charAt(ind) == '\t')
{
i += Settings.indentSizeInSpaces;
i /= Settings.indentSizeInSpaces;
i *= Settings.indentSizeInSpaces;
if (i > col) return true;
}
else
i++;
}
return false;
}
/**
* Get the type of the character at the given position in the given
* character sequence.
*
* @param str
* The character sequence in question.
* @param pos
* The position of the character whose type is returned
* @return Returns the type of the character.
*/
public static int selGetKind(CharSequence str, int pos)
{
if (!(pos >= 0 && pos < str.length())) return ChType.WHITE;
int ohfukku = str.charAt(pos);
if (ohfukku > 255) return ChType.WORD;
return chType[ohfukku];
}
/**
* Basically, returns whether selGetKind(str, pos) == otype.
*
* @param str
* The character sequence in question.
* @param pos
* The position of the character whose type is checked.
* @param otype
* The original type against which this character will be
* matched.
* @return Returns whether the type of the described character matches the
* given original type.
*/
public static boolean selOfKind(CharSequence str, int pos, int otype)
{
if (!(pos >= 0 && pos < str.length())) return otype == ChType.WHITE;
int ohfukku = str.charAt(pos);
if (ohfukku > 255) return otype == ChType.WORD;
return chType[ohfukku] == otype;
}
/**
* Get font metric information for the active font.
*
* @return Returns the FontMetrics of the current font.
*/
public FontMetrics getFontMetrics()
{
return getFontMetrics(getFont());
}
/**
* Get the largest dimensions of any glyph that will be rendered with the
* current font.
*
* @return Returns a Dimension representing the largest sizes glyphs in this
* font attain.
*/
public Dimension getMaxGlyphSize()
{
return new Dimension(monoAdvance,lineHeight);
}
/**
* Draw the given characters with full highlighting.
*
* @param g
* The graphics object to render to.
* @param a
* The characters to render.
* @param sp
* The starting position in the given array.
* @param ep
* The ending position in the given array.
* @param xx
* The x coordinate at which to start render.
* @param ty
* The y coordinate at which to start render
* @return The new x coordinate from which to render.
*/
private int drawChars(Graphics g, char[] a, int sp, int ep, int xx, int ty)
{
Color c = g.getColor();
for (int i = sp; i < ep; i++)
{
if (a[i] == '\t')
{
final int incby = Settings.indentSizeInSpaces * monoAdvance, xxp = xx;
xx = ((xx + incby) / incby) * incby;
if (Settings.renderTabs)
{
g.setColor(new Color(255,0,0));
g.drawLine(xxp + 2,ty - (lineHeight / 3),xx - 2,ty - (lineHeight / 3));
g.drawLine(xxp + 2,ty - (lineHeight / 3) - (lineHeight / 5),xxp + 2,ty - (lineHeight / 3)
+ (lineHeight / 5));
g.drawLine(xx - 2,ty - (lineHeight / 3) - (lineHeight / 5),xx - 2,ty - (lineHeight / 3)
+ (lineHeight / 5));
g.setColor(c);
}
continue;
}
g.drawChars(a,i,1,xx,getInsets().top + ty);
xx += monoAdvance;
g.setColor(c);
}
return xx;
}
/** This is the font for which we have cached derived fonts. This prevents drawing with stale fonts. */
private Font baseFont = null;
/** This is a map of our derived fonts by the flags with which they were derived from the base font. */
private HashMap<Integer,Font> specialFonts = new HashMap<Integer,Font>();
/**
* Paint the line with the given index to the given Graphics object,
* starting
* at the given y-coordinate.
*
* @param g
* The graphics object to paint to.
* @param lineNum
* The index of the line to render.
* @param ty
* The y-coordinate at which to render the baseline.
*/
private void drawLine(Graphics g, int lineNum, int ty)
{
if (baseFont != getFont())
{
baseFont = getFont();
specialFonts.clear();
}
g.setColor(getForeground());
Font drawingFont = baseFont;
g.setFont(drawingFont);
int fontFlags = 0;
StringBuilder line = code.getsb(lineNum);
int xx = getInsets().left;
char[] a = line.toString().toCharArray();
Color c = g.getColor();
if (marker == null)
{
drawChars(g,a,0,a.length,xx,ty);
}
else
{
ArrayList<TokenMarkerInfo> tmall = marker.getStyles(code.get(lineNum));
int pos = 0;
for (TokenMarkerInfo tm : tmall)
{
// Start by printing normal characters until we reach
// styleBlock.startPos
xx = drawChars(g,a,pos,tm.startPos,xx,ty);
// Print the remaining characters in the styleBlock range
g.setColor(tm.color != null ? tm.color : c);
fontFlags = tm.fontStyle;
if (specialFonts.containsKey(fontFlags))
drawingFont = specialFonts.get(fontFlags);
else
{
drawingFont = baseFont.deriveFont(fontFlags);
specialFonts.put(fontFlags,drawingFont);
}
g.setFont(drawingFont);
xx = drawChars(g,a,tm.startPos,tm.endPos,xx,ty);
pos = tm.endPos;
g.setFont(baseFont);
g.setColor(c);
}
}
}
/** @param g The graphics object to which to paint. */
@Override
public void paintComponent(Graphics g)
{
Object map = Toolkit.getDefaultToolkit().getDesktopProperty("awt.font.desktophints"); //$NON-NLS-1$
if (map != null) ((Graphics2D) g).addRenderingHints((Map<?,?>) map);
Rectangle clip = g.getClipBounds();
// Fill background
g.setColor(getBackground());
g.fillRect(clip.x,clip.y,clip.width,clip.height);
for (Highlighter a : highlighters)
a.paint(g,getInsets(),metrics,0,code.size());
// Draw each line
final int insetY = lineLeading + lineAscent;
int lineNum = clip.y / lineHeight;
for (int ty = lineNum * lineHeight + insetY; ty < clip.y + clip.height + lineHeight
&& lineNum < code.size(); ty += lineHeight)
drawLine(g,lineNum++,ty);
if (isFocusOwner()) caret.paint(g,sel);
}
/**
* A convenience repaint method which can convert a row/col pair into x/y
* space.
*
* @param col
* The column at which to start the repaint.
* @param row
* The row at which to start the repaint.
* @param w
* The width of the region to repaint.
* @param h
* The height of the region to repaint.
* @param convert
* True to convert row/col into x/y space. False to treat as x/y.
*/
public void repaint(int col, int row, int w, int h, boolean convert)
{
if (convert)
{
Dimension g = getMaxGlyphSize();
col *= g.width;
row *= g.height;
}
repaint(col,row,w,h);
}
// Input handling
/**
* Translates a mouse coordinate to a text coordinate (y = row, x = col).
*
* @param m
* The mouse coordinates to translate.
* @param bound
* Whether the coordinate should be trimmed to a valid column.
* @return A point representing the text coordinate, where Point.x is the
* column,
* and point.y is the row in the code.
*/
public Point mouseToPoint(Point m, boolean bound)
{
Point p = m;
int row = p.y / lineHeight;
row = Math.max(Math.min(row,code.size() - 1),0);
int col = bound ? line_offset_from(row,p.x) : (int) Math.round(p.x / (double) monoAdvance);
if (!bound) return new Point(Math.max(col,0),row);
col = Math.max(Math.min(col,code.getsb(row).length()),0);
return new Point(col,row);
}
/**
* Whether or not mouseReleased should adjust the caret and focus.
* This flag is set by mousePressed if it wanted to adjust the caret
* and focus but couldn't because of a possible DnD operation.
*/
private boolean shouldHandleRelease = false;
/**
* Handle a mouse event, such as clicks, double clicks, drags, for
* selection,
* scrolling, and general mouse-related code manipulation.
*
* @param e
* The mouse event to handle.
*/
protected void handleMouseEvent(MouseEvent e)
{
// / FIXME: Double-click-and-drag is supposed to wrap the start and
// / end caret positions to word endings.
if (e.getID() == MouseEvent.MOUSE_PRESSED) requestFocusInWindow();
// if ((e.getModifiersEx() & MouseEvent.BUTTON3_DOWN_MASK) != 0
// && (e.getID() == MouseEvent.MOUSE_PRESSED)) dragger.query();
if (SwingUtilities.isLeftMouseButton(e))
{
switch (e.getID())
{
case MouseEvent.MOUSE_ENTERED:
return;
case MouseEvent.MOUSE_PRESSED:
dragger.mousePressed(e);
if (e.isConsumed()) shouldHandleRelease = true;
break;
case MouseEvent.MOUSE_RELEASED:
dragger.mouseReleased(e);
removeMouseAutoScroll();
break;
case MouseEvent.MOUSE_DRAGGED:
if (!hasFocus()) return;
dragger.mouseDragged(e);
break;
}
if (e.isConsumed() || e.getID() == MouseEvent.MOUSE_EXITED) return;
if ((e.getModifiers() & (InputEvent.ALT_MASK | InputEvent.CTRL_MASK)) != 0)
sel.changeType(ST.RECT);
else
sel.changeType(ST.NORM);
Point sp = new Point(caret.col,caret.row);
Point p = mouseToPoint(e.getPoint(),sel.type != ST.RECT);
caret.col = p.x;
caret.row = p.y;
caret.colw = sel.type == ST.RECT ? caret.col * monoAdvance : line_wid_at(caret.row,caret.col);
if (e.getClickCount() == 2)
sel.special.setHandler(sel.wordSelHandler);
else if (e.getClickCount() == 3)
sel.special.setHandler(sel.lineSelHandler);
else if (e.getID() == MouseEvent.MOUSE_PRESSED) sel.special.valid = false;
updateMouseAutoScroll(e.getPoint());
if (sel.special.valid) sel.special.adjust();
// cleanup (deselect, flash, repaint)
if (!sel.special.valid
&& (e.getModifiers() & Event.SHIFT_MASK) == 0
&& (e.getID() == MouseEvent.MOUSE_PRESSED || (e.getID() == MouseEvent.MOUSE_RELEASED && shouldHandleRelease)))
sel.deselect(false);
shouldHandleRelease = false;
caret.flashOn();
if (sp.x != caret.col || sp.y != caret.row)
{
caret.positionChanged();
undoCanMerge = false;
}
if (e.getID() == MouseEvent.MOUSE_RELEASED) sel.selectionChanged();
repaint();
return;
}
else if (SwingUtilities.isMiddleMouseButton(e))
{
if (e.getID() != MouseEvent.MOUSE_PRESSED) return;
Point p = mouseToPoint(e.getPoint(),true);
ST sto = sel.type;
sel.type = ST.NORM;
UndoPatch up = new UndoPatch(p.y,Math.min(code.size() - 1,p.y + sel.getMiddlePasteRipple()));
up.cbefore.stype = sto;
sel.col = caret.col = p.x;
sel.row = caret.row = p.y;
caret.positionChanged();
final int mcr = sel.middleClickPaste();
doCodeSize(true);
up.realize(mcr);
storeUndo(up,OPT.PASTE);
repaint();
}
}
/** Handle most mouse events by delegating to super. */
@Override
protected void processMouseEvent(MouseEvent e)
{
super.processMouseEvent(e);
handleMouseEvent(e);
}
/** Handle mouse movement by delegating to super. */
@Override
protected void processMouseMotionEvent(MouseEvent e)
{
super.processMouseMotionEvent(e);
handleMouseEvent(e);
}
/**
* Handle when the user types a key.
* @param e The key type event.
*/
protected void processKeyTyped(KeyEvent e)
{
final Point sc = new Point(caret.col,caret.row);
switch (e.getKeyChar())
{
case KeyEvent.VK_ENTER:
if (sel.type == Selection.ST.NORM)
{
UndoPatch up = new UndoPatch();
sel.deleteSel();
StringBuilder nr = code.getsb(caret.row);
int offset = 0;
StringBuilder ins = new StringBuilder();
- for (int i = 0; i < nr.length(); i++)
+ for (int i = 0; i < nr.length() && i < caret.col; i++)
if (Character.isWhitespace(nr.charAt(i)))
{
offset++;
ins.append(nr.charAt(i));
}
else
break;
int iind = myLang.hasIndentAfter(nr.toString());
if (iind != -1)
{
String ind = myLang.getIndent(iind);
ins.append(ind);
offset += ind.length();
}
code.add(++caret.row,ins + nr.substring(caret.col));
nr.delete(caret.col,nr.length());
sel.col = caret.col = offset;
caret.colw = line_wid_at(caret.row,caret.col);
up.realize(caret.row);
storeUndo(up,OPT.ENTER);
}
// RECT falls to here
sel.deselect(true);
break;
case KeyEvent.VK_BACK_SPACE:
switch (sel.type)
{
case NORM:
{
UndoPatch up = new UndoPatch();
int otype = selGetKind(code.getsb(caret.row),caret.col - 1);
if (!sel.deleteSel())
{
if (Settings.smartBackspace && otype == ChType.WHITE && caret.col > 0
&& all_white(code.getsb(caret.row).substring(0,caret.col)))
{
unindent(caret.row);
caret.col = sel.col;
up.realize(caret.row);
storeUndo(up,OPT.BACKSPACE);
break;
}
//
do
{
if (caret.col > 0)
{
code.getsb(caret.row).delete(caret.col - 1,caret.col);
--caret.col;
}
else if (caret.row > 0)
{
StringBuilder s1 = code.getsb(caret.row - 1);
StringBuilder s2 = code.getsb(caret.row);
code.remove(caret.row--);
up.prefix_row(code.get(caret.row));
caret.col = s1.length();
s1.append(s2);
}
else
break;
}
while (e.isControlDown() && selOfKind(code.getsb(caret.row),caret.col - 1,otype));
}
caret.colw = line_wid_at(caret.row,caret.col);
sel.deselect(false);
up.realize(caret.row);
storeUndo(up,OPT.BACKSPACE);
break;
}
case RECT:
{
UndoPatch up = new UndoPatch();
int otype = selGetKind(code.getsb(caret.row),caret.col - 1);
if (!sel.deleteSel())
{
if (e.isControlDown())
{
// Control-Backspace on multiple lines.
// We'll handle this by determining the smallest
// word/pattern we
// can control-backspace over, and running with it on
// all lines.
// Nab the smallest distance
int mindist = -1;
for (int y = Math.min(sel.row,caret.row); y <= Math.max(sel.row,caret.row); y++)
{
int actcol = column_to_index(y,caret.col);
StringBuilder sb = code.getsb(y);
otype = selGetKind(sb,actcol - 1);
int mcol = actcol, mydist = 0;
do
{
if (mcol > 0)
if (mcol < sb.length())
{
if (sb.charAt(mcol--) == '\t')
{
mydist += Settings.indentSizeInSpaces;
mydist /= Settings.indentSizeInSpaces;
mydist *= Settings.indentSizeInSpaces;
}
else
mydist += 1;
}
else
{
mydist++;
mcol--;
}
else
break;
}
while (selOfKind(code.getsb(y),mcol - 1,otype));
if (mindist == -1 || mydist < mindist) mindist = mydist;
}
int cs = caret.col - mindist, ce = caret.col;
sel.col = caret.col = cs;
caret.colw = line_wid_at(caret.row,caret.col);
for (int y = Math.min(sel.row,caret.row); y <= Math.max(sel.row,caret.row); y++)
code.getsb(y).delete(column_to_index(y,cs),column_to_index(y,ce));
}
else if (caret.col > 0)
{
for (int y = Math.min(sel.row,caret.row); y <= Math.max(sel.row,caret.row); y++)
code.getsb(y).delete(column_to_index(y,caret.col - 1),
column_to_index(y,caret.col));
sel.col = --caret.col;
caret.colw = caret.col * monoAdvance;
}
}
up.realize(Math.max(caret.row,sel.row));
storeUndo(up,OPT.BACKSPACE);
break;
}
}
break;
case KeyEvent.VK_DELETE:
switch (sel.type)
{
case NORM:
{
UndoPatch up = new UndoPatch();
int otype = selGetKind(code.getsb(caret.row),caret.col);
if (!sel.deleteSel()) do
{
if (caret.col < code.getsb(caret.row).length())
code.getsb(caret.row).delete(caret.col,caret.col + 1);
else if (caret.row + 1 < code.size())
{
StringBuilder s1 = code.getsb(caret.row);
StringBuilder s2 = code.getsb(caret.row + 1);
code.remove(caret.row + 1);
s1.append(s2);
}
else
break;
}
while (e.isControlDown() && selOfKind(code.getsb(caret.row),caret.col,otype));
up.realize(caret.row);
storeUndo(up,OPT.DELETE);
break;
}
case RECT:
{
UndoPatch up = new UndoPatch();
int otype = selGetKind(code.getsb(caret.row),caret.col);
if (!sel.deleteSel())
{
for (int y = Math.min(sel.row,caret.row); y <= Math.max(sel.row,caret.row); y++)
{
int dcol = column_to_index(y,caret.col);
otype = selGetKind(code.getsb(y),dcol);
do
{
if (dcol < code.getsb(y).length())
code.getsb(y).delete(dcol,dcol + 1);
else
break;
}
while (e.isControlDown() && selOfKind(code.getsb(y),dcol,otype));
}
}
up.realize(caret.row);
storeUndo(up,OPT.DELETE);
break;
}
}
break;
case KeyEvent.VK_TAB:
if (!sel.isEmpty())
{
UndoPatch up = new UndoPatch();
String tab = Settings.indentRepString;
int yx = Math.max(sel.row,caret.row);
for (int y = Math.min(sel.row,caret.row); y <= yx; y++)
code.getsb(y).insert(0,tab);
sel.col += tab.length();
caret.col += tab.length();
up.realize(Math.max(sel.row,caret.row));
storeUndo(up,OPT.INDENT);
break;
}
UndoPatch up = new UndoPatch();
sel.insert(Settings.indentRepString);
up.realize(caret.row);
storeUndo(up,OPT.TYPED);
break;
case '\u0018': // cancel (not sure why it's VK_FINAL instead of
// VK_CANCEL)
case KeyEvent.VK_ESCAPE: // escape (in paramString, this is \u001B,
// which is VK_ESCAPE
case KeyEvent.CHAR_UNDEFINED:
// these cases are taken from KeyEvent.paramString
break;
default:
if (e.isControlDown() || e.isAltDown())
{
switch (e.getKeyCode())
{
// Handle bindings. Usually this is handled by registering key
// bindings,
// in which case it is usually consumed before it gets here.
default:
break;
}
}
else
{
UndoPatch up2 = new UndoPatch();
sel.insert(e.getKeyChar());
up2.realize(caret.row);
storeUndo(up2,e.getKeyChar() == ' ' ? OPT.SPACE : OPT.TYPED);
}
break;
}
if (sc.x != caret.col || sc.y != caret.row) caret.positionChanged();
doCodeSize(true);
// doShowCursor();
}
/**
* Test if a string comprises only whitespace characters.
* @param str String to test.
* @return Whether the string is entirely whitespace.
*/
private static boolean all_white(String str)
{
for (int i = 0; i < str.length(); i++)
if (!Character.isWhitespace(str.charAt(i))) return false;
return true;
}
/**
* Process a generic key press.
* @param e The key press event.
*/
protected void processKeyPressed(KeyEvent e)
{
// Note to developers: please consume keys that you use.
// This way, containers don't still see them as usable
// (e.g. arrow keys triggering the scrollbar)
Point sc = new Point(caret.col,caret.row);
switch (e.getKeyCode())
{
case KeyEvent.VK_INSERT:
caret.insert ^= true;
e.consume();
break;
case KeyEvent.VK_LEFT:
int otype = selGetKind(code.getsb(caret.row),caret.col - 1);
do
{
if (caret.col > 0)
--caret.col;
else if (caret.row > 0 && sel.type != ST.RECT)
{
caret.row--;
caret.col = code.getsb(caret.row).length();
}
else
break;
}
while (e.isControlDown() && selOfKind(code.getsb(caret.row),caret.col - 1,otype));
undoCanMerge = false;
caret.colw = line_wid_at(caret.row,caret.col);
if (e.isAltDown())
sel.changeType(ST.RECT);
else if (e.isShiftDown())
sel.changeType(ST.NORM);
else
sel.deselect(true);
doCodeSize(false);
e.consume();
break;
case KeyEvent.VK_RIGHT:
otype = selGetKind(code.getsb(caret.row),caret.col);
do
{
if (sel.type == ST.RECT || caret.col < code.getsb(caret.row).length())
++caret.col;
else if (caret.row + 1 < code.size() && sel.type != ST.RECT)
{
caret.row++;
caret.col = 0;
}
else
break;
}
while (e.isControlDown() && selOfKind(code.getsb(caret.row),caret.col,otype));
undoCanMerge = false;
caret.colw = line_wid_at(caret.row,caret.col);
if (e.isAltDown())
sel.changeType(ST.RECT);
else if (e.isShiftDown())
sel.changeType(ST.NORM);
else
sel.deselect(true);
e.consume();
break;
case KeyEvent.VK_UP:
if (caret.row > 0)
{
if (sel.type == ST.RECT)
--caret.row;
else
{
caret.col = line_offset_from(--caret.row,caret.colw);
if (caret.col > code.getsb(caret.row).length())
caret.col = code.getsb(caret.row).length();
}
}
else
caret.colw = caret.col = 0;
undoCanMerge = false;
if (e.isAltDown())
sel.changeType(ST.RECT);
else if (e.isShiftDown())
sel.changeType(ST.NORM);
else
sel.deselect(true);
e.consume();
break;
case KeyEvent.VK_DOWN:
if (caret.row + 1 < code.size())
{
if (sel.type == ST.RECT)
++caret.row;
else
{
caret.col = line_offset_from(++caret.row,caret.colw);
if (caret.col > code.getsb(caret.row).length())
caret.col = code.getsb(caret.row).length();
}
}
else
caret.colw = line_wid_at(caret.row,caret.col = code.getsb(caret.row).length());
undoCanMerge = false;
if (e.isAltDown())
sel.changeType(ST.RECT);
else if (e.isShiftDown())
sel.changeType(ST.NORM);
else
sel.deselect(true);
e.consume();
break;
case KeyEvent.VK_END:
if (e.isControlDown()) caret.row = code.size() - 1;
caret.colw = line_wid_at(caret.row,caret.col = code.getsb(caret.row).length());
if (e.isAltDown())
sel.changeType(ST.RECT);
else if (!e.isShiftDown()) sel.deselect(true);
e.consume();
break;
case KeyEvent.VK_HOME:
if (e.isControlDown()) caret.row = 0;
int P = 0;
while (P < code.getsb(caret.row).length()
&& Character.isWhitespace(code.getsb(caret.row).charAt(P)))
P++;
if (caret.col == P) P = 0;
caret.colw = P;
caret.col = P;
if (e.isAltDown())
sel.changeType(ST.RECT);
else if (e.isShiftDown())
sel.changeType(ST.NORM);
else
sel.deselect(true);
e.consume();
break;
case KeyEvent.VK_PAGE_UP:
int height = (getParent() instanceof JViewport) ? getParent().getHeight() : getHeight();
caret.row = Math.max(0,caret.row - height / lineHeight);
if (sel.type != ST.RECT) caret.col = Math.min(caret.col,code.getsb(caret.row).length());
// FIXME: If parent is viewport, also scroll that a screenfull
if (!e.isShiftDown()) sel.deselect(true);
e.consume();
break;
case KeyEvent.VK_PAGE_DOWN:
height = (getParent() instanceof JViewport) ? getParent().getHeight() : getHeight();
caret.row = Math.min(code.size() - 1,caret.row + height / lineHeight);
if (sel.type != ST.RECT) caret.col = Math.min(caret.col,code.getsb(caret.row).length());
// FIXME: If parent is viewport, also scroll that a screenfull
if (!e.isShiftDown()) sel.deselect(true);
e.consume();
break;
}
if (sc.x != caret.col || sc.y != caret.row) caret.positionChanged();
fitToCode();
// doShowCursor();
}
/** Handle a component key event; a type or a generic press. */
@Override
protected void processComponentKeyEvent(KeyEvent e)
{
caret.flashOn();
switch (e.getID())
{
case KeyEvent.KEY_TYPED:
processKeyTyped(e);
break;
case KeyEvent.KEY_PRESSED:
processKeyPressed(e);
break;
}
}
// Line Change Listeners
/**
* A LineChange is invoked whenever characters are added/removed
* from lines, whether the line exists or is created. For only
* listening to whether lines are added/removed, use Code.CodeListener.
*/
public interface LineChangeListener extends EventListener
{
/**
* @param code The code that was changed.
* @param start The index of the first line changed.
* @param end The index of the last line changed.
*/
void linesChanged(Code code, int start, int end);
}
/** @param listener The listener to add. */
public void addLineChangeListener(LineChangeListener listener)
{
listenerList.add(LineChangeListener.class,listener);
}
/** @param listener The listener to remove. */
public void removeLineChangeListener(LineChangeListener listener)
{
listenerList.remove(LineChangeListener.class,listener);
}
/** Fires a line change event to all listeners.
* @param start The first line changed.
* @param end The last line changed. */
protected void fireLineChange(int start, int end)
{
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length - 2; i >= 0; i -= 2)
if (listeners[i] == LineChangeListener.class)
{
// Lazily create the event:
// if (e == null)
// e = new ListSelectionEvent(this, firstIndex, lastIndex);
((LineChangeListener) listeners[i + 1]).linesChanged(code,start,end);
}
}
// Inner classes (mostly drag and drop)
/**
* Listens for mouse events for the purposes of detecting drag gestures.
* BasicTextUI will maintain one of these per AppContext.
*/
class DragListener
{
/** True if a drag has been initiated. */
private boolean dragStarted;
/** Motion threshold before a drag is initiated. */
private int motionThreshold;
/** The event that sparked the drag. */
private MouseEvent dndArmedEvent;
/** Construct with default threshold. */
public DragListener()
{
motionThreshold = getDefaultThreshold();
}
/**
* @return The system default motion threshold for beginning a drag.
*/
public int getDefaultThreshold()
{
Integer ti = (Integer) Toolkit.getDefaultToolkit().getDesktopProperty(
"DnD.gestureMotionThreshold");
return ti == null ? 5 : ti.intValue();
}
/**
* Handle a mouse press.
* @param e The mouse event.
*/
public void mousePressed(MouseEvent e)
{
dragStarted = false;
if (isDragPossible(e.getPoint()))
{
dndArmedEvent = e;
e.consume();
}
}
/**
* Handle a mouse release.
* @param e The mouse event.
*/
public void mouseReleased(MouseEvent e)
{
if (dragStarted) e.consume();
dndArmedEvent = null;
}
/**
* Handle a mouse drag.
* @param e The mouse event.
*/
public void mouseDragged(MouseEvent e)
{
if (dragStarted)
{
e.consume();
return;
}
if (dndArmedEvent == null) return;
int dx = Math.abs(e.getX() - dndArmedEvent.getX());
int dy = Math.abs(e.getY() - dndArmedEvent.getY());
if ((dx > motionThreshold) || (dy > motionThreshold))
{
TransferHandler th = JoshText.this.getTransferHandler();
int act = e.isControlDown() ? TransferHandler.COPY : TransferHandler.MOVE;
dragStarted = true;
th.exportAsDrag(JoshText.this,dndArmedEvent,act);
dndArmedEvent = null;
}
e.consume();
}
/** Determines if the press event is located over a selection.
* @param mousePt The Point representing the mouse.
* @return Whether the drag is possible; if the press event is located over a selection. */
protected boolean isDragPossible(Point mousePt)
{
Point p = mouseToPoint(mousePt,false);
return sel.contains(p.y,p.x);
}
/** Print debug info. */
public void query()
{
System.out.println(dragStarted + "," + dndArmedEvent);
}
}
/**
* @author IsmAvatar
* Class to handle drag and drop text in JoshEdit.
*/
class JoshTextTransferHandler extends TransferHandler
{
/** Shut up, ECJ. */
private static final long serialVersionUID = 1L;
/** Construct, establishing listeners. */
public JoshTextTransferHandler()
{
addPropertyChangeListener("dropLocation",new PropertyChangeListener()
{
@Override
public void propertyChange(PropertyChangeEvent pce)
{
repaintDropLocation(pce.getOldValue());
repaintDropLocation(pce.getNewValue());
}
});
}
/**
* Repaint to reflect text drop.
* @param drop The object being dropped.
*/
public void repaintDropLocation(Object drop)
{
if (drop == null || !(drop instanceof DropLocation)) repaint();
DropLocation loc = (DropLocation) drop;
loc.getDropPoint();
}
/** @see javax.swing.TransferHandler#getSourceActions(javax.swing.JComponent) */
@Override
public int getSourceActions(JComponent c)
{
return COPY_OR_MOVE;
}
/** @see javax.swing.TransferHandler#createTransferable(javax.swing.JComponent) */
@Override
protected Transferable createTransferable(JComponent c)
{
if (!(c instanceof JoshText)) return null;
JoshText j = (JoshText) c;
if (j.sel.isEmpty()) return null;
return new StringSelection(j.sel.getSelectedTextForCopy());
}
/** Upon drag completion, if drag was MOVE, not COPY, delete the moved text. */
@Override
protected void exportDone(JComponent source, Transferable data, int action)
{
UndoPatch up = new UndoPatch();
if (action == MOVE && source instanceof JoshText)
{
((JoshText) source).sel.deleteSel();
up.realize(Math.max(caret.row,sel.row));
storeUndo(up,OPT.DELETE);
}
repaint();
}
/** Test if we can import a given draggable; ie, test if it's a string. */
@Override
public boolean canImport(TransferSupport info)
{
return info.isDataFlavorSupported(DataFlavor.stringFlavor);
// if (info.isDrop()) dropPoint =
// mouseToPoint(info.getDropLocation().getDropPoint(),true);
// return true;
}
/** @see javax.swing.TransferHandler#importData(javax.swing.TransferHandler.TransferSupport) */
@Override
public boolean importData(TransferSupport info)
{
Transferable t = info.getTransferable();
String data;
try
{
data = (String) t.getTransferData(DataFlavor.stringFlavor);
}
catch (Exception e)
{
return false;
}
UndoPatch up = new UndoPatch();
if (info.isDrop())
{
Point p = mouseToPoint(info.getDropLocation().getDropPoint(),true);
caret.row = p.y;
caret.col = p.x;
sel.deselect(false);
sel.type = ST.NORM;
up.startRow = caret.row;
up.reconstruct(p.y,Math.min(code.size() - 1,p.y + sel.getInsertRipple(data)));
}
int er = 0;
if (data.length() > 0 && data.charAt(data.length() - 1) == 0)
er = Math.max(1,sel.insertRect(data.substring(0,data.length() - 1))) - 1;
else
sel.insert(data);
up.realize(caret.row + er);
storeUndo(up,OPT.PASTE);
repaint();
return true;
}
}
// Scrollable
/** @see javax.swing.Scrollable#getPreferredScrollableViewportSize() */
@Override
public Dimension getPreferredScrollableViewportSize()
{
return new Dimension(320,240);
}
/** @see javax.swing.Scrollable#getScrollableUnitIncrement(java.awt.Rectangle, int, int) */
@Override
public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction)
{
switch (orientation)
{
case SwingConstants.VERTICAL:
return getFontMetrics(getFont()).getHeight();
case SwingConstants.HORIZONTAL:
return monoAdvance;
default:
throw new IllegalArgumentException("Invalid orientation: " + orientation);
}
}
/** @see javax.swing.Scrollable#getScrollableBlockIncrement(java.awt.Rectangle, int, int) */
@Override
public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction)
{
switch (orientation)
{
case SwingConstants.VERTICAL:
return visibleRect.height;
case SwingConstants.HORIZONTAL:
return visibleRect.width;
default:
throw new IllegalArgumentException("Invalid orientation: " + orientation);
}
}
/** @see javax.swing.Scrollable#getScrollableTracksViewportHeight() */
@Override
public boolean getScrollableTracksViewportHeight()
{
return false;
}
/** The scrollable should not track the viewport width. */
@Override
public boolean getScrollableTracksViewportWidth()
{
return false;
}
/** Handle a resize. */
void fireResize()
{
Container a = getParent();
if (a == null) return;
int w = a.getWidth(), h = a.getHeight();
Dimension ps = getMinimumSize();
ps.width = Math.max(ps.width,w);
ps.height = Math.max(ps.height,h);
setPreferredSize(ps);
setSize(ps);
}
/** Listen to parent component */
@Override
public void componentResized(ComponentEvent e)
{
fireResize();
}
/** Repaint when covered partially by another window. */
@Override
public void componentHidden(ComponentEvent e)
{
repaint();
}
/** @see java.awt.event.ComponentListener#componentMoved(java.awt.event.ComponentEvent) */
@Override
public void componentMoved(ComponentEvent e)
{
repaint();
}
/** @see java.awt.event.ComponentListener#componentShown(java.awt.event.ComponentEvent) */
@Override
public void componentShown(ComponentEvent e)
{
repaint();
}
/** Be a clipboard owner and do not give a fuck. */
@Override
public void lostOwnership(Clipboard arg0, Transferable arg1)
{
// WHOGIVESAFUCK.jpg
}
// -----------------------------------------------------------------
// ----- Mark Matching Brackets ------------------------------------
// -----------------------------------------------------------------
/**
* @author Josh Ventura
* The status of a match; there are three match states.
*/
static enum MatchState
{
/** No attempt is presently being made to match anything. */
NOT_MATCHING,
/** A match was attempted, but none was found. */
NO_MATCH,
/** A match was successfully located. */
MATCHING
}
/**
* @author Josh Ventura
* A highlighter to mark pairs of matching brackets.
*/
class BracketHighlighter implements Highlighter,CaretListener
{
/** The state of our match. */
MatchState matching;
/** The line on which the match was found. */
int matchLine;
/** The column at which the match was found. */
int matchPos;
/** Paint a box around each bracket in the match. */
@Override
public void paint(Graphics g, Insets i, CodeMetrics gm, int line_start, int line_end)
{
Color c = g.getColor();
if (matching == MatchState.MATCHING)
{
g.setColor(new Color(100,100,100));
g.drawRect(line_wid_at(matchLine,matchPos),matchLine * lineHeight,monoAdvance,lineHeight);
}
else if (matching == MatchState.NO_MATCH)
{
g.setColor(new Color(255,0,0));
g.fillRect(line_wid_at(matchLine,matchPos),matchLine * lineHeight,monoAdvance,lineHeight);
}
g.setColor(c);
}
/**
* @param m The current BracketMatch instance.
* @param x The column of the most recent match candidate.
* @param y The row of the most recent match candidate.
* @return True if the match candidate is indeed the match to the original bracket.
*/
private boolean matchFound(BracketMatch m, int x, int y)
{
if (--m.count <= 0)
{
matchLine = y;
matchPos = x;
matching = MatchState.MATCHING;
return true;
}
return false;
}
/**
* @author Josh Ventura
* Class to match various brackets; parentheses, square brackets, braces.
*/
class BracketMatch
{
/** The character of the bracket to be matched. */
char match;
/** The character of the matching bracket; the opposite-side bracket. */
char opposite;
/** The number of nested brackets during this matching process. */
short count;
/**
* @param m The character of the bracket to be matched.
* @param o The character of the matching bracket; the opposite-side bracket.
* @param c The number of nested brackets during this matching process.
*/
public BracketMatch(char m, char o, short c)
{
match = m;
opposite = o;
count = c;
}
}
/**
* @param row The row of the bracket to match.
* @param col The column of the bracket to match.
* @param match The BracketMatch instance for this match attempt.
*/
private void findMatchForward(int row, int col, BracketMatch match)
{
int y = row;
int blockType = 0;
StringBuilder sb = code.getsb(y);
// Figure out what kind of block we're in, if any.
ArrayList<TokenMarkerInfo> tmall = marker.getStyles(code.get(y));
int offset;
for (offset = 0; offset < tmall.size(); offset++)
{
TokenMarkerInfo tm = tmall.get(offset);
if (col < tm.startPos) break; // The blocks have skipped us.
if (col >= tm.startPos && col < tm.endPos)
{
blockType = tm.blockHash;
break;
}
}
if (subFindMatchForward(match,sb,tmall,offset,col,blockType,y)) return;
for (y++; y < code.size(); y++)
{
tmall = marker.getStyles(code.get(y));
if (subFindMatchForward(match,code.getsb(y),tmall,0,0,blockType,y)) return;
}
}
/**
* @param match The BracketMatch class representing this search.
* @param sb The StringBuilder of the line to search.The position from which to continue searching.
* @param tmall All marker tokens for this line.
* @param offset The marker token index from which to continue searching.
* @param spos The position from which to continue searching.
* @param blockType The type of block in which we are interested.
* @param y Our row number.
* @return True if the match was found in this line, false otherwise.
* Info about the match will be contained in the match parameter.
*/
private boolean subFindMatchForward(BracketMatch match, StringBuilder sb,
ArrayList<TokenMarkerInfo> tmall, int offset, int spos, int blockType, int y)
{
int pos = spos;
for (int i = offset; i < tmall.size(); i++)
{
TokenMarkerInfo tm = tmall.get(i);
if (blockType == 0) // If our start wasn't in a block
for (; pos < tm.startPos; pos++)
// Check outside this block's range
if (sb.charAt(pos) == match.match)
{
if (matchFound(match,pos,y)) return true;
}
else if (sb.charAt(pos) == match.opposite) match.count++;
if (blockType == tmall.get(i).blockHash) // If the block has the
// same type
for (pos = Math.max(spos,tm.startPos); pos < tm.endPos; pos++)
// Check inside it
if (sb.charAt(pos) == match.match)
{
if (matchFound(match,pos,y)) return true;
}
else if (sb.charAt(pos) == match.opposite) match.count++;
pos = tm.endPos;
}
return false;
}
/**
* @param row The row of the bracket to match.
* @param col The column of the bracket to match.
* @param match The BracketMatch instance for this match attempt.
*/
private void findMatchBackward(int row, int col, BracketMatch match)
{
int y = row;
int blockType = 0;
StringBuilder sb = code.getsb(y);
// Figure out what kind of block we're in, if any.
ArrayList<TokenMarkerInfo> tmall = marker.getStyles(code.get(y));
int offset;
for (offset = 0; offset < tmall.size(); offset++)
{
TokenMarkerInfo tm = tmall.get(offset);
if (col < tm.startPos) break; // The blocks have skipped us.
if (col >= tm.startPos && col < tm.endPos)
{
blockType = tm.blockHash;
break;
}
}
if (subFindMatchBackward(match,sb,tmall,offset,caret.col,blockType,y)) return;
for (y--; y >= 0; y--)
{
tmall = marker.getStyles(code.get(y));
if (subFindMatchBackward(match,code.getsb(y),tmall,tmall.size() - 1,code.getsb(y).length(),
blockType,y)) return;
}
}
/**
* @param match The BracketMatch class representing this search.
* @param sb The StringBuilder of the line to search.The position from which to continue searching.
* @param tmall All marker tokens for this line.
* @param offset The marker token index from which to continue searching.
* @param spos The position from which to continue searching.
* @param blockType The type of block in which we are interested.
* @param y Our row number.
* @return True if the match was found in this line, false otherwise.
* Info about the match will be contained in the match parameter.
*/
private boolean subFindMatchBackward(BracketMatch match, StringBuilder sb,
ArrayList<TokenMarkerInfo> tmall, int offset, int spos, int blockType, int y)
{
int pos = spos;
int i = offset;
TokenMarkerInfo tm = tmall.get(i);
for (;;)
{
if (blockType == tmall.get(i).blockHash) // If the block has the
// same type
for (pos = Math.min(spos,tm.endPos - 1); pos >= tm.startPos; pos--)
// Check inside it
if (sb.charAt(pos) == match.match)
{
if (matchFound(match,pos,y)) return true;
}
else if (sb.charAt(pos) == match.opposite) match.count++;
if (i > 0)
{
tm = tmall.get(--i);
if (blockType == 0) // If our start wasn't in a block
for (pos = tm.startPos - 1; pos >= tm.endPos; pos--)
// Check outside this block's range
if (sb.charAt(pos) == match.match)
{
if (matchFound(match,pos,y)) return true;
}
else if (sb.charAt(pos) == match.opposite) match.count++;
}
else
{
if (blockType == 0) // If our start wasn't in a block
for (pos = tm.startPos - 1; pos >= 0; pos--)
// Check outside this block's range
if (sb.charAt(pos) == match.match)
{
if (matchFound(match,pos,y)) return true;
}
else if (sb.charAt(pos) == match.opposite) match.count++;
break;
}
}
return false;
}
/** Callback for when the caret position changes. */
@Override
public void caretUpdate(CaretEvent ce)
{
matching = MatchState.NOT_MATCHING;
StringBuilder sb = code.getsb(caret.row);
String start = "([{", end = ")]}";
for (int x : new int[] { caret.col - 1,caret.col })
if (x >= 0 && x < sb.length())
{
char c = sb.charAt(x);
int p = start.indexOf(c);
if (p != -1)
{
findMatchForward(caret.row,x,new BracketMatch(end.charAt(p),start.charAt(p),(short) 0));
return;
}
p = end.indexOf(c);
if (p != -1)
{
findMatchBackward(caret.row,x,new BracketMatch(start.charAt(p),end.charAt(p),(short) 0));
return;
}
}
}
}
// -----------------------------------------------------------------
// ----- Be Undoable -----------------------------------------------
// -----------------------------------------------------------------
/**
* A class of a dozen types an UndoPatch can have.
*
* @author josh
*/
static final class OPT
{
/** The patch is a one-of-a-kind that isn't worth its own constant. */
public static final int OTHER = 0;
/** The patch contains something the user typed. */
public static final int TYPED = 1;
/** The patch is from backspacing over something. */
public static final int BACKSPACE = 2;
/** The patch is from deleting something. */
public static final int DELETE = 3;
/**
* The patch is from typing a space; 'space' gets its
* own type to allow changing merge behavior around it
*/
public static final int SPACE = 4;
/** The patch is from a newline insertion. */
public static final int ENTER = 5;
/** The patch is from the 'paste' function. */
public static final int PASTE = 6;
/** The patch is from changing line indentation. */
public static final int INDENT = 7;
/** The patch is from the 'duplicate line' function. */
public static final int DUPLICATE = 8;
/** The patch is from a find-replace replace. */
public static final int REPLACE = 9;
/** The patch is from the 'swap lines' function. */
public static final int SWAP = 10;
/** The patch is from the 'unswap lines' function. */
public static final int UNSWAP = 11;
}
/**
* A class for storing two patches of code used in the
* Undo and Redo mechanisms. An UndoPatch contains sufficient
* information to be undone and applied any number of times
* during its lifecycle, with perfect accuracy assuming each
* patch is applied in the same order it was created and reverted
* in the opposite. (And was, of course, constructed properly.)
*
* @author josh
*/
class UndoPatch
{
/** The type of this UndoPatch; a member of {@link OPT} */
int opTag;
/**
* The text stored before the code was modified, hereafter
* referred to as the "pre-patch text."
*/
Line[] oldText;
/**
* The text as it stood after the modifications that sparked
* the creation of this UndoPatch, hereafter just "patch text."
*/
Line[] patchText;
/**
* The index of the row that begins both segments of text.
* In other words, both oldText and patchText must start at the same
* line.
*/
int startRow;
/** Caret/selection information from before the action in this undo item. */
CaretData cbefore = new CaretData();
/** Caret/selection information for immediately after the action in this undo item. */
CaretData cafter = new CaretData();
/**
* Storage class for grabbing caret data and later replacing it.
*/
class CaretData
{
/** The stored caret.column. */
public int ccol;
/** The stored caret.row. */
public int crow;
/** The stored sel.column. */
public int scol;
/** The stored sel.row. */
public int srow;
/** The stored sel.type*/
ST stype;
/**
* Grab the current caret indexes for use later.
*/
public void grab()
{
ccol = caret.col;
crow = caret.row;
scol = sel.col;
srow = sel.row;
stype = sel.type;
}
/**
* Replace previously grabbed caret data, modifying this.caret.
*/
public void replace()
{
caret.col = ccol;
caret.row = crow;
sel.col = scol;
sel.row = srow;
sel.type = stype;
}
/**
* Copy data from another instance.
* @param cfrom The CaretData class to copy from.
*/
public void copy(CaretData cfrom)
{
ccol = cfrom.ccol;
crow = cfrom.crow;
scol = cfrom.scol;
srow = cfrom.srow;
stype = cfrom.stype;
}
}
/**
* Construct a complete, finalized UndoPatch manually.
*
* @param t
* The pre-patch code.
* @param ot
* The patch code.
* @param sr
* The index of the starting row of the two codes.
*/
UndoPatch(Line[] t, Line[] ot, int sr)
{
oldText = ot;
patchText = t;
startRow = sr;
}
/**
* Prefixes a line to the stored pre-patch code, decrementing
* the recorded startRow to account for the change.
*
* @param ln
* The line to prefix to our stored pre-patch code.
*/
public void prefix_row(Line ln)
{
startRow--;
Line[] ancient = oldText;
oldText = new Line[oldText.length + 1];
oldText[0] = ln;
for (int i = 0; i < ancient.length; i++)
oldText[i + 1] = ancient[i];
}
/**
* A convenience constructor; same as calling the other overload as
* UndoPatch(<caret.row,sel.row>.sort).
*/
UndoPatch()
{
this(Math.min(caret.row,sel.row),Math.max(caret.row,sel.row));
}
/**
* Construct a new UndoPatch, copying in pre-patch code from
* {@link code} in the given row interval.
*
* @param startRow
* @param endRow
*/
UndoPatch(int startRow, int endRow)
{
final int lc = endRow - startRow + 1;
oldText = new Line[lc];
for (int i = 0; i < lc; i++)
oldText[i] = new Line(code.get(startRow + i));
this.startRow = startRow;
cbefore.grab();
}
/**
* Reconstruct the stored pre-patch text by copying from JoshText.code in
* the given row range.
*
* @param newStartRow
* The index of the first row to copy.
* @param newEndRow
* The index of the last row to copy.
*/
public void reconstruct(int newStartRow, int newEndRow)
{
final int lc = newEndRow - newStartRow + 1;
oldText = new Line[lc];
for (int i = 0; i < lc; i++)
oldText[i] = new Line(code.get(startRow + i));
startRow = newStartRow;
}
/**
* Populates the patchText member by copying data stored in this.code
* from the previously given starting line this.startRow to the newly
* specified end row.
*
* @param endRow
* The row at which to stop copying the patch text.
*/
public void realize(int endRow)
{
fireLineChange(startRow,endRow);
final int lc = endRow - startRow + 1;
patchText = new Line[lc];
for (int i = 0; i < lc; i++)
patchText[i] = new Line(code.get(startRow + i));
cafter.grab();
}
}
/**
* An array of all available UndoPatches to be reverted (as in Undo) or
* re-applied (as in Redo).
*/
private ArrayList<UndoPatch> undoPatches = new ArrayList<UndoPatch>();
/**
* A control variable that determines whether a new
* UndoPatch can be merged with an old if it is compatible.
*/
private boolean undoCanMerge = true;
/**
* Our position in {@link undoPatches}.
*/
private int patchIndex = 0;
/**
* Undo the most recently stored UndoPatch.
* The patch itself is not moved; instead, patchIndex is decremented.
*/
public void undo()
{
if (patchIndex == 0) return;
UndoPatch p = undoPatches.get(--patchIndex);
// Reverse patch
int prow;
for (prow = 0; prow < p.patchText.length; prow++)
{
if (prow >= p.oldText.length)
{
for (int da = p.patchText.length - prow; da > 0; da--)
code.remove(p.startRow + prow);
break;
}
code.set(p.startRow + prow,new Line(p.oldText[prow]));
}
while (prow < p.oldText.length)
{
code.add(p.startRow + prow,new Line(p.oldText[prow]));
prow++;
}
p.cbefore.replace();
fireLineChange(p.startRow,p.startRow + p.oldText.length);
repaint();
}
/**
* Re-apply the UndoPatch that has most recently been undone.
* If no previous UndoPatch has been reverted, return without error.
*/
public void redo()
{
if (patchIndex >= undoPatches.size()) return;
UndoPatch p = undoPatches.get(patchIndex++);
// Perform patch
int prow;
for (prow = 0; prow < p.oldText.length; prow++)
{
if (prow >= p.patchText.length)
{
for (int da = p.oldText.length - prow; da > 0; da--)
code.remove(p.startRow + prow);
break;
}
code.set(p.startRow + prow,new Line(p.patchText[prow]));
}
while (prow < p.patchText.length)
{
code.add(p.startRow + prow,new Line(p.patchText[prow]));
prow++;
}
p.cafter.replace();
fireLineChange(p.startRow,p.startRow + p.oldText.length);
repaint();
}
/**
* Store an UndoPatch so we can undo it later.
*
* @param undo
* The UndoPatch to store.
* @param patchType
* The type of the patch, as a constant from OPT.
*/
public void storeUndo(UndoPatch undo, int patchType)
{
undo.opTag = patchType;
while (patchIndex < undoPatches.size())
undoPatches.remove(undoPatches.size() - 1);
if (!undoCanMerge || patchIndex == 0 || !undoCompatible(undoPatches.get(patchIndex - 1),undo))
{
undoPatches.add(undo);
undoCanMerge = true;
patchIndex++;
}
else
undoMerge(undo,undoPatches.get(patchIndex - 1));
}
/**
* Merge two undo patches into one, assuming the patches have the
* same starting line index and line count.
*
* @param merge
* The new UndoPatch to merge in.
* @param into
* The old UndoPatch into which we will merge the new one.
*/
private static void undoMerge(UndoPatch merge, UndoPatch into)
{
into.patchText = merge.patchText;
into.cafter.copy(merge.cafter);
into.opTag = merge.opTag;
}
/**
* Utility function to check if two UndoPatches are ideal candidates for
* merging.
*
* @param up1
* Some UndoPatch, which will be tested for merge sanity.
* @param up2
* Some other UndoPatch against which to test the first for
* compatibility.
* @return Whether, given the two undo patches, they should be merged
* instead of pushing the new one.
* @note It is immaterial which UndoPatch is newer.
*/
private static boolean undoCompatible(UndoPatch up1, UndoPatch up2)
{
if ((up1.opTag != up2.opTag && up2.opTag != OPT.SPACE) || up1.startRow != up2.startRow)
return false;
if (up1.oldText.length != up1.patchText.length || up1.oldText.length != up2.oldText.length
|| up2.patchText.length != up2.patchText.length) return false;
return true;
}
/** @see java.awt.event.FocusListener#focusGained(java.awt.event.FocusEvent) */
@Override
public void focusGained(FocusEvent arg0)
{
FindDialog.getInstance().selectedJoshText = this;
}
/** @see java.awt.event.FocusListener#focusLost(java.awt.event.FocusEvent) */
@Override
public void focusLost(FocusEvent arg0)
{ // Unused
}
/**
* Check if the text has been modified since open.
* @return Returns true if the code has been changed, false otherwise.
*/
public boolean isChanged()
{
return !undoPatches.isEmpty();
}
}
| true | true | protected void processKeyTyped(KeyEvent e)
{
final Point sc = new Point(caret.col,caret.row);
switch (e.getKeyChar())
{
case KeyEvent.VK_ENTER:
if (sel.type == Selection.ST.NORM)
{
UndoPatch up = new UndoPatch();
sel.deleteSel();
StringBuilder nr = code.getsb(caret.row);
int offset = 0;
StringBuilder ins = new StringBuilder();
for (int i = 0; i < nr.length(); i++)
if (Character.isWhitespace(nr.charAt(i)))
{
offset++;
ins.append(nr.charAt(i));
}
else
break;
int iind = myLang.hasIndentAfter(nr.toString());
if (iind != -1)
{
String ind = myLang.getIndent(iind);
ins.append(ind);
offset += ind.length();
}
code.add(++caret.row,ins + nr.substring(caret.col));
nr.delete(caret.col,nr.length());
sel.col = caret.col = offset;
caret.colw = line_wid_at(caret.row,caret.col);
up.realize(caret.row);
storeUndo(up,OPT.ENTER);
}
// RECT falls to here
sel.deselect(true);
break;
case KeyEvent.VK_BACK_SPACE:
switch (sel.type)
{
case NORM:
{
UndoPatch up = new UndoPatch();
int otype = selGetKind(code.getsb(caret.row),caret.col - 1);
if (!sel.deleteSel())
{
if (Settings.smartBackspace && otype == ChType.WHITE && caret.col > 0
&& all_white(code.getsb(caret.row).substring(0,caret.col)))
{
unindent(caret.row);
caret.col = sel.col;
up.realize(caret.row);
storeUndo(up,OPT.BACKSPACE);
break;
}
//
do
{
if (caret.col > 0)
{
code.getsb(caret.row).delete(caret.col - 1,caret.col);
--caret.col;
}
else if (caret.row > 0)
{
StringBuilder s1 = code.getsb(caret.row - 1);
StringBuilder s2 = code.getsb(caret.row);
code.remove(caret.row--);
up.prefix_row(code.get(caret.row));
caret.col = s1.length();
s1.append(s2);
}
else
break;
}
while (e.isControlDown() && selOfKind(code.getsb(caret.row),caret.col - 1,otype));
}
caret.colw = line_wid_at(caret.row,caret.col);
sel.deselect(false);
up.realize(caret.row);
storeUndo(up,OPT.BACKSPACE);
break;
}
case RECT:
{
UndoPatch up = new UndoPatch();
int otype = selGetKind(code.getsb(caret.row),caret.col - 1);
if (!sel.deleteSel())
{
if (e.isControlDown())
{
// Control-Backspace on multiple lines.
// We'll handle this by determining the smallest
// word/pattern we
// can control-backspace over, and running with it on
// all lines.
// Nab the smallest distance
int mindist = -1;
for (int y = Math.min(sel.row,caret.row); y <= Math.max(sel.row,caret.row); y++)
{
int actcol = column_to_index(y,caret.col);
StringBuilder sb = code.getsb(y);
otype = selGetKind(sb,actcol - 1);
int mcol = actcol, mydist = 0;
do
{
if (mcol > 0)
if (mcol < sb.length())
{
if (sb.charAt(mcol--) == '\t')
{
mydist += Settings.indentSizeInSpaces;
mydist /= Settings.indentSizeInSpaces;
mydist *= Settings.indentSizeInSpaces;
}
else
mydist += 1;
}
else
{
mydist++;
mcol--;
}
else
break;
}
while (selOfKind(code.getsb(y),mcol - 1,otype));
if (mindist == -1 || mydist < mindist) mindist = mydist;
}
int cs = caret.col - mindist, ce = caret.col;
sel.col = caret.col = cs;
caret.colw = line_wid_at(caret.row,caret.col);
for (int y = Math.min(sel.row,caret.row); y <= Math.max(sel.row,caret.row); y++)
code.getsb(y).delete(column_to_index(y,cs),column_to_index(y,ce));
}
else if (caret.col > 0)
{
for (int y = Math.min(sel.row,caret.row); y <= Math.max(sel.row,caret.row); y++)
code.getsb(y).delete(column_to_index(y,caret.col - 1),
column_to_index(y,caret.col));
sel.col = --caret.col;
caret.colw = caret.col * monoAdvance;
}
}
up.realize(Math.max(caret.row,sel.row));
storeUndo(up,OPT.BACKSPACE);
break;
}
}
break;
case KeyEvent.VK_DELETE:
switch (sel.type)
{
case NORM:
{
UndoPatch up = new UndoPatch();
int otype = selGetKind(code.getsb(caret.row),caret.col);
if (!sel.deleteSel()) do
{
if (caret.col < code.getsb(caret.row).length())
code.getsb(caret.row).delete(caret.col,caret.col + 1);
else if (caret.row + 1 < code.size())
{
StringBuilder s1 = code.getsb(caret.row);
StringBuilder s2 = code.getsb(caret.row + 1);
code.remove(caret.row + 1);
s1.append(s2);
}
else
break;
}
while (e.isControlDown() && selOfKind(code.getsb(caret.row),caret.col,otype));
up.realize(caret.row);
storeUndo(up,OPT.DELETE);
break;
}
case RECT:
{
UndoPatch up = new UndoPatch();
int otype = selGetKind(code.getsb(caret.row),caret.col);
if (!sel.deleteSel())
{
for (int y = Math.min(sel.row,caret.row); y <= Math.max(sel.row,caret.row); y++)
{
int dcol = column_to_index(y,caret.col);
otype = selGetKind(code.getsb(y),dcol);
do
{
if (dcol < code.getsb(y).length())
code.getsb(y).delete(dcol,dcol + 1);
else
break;
}
while (e.isControlDown() && selOfKind(code.getsb(y),dcol,otype));
}
}
up.realize(caret.row);
storeUndo(up,OPT.DELETE);
break;
}
}
break;
case KeyEvent.VK_TAB:
if (!sel.isEmpty())
{
UndoPatch up = new UndoPatch();
String tab = Settings.indentRepString;
int yx = Math.max(sel.row,caret.row);
for (int y = Math.min(sel.row,caret.row); y <= yx; y++)
code.getsb(y).insert(0,tab);
sel.col += tab.length();
caret.col += tab.length();
up.realize(Math.max(sel.row,caret.row));
storeUndo(up,OPT.INDENT);
break;
}
UndoPatch up = new UndoPatch();
sel.insert(Settings.indentRepString);
up.realize(caret.row);
storeUndo(up,OPT.TYPED);
break;
case '\u0018': // cancel (not sure why it's VK_FINAL instead of
// VK_CANCEL)
case KeyEvent.VK_ESCAPE: // escape (in paramString, this is \u001B,
// which is VK_ESCAPE
case KeyEvent.CHAR_UNDEFINED:
// these cases are taken from KeyEvent.paramString
break;
default:
if (e.isControlDown() || e.isAltDown())
{
switch (e.getKeyCode())
{
// Handle bindings. Usually this is handled by registering key
// bindings,
// in which case it is usually consumed before it gets here.
default:
break;
}
}
else
{
UndoPatch up2 = new UndoPatch();
sel.insert(e.getKeyChar());
up2.realize(caret.row);
storeUndo(up2,e.getKeyChar() == ' ' ? OPT.SPACE : OPT.TYPED);
}
break;
}
if (sc.x != caret.col || sc.y != caret.row) caret.positionChanged();
doCodeSize(true);
// doShowCursor();
}
| protected void processKeyTyped(KeyEvent e)
{
final Point sc = new Point(caret.col,caret.row);
switch (e.getKeyChar())
{
case KeyEvent.VK_ENTER:
if (sel.type == Selection.ST.NORM)
{
UndoPatch up = new UndoPatch();
sel.deleteSel();
StringBuilder nr = code.getsb(caret.row);
int offset = 0;
StringBuilder ins = new StringBuilder();
for (int i = 0; i < nr.length() && i < caret.col; i++)
if (Character.isWhitespace(nr.charAt(i)))
{
offset++;
ins.append(nr.charAt(i));
}
else
break;
int iind = myLang.hasIndentAfter(nr.toString());
if (iind != -1)
{
String ind = myLang.getIndent(iind);
ins.append(ind);
offset += ind.length();
}
code.add(++caret.row,ins + nr.substring(caret.col));
nr.delete(caret.col,nr.length());
sel.col = caret.col = offset;
caret.colw = line_wid_at(caret.row,caret.col);
up.realize(caret.row);
storeUndo(up,OPT.ENTER);
}
// RECT falls to here
sel.deselect(true);
break;
case KeyEvent.VK_BACK_SPACE:
switch (sel.type)
{
case NORM:
{
UndoPatch up = new UndoPatch();
int otype = selGetKind(code.getsb(caret.row),caret.col - 1);
if (!sel.deleteSel())
{
if (Settings.smartBackspace && otype == ChType.WHITE && caret.col > 0
&& all_white(code.getsb(caret.row).substring(0,caret.col)))
{
unindent(caret.row);
caret.col = sel.col;
up.realize(caret.row);
storeUndo(up,OPT.BACKSPACE);
break;
}
//
do
{
if (caret.col > 0)
{
code.getsb(caret.row).delete(caret.col - 1,caret.col);
--caret.col;
}
else if (caret.row > 0)
{
StringBuilder s1 = code.getsb(caret.row - 1);
StringBuilder s2 = code.getsb(caret.row);
code.remove(caret.row--);
up.prefix_row(code.get(caret.row));
caret.col = s1.length();
s1.append(s2);
}
else
break;
}
while (e.isControlDown() && selOfKind(code.getsb(caret.row),caret.col - 1,otype));
}
caret.colw = line_wid_at(caret.row,caret.col);
sel.deselect(false);
up.realize(caret.row);
storeUndo(up,OPT.BACKSPACE);
break;
}
case RECT:
{
UndoPatch up = new UndoPatch();
int otype = selGetKind(code.getsb(caret.row),caret.col - 1);
if (!sel.deleteSel())
{
if (e.isControlDown())
{
// Control-Backspace on multiple lines.
// We'll handle this by determining the smallest
// word/pattern we
// can control-backspace over, and running with it on
// all lines.
// Nab the smallest distance
int mindist = -1;
for (int y = Math.min(sel.row,caret.row); y <= Math.max(sel.row,caret.row); y++)
{
int actcol = column_to_index(y,caret.col);
StringBuilder sb = code.getsb(y);
otype = selGetKind(sb,actcol - 1);
int mcol = actcol, mydist = 0;
do
{
if (mcol > 0)
if (mcol < sb.length())
{
if (sb.charAt(mcol--) == '\t')
{
mydist += Settings.indentSizeInSpaces;
mydist /= Settings.indentSizeInSpaces;
mydist *= Settings.indentSizeInSpaces;
}
else
mydist += 1;
}
else
{
mydist++;
mcol--;
}
else
break;
}
while (selOfKind(code.getsb(y),mcol - 1,otype));
if (mindist == -1 || mydist < mindist) mindist = mydist;
}
int cs = caret.col - mindist, ce = caret.col;
sel.col = caret.col = cs;
caret.colw = line_wid_at(caret.row,caret.col);
for (int y = Math.min(sel.row,caret.row); y <= Math.max(sel.row,caret.row); y++)
code.getsb(y).delete(column_to_index(y,cs),column_to_index(y,ce));
}
else if (caret.col > 0)
{
for (int y = Math.min(sel.row,caret.row); y <= Math.max(sel.row,caret.row); y++)
code.getsb(y).delete(column_to_index(y,caret.col - 1),
column_to_index(y,caret.col));
sel.col = --caret.col;
caret.colw = caret.col * monoAdvance;
}
}
up.realize(Math.max(caret.row,sel.row));
storeUndo(up,OPT.BACKSPACE);
break;
}
}
break;
case KeyEvent.VK_DELETE:
switch (sel.type)
{
case NORM:
{
UndoPatch up = new UndoPatch();
int otype = selGetKind(code.getsb(caret.row),caret.col);
if (!sel.deleteSel()) do
{
if (caret.col < code.getsb(caret.row).length())
code.getsb(caret.row).delete(caret.col,caret.col + 1);
else if (caret.row + 1 < code.size())
{
StringBuilder s1 = code.getsb(caret.row);
StringBuilder s2 = code.getsb(caret.row + 1);
code.remove(caret.row + 1);
s1.append(s2);
}
else
break;
}
while (e.isControlDown() && selOfKind(code.getsb(caret.row),caret.col,otype));
up.realize(caret.row);
storeUndo(up,OPT.DELETE);
break;
}
case RECT:
{
UndoPatch up = new UndoPatch();
int otype = selGetKind(code.getsb(caret.row),caret.col);
if (!sel.deleteSel())
{
for (int y = Math.min(sel.row,caret.row); y <= Math.max(sel.row,caret.row); y++)
{
int dcol = column_to_index(y,caret.col);
otype = selGetKind(code.getsb(y),dcol);
do
{
if (dcol < code.getsb(y).length())
code.getsb(y).delete(dcol,dcol + 1);
else
break;
}
while (e.isControlDown() && selOfKind(code.getsb(y),dcol,otype));
}
}
up.realize(caret.row);
storeUndo(up,OPT.DELETE);
break;
}
}
break;
case KeyEvent.VK_TAB:
if (!sel.isEmpty())
{
UndoPatch up = new UndoPatch();
String tab = Settings.indentRepString;
int yx = Math.max(sel.row,caret.row);
for (int y = Math.min(sel.row,caret.row); y <= yx; y++)
code.getsb(y).insert(0,tab);
sel.col += tab.length();
caret.col += tab.length();
up.realize(Math.max(sel.row,caret.row));
storeUndo(up,OPT.INDENT);
break;
}
UndoPatch up = new UndoPatch();
sel.insert(Settings.indentRepString);
up.realize(caret.row);
storeUndo(up,OPT.TYPED);
break;
case '\u0018': // cancel (not sure why it's VK_FINAL instead of
// VK_CANCEL)
case KeyEvent.VK_ESCAPE: // escape (in paramString, this is \u001B,
// which is VK_ESCAPE
case KeyEvent.CHAR_UNDEFINED:
// these cases are taken from KeyEvent.paramString
break;
default:
if (e.isControlDown() || e.isAltDown())
{
switch (e.getKeyCode())
{
// Handle bindings. Usually this is handled by registering key
// bindings,
// in which case it is usually consumed before it gets here.
default:
break;
}
}
else
{
UndoPatch up2 = new UndoPatch();
sel.insert(e.getKeyChar());
up2.realize(caret.row);
storeUndo(up2,e.getKeyChar() == ' ' ? OPT.SPACE : OPT.TYPED);
}
break;
}
if (sc.x != caret.col || sc.y != caret.row) caret.positionChanged();
doCodeSize(true);
// doShowCursor();
}
|
diff --git a/src/de/uni_koblenz/jgralab/greql2/parser/ManualGreqlLexer.java b/src/de/uni_koblenz/jgralab/greql2/parser/ManualGreqlLexer.java
index 90e34fafd..e1dda820e 100644
--- a/src/de/uni_koblenz/jgralab/greql2/parser/ManualGreqlLexer.java
+++ b/src/de/uni_koblenz/jgralab/greql2/parser/ManualGreqlLexer.java
@@ -1,355 +1,358 @@
package de.uni_koblenz.jgralab.greql2.parser;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import de.uni_koblenz.jgralab.greql2.exception.ParsingException;
public class ManualGreqlLexer {
protected static Map<TokenTypes, String> fixedTokens;
{
fixedTokens = new HashMap<TokenTypes, String>();
fixedTokens.put(TokenTypes.T, "T");
fixedTokens.put(TokenTypes.AND, "and");
fixedTokens.put(TokenTypes.FALSE, "false");
fixedTokens.put(TokenTypes.NOT, "not");
fixedTokens.put(TokenTypes.NULL_VALUE, "null");
fixedTokens.put(TokenTypes.OR, "or");
fixedTokens.put(TokenTypes.TRUE, "true");
fixedTokens.put(TokenTypes.XOR, "xor");
fixedTokens.put(TokenTypes.AS, "as");
fixedTokens.put(TokenTypes.BAG, "bag");
fixedTokens.put(TokenTypes.MAP, "map");
fixedTokens.put(TokenTypes.E, "E");
fixedTokens.put(TokenTypes.ESUBGRAPH, "eSubgraph");
fixedTokens.put(TokenTypes.EXISTS_ONE, "exists!");
fixedTokens.put(TokenTypes.EXISTS, "exists");
fixedTokens.put(TokenTypes.END, "end");
fixedTokens.put(TokenTypes.FORALL, "forall");
fixedTokens.put(TokenTypes.FROM, "from");
fixedTokens.put(TokenTypes.IN, "in");
fixedTokens.put(TokenTypes.LET, "let");
fixedTokens.put(TokenTypes.LIST, "list");
fixedTokens.put(TokenTypes.PATH, "pathconstruction");
fixedTokens.put(TokenTypes.PATHSYSTEM, "pathsystemconstruction");
fixedTokens.put(TokenTypes.REC, "rec");
fixedTokens.put(TokenTypes.REPORT, "report");
fixedTokens.put(TokenTypes.REPORTSET, "reportSet");
fixedTokens.put(TokenTypes.REPORTBAG, "reportBag");
fixedTokens.put(TokenTypes.REPORTTABLE, "reportTable");
fixedTokens.put(TokenTypes.REPORTMAP, "reportMap");
fixedTokens.put(TokenTypes.STORE, "store");
fixedTokens.put(TokenTypes.SET, "set");
fixedTokens.put(TokenTypes.TUP, "tup");
fixedTokens.put(TokenTypes.USING, "using");
fixedTokens.put(TokenTypes.V, "V");
fixedTokens.put(TokenTypes.VSUBGRAPH, "vSubgraph");
fixedTokens.put(TokenTypes.WHERE, "where");
fixedTokens.put(TokenTypes.WITH, "with");
fixedTokens.put(TokenTypes.QUESTION, "?");
fixedTokens.put(TokenTypes.EXCL, "!");
fixedTokens.put(TokenTypes.COLON, ":");
fixedTokens.put(TokenTypes.COMMA, ",");
fixedTokens.put(TokenTypes.DOT, ".");
fixedTokens.put(TokenTypes.DOTDOT, "..");
fixedTokens.put(TokenTypes.AT, "@");
fixedTokens.put(TokenTypes.LPAREN, "(");
fixedTokens.put(TokenTypes.RPAREN, ")");
fixedTokens.put(TokenTypes.LBRACK, "[");
fixedTokens.put(TokenTypes.RBRACK, "]");
fixedTokens.put(TokenTypes.LCURLY, "{");
fixedTokens.put(TokenTypes.RCURLY, "}");
fixedTokens.put(TokenTypes.EDGESTART, "<-");
fixedTokens.put(TokenTypes.EDGEEND, "->");
fixedTokens.put(TokenTypes.EDGE, "--");
fixedTokens.put(TokenTypes.RARROW, "-->");
fixedTokens.put(TokenTypes.LARROW, "<--");
fixedTokens.put(TokenTypes.ARROW, "<->");
fixedTokens.put(TokenTypes.ASSIGN, ":=");
fixedTokens.put(TokenTypes.EQUAL, "=");
fixedTokens.put(TokenTypes.MATCH, "=~");
fixedTokens.put(TokenTypes.NOT_EQUAL, "<>");
fixedTokens.put(TokenTypes.LE, "<=");
fixedTokens.put(TokenTypes.GE, ">=");
fixedTokens.put(TokenTypes.L_T, "<");
fixedTokens.put(TokenTypes.G_T, ">");
fixedTokens.put(TokenTypes.DIV, "/");
fixedTokens.put(TokenTypes.PLUS, "+");
fixedTokens.put(TokenTypes.MINUS, "-");
fixedTokens.put(TokenTypes.STAR, "*");
fixedTokens.put(TokenTypes.MOD, "%");
fixedTokens.put(TokenTypes.PLUSPLUS, "++");
fixedTokens.put(TokenTypes.SEMI, ";");
fixedTokens.put(TokenTypes.CARET, "^");
fixedTokens.put(TokenTypes.BOR, "|");
fixedTokens.put(TokenTypes.AMP, "&");
fixedTokens.put(TokenTypes.SMILEY, ":-)");
fixedTokens.put(TokenTypes.HASH, "#");
fixedTokens.put(TokenTypes.OUTAGGREGATION, "<>--");
fixedTokens.put(TokenTypes.INAGGREGATION, "--<>");
fixedTokens.put(TokenTypes.PATHSYSTEMSTART, "-<");
fixedTokens.put(TokenTypes.IMPORT, "import");
}
protected String query = null;
protected int position = 0;
public ManualGreqlLexer(String source) {
this.query = source;
if (query == null) {
throw new NullPointerException(
"Cannot parse nullpointer as GReQL query");
}
}
public static String getTokenString(TokenTypes token) {
return fixedTokens.get(token);
}
private final static boolean isSeparator(int c) {
return (c == ';') || (c == '<') || (c == '>') || (c == '(')
|| (c == ')') || (c == '{') || (c == '}') || (c == ':')
|| (c == '[') || (c == ']') || (c == ',') || (c == ' ')
|| (c == '\n') || (c == '\t') || (c == '.') || (c == '-')
|| (c == '+') || (c == '*') || (c == '/') || (c == '%')
|| (c == '~') || (c == '=') || (c == '?') || (c == '^')
|| (c == '|') || (c == '!') || (c == '@');
}
public Token getNextToken() {
TokenTypes recognizedTokenType = null;
Token recognizedToken = null;
int bml = 0; // best match length
skipWs();
// recognize fixed tokens
for (Entry<TokenTypes, String> currentEntry : fixedTokens.entrySet()) {
String currentString = currentEntry.getValue();
int currLen = currentString.length();
if (bml > currLen) {
continue;
}
if (query.regionMatches(position, currentString, 0, currLen)) {
if (((position + currLen) == query.length())
|| isSeparator(query.charAt(position + currLen - 1))
|| isSeparator(query.charAt(position + currLen))) {
bml = currLen;
recognizedTokenType = currentEntry.getKey();
}
}
}
// recognize strings and identifiers
if (recognizedTokenType == null) {
if (query.charAt(position) == '\"') { // String
position++;
int start = position;
StringBuilder sb = new StringBuilder();
while ((position < query.length())
&& (query.charAt(position) != '\"')) {
if (query.charAt(position) == '\\') {
if (position == query.length()) {
throw new ParsingException(
"String started at position " + start
+ " but is not closed in query",
query.substring(start, position), start,
position - start, query);
}
if ((query.charAt(position + 1) == '\"')
|| (query.charAt(position + 1) == '\\')) {
position++;
}
}
sb.append(query.charAt(position));
position++;
}
if ((position >= query.length())
|| (query.charAt(position) != '\"')) {
throw new ParsingException("String started at position "
+ start + " but is not closed in query", sb
.toString(), start, position - start, query);
}
recognizedTokenType = TokenTypes.STRING;
recognizedToken = new ComplexToken(recognizedTokenType, start,
position, sb.toString());
position++;
} else {
// identifier and literals
StringBuffer nextPossibleToken = new StringBuffer();
int start = position;
while ((query.length() > position)
&& (!isSeparator(query.charAt(position)))) {
nextPossibleToken.append(query.charAt(position++));
}
+ if (query.length() <= position) {
+ return new SimpleToken(TokenTypes.EOF, start, 0);
+ }
String tokenText = nextPossibleToken.toString();
if (tokenText.equals("thisVertex")) {
recognizedToken = new ComplexToken(TokenTypes.THISVERTEX,
start, position - start, tokenText);
} else if (tokenText.equals("thisEdge")) {
recognizedToken = new ComplexToken(TokenTypes.THISEDGE,
start, position - start, tokenText);
} else if (startsWithNumber(tokenText)) {
recognizedToken = matchNumericToken(start,
position - start, tokenText);
} else {
recognizedToken = new ComplexToken(TokenTypes.IDENTIFIER,
start, position - start, tokenText);
}
}
} else {
recognizedToken = new SimpleToken(recognizedTokenType, position,
bml);
position += bml;
}
if (recognizedToken == null) {
throw new ParsingException(
"Error while scanning query at position", null, position,
position, query);
}
return recognizedToken;
}
private final boolean startsWithNumber(String text) {
char c = text.charAt(0);
return (c >= Character.valueOf('0')) && (c <= Character.valueOf('9'));
}
// TODO: Exponenten
private final Token matchNumericToken(int start, int end, String text) {
int value = 0;
int decValue = 0;
TokenTypes type = null;
if ((text.charAt(0) == '0') && (text.charAt(text.length() - 1) != 'f')
&& (text.charAt(text.length() - 1) != 'F')
&& (text.charAt(text.length() - 1) != 'd')
&& (text.charAt(text.length() - 1) != 'D')) {
if (text.length() == 1) {
type = TokenTypes.INTLITERAL;
value = 0;
} else if ((text.charAt(1) == 'x') || (text.charAt(1) == 'X')) {
type = TokenTypes.HEXLITERAL;
try {
value = Integer.parseInt(text.substring(2), 16);
} catch (NumberFormatException ex) {
throw new ParsingException("Not a valid hex number", text,
start, end - start, query);
}
} else {
type = TokenTypes.OCTLITERAL;
try {
value = Integer.parseInt(text.substring(1), 8);
decValue = Integer.parseInt(text);
} catch (NumberFormatException ex) {
throw new ParsingException("Not a valid octal number",
text, start, end - start, query);
}
}
} else {
switch (text.charAt(text.length() - 1)) {
case 'h':
type = TokenTypes.HEXLITERAL;
try {
value = Integer.parseInt(text.substring(0,
text.length() - 1), 16);
} catch (NumberFormatException ex) {
throw new ParsingException("Not a valid hex number", text,
start, end - start, query);
}
break;
case 'd':
case 'D':
case 'f':
case 'F':
type = TokenTypes.REALLITERAL;
try {
String tokenString = text.substring(0, text.length() - 1);
System.out.println("TokenString: " + tokenString);
return new RealToken(type, start, end - start, Double
.parseDouble(tokenString));
} catch (NumberFormatException ex) {
throw new ParsingException("Not a valid float number",
text, start, end - start, query);
}
default:
type = TokenTypes.INTLITERAL;
try {
value = Integer.parseInt(text);
} catch (NumberFormatException ex) {
throw new ParsingException("Not a valid integer number",
text, start, end - start, query);
}
}
}
if (type != TokenTypes.OCTLITERAL) {
decValue = value;
}
return new IntegerToken(type, start, end - start, value, decValue);
}
public boolean hasNextToken() {
skipWs();
return (position < query.length());
}
private final static boolean isWs(int c) {
return (c == ' ') || (c == '\n') || (c == '\t') || (c == '\r');
}
private final void skipWs() {
// skip whitespace and consecutive single line comments
do {
// skip whitespace
while ((position < query.length()) && isWs(query.charAt(position))) {
position++;
}
// skip single line comments
if ((position < query.length() - 2)
&& (query.substring(position, position + 2).equals("//"))) {
position++;
while ((position < query.length())
&& (query.charAt(position) != '\n')) {
position++;
}
if ((position < query.length()) && (query.charAt(position) == '\n')) {
position++;
}
}
//skip multiline comments
if ((position < query.length() - 4)
&& (query.substring(position, position + 2).equals("/*"))) {
position++;
while ((position < query.length()-1)
&& (query.substring(position, position + 2).equals("*/"))) {
position++;
}
if ((position < query.length()) && (query.substring(position, position + 2).equals("*/"))) {
position+=2;
}
}
} while (
((position < query.length()) && (isWs(query.charAt(position))))
|| ((position < query.length() - 2) && (query.substring(position, position + 2).equals("//")))
|| ((position < query.length() - 4) && (query.substring(position, position + 2).equals("/*")))
);
}
public static List<Token> scan(String query) {
List<Token> list = new ArrayList<Token>();
ManualGreqlLexer lexer = new ManualGreqlLexer(query);
while (lexer.hasNextToken()) {
Token nextToken = lexer.getNextToken();
list.add(nextToken);
}
if (list.isEmpty() || (list.get(list.size()-1).type != TokenTypes.EOF)) {
list.add(new SimpleToken(TokenTypes.EOF, lexer.position, 0));
}
return list;
}
}
| true | true | public Token getNextToken() {
TokenTypes recognizedTokenType = null;
Token recognizedToken = null;
int bml = 0; // best match length
skipWs();
// recognize fixed tokens
for (Entry<TokenTypes, String> currentEntry : fixedTokens.entrySet()) {
String currentString = currentEntry.getValue();
int currLen = currentString.length();
if (bml > currLen) {
continue;
}
if (query.regionMatches(position, currentString, 0, currLen)) {
if (((position + currLen) == query.length())
|| isSeparator(query.charAt(position + currLen - 1))
|| isSeparator(query.charAt(position + currLen))) {
bml = currLen;
recognizedTokenType = currentEntry.getKey();
}
}
}
// recognize strings and identifiers
if (recognizedTokenType == null) {
if (query.charAt(position) == '\"') { // String
position++;
int start = position;
StringBuilder sb = new StringBuilder();
while ((position < query.length())
&& (query.charAt(position) != '\"')) {
if (query.charAt(position) == '\\') {
if (position == query.length()) {
throw new ParsingException(
"String started at position " + start
+ " but is not closed in query",
query.substring(start, position), start,
position - start, query);
}
if ((query.charAt(position + 1) == '\"')
|| (query.charAt(position + 1) == '\\')) {
position++;
}
}
sb.append(query.charAt(position));
position++;
}
if ((position >= query.length())
|| (query.charAt(position) != '\"')) {
throw new ParsingException("String started at position "
+ start + " but is not closed in query", sb
.toString(), start, position - start, query);
}
recognizedTokenType = TokenTypes.STRING;
recognizedToken = new ComplexToken(recognizedTokenType, start,
position, sb.toString());
position++;
} else {
// identifier and literals
StringBuffer nextPossibleToken = new StringBuffer();
int start = position;
while ((query.length() > position)
&& (!isSeparator(query.charAt(position)))) {
nextPossibleToken.append(query.charAt(position++));
}
String tokenText = nextPossibleToken.toString();
if (tokenText.equals("thisVertex")) {
recognizedToken = new ComplexToken(TokenTypes.THISVERTEX,
start, position - start, tokenText);
} else if (tokenText.equals("thisEdge")) {
recognizedToken = new ComplexToken(TokenTypes.THISEDGE,
start, position - start, tokenText);
} else if (startsWithNumber(tokenText)) {
recognizedToken = matchNumericToken(start,
position - start, tokenText);
} else {
recognizedToken = new ComplexToken(TokenTypes.IDENTIFIER,
start, position - start, tokenText);
}
}
} else {
recognizedToken = new SimpleToken(recognizedTokenType, position,
bml);
position += bml;
}
if (recognizedToken == null) {
throw new ParsingException(
"Error while scanning query at position", null, position,
position, query);
}
return recognizedToken;
}
| public Token getNextToken() {
TokenTypes recognizedTokenType = null;
Token recognizedToken = null;
int bml = 0; // best match length
skipWs();
// recognize fixed tokens
for (Entry<TokenTypes, String> currentEntry : fixedTokens.entrySet()) {
String currentString = currentEntry.getValue();
int currLen = currentString.length();
if (bml > currLen) {
continue;
}
if (query.regionMatches(position, currentString, 0, currLen)) {
if (((position + currLen) == query.length())
|| isSeparator(query.charAt(position + currLen - 1))
|| isSeparator(query.charAt(position + currLen))) {
bml = currLen;
recognizedTokenType = currentEntry.getKey();
}
}
}
// recognize strings and identifiers
if (recognizedTokenType == null) {
if (query.charAt(position) == '\"') { // String
position++;
int start = position;
StringBuilder sb = new StringBuilder();
while ((position < query.length())
&& (query.charAt(position) != '\"')) {
if (query.charAt(position) == '\\') {
if (position == query.length()) {
throw new ParsingException(
"String started at position " + start
+ " but is not closed in query",
query.substring(start, position), start,
position - start, query);
}
if ((query.charAt(position + 1) == '\"')
|| (query.charAt(position + 1) == '\\')) {
position++;
}
}
sb.append(query.charAt(position));
position++;
}
if ((position >= query.length())
|| (query.charAt(position) != '\"')) {
throw new ParsingException("String started at position "
+ start + " but is not closed in query", sb
.toString(), start, position - start, query);
}
recognizedTokenType = TokenTypes.STRING;
recognizedToken = new ComplexToken(recognizedTokenType, start,
position, sb.toString());
position++;
} else {
// identifier and literals
StringBuffer nextPossibleToken = new StringBuffer();
int start = position;
while ((query.length() > position)
&& (!isSeparator(query.charAt(position)))) {
nextPossibleToken.append(query.charAt(position++));
}
if (query.length() <= position) {
return new SimpleToken(TokenTypes.EOF, start, 0);
}
String tokenText = nextPossibleToken.toString();
if (tokenText.equals("thisVertex")) {
recognizedToken = new ComplexToken(TokenTypes.THISVERTEX,
start, position - start, tokenText);
} else if (tokenText.equals("thisEdge")) {
recognizedToken = new ComplexToken(TokenTypes.THISEDGE,
start, position - start, tokenText);
} else if (startsWithNumber(tokenText)) {
recognizedToken = matchNumericToken(start,
position - start, tokenText);
} else {
recognizedToken = new ComplexToken(TokenTypes.IDENTIFIER,
start, position - start, tokenText);
}
}
} else {
recognizedToken = new SimpleToken(recognizedTokenType, position,
bml);
position += bml;
}
if (recognizedToken == null) {
throw new ParsingException(
"Error while scanning query at position", null, position,
position, query);
}
return recognizedToken;
}
|
diff --git a/wikAPIdia-sr/src/main/java/org/wikapidia/sr/MatrixBuilder.java b/wikAPIdia-sr/src/main/java/org/wikapidia/sr/MatrixBuilder.java
index d7d1c773..7cc121dd 100644
--- a/wikAPIdia-sr/src/main/java/org/wikapidia/sr/MatrixBuilder.java
+++ b/wikAPIdia-sr/src/main/java/org/wikapidia/sr/MatrixBuilder.java
@@ -1,78 +1,80 @@
package org.wikapidia.sr;
import org.apache.commons.cli.*;
import org.apache.commons.io.FileUtils;
import org.wikapidia.conf.ConfigurationException;
import org.wikapidia.conf.Configurator;
import org.wikapidia.conf.DefaultOptionBuilder;
import org.wikapidia.core.WikapidiaException;
import org.wikapidia.core.cmd.Env;
import org.wikapidia.core.dao.DaoException;
import org.wikapidia.core.lang.LanguageSet;
import java.io.File;
import java.io.IOException;
/**
* @author Matt Lesicko
*/
public class MatrixBuilder {
public static void main(String args[]) throws ConfigurationException, IOException, WikapidiaException, DaoException {
Options options = new Options();
options.addOption(
new DefaultOptionBuilder()
.hasArg()
.withLongOpt("universal")
.withDescription("set a universal metric")
.create("u"));
options.addOption(
new DefaultOptionBuilder()
.hasArg()
.withLongOpt("metric")
.withDescription("set a local metric")
.create("m"));
options.addOption(
new DefaultOptionBuilder()
.hasArg()
.withLongOpt("max-results")
.withDescription("maximum number of results")
.create("r"));
Env.addStandardOptions(options);
CommandLineParser parser = new PosixParser();
CommandLine cmd;
try {
cmd = parser.parse(options, args);
} catch (ParseException e) {
System.err.println("Invalid option usage: " + e.getMessage());
new HelpFormatter().printHelp("MatrixBuilder", options);
return;
}
Env env = new Env(cmd);
Configurator c = env.getConfigurator();
if (!cmd.hasOption("m")&&!cmd.hasOption("u")){
- throw new IllegalArgumentException("Must specify a metric to build the matrix for.");
+ System.err.println("Must specify a metric using -u or -m");
+ new HelpFormatter().printHelp("MatrixBuilder", options);
+ return;
}
LanguageSet languages = env.getLanguages();
String path = c.getConf().get().getString("sr.metric.path");
int maxResults = cmd.hasOption("r")? Integer.parseInt(cmd.getOptionValue("r")) : c.getConf().get().getInt("sr.normalizer.defaultmaxresults");
LocalSRMetric sr=null;
UniversalSRMetric usr=null;
if (cmd.hasOption("m")){
FileUtils.deleteDirectory(new File(path + cmd.getOptionValue("m") + "/" + "matrix/"));
(new File(path + cmd.getOptionValue("m") + "/" + "matrix/")).mkdirs();
sr = c.get(LocalSRMetric.class,cmd.getOptionValue("m"));
sr.writeCosimilarity(path,languages,maxResults);
}
if (cmd.hasOption("u")){
FileUtils.deleteDirectory(new File(path+cmd.getOptionValue("u")+"/"+"matrix/"));
(new File(path + cmd.getOptionValue("u") + "/" + "matrix/")).mkdirs();
usr = c.get(UniversalSRMetric.class,cmd.getOptionValue("u"));
usr.writeCosimilarity(path,maxResults);
}
}
}
| true | true | public static void main(String args[]) throws ConfigurationException, IOException, WikapidiaException, DaoException {
Options options = new Options();
options.addOption(
new DefaultOptionBuilder()
.hasArg()
.withLongOpt("universal")
.withDescription("set a universal metric")
.create("u"));
options.addOption(
new DefaultOptionBuilder()
.hasArg()
.withLongOpt("metric")
.withDescription("set a local metric")
.create("m"));
options.addOption(
new DefaultOptionBuilder()
.hasArg()
.withLongOpt("max-results")
.withDescription("maximum number of results")
.create("r"));
Env.addStandardOptions(options);
CommandLineParser parser = new PosixParser();
CommandLine cmd;
try {
cmd = parser.parse(options, args);
} catch (ParseException e) {
System.err.println("Invalid option usage: " + e.getMessage());
new HelpFormatter().printHelp("MatrixBuilder", options);
return;
}
Env env = new Env(cmd);
Configurator c = env.getConfigurator();
if (!cmd.hasOption("m")&&!cmd.hasOption("u")){
throw new IllegalArgumentException("Must specify a metric to build the matrix for.");
}
LanguageSet languages = env.getLanguages();
String path = c.getConf().get().getString("sr.metric.path");
int maxResults = cmd.hasOption("r")? Integer.parseInt(cmd.getOptionValue("r")) : c.getConf().get().getInt("sr.normalizer.defaultmaxresults");
LocalSRMetric sr=null;
UniversalSRMetric usr=null;
if (cmd.hasOption("m")){
FileUtils.deleteDirectory(new File(path + cmd.getOptionValue("m") + "/" + "matrix/"));
(new File(path + cmd.getOptionValue("m") + "/" + "matrix/")).mkdirs();
sr = c.get(LocalSRMetric.class,cmd.getOptionValue("m"));
sr.writeCosimilarity(path,languages,maxResults);
}
if (cmd.hasOption("u")){
FileUtils.deleteDirectory(new File(path+cmd.getOptionValue("u")+"/"+"matrix/"));
(new File(path + cmd.getOptionValue("u") + "/" + "matrix/")).mkdirs();
usr = c.get(UniversalSRMetric.class,cmd.getOptionValue("u"));
usr.writeCosimilarity(path,maxResults);
}
}
| public static void main(String args[]) throws ConfigurationException, IOException, WikapidiaException, DaoException {
Options options = new Options();
options.addOption(
new DefaultOptionBuilder()
.hasArg()
.withLongOpt("universal")
.withDescription("set a universal metric")
.create("u"));
options.addOption(
new DefaultOptionBuilder()
.hasArg()
.withLongOpt("metric")
.withDescription("set a local metric")
.create("m"));
options.addOption(
new DefaultOptionBuilder()
.hasArg()
.withLongOpt("max-results")
.withDescription("maximum number of results")
.create("r"));
Env.addStandardOptions(options);
CommandLineParser parser = new PosixParser();
CommandLine cmd;
try {
cmd = parser.parse(options, args);
} catch (ParseException e) {
System.err.println("Invalid option usage: " + e.getMessage());
new HelpFormatter().printHelp("MatrixBuilder", options);
return;
}
Env env = new Env(cmd);
Configurator c = env.getConfigurator();
if (!cmd.hasOption("m")&&!cmd.hasOption("u")){
System.err.println("Must specify a metric using -u or -m");
new HelpFormatter().printHelp("MatrixBuilder", options);
return;
}
LanguageSet languages = env.getLanguages();
String path = c.getConf().get().getString("sr.metric.path");
int maxResults = cmd.hasOption("r")? Integer.parseInt(cmd.getOptionValue("r")) : c.getConf().get().getInt("sr.normalizer.defaultmaxresults");
LocalSRMetric sr=null;
UniversalSRMetric usr=null;
if (cmd.hasOption("m")){
FileUtils.deleteDirectory(new File(path + cmd.getOptionValue("m") + "/" + "matrix/"));
(new File(path + cmd.getOptionValue("m") + "/" + "matrix/")).mkdirs();
sr = c.get(LocalSRMetric.class,cmd.getOptionValue("m"));
sr.writeCosimilarity(path,languages,maxResults);
}
if (cmd.hasOption("u")){
FileUtils.deleteDirectory(new File(path+cmd.getOptionValue("u")+"/"+"matrix/"));
(new File(path + cmd.getOptionValue("u") + "/" + "matrix/")).mkdirs();
usr = c.get(UniversalSRMetric.class,cmd.getOptionValue("u"));
usr.writeCosimilarity(path,maxResults);
}
}
|
diff --git a/gson/src/main/java/com/google/gson/TypeInfoFactory.java b/gson/src/main/java/com/google/gson/TypeInfoFactory.java
index e02b647..deb88a2 100644
--- a/gson/src/main/java/com/google/gson/TypeInfoFactory.java
+++ b/gson/src/main/java/com/google/gson/TypeInfoFactory.java
@@ -1,124 +1,130 @@
/*
* Copyright (C) 2008 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.gson;
import java.lang.reflect.Field;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.lang.reflect.WildcardType;
/**
* A static factory class used to construct the "TypeInfo" objects.
*
* @author Inderjeet Singh
* @author Joel Leitch
*/
final class TypeInfoFactory {
private TypeInfoFactory() {
// Not instantiable since it provides factory methods only.
}
public static TypeInfoArray getTypeInfoForArray(Type type) {
Preconditions.checkArgument(TypeUtils.isArray(type));
return new TypeInfoArray(type);
}
/**
* Evaluates the "actual" type for the field. If the field is a "TypeVariable" or has a
* "TypeVariable" in a parameterized type then it evaluates the real type.
*
* @param f the actual field object to retrieve the type from
* @param typeDefiningF the type that contains the field {@code f}
* @return the type information for the field
*/
public static TypeInfo getTypeInfoForField(Field f, Type typeDefiningF) {
Class<?> classDefiningF = TypeUtils.toRawClass(typeDefiningF);
Type type = f.getGenericType();
Type actualType = getActualType(type, typeDefiningF, classDefiningF);
return new TypeInfo(actualType);
}
private static Type getActualType(
Type typeToEvaluate, Type parentType, Class<?> rawParentClass) {
if (typeToEvaluate instanceof Class) {
return typeToEvaluate;
} else if (typeToEvaluate instanceof ParameterizedType) {
ParameterizedType castedType = (ParameterizedType) typeToEvaluate;
Type owner = castedType.getOwnerType();
Type[] actualTypeParameters =
extractRealTypes(castedType.getActualTypeArguments(), parentType, rawParentClass);
Type rawType = castedType.getRawType();
return new ParameterizedTypeImpl(rawType, actualTypeParameters, owner);
} else if (typeToEvaluate instanceof GenericArrayType) {
GenericArrayType castedType = (GenericArrayType) typeToEvaluate;
Type componentType = castedType.getGenericComponentType();
Type actualType = getActualType(componentType, parentType, rawParentClass);
if (componentType.equals(actualType)) {
return castedType;
} else {
if (actualType instanceof Class) {
return TypeUtils.wrapWithArray(TypeUtils.toRawClass(actualType));
} else {
return new GenericArrayTypeImpl(actualType);
}
}
} else if (typeToEvaluate instanceof TypeVariable) {
- // The class definition has the actual types used for the type variables.
- // Find the matching actual type for the Type Variable used for the field.
- // For example, class Foo<A> { A a; }
- // new Foo<Integer>(); defines the actual type of A to be Integer.
- // So, to find the type of the field a, we will have to look at the class'
- // actual type arguments.
- TypeVariable<?> fieldTypeVariable = (TypeVariable<?>) typeToEvaluate;
- TypeVariable<?>[] classTypeVariables = rawParentClass.getTypeParameters();
- ParameterizedType objParameterizedType = (ParameterizedType) parentType;
- int indexOfActualTypeArgument = getIndex(classTypeVariables, fieldTypeVariable);
- Type[] actualTypeArguments = objParameterizedType.getActualTypeArguments();
- return actualTypeArguments[indexOfActualTypeArgument];
+ if (parentType instanceof ParameterizedType) {
+ // The class definition has the actual types used for the type variables.
+ // Find the matching actual type for the Type Variable used for the field.
+ // For example, class Foo<A> { A a; }
+ // new Foo<Integer>(); defines the actual type of A to be Integer.
+ // So, to find the type of the field a, we will have to look at the class'
+ // actual type arguments.
+ TypeVariable<?> fieldTypeVariable = (TypeVariable<?>) typeToEvaluate;
+ TypeVariable<?>[] classTypeVariables = rawParentClass.getTypeParameters();
+ ParameterizedType objParameterizedType = (ParameterizedType) parentType;
+ int indexOfActualTypeArgument = getIndex(classTypeVariables, fieldTypeVariable);
+ Type[] actualTypeArguments = objParameterizedType.getActualTypeArguments();
+ return actualTypeArguments[indexOfActualTypeArgument];
+ } else {
+ throw new UnsupportedOperationException("Expecting parameterized type, got " + parentType
+ + ".\n Are you missing the use of TypeToken idiom?\n See "
+ + "http://sites.google.com/site/gson/gson-user-guide#TOC-Serializing-and-Deserializing-Gener");
+ }
} else if (typeToEvaluate instanceof WildcardType) {
WildcardType castedType = (WildcardType) typeToEvaluate;
return getActualType(castedType.getUpperBounds()[0], parentType, rawParentClass);
} else {
throw new IllegalArgumentException("Type \'" + typeToEvaluate + "\' is not a Class, "
+ "ParameterizedType, GenericArrayType or TypeVariable. Can't extract type.");
}
}
private static Type[] extractRealTypes(
Type[] actualTypeArguments, Type parentType, Class<?> rawParentClass) {
Preconditions.checkNotNull(actualTypeArguments);
Type[] retTypes = new Type[actualTypeArguments.length];
for (int i = 0; i < actualTypeArguments.length; ++i) {
retTypes[i] = getActualType(actualTypeArguments[i], parentType, rawParentClass);
}
return retTypes;
}
private static int getIndex(TypeVariable<?>[] types, TypeVariable<?> type) {
for (int i = 0; i < types.length; ++i) {
if (type.equals(types[i])) {
return i;
}
}
throw new IllegalStateException(
"How can the type variable not be present in the class declaration!");
}
}
| true | true | private static Type getActualType(
Type typeToEvaluate, Type parentType, Class<?> rawParentClass) {
if (typeToEvaluate instanceof Class) {
return typeToEvaluate;
} else if (typeToEvaluate instanceof ParameterizedType) {
ParameterizedType castedType = (ParameterizedType) typeToEvaluate;
Type owner = castedType.getOwnerType();
Type[] actualTypeParameters =
extractRealTypes(castedType.getActualTypeArguments(), parentType, rawParentClass);
Type rawType = castedType.getRawType();
return new ParameterizedTypeImpl(rawType, actualTypeParameters, owner);
} else if (typeToEvaluate instanceof GenericArrayType) {
GenericArrayType castedType = (GenericArrayType) typeToEvaluate;
Type componentType = castedType.getGenericComponentType();
Type actualType = getActualType(componentType, parentType, rawParentClass);
if (componentType.equals(actualType)) {
return castedType;
} else {
if (actualType instanceof Class) {
return TypeUtils.wrapWithArray(TypeUtils.toRawClass(actualType));
} else {
return new GenericArrayTypeImpl(actualType);
}
}
} else if (typeToEvaluate instanceof TypeVariable) {
// The class definition has the actual types used for the type variables.
// Find the matching actual type for the Type Variable used for the field.
// For example, class Foo<A> { A a; }
// new Foo<Integer>(); defines the actual type of A to be Integer.
// So, to find the type of the field a, we will have to look at the class'
// actual type arguments.
TypeVariable<?> fieldTypeVariable = (TypeVariable<?>) typeToEvaluate;
TypeVariable<?>[] classTypeVariables = rawParentClass.getTypeParameters();
ParameterizedType objParameterizedType = (ParameterizedType) parentType;
int indexOfActualTypeArgument = getIndex(classTypeVariables, fieldTypeVariable);
Type[] actualTypeArguments = objParameterizedType.getActualTypeArguments();
return actualTypeArguments[indexOfActualTypeArgument];
} else if (typeToEvaluate instanceof WildcardType) {
WildcardType castedType = (WildcardType) typeToEvaluate;
return getActualType(castedType.getUpperBounds()[0], parentType, rawParentClass);
} else {
throw new IllegalArgumentException("Type \'" + typeToEvaluate + "\' is not a Class, "
+ "ParameterizedType, GenericArrayType or TypeVariable. Can't extract type.");
}
}
| private static Type getActualType(
Type typeToEvaluate, Type parentType, Class<?> rawParentClass) {
if (typeToEvaluate instanceof Class) {
return typeToEvaluate;
} else if (typeToEvaluate instanceof ParameterizedType) {
ParameterizedType castedType = (ParameterizedType) typeToEvaluate;
Type owner = castedType.getOwnerType();
Type[] actualTypeParameters =
extractRealTypes(castedType.getActualTypeArguments(), parentType, rawParentClass);
Type rawType = castedType.getRawType();
return new ParameterizedTypeImpl(rawType, actualTypeParameters, owner);
} else if (typeToEvaluate instanceof GenericArrayType) {
GenericArrayType castedType = (GenericArrayType) typeToEvaluate;
Type componentType = castedType.getGenericComponentType();
Type actualType = getActualType(componentType, parentType, rawParentClass);
if (componentType.equals(actualType)) {
return castedType;
} else {
if (actualType instanceof Class) {
return TypeUtils.wrapWithArray(TypeUtils.toRawClass(actualType));
} else {
return new GenericArrayTypeImpl(actualType);
}
}
} else if (typeToEvaluate instanceof TypeVariable) {
if (parentType instanceof ParameterizedType) {
// The class definition has the actual types used for the type variables.
// Find the matching actual type for the Type Variable used for the field.
// For example, class Foo<A> { A a; }
// new Foo<Integer>(); defines the actual type of A to be Integer.
// So, to find the type of the field a, we will have to look at the class'
// actual type arguments.
TypeVariable<?> fieldTypeVariable = (TypeVariable<?>) typeToEvaluate;
TypeVariable<?>[] classTypeVariables = rawParentClass.getTypeParameters();
ParameterizedType objParameterizedType = (ParameterizedType) parentType;
int indexOfActualTypeArgument = getIndex(classTypeVariables, fieldTypeVariable);
Type[] actualTypeArguments = objParameterizedType.getActualTypeArguments();
return actualTypeArguments[indexOfActualTypeArgument];
} else {
throw new UnsupportedOperationException("Expecting parameterized type, got " + parentType
+ ".\n Are you missing the use of TypeToken idiom?\n See "
+ "http://sites.google.com/site/gson/gson-user-guide#TOC-Serializing-and-Deserializing-Gener");
}
} else if (typeToEvaluate instanceof WildcardType) {
WildcardType castedType = (WildcardType) typeToEvaluate;
return getActualType(castedType.getUpperBounds()[0], parentType, rawParentClass);
} else {
throw new IllegalArgumentException("Type \'" + typeToEvaluate + "\' is not a Class, "
+ "ParameterizedType, GenericArrayType or TypeVariable. Can't extract type.");
}
}
|
diff --git a/src-gwt/com/alkacon/geranium/client/util/PositionBean.java b/src-gwt/com/alkacon/geranium/client/util/PositionBean.java
index ae70b86..bf03600 100644
--- a/src-gwt/com/alkacon/geranium/client/util/PositionBean.java
+++ b/src-gwt/com/alkacon/geranium/client/util/PositionBean.java
@@ -1,393 +1,404 @@
/*
* This library is part of Geranium -
* an open source UI library for GWT.
*
* Copyright (c) Alkacon Software GmbH (http://www.alkacon.com)-
*
* 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 (at your option) 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. See the GNU
* Lesser General Public License for more details.
*
* For further information about Alkacon Software, please see the
* company website: http://www.alkacon.com
*
* 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 com.alkacon.geranium.client.util;
import com.alkacon.geranium.client.util.DomUtil.Style;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.Node;
import com.google.gwt.dom.client.NodeList;
import com.google.gwt.dom.client.Style.Display;
import com.google.gwt.dom.client.Style.Overflow;
import com.google.gwt.dom.client.Style.Position;
import com.google.gwt.user.client.ui.UIObject;
/**
* Bean holding the position data of a HTML DOM element.<p>
*/
public class PositionBean {
/** Position area. */
public static enum Area {
/** Bottom border. */
BORDER_BOTTOM,
/** Left border. */
BORDER_LEFT,
/** Right border. */
BORDER_RIGHT,
/** Top border. */
BORDER_TOP,
/** The center. */
CENTER,
/** Bottom left corner. */
CORNER_BOTTOM_LEFT,
/** Bottom right corner. */
CORNER_BOTTOM_RIGHT,
/** Top left corner. */
CORNER_TOP_LEFT,
/** Top right corner. */
CORNER_TOP_RIGHT
}
/** Element height. */
private int m_height;
/** Position left. */
private int m_left;
/** Position top. */
private int m_top;
/** Element width. */
private int m_width;
/**
* Constructor.<p>
*/
public PositionBean() {
// default constructor
}
/**
* Copy constructor. Generating a copy of the given model.<p>
*
* @param model the model to copy
*/
public PositionBean(PositionBean model) {
m_height = model.getHeight();
m_left = model.getLeft();
m_top = model.getTop();
m_width = model.getWidth();
}
/**
* Collects the position information of the given UI object and returns a position info bean.<p>
*
* @param element the object to read the position data from
*
* @return the position data
*/
public static PositionBean generatePositionInfo(Element element) {
PositionBean result = new PositionBean();
result.setHeight(element.getOffsetHeight());
result.setWidth(element.getOffsetWidth());
result.setTop(element.getAbsoluteTop());
result.setLeft(element.getAbsoluteLeft());
return result;
}
/**
* Collects the position information of the given UI object and returns a position info bean.<p>
*
* @param uiObject the object to read the position data from
*
* @return the position data
*/
public static PositionBean generatePositionInfo(UIObject uiObject) {
return generatePositionInfo(uiObject.getElement());
}
/**
* Returns a position info representing the dimensions of all visible child elements of the given panel (excluding elements with position:absolute).
* If the panel has no visible child elements, it's outer dimensions are returned.<p>
*
* @param panel the panel
*
* @return the position info
*/
public static PositionBean getInnerDimensions(Element panel) {
return getInnerDimensions(panel, 2, false);
}
/**
* Returns a position info representing the dimensions of all visible child elements of the given panel (excluding elements with position:absolute).
* If the panel has no visible child elements, it's outer dimensions are returned.<p>
*
* @param panel the panel
* @param levels the levels to traverse down the DOM tree
* @param includeSelf <code>true</code> to include the outer dimensions of the given panel
*
* @return the position info
*/
public static PositionBean getInnerDimensions(Element panel, int levels, boolean includeSelf) {
boolean first = true;
int top = 0;
int left = 0;
int bottom = 0;
int right = 0;
// if overflow is set to hidden, use the outer dimensions
if (!Overflow.HIDDEN.getCssName().equals(DomUtil.getCurrentStyle(panel, Style.overflow))) {
if (!includeSelf) {
// check for any text content
NodeList<Node> children = panel.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
if ((children.getItem(i).getNodeType() == Node.TEXT_NODE)
&& (children.getItem(i).getNodeValue().trim().length() > 0)) {
includeSelf = true;
break;
}
}
}
if (includeSelf) {
top = panel.getAbsoluteTop();
left = panel.getAbsoluteLeft();
bottom = top + panel.getOffsetHeight();
right = left + panel.getOffsetWidth();
first = false;
}
Element child = panel.getFirstChildElement();
while (child != null) {
+ String tagName = child.getTagName();
+ if (tagName.equalsIgnoreCase("br")
+ || tagName.equalsIgnoreCase("tr")
+ || tagName.equalsIgnoreCase("thead")
+ || tagName.equalsIgnoreCase("tfoot")
+ || tagName.equalsIgnoreCase("script")
+ || tagName.equalsIgnoreCase("style")) {
+ // ignore tags with no relevant position info
+ child = child.getNextSiblingElement();
+ continue;
+ }
String positioning = DomUtil.getCurrentStyle(child, Style.position);
if (!Display.NONE.getCssName().equals(DomUtil.getCurrentStyle(child, Style.display))
&& !(positioning.equalsIgnoreCase(Position.ABSOLUTE.getCssName()) || positioning.equalsIgnoreCase(Position.FIXED.getCssName()))) {
PositionBean childDimensions = levels > 0
? getInnerDimensions(child, levels - 1, true)
: generatePositionInfo(panel);
if (first) {
first = false;
top = childDimensions.getTop();
left = childDimensions.getLeft();
bottom = top + childDimensions.getHeight();
right = left + childDimensions.getWidth();
} else {
int wTop = childDimensions.getTop();
top = top < wTop ? top : wTop;
int wLeft = childDimensions.getLeft();
left = left < wLeft ? left : wLeft;
int wBottom = wTop + childDimensions.getHeight();
bottom = bottom > wBottom ? bottom : wBottom;
int wRight = wLeft + childDimensions.getWidth();
right = right > wRight ? right : wRight;
}
}
child = child.getNextSiblingElement();
}
}
if (!first) {
PositionBean result = new PositionBean();
result.setHeight(bottom - top);
result.setWidth(right - left);
result.setTop(top);
result.setLeft(left);
return result;
} else {
return generatePositionInfo(panel);
}
}
/**
* Returns over which area of this the given position is. Will return <code>null</code> if the provided position is not within this position.<p>
*
* @param absLeft the left position
* @param absTop the right position
* @param offset the border offset
*
* @return the area
*/
public Area getArea(int absLeft, int absTop, int offset) {
if (isOverElement(absLeft, absTop)) {
if (absLeft < (m_left + 10)) {
// left border
if (absTop < (m_top + offset)) {
// top left corner
return Area.CORNER_TOP_LEFT;
} else if (absTop > ((m_top + m_height) - offset)) {
// bottom left corner
return Area.CORNER_BOTTOM_LEFT;
}
return Area.BORDER_LEFT;
}
if (absLeft > ((m_left + m_width) - offset)) {
// right border
if (absTop < (m_top + offset)) {
// top right corner
return Area.CORNER_TOP_RIGHT;
// fixing opposite corner
} else if (absTop > ((m_top + m_height) - offset)) {
// bottom right corner
return Area.CORNER_BOTTOM_RIGHT;
// fixing opposite corner
}
return Area.BORDER_RIGHT;
}
if (absTop < (m_top + offset)) {
// border top
return Area.BORDER_TOP;
} else if (absTop > ((m_top + m_height) - offset)) {
// border bottom
return Area.BORDER_BOTTOM;
}
return Area.CENTER;
}
return null;
}
/**
* Returns the height.<p>
*
* @return the height
*/
public int getHeight() {
return m_height;
}
/**
* Returns the left.<p>
*
* @return the left
*/
public int getLeft() {
return m_left;
}
/**
* Returns the top.<p>
*
* @return the top
*/
public int getTop() {
return m_top;
}
/**
* Returns the width.<p>
*
* @return the width
*/
public int getWidth() {
return m_width;
}
/**
* Returns if given position is inside the position beans coordinates.<p>
*
* @param absLeft the absolute left position
* @param absTop the absolute top position
*
* @return true if the given position if within the beans coordinates
*/
public boolean isOverElement(int absLeft, int absTop) {
if ((absTop > m_top) && (absTop < (m_top + m_height)) && (absLeft > m_left) && (absLeft < (m_left + m_width))) {
return true;
}
/* */
return false;
}
/**
* Returns if given absolute top is above the vertical middle of the position beans coordinates.<p>
*
* @param absTop the absolute top position
* @return true if given absolute top is above the vertical middle
*/
public boolean isOverTopHalf(int absTop) {
if (absTop < (m_top + (m_height / 2))) {
return true;
}
return false;
}
/**
* Sets the height.<p>
*
* @param height the height to set
*/
public void setHeight(int height) {
m_height = height;
}
/**
* Sets the left.<p>
*
* @param left the left to set
*/
public void setLeft(int left) {
m_left = left;
}
/**
* Sets the top.<p>
*
* @param top the top to set
*/
public void setTop(int top) {
m_top = top;
}
/**
* Sets the width.<p>
*
* @param width the width to set
*/
public void setWidth(int width) {
m_width = width;
}
/**
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "top: " + m_top + " left: " + m_left + " height: " + m_height + " width: " + m_width;
}
}
| true | true | public static PositionBean getInnerDimensions(Element panel, int levels, boolean includeSelf) {
boolean first = true;
int top = 0;
int left = 0;
int bottom = 0;
int right = 0;
// if overflow is set to hidden, use the outer dimensions
if (!Overflow.HIDDEN.getCssName().equals(DomUtil.getCurrentStyle(panel, Style.overflow))) {
if (!includeSelf) {
// check for any text content
NodeList<Node> children = panel.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
if ((children.getItem(i).getNodeType() == Node.TEXT_NODE)
&& (children.getItem(i).getNodeValue().trim().length() > 0)) {
includeSelf = true;
break;
}
}
}
if (includeSelf) {
top = panel.getAbsoluteTop();
left = panel.getAbsoluteLeft();
bottom = top + panel.getOffsetHeight();
right = left + panel.getOffsetWidth();
first = false;
}
Element child = panel.getFirstChildElement();
while (child != null) {
String positioning = DomUtil.getCurrentStyle(child, Style.position);
if (!Display.NONE.getCssName().equals(DomUtil.getCurrentStyle(child, Style.display))
&& !(positioning.equalsIgnoreCase(Position.ABSOLUTE.getCssName()) || positioning.equalsIgnoreCase(Position.FIXED.getCssName()))) {
PositionBean childDimensions = levels > 0
? getInnerDimensions(child, levels - 1, true)
: generatePositionInfo(panel);
if (first) {
first = false;
top = childDimensions.getTop();
left = childDimensions.getLeft();
bottom = top + childDimensions.getHeight();
right = left + childDimensions.getWidth();
} else {
int wTop = childDimensions.getTop();
top = top < wTop ? top : wTop;
int wLeft = childDimensions.getLeft();
left = left < wLeft ? left : wLeft;
int wBottom = wTop + childDimensions.getHeight();
bottom = bottom > wBottom ? bottom : wBottom;
int wRight = wLeft + childDimensions.getWidth();
right = right > wRight ? right : wRight;
}
}
child = child.getNextSiblingElement();
}
}
if (!first) {
PositionBean result = new PositionBean();
result.setHeight(bottom - top);
result.setWidth(right - left);
result.setTop(top);
result.setLeft(left);
return result;
} else {
return generatePositionInfo(panel);
}
}
| public static PositionBean getInnerDimensions(Element panel, int levels, boolean includeSelf) {
boolean first = true;
int top = 0;
int left = 0;
int bottom = 0;
int right = 0;
// if overflow is set to hidden, use the outer dimensions
if (!Overflow.HIDDEN.getCssName().equals(DomUtil.getCurrentStyle(panel, Style.overflow))) {
if (!includeSelf) {
// check for any text content
NodeList<Node> children = panel.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
if ((children.getItem(i).getNodeType() == Node.TEXT_NODE)
&& (children.getItem(i).getNodeValue().trim().length() > 0)) {
includeSelf = true;
break;
}
}
}
if (includeSelf) {
top = panel.getAbsoluteTop();
left = panel.getAbsoluteLeft();
bottom = top + panel.getOffsetHeight();
right = left + panel.getOffsetWidth();
first = false;
}
Element child = panel.getFirstChildElement();
while (child != null) {
String tagName = child.getTagName();
if (tagName.equalsIgnoreCase("br")
|| tagName.equalsIgnoreCase("tr")
|| tagName.equalsIgnoreCase("thead")
|| tagName.equalsIgnoreCase("tfoot")
|| tagName.equalsIgnoreCase("script")
|| tagName.equalsIgnoreCase("style")) {
// ignore tags with no relevant position info
child = child.getNextSiblingElement();
continue;
}
String positioning = DomUtil.getCurrentStyle(child, Style.position);
if (!Display.NONE.getCssName().equals(DomUtil.getCurrentStyle(child, Style.display))
&& !(positioning.equalsIgnoreCase(Position.ABSOLUTE.getCssName()) || positioning.equalsIgnoreCase(Position.FIXED.getCssName()))) {
PositionBean childDimensions = levels > 0
? getInnerDimensions(child, levels - 1, true)
: generatePositionInfo(panel);
if (first) {
first = false;
top = childDimensions.getTop();
left = childDimensions.getLeft();
bottom = top + childDimensions.getHeight();
right = left + childDimensions.getWidth();
} else {
int wTop = childDimensions.getTop();
top = top < wTop ? top : wTop;
int wLeft = childDimensions.getLeft();
left = left < wLeft ? left : wLeft;
int wBottom = wTop + childDimensions.getHeight();
bottom = bottom > wBottom ? bottom : wBottom;
int wRight = wLeft + childDimensions.getWidth();
right = right > wRight ? right : wRight;
}
}
child = child.getNextSiblingElement();
}
}
if (!first) {
PositionBean result = new PositionBean();
result.setHeight(bottom - top);
result.setWidth(right - left);
result.setTop(top);
result.setLeft(left);
return result;
} else {
return generatePositionInfo(panel);
}
}
|
diff --git a/src/com/android/launcher2/LauncherModel.java b/src/com/android/launcher2/LauncherModel.java
index 7e4901e0..bc88a987 100644
--- a/src/com/android/launcher2/LauncherModel.java
+++ b/src/com/android/launcher2/LauncherModel.java
@@ -1,2173 +1,2174 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.launcher2;
import android.app.SearchManager;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProviderInfo;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentProviderClient;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.Intent.ShortcutIconResource;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Parcelable;
import android.os.Process;
import android.os.RemoteException;
import android.os.SystemClock;
import android.util.Log;
import com.android.launcher.R;
import com.android.launcher2.InstallWidgetReceiver.WidgetMimeTypeHandlerData;
import java.lang.ref.WeakReference;
import java.net.URISyntaxException;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
/**
* Maintains in-memory state of the Launcher. It is expected that there should be only one
* LauncherModel object held in a static. Also provide APIs for updating the database state
* for the Launcher.
*/
public class LauncherModel extends BroadcastReceiver {
static final boolean DEBUG_LOADERS = false;
static final String TAG = "Launcher.Model";
private static final int ITEMS_CHUNK = 6; // batch size for the workspace icons
private final boolean mAppsCanBeOnExternalStorage;
private int mBatchSize; // 0 is all apps at once
private int mAllAppsLoadDelay; // milliseconds between batches
private final LauncherApplication mApp;
private final Object mLock = new Object();
private DeferredHandler mHandler = new DeferredHandler();
private LoaderTask mLoaderTask;
private static final HandlerThread sWorkerThread = new HandlerThread("launcher-loader");
static {
sWorkerThread.start();
}
private static final Handler sWorker = new Handler(sWorkerThread.getLooper());
// We start off with everything not loaded. After that, we assume that
// our monitoring of the package manager provides all updates and we never
// need to do a requery. These are only ever touched from the loader thread.
private boolean mWorkspaceLoaded;
private boolean mAllAppsLoaded;
private WeakReference<Callbacks> mCallbacks;
// < only access in worker thread >
private AllAppsList mAllAppsList;
// sItemsIdMap maps *all* the ItemInfos (shortcuts, folders, and widgets) created by
// LauncherModel to their ids
static final HashMap<Long, ItemInfo> sItemsIdMap = new HashMap<Long, ItemInfo>();
// sItems is passed to bindItems, which expects a list of all folders and shortcuts created by
// LauncherModel that are directly on the home screen (however, no widgets or shortcuts
// within folders).
static final ArrayList<ItemInfo> sWorkspaceItems = new ArrayList<ItemInfo>();
// sAppWidgets is all LauncherAppWidgetInfo created by LauncherModel. Passed to bindAppWidget()
static final ArrayList<LauncherAppWidgetInfo> sAppWidgets =
new ArrayList<LauncherAppWidgetInfo>();
// sFolders is all FolderInfos created by LauncherModel. Passed to bindFolders()
static final HashMap<Long, FolderInfo> sFolders = new HashMap<Long, FolderInfo>();
// sDbIconCache is the set of ItemInfos that need to have their icons updated in the database
static final HashMap<Object, byte[]> sDbIconCache = new HashMap<Object, byte[]>();
// </ only access in worker thread >
private IconCache mIconCache;
private Bitmap mDefaultIcon;
private static int mCellCountX;
private static int mCellCountY;
protected int mPreviousConfigMcc;
public interface Callbacks {
public boolean setLoadOnResume();
public int getCurrentWorkspaceScreen();
public void startBinding();
public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end);
public void bindFolders(HashMap<Long,FolderInfo> folders);
public void finishBindingItems();
public void bindAppWidget(LauncherAppWidgetInfo info);
public void bindAllApplications(ArrayList<ApplicationInfo> apps);
public void bindAppsAdded(ArrayList<ApplicationInfo> apps);
public void bindAppsUpdated(ArrayList<ApplicationInfo> apps);
public void bindAppsRemoved(ArrayList<ApplicationInfo> apps, boolean permanent);
public void bindPackagesUpdated();
public boolean isAllAppsVisible();
public boolean isAllAppsButtonRank(int rank);
public void bindSearchablesChanged();
}
LauncherModel(LauncherApplication app, IconCache iconCache) {
mAppsCanBeOnExternalStorage = !Environment.isExternalStorageEmulated();
mApp = app;
mAllAppsList = new AllAppsList(iconCache);
mIconCache = iconCache;
mDefaultIcon = Utilities.createIconBitmap(
mIconCache.getFullResDefaultActivityIcon(), app);
final Resources res = app.getResources();
mAllAppsLoadDelay = res.getInteger(R.integer.config_allAppsBatchLoadDelay);
mBatchSize = res.getInteger(R.integer.config_allAppsBatchSize);
Configuration config = res.getConfiguration();
mPreviousConfigMcc = config.mcc;
}
public Bitmap getFallbackIcon() {
return Bitmap.createBitmap(mDefaultIcon);
}
public void unbindWorkspaceItems() {
sWorker.post(new Runnable() {
@Override
public void run() {
unbindWorkspaceItemsOnMainThread();
}
});
}
/** Unbinds all the sWorkspaceItems on the main thread, and return a copy of sWorkspaceItems
* that is save to reference from the main thread. */
private ArrayList<ItemInfo> unbindWorkspaceItemsOnMainThread() {
// Ensure that we don't use the same workspace items data structure on the main thread
// by making a copy of workspace items first.
final ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>(sWorkspaceItems);
final ArrayList<ItemInfo> appWidgets = new ArrayList<ItemInfo>(sAppWidgets);
mHandler.post(new Runnable() {
@Override
public void run() {
for (ItemInfo item : workspaceItems) {
item.unbind();
}
for (ItemInfo item : appWidgets) {
item.unbind();
}
}
});
return workspaceItems;
}
/**
* Adds an item to the DB if it was not created previously, or move it to a new
* <container, screen, cellX, cellY>
*/
static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container,
int screen, int cellX, int cellY) {
if (item.container == ItemInfo.NO_ID) {
// From all apps
addItemToDatabase(context, item, container, screen, cellX, cellY, false);
} else {
// From somewhere else
moveItemInDatabase(context, item, container, screen, cellX, cellY);
}
}
static void updateItemInDatabaseHelper(Context context, final ContentValues values,
final ItemInfo item, final String callingFunction) {
final long itemId = item.id;
final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
final ContentResolver cr = context.getContentResolver();
Runnable r = new Runnable() {
public void run() {
cr.update(uri, values, null, null);
ItemInfo modelItem = sItemsIdMap.get(itemId);
if (item != modelItem) {
// the modelItem needs to match up perfectly with item if our model is to be
// consistent with the database-- for now, just require modelItem == item
String msg = "item: " + ((item != null) ? item.toString() : "null") +
"modelItem: " + ((modelItem != null) ? modelItem.toString() : "null") +
"Error: ItemInfo passed to " + callingFunction + " doesn't match original";
throw new RuntimeException(msg);
}
// Items are added/removed from the corresponding FolderInfo elsewhere, such
// as in Workspace.onDrop. Here, we just add/remove them from the list of items
// that are on the desktop, as appropriate
if (modelItem.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
modelItem.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
if (!sWorkspaceItems.contains(modelItem)) {
sWorkspaceItems.add(modelItem);
}
} else {
sWorkspaceItems.remove(modelItem);
}
}
};
if (sWorkerThread.getThreadId() == Process.myTid()) {
r.run();
} else {
sWorker.post(r);
}
}
/**
* Move an item in the DB to a new <container, screen, cellX, cellY>
*/
static void moveItemInDatabase(Context context, final ItemInfo item, final long container,
final int screen, final int cellX, final int cellY) {
item.container = container;
item.cellX = cellX;
item.cellY = cellY;
// We store hotseat items in canonical form which is this orientation invariant position
// in the hotseat
if (context instanceof Launcher && screen < 0 &&
container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
item.screen = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
} else {
item.screen = screen;
}
final ContentValues values = new ContentValues();
values.put(LauncherSettings.Favorites.CONTAINER, item.container);
values.put(LauncherSettings.Favorites.CELLX, item.cellX);
values.put(LauncherSettings.Favorites.CELLY, item.cellY);
values.put(LauncherSettings.Favorites.SCREEN, item.screen);
updateItemInDatabaseHelper(context, values, item, "moveItemInDatabase");
}
/**
* Move and/or resize item in the DB to a new <container, screen, cellX, cellY, spanX, spanY>
*/
static void modifyItemInDatabase(Context context, final ItemInfo item, final long container,
final int screen, final int cellX, final int cellY, final int spanX, final int spanY) {
item.container = container;
item.cellX = cellX;
item.cellY = cellY;
item.spanX = spanX;
item.spanY = spanY;
// We store hotseat items in canonical form which is this orientation invariant position
// in the hotseat
if (context instanceof Launcher && screen < 0 &&
container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
item.screen = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
} else {
item.screen = screen;
}
final ContentValues values = new ContentValues();
values.put(LauncherSettings.Favorites.CONTAINER, item.container);
values.put(LauncherSettings.Favorites.CELLX, item.cellX);
values.put(LauncherSettings.Favorites.CELLY, item.cellY);
values.put(LauncherSettings.Favorites.SPANX, item.spanX);
values.put(LauncherSettings.Favorites.SPANY, item.spanY);
values.put(LauncherSettings.Favorites.SCREEN, item.screen);
updateItemInDatabaseHelper(context, values, item, "moveItemInDatabase");
}
/**
* Update an item to the database in a specified container.
*/
static void updateItemInDatabase(Context context, final ItemInfo item) {
final ContentValues values = new ContentValues();
item.onAddToDatabase(values);
item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
updateItemInDatabaseHelper(context, values, item, "updateItemInDatabase");
}
/**
* Returns true if the shortcuts already exists in the database.
* we identify a shortcut by its title and intent.
*/
static boolean shortcutExists(Context context, String title, Intent intent) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
new String[] { "title", "intent" }, "title=? and intent=?",
new String[] { title, intent.toUri(0) }, null);
boolean result = false;
try {
result = c.moveToFirst();
} finally {
c.close();
}
return result;
}
/**
* Returns an ItemInfo array containing all the items in the LauncherModel.
* The ItemInfo.id is not set through this function.
*/
static ArrayList<ItemInfo> getItemsInLocalCoordinates(Context context) {
ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] {
LauncherSettings.Favorites.ITEM_TYPE, LauncherSettings.Favorites.CONTAINER,
LauncherSettings.Favorites.SCREEN, LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY,
LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY }, null, null, null);
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX);
final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY);
try {
while (c.moveToNext()) {
ItemInfo item = new ItemInfo();
item.cellX = c.getInt(cellXIndex);
item.cellY = c.getInt(cellYIndex);
item.spanX = c.getInt(spanXIndex);
item.spanY = c.getInt(spanYIndex);
item.container = c.getInt(containerIndex);
item.itemType = c.getInt(itemTypeIndex);
item.screen = c.getInt(screenIndex);
items.add(item);
}
} catch (Exception e) {
items.clear();
} finally {
c.close();
}
return items;
}
/**
* Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
*/
FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
"_id=? and (itemType=? or itemType=?)",
new String[] { String.valueOf(id),
String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null);
try {
if (c.moveToFirst()) {
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
FolderInfo folderInfo = null;
switch (c.getInt(itemTypeIndex)) {
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
folderInfo = findOrMakeFolder(folderList, id);
break;
}
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
folderInfo.container = c.getInt(containerIndex);
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
return folderInfo;
}
} finally {
c.close();
}
return null;
}
/**
* Add an item to the database in a specified container. Sets the container, screen, cellX and
* cellY fields of the item. Also assigns an ID to the item.
*/
static void addItemToDatabase(Context context, final ItemInfo item, final long container,
final int screen, final int cellX, final int cellY, final boolean notify) {
item.container = container;
item.cellX = cellX;
item.cellY = cellY;
// We store hotseat items in canonical form which is this orientation invariant position
// in the hotseat
if (context instanceof Launcher && screen < 0 &&
container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
item.screen = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
} else {
item.screen = screen;
}
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
LauncherApplication app = (LauncherApplication) context.getApplicationContext();
item.id = app.getLauncherProvider().generateNewId();
values.put(LauncherSettings.Favorites._ID, item.id);
item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
Runnable r = new Runnable() {
public void run() {
cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
if (sItemsIdMap.containsKey(item.id)) {
// we should not be adding new items in the db with the same id
throw new RuntimeException("Error: ItemInfo id (" + item.id + ") passed to " +
"addItemToDatabase already exists." + item.toString());
}
sItemsIdMap.put(item.id, item);
switch (item.itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
sFolders.put(item.id, (FolderInfo) item);
// Fall through
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
sWorkspaceItems.add(item);
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
sAppWidgets.add((LauncherAppWidgetInfo) item);
break;
}
}
};
if (sWorkerThread.getThreadId() == Process.myTid()) {
r.run();
} else {
sWorker.post(r);
}
}
/**
* Creates a new unique child id, for a given cell span across all layouts.
*/
static int getCellLayoutChildId(
long container, int screen, int localCellX, int localCellY, int spanX, int spanY) {
return (((int) container & 0xFF) << 24)
| (screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF);
}
static int getCellCountX() {
return mCellCountX;
}
static int getCellCountY() {
return mCellCountY;
}
/**
* Updates the model orientation helper to take into account the current layout dimensions
* when performing local/canonical coordinate transformations.
*/
static void updateWorkspaceLayoutCells(int shortAxisCellCount, int longAxisCellCount) {
mCellCountX = shortAxisCellCount;
mCellCountY = longAxisCellCount;
}
/**
* Removes the specified item from the database
* @param context
* @param item
*/
static void deleteItemFromDatabase(Context context, final ItemInfo item) {
final ContentResolver cr = context.getContentResolver();
final Uri uriToDelete = LauncherSettings.Favorites.getContentUri(item.id, false);
Runnable r = new Runnable() {
public void run() {
cr.delete(uriToDelete, null, null);
switch (item.itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
sFolders.remove(item.id);
sWorkspaceItems.remove(item);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
sWorkspaceItems.remove(item);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
sAppWidgets.remove((LauncherAppWidgetInfo) item);
break;
}
sItemsIdMap.remove(item.id);
sDbIconCache.remove(item);
}
};
if (sWorkerThread.getThreadId() == Process.myTid()) {
r.run();
} else {
sWorker.post(r);
}
}
/**
* Remove the contents of the specified folder from the database
*/
static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) {
final ContentResolver cr = context.getContentResolver();
Runnable r = new Runnable() {
public void run() {
cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
sItemsIdMap.remove(info.id);
sFolders.remove(info.id);
sDbIconCache.remove(info);
sWorkspaceItems.remove(info);
cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
for (ItemInfo childInfo : info.contents) {
sItemsIdMap.remove(childInfo.id);
sDbIconCache.remove(childInfo);
}
}
};
if (sWorkerThread.getThreadId() == Process.myTid()) {
r.run();
} else {
sWorker.post(r);
}
}
/**
* Set this as the current Launcher activity object for the loader.
*/
public void initialize(Callbacks callbacks) {
synchronized (mLock) {
mCallbacks = new WeakReference<Callbacks>(callbacks);
}
}
/**
* Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
* ACTION_PACKAGE_CHANGED.
*/
@Override
public void onReceive(Context context, Intent intent) {
if (DEBUG_LOADERS) Log.d(TAG, "onReceive intent=" + intent);
final String action = intent.getAction();
if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
|| Intent.ACTION_PACKAGE_REMOVED.equals(action)
|| Intent.ACTION_PACKAGE_ADDED.equals(action)) {
final String packageName = intent.getData().getSchemeSpecificPart();
final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
int op = PackageUpdatedTask.OP_NONE;
if (packageName == null || packageName.length() == 0) {
// they sent us a bad intent
return;
}
if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
op = PackageUpdatedTask.OP_UPDATE;
} else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
if (!replacing) {
op = PackageUpdatedTask.OP_REMOVE;
}
// else, we are replacing the package, so a PACKAGE_ADDED will be sent
// later, we will update the package at this time
} else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
if (!replacing) {
op = PackageUpdatedTask.OP_ADD;
} else {
op = PackageUpdatedTask.OP_UPDATE;
}
}
if (op != PackageUpdatedTask.OP_NONE) {
enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName }));
}
} else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
// First, schedule to add these apps back in.
String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packages));
// Then, rebind everything.
startLoaderFromBackground();
} else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
enqueuePackageUpdated(new PackageUpdatedTask(
PackageUpdatedTask.OP_UNAVAILABLE, packages));
} else if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
// If we have changed locale we need to clear out the labels in all apps/workspace.
forceReload();
} else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
// Check if configuration change was an mcc/mnc change which would affect app resources
// and we would need to clear out the labels in all apps/workspace. Same handling as
// above for ACTION_LOCALE_CHANGED
Configuration currentConfig = context.getResources().getConfiguration();
if (mPreviousConfigMcc != currentConfig.mcc) {
Log.d(TAG, "Reload apps on config change. curr_mcc:"
+ currentConfig.mcc + " prevmcc:" + mPreviousConfigMcc);
forceReload();
}
// Update previousConfig
mPreviousConfigMcc = currentConfig.mcc;
} else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) ||
SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) {
if (mCallbacks != null) {
Callbacks callbacks = mCallbacks.get();
if (callbacks != null) {
callbacks.bindSearchablesChanged();
}
}
}
}
private void forceReload() {
resetLoadedState(true, true);
// Do this here because if the launcher activity is running it will be restarted.
// If it's not running startLoaderFromBackground will merely tell it that it needs
// to reload.
startLoaderFromBackground();
}
public void resetLoadedState(boolean resetAllAppsLoaded, boolean resetWorkspaceLoaded) {
synchronized (mLock) {
// Stop any existing loaders first, so they don't set mAllAppsLoaded or
// mWorkspaceLoaded to true later
stopLoaderLocked();
if (resetAllAppsLoaded) mAllAppsLoaded = false;
if (resetWorkspaceLoaded) mWorkspaceLoaded = false;
}
}
/**
* When the launcher is in the background, it's possible for it to miss paired
* configuration changes. So whenever we trigger the loader from the background
* tell the launcher that it needs to re-run the loader when it comes back instead
* of doing it now.
*/
public void startLoaderFromBackground() {
boolean runLoader = false;
if (mCallbacks != null) {
Callbacks callbacks = mCallbacks.get();
if (callbacks != null) {
// Only actually run the loader if they're not paused.
if (!callbacks.setLoadOnResume()) {
runLoader = true;
}
}
}
if (runLoader) {
startLoader(false);
}
}
// If there is already a loader task running, tell it to stop.
// returns true if isLaunching() was true on the old task
private boolean stopLoaderLocked() {
boolean isLaunching = false;
LoaderTask oldTask = mLoaderTask;
if (oldTask != null) {
if (oldTask.isLaunching()) {
isLaunching = true;
}
oldTask.stopLocked();
}
return isLaunching;
}
public void startLoader(boolean isLaunching) {
synchronized (mLock) {
if (DEBUG_LOADERS) {
Log.d(TAG, "startLoader isLaunching=" + isLaunching);
}
// Don't bother to start the thread if we know it's not going to do anything
if (mCallbacks != null && mCallbacks.get() != null) {
// If there is already one running, tell it to stop.
// also, don't downgrade isLaunching if we're already running
isLaunching = isLaunching || stopLoaderLocked();
mLoaderTask = new LoaderTask(mApp, isLaunching);
sWorkerThread.setPriority(Thread.NORM_PRIORITY);
sWorker.post(mLoaderTask);
}
}
}
public void stopLoader() {
synchronized (mLock) {
if (mLoaderTask != null) {
mLoaderTask.stopLocked();
}
}
}
public boolean isAllAppsLoaded() {
return mAllAppsLoaded;
}
boolean isLoadingWorkspace() {
synchronized (mLock) {
if (mLoaderTask != null) {
return mLoaderTask.isLoadingWorkspace();
}
}
return false;
}
/**
* Runnable for the thread that loads the contents of the launcher:
* - workspace icons
* - widgets
* - all apps icons
*/
private class LoaderTask implements Runnable {
private Context mContext;
private Thread mWaitThread;
private boolean mIsLaunching;
private boolean mIsLoadingAndBindingWorkspace;
private boolean mStopped;
private boolean mLoadAndBindStepFinished;
private HashMap<Object, CharSequence> mLabelCache;
LoaderTask(Context context, boolean isLaunching) {
mContext = context;
mIsLaunching = isLaunching;
mLabelCache = new HashMap<Object, CharSequence>();
}
boolean isLaunching() {
return mIsLaunching;
}
boolean isLoadingWorkspace() {
return mIsLoadingAndBindingWorkspace;
}
private void loadAndBindWorkspace() {
mIsLoadingAndBindingWorkspace = true;
// Load the workspace
if (DEBUG_LOADERS) {
Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded);
}
if (!mWorkspaceLoaded) {
loadWorkspace();
synchronized (LoaderTask.this) {
if (mStopped) {
return;
}
mWorkspaceLoaded = true;
}
}
// Bind the workspace
bindWorkspace();
}
private void waitForIdle() {
// Wait until the either we're stopped or the other threads are done.
// This way we don't start loading all apps until the workspace has settled
// down.
synchronized (LoaderTask.this) {
final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
mHandler.postIdle(new Runnable() {
public void run() {
synchronized (LoaderTask.this) {
mLoadAndBindStepFinished = true;
if (DEBUG_LOADERS) {
Log.d(TAG, "done with previous binding step");
}
LoaderTask.this.notify();
}
}
});
while (!mStopped && !mLoadAndBindStepFinished) {
try {
this.wait();
} catch (InterruptedException ex) {
// Ignore
}
}
if (DEBUG_LOADERS) {
Log.d(TAG, "waited "
+ (SystemClock.uptimeMillis()-workspaceWaitTime)
+ "ms for previous step to finish binding");
}
}
}
public void run() {
// Optimize for end-user experience: if the Launcher is up and // running with the
// All Apps interface in the foreground, load All Apps first. Otherwise, load the
// workspace first (default).
final Callbacks cbk = mCallbacks.get();
final boolean loadWorkspaceFirst = cbk != null ? (!cbk.isAllAppsVisible()) : true;
keep_running: {
// Elevate priority when Home launches for the first time to avoid
// starving at boot time. Staring at a blank home is not cool.
synchronized (mLock) {
if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " +
(mIsLaunching ? "DEFAULT" : "BACKGROUND"));
android.os.Process.setThreadPriority(mIsLaunching
? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
}
if (loadWorkspaceFirst) {
if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace");
loadAndBindWorkspace();
} else {
if (DEBUG_LOADERS) Log.d(TAG, "step 1: special: loading all apps");
loadAndBindAllApps();
}
if (mStopped) {
break keep_running;
}
// Whew! Hard work done. Slow us down, and wait until the UI thread has
// settled down.
synchronized (mLock) {
if (mIsLaunching) {
if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND");
android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
}
}
waitForIdle();
// second step
if (loadWorkspaceFirst) {
if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps");
loadAndBindAllApps();
} else {
if (DEBUG_LOADERS) Log.d(TAG, "step 2: special: loading workspace");
loadAndBindWorkspace();
}
// Restore the default thread priority after we are done loading items
synchronized (mLock) {
android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
}
}
// Update the saved icons if necessary
if (DEBUG_LOADERS) Log.d(TAG, "Comparing loaded icons to database icons");
for (Object key : sDbIconCache.keySet()) {
updateSavedIcon(mContext, (ShortcutInfo) key, sDbIconCache.get(key));
}
sDbIconCache.clear();
// Clear out this reference, otherwise we end up holding it until all of the
// callback runnables are done.
mContext = null;
synchronized (mLock) {
// If we are still the last one to be scheduled, remove ourselves.
if (mLoaderTask == this) {
mLoaderTask = null;
}
}
}
public void stopLocked() {
synchronized (LoaderTask.this) {
mStopped = true;
this.notify();
}
}
/**
* Gets the callbacks object. If we've been stopped, or if the launcher object
* has somehow been garbage collected, return null instead. Pass in the Callbacks
* object that was around when the deferred message was scheduled, and if there's
* a new Callbacks object around then also return null. This will save us from
* calling onto it with data that will be ignored.
*/
Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
synchronized (mLock) {
if (mStopped) {
return null;
}
if (mCallbacks == null) {
return null;
}
final Callbacks callbacks = mCallbacks.get();
if (callbacks != oldCallbacks) {
return null;
}
if (callbacks == null) {
Log.w(TAG, "no mCallbacks");
return null;
}
return callbacks;
}
}
// check & update map of what's occupied; used to discard overlapping/invalid items
private boolean checkItemPlacement(ItemInfo occupied[][][], ItemInfo item) {
int containerIndex = item.screen;
if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
// Return early if we detect that an item is under the hotseat button
if (mCallbacks == null || mCallbacks.get().isAllAppsButtonRank(item.screen)) {
return false;
}
// We use the last index to refer to the hotseat and the screen as the rank, so
// test and update the occupied state accordingly
if (occupied[Launcher.SCREEN_COUNT][item.screen][0] != null) {
Log.e(TAG, "Error loading shortcut into hotseat " + item
+ " into position (" + item.screen + ":" + item.cellX + "," + item.cellY
+ ") occupied by " + occupied[Launcher.SCREEN_COUNT][item.screen][0]);
return false;
} else {
occupied[Launcher.SCREEN_COUNT][item.screen][0] = item;
return true;
}
} else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
// Skip further checking if it is not the hotseat or workspace container
return true;
}
// Check if any workspace icons overlap with each other
for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
if (occupied[containerIndex][x][y] != null) {
Log.e(TAG, "Error loading shortcut " + item
+ " into cell (" + containerIndex + "-" + item.screen + ":"
+ x + "," + y
+ ") occupied by "
+ occupied[containerIndex][x][y]);
return false;
}
}
}
for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
occupied[containerIndex][x][y] = item;
}
}
return true;
}
private void loadWorkspace() {
final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
final Context context = mContext;
final ContentResolver contentResolver = context.getContentResolver();
final PackageManager manager = context.getPackageManager();
final AppWidgetManager widgets = AppWidgetManager.getInstance(context);
final boolean isSafeMode = manager.isSafeMode();
// Make sure the default workspace is loaded, if needed
mApp.getLauncherProvider().loadDefaultFavoritesIfNecessary();
sWorkspaceItems.clear();
sAppWidgets.clear();
sFolders.clear();
sItemsIdMap.clear();
sDbIconCache.clear();
final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
final Cursor c = contentResolver.query(
LauncherSettings.Favorites.CONTENT_URI, null, null, null, null);
// +1 for the hotseat (it can be larger than the workspace)
// Load workspace in reverse order to ensure that latest items are loaded first (and
// before any earlier duplicates)
final ItemInfo occupied[][][] =
new ItemInfo[Launcher.SCREEN_COUNT + 1][mCellCountX + 1][mCellCountY + 1];
try {
final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
final int intentIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.INTENT);
final int titleIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.TITLE);
final int iconTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_TYPE);
final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
final int iconPackageIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_PACKAGE);
final int iconResourceIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_RESOURCE);
final int containerIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.CONTAINER);
final int itemTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ITEM_TYPE);
final int appWidgetIdIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.APPWIDGET_ID);
final int screenIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLY);
final int spanXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.SPANX);
final int spanYIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SPANY);
//final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
//final int displayModeIndex = c.getColumnIndexOrThrow(
// LauncherSettings.Favorites.DISPLAY_MODE);
ShortcutInfo info;
String intentDescription;
LauncherAppWidgetInfo appWidgetInfo;
int container;
long id;
Intent intent;
while (!mStopped && c.moveToNext()) {
try {
int itemType = c.getInt(itemTypeIndex);
switch (itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
intentDescription = c.getString(intentIndex);
try {
intent = Intent.parseUri(intentDescription, 0);
} catch (URISyntaxException e) {
continue;
}
if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
info = getShortcutInfo(manager, intent, context, c, iconIndex,
titleIndex, mLabelCache);
} else {
info = getShortcutInfo(c, context, iconTypeIndex,
iconPackageIndex, iconResourceIndex, iconIndex,
titleIndex);
// App shortcuts that used to be automatically added to Launcher
// didn't always have the correct intent flags set, so do that here
if (intent.getAction().equals(Intent.ACTION_MAIN) &&
intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
intent.addFlags(
Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
}
}
if (info != null) {
info.intent = intent;
info.id = c.getLong(idIndex);
container = c.getInt(containerIndex);
info.container = container;
info.screen = c.getInt(screenIndex);
info.cellX = c.getInt(cellXIndex);
info.cellY = c.getInt(cellYIndex);
// check & update map of what's occupied
if (!checkItemPlacement(occupied, info)) {
break;
}
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
sWorkspaceItems.add(info);
break;
default:
// Item is in a user folder
FolderInfo folderInfo =
findOrMakeFolder(sFolders, container);
folderInfo.add(info);
break;
}
sItemsIdMap.put(info.id, info);
// now that we've loaded everthing re-save it with the
// icon in case it disappears somehow.
queueIconToBeChecked(sDbIconCache, info, c, iconIndex);
} else {
// Failed to load the shortcut, probably because the
// activity manager couldn't resolve it (maybe the app
// was uninstalled), or the db row was somehow screwed up.
// Delete it.
id = c.getLong(idIndex);
Log.e(TAG, "Error loading shortcut " + id + ", removing it");
contentResolver.delete(LauncherSettings.Favorites.getContentUri(
id, false), null, null);
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
id = c.getLong(idIndex);
FolderInfo folderInfo = findOrMakeFolder(sFolders, id);
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
container = c.getInt(containerIndex);
folderInfo.container = container;
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
// check & update map of what's occupied
if (!checkItemPlacement(occupied, folderInfo)) {
break;
}
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
sWorkspaceItems.add(folderInfo);
break;
}
sItemsIdMap.put(folderInfo.id, folderInfo);
sFolders.put(folderInfo.id, folderInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
// Read all Launcher-specific widget details
int appWidgetId = c.getInt(appWidgetIdIndex);
id = c.getLong(idIndex);
final AppWidgetProviderInfo provider =
widgets.getAppWidgetInfo(appWidgetId);
if (!isSafeMode && (provider == null || provider.provider == null ||
provider.provider.getPackageName() == null)) {
String log = "Deleting widget that isn't installed anymore: id="
+ id + " appWidgetId=" + appWidgetId;
Log.e(TAG, log);
Launcher.sDumpLogs.add(log);
itemsToRemove.add(id);
} else {
appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
provider.provider);
appWidgetInfo.id = id;
appWidgetInfo.screen = c.getInt(screenIndex);
appWidgetInfo.cellX = c.getInt(cellXIndex);
appWidgetInfo.cellY = c.getInt(cellYIndex);
appWidgetInfo.spanX = c.getInt(spanXIndex);
appWidgetInfo.spanY = c.getInt(spanYIndex);
int[] minSpan = Launcher.getMinSpanForWidget(context, provider);
appWidgetInfo.minSpanX = minSpan[0];
appWidgetInfo.minSpanY = minSpan[1];
container = c.getInt(containerIndex);
if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Log.e(TAG, "Widget found where container "
+ "!= CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
continue;
}
appWidgetInfo.container = c.getInt(containerIndex);
// check & update map of what's occupied
if (!checkItemPlacement(occupied, appWidgetInfo)) {
break;
}
sItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
sAppWidgets.add(appWidgetInfo);
}
break;
}
} catch (Exception e) {
Log.w(TAG, "Desktop items loading interrupted:", e);
}
}
} finally {
c.close();
}
if (itemsToRemove.size() > 0) {
ContentProviderClient client = contentResolver.acquireContentProviderClient(
LauncherSettings.Favorites.CONTENT_URI);
// Remove dead items
for (long id : itemsToRemove) {
if (DEBUG_LOADERS) {
Log.d(TAG, "Removed id = " + id);
}
// Don't notify content observers
try {
client.delete(LauncherSettings.Favorites.getContentUri(id, false),
null, null);
} catch (RemoteException e) {
Log.w(TAG, "Could not remove id = " + id);
}
}
}
if (DEBUG_LOADERS) {
Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
Log.d(TAG, "workspace layout: ");
for (int y = 0; y < mCellCountY; y++) {
String line = "";
for (int s = 0; s < Launcher.SCREEN_COUNT; s++) {
if (s > 0) {
line += " | ";
}
for (int x = 0; x < mCellCountX; x++) {
line += ((occupied[s][x][y] != null) ? "#" : ".");
}
}
Log.d(TAG, "[ " + line + " ]");
}
}
}
/**
* Read everything out of our database.
*/
private void bindWorkspace() {
final long t = SystemClock.uptimeMillis();
// Don't use these two variables in any of the callback runnables.
// Otherwise we hold a reference to them.
final Callbacks oldCallbacks = mCallbacks.get();
if (oldCallbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderTask running with no launcher");
return;
}
// Get the list of workspace items to load and unbind the existing ShortcutInfos
// before we call startBinding() below.
final int currentScreen = oldCallbacks.getCurrentWorkspaceScreen();
final ArrayList<ItemInfo> tmpWorkspaceItems = unbindWorkspaceItemsOnMainThread();
// Order the items for loading as follows: current workspace, hotseat, everything else
Collections.sort(tmpWorkspaceItems, new Comparator<ItemInfo>() {
@Override
public int compare(ItemInfo lhs, ItemInfo rhs) {
int cellCountX = LauncherModel.getCellCountX();
int cellCountY = LauncherModel.getCellCountY();
int screenOffset = cellCountX * cellCountY;
int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat
long lr = (lhs.container * containerOffset + lhs.screen * screenOffset +
lhs.cellY * cellCountX + lhs.cellX);
long rr = (rhs.container * containerOffset + rhs.screen * screenOffset +
rhs.cellY * cellCountX + rhs.cellX);
return (int) (lr - rr);
}
});
// Precondition: the items are ordered by page, screen
final ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>();
for (ItemInfo ii : tmpWorkspaceItems) {
// Prepend the current items, hotseat items, append everything else
if (ii.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
ii.screen == currentScreen) {
workspaceItems.add(0, ii);
} else if (ii.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
workspaceItems.add(0, ii);
} else {
workspaceItems.add(ii);
}
}
// Tell the workspace that we're about to start firing items at it
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.startBinding();
}
}
});
// Add the items to the workspace.
int N = workspaceItems.size();
for (int i=0; i<N; i+=ITEMS_CHUNK) {
final int start = i;
final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindItems(workspaceItems, start, start+chunkSize);
}
}
});
}
// Ensure that we don't use the same folders data structure on the main thread
final HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>(sFolders);
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindFolders(folders);
}
}
});
// Wait until the queue goes empty.
mHandler.post(new Runnable() {
public void run() {
if (DEBUG_LOADERS) {
Log.d(TAG, "Going to start binding widgets soon.");
}
}
});
// Bind the widgets, one at a time.
// WARNING: this is calling into the workspace from the background thread,
// but since getCurrentScreen() just returns the int, we should be okay. This
// is just a hint for the order, and if it's wrong, we'll be okay.
// TODO: instead, we should have that push the current screen into here.
N = sAppWidgets.size();
// once for the current screen
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = sAppWidgets.get(i);
if (widget.screen == currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// once for the other screens
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = sAppWidgets.get(i);
if (widget.screen != currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// Tell the workspace that we're done.
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.finishBindingItems();
}
}
});
- // If we're profiling, this is the last thing in the queue.
+ // Cleanup
mHandler.post(new Runnable() {
public void run() {
+ // If we're profiling, ensure this is the last thing in the queue.
if (DEBUG_LOADERS) {
Log.d(TAG, "bound workspace in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
mIsLoadingAndBindingWorkspace = false;
}
});
}
private void loadAndBindAllApps() {
if (DEBUG_LOADERS) {
Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
}
if (!mAllAppsLoaded) {
loadAllAppsByBatch();
synchronized (LoaderTask.this) {
if (mStopped) {
return;
}
mAllAppsLoaded = true;
}
} else {
onlyBindAllApps();
}
}
private void onlyBindAllApps() {
final Callbacks oldCallbacks = mCallbacks.get();
if (oldCallbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
return;
}
// shallow copy
@SuppressWarnings("unchecked")
final ArrayList<ApplicationInfo> list
= (ArrayList<ApplicationInfo>) mAllAppsList.data.clone();
mHandler.post(new Runnable() {
public void run() {
final long t = SystemClock.uptimeMillis();
final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindAllApplications(list);
}
if (DEBUG_LOADERS) {
Log.d(TAG, "bound all " + list.size() + " apps from cache in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
}
});
}
private void loadAllAppsByBatch() {
final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
// Don't use these two variables in any of the callback runnables.
// Otherwise we hold a reference to them.
final Callbacks oldCallbacks = mCallbacks.get();
if (oldCallbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderTask running with no launcher (loadAllAppsByBatch)");
return;
}
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
final PackageManager packageManager = mContext.getPackageManager();
List<ResolveInfo> apps = null;
int N = Integer.MAX_VALUE;
int startIndex;
int i=0;
int batchSize = -1;
while (i < N && !mStopped) {
if (i == 0) {
mAllAppsList.clear();
final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
apps = packageManager.queryIntentActivities(mainIntent, 0);
if (DEBUG_LOADERS) {
Log.d(TAG, "queryIntentActivities took "
+ (SystemClock.uptimeMillis()-qiaTime) + "ms");
}
if (apps == null) {
return;
}
N = apps.size();
if (DEBUG_LOADERS) {
Log.d(TAG, "queryIntentActivities got " + N + " apps");
}
if (N == 0) {
// There are no apps?!?
return;
}
if (mBatchSize == 0) {
batchSize = N;
} else {
batchSize = mBatchSize;
}
final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Collections.sort(apps,
new LauncherModel.ShortcutNameComparator(packageManager, mLabelCache));
if (DEBUG_LOADERS) {
Log.d(TAG, "sort took "
+ (SystemClock.uptimeMillis()-sortTime) + "ms");
}
}
final long t2 = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
startIndex = i;
for (int j=0; i<N && j<batchSize; j++) {
// This builds the icon bitmaps.
mAllAppsList.add(new ApplicationInfo(packageManager, apps.get(i),
mIconCache, mLabelCache));
i++;
}
final boolean first = i <= batchSize;
final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
final ArrayList<ApplicationInfo> added = mAllAppsList.added;
mAllAppsList.added = new ArrayList<ApplicationInfo>();
mHandler.post(new Runnable() {
public void run() {
final long t = SystemClock.uptimeMillis();
if (callbacks != null) {
if (first) {
callbacks.bindAllApplications(added);
} else {
callbacks.bindAppsAdded(added);
}
if (DEBUG_LOADERS) {
Log.d(TAG, "bound " + added.size() + " apps in "
+ (SystemClock.uptimeMillis() - t) + "ms");
}
} else {
Log.i(TAG, "not binding apps: no Launcher activity");
}
}
});
if (DEBUG_LOADERS) {
Log.d(TAG, "batch of " + (i-startIndex) + " icons processed in "
+ (SystemClock.uptimeMillis()-t2) + "ms");
}
if (mAllAppsLoadDelay > 0 && i < N) {
try {
if (DEBUG_LOADERS) {
Log.d(TAG, "sleeping for " + mAllAppsLoadDelay + "ms");
}
Thread.sleep(mAllAppsLoadDelay);
} catch (InterruptedException exc) { }
}
}
if (DEBUG_LOADERS) {
Log.d(TAG, "cached all " + N + " apps in "
+ (SystemClock.uptimeMillis()-t) + "ms"
+ (mAllAppsLoadDelay > 0 ? " (including delay)" : ""));
}
}
public void dumpState() {
Log.d(TAG, "mLoaderTask.mContext=" + mContext);
Log.d(TAG, "mLoaderTask.mWaitThread=" + mWaitThread);
Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
Log.d(TAG, "mItems size=" + sWorkspaceItems.size());
}
}
void enqueuePackageUpdated(PackageUpdatedTask task) {
sWorker.post(task);
}
private class PackageUpdatedTask implements Runnable {
int mOp;
String[] mPackages;
public static final int OP_NONE = 0;
public static final int OP_ADD = 1;
public static final int OP_UPDATE = 2;
public static final int OP_REMOVE = 3; // uninstlled
public static final int OP_UNAVAILABLE = 4; // external media unmounted
public PackageUpdatedTask(int op, String[] packages) {
mOp = op;
mPackages = packages;
}
public void run() {
final Context context = mApp;
final String[] packages = mPackages;
final int N = packages.length;
switch (mOp) {
case OP_ADD:
for (int i=0; i<N; i++) {
if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
mAllAppsList.addPackage(context, packages[i]);
}
break;
case OP_UPDATE:
for (int i=0; i<N; i++) {
if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
mAllAppsList.updatePackage(context, packages[i]);
}
break;
case OP_REMOVE:
case OP_UNAVAILABLE:
for (int i=0; i<N; i++) {
if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
mAllAppsList.removePackage(packages[i]);
}
break;
}
ArrayList<ApplicationInfo> added = null;
ArrayList<ApplicationInfo> removed = null;
ArrayList<ApplicationInfo> modified = null;
if (mAllAppsList.added.size() > 0) {
added = mAllAppsList.added;
mAllAppsList.added = new ArrayList<ApplicationInfo>();
}
if (mAllAppsList.removed.size() > 0) {
removed = mAllAppsList.removed;
mAllAppsList.removed = new ArrayList<ApplicationInfo>();
for (ApplicationInfo info: removed) {
mIconCache.remove(info.intent.getComponent());
}
}
if (mAllAppsList.modified.size() > 0) {
modified = mAllAppsList.modified;
mAllAppsList.modified = new ArrayList<ApplicationInfo>();
}
final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == null) {
Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
return;
}
if (added != null) {
final ArrayList<ApplicationInfo> addedFinal = added;
mHandler.post(new Runnable() {
public void run() {
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == cb && cb != null) {
callbacks.bindAppsAdded(addedFinal);
}
}
});
}
if (modified != null) {
final ArrayList<ApplicationInfo> modifiedFinal = modified;
mHandler.post(new Runnable() {
public void run() {
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == cb && cb != null) {
callbacks.bindAppsUpdated(modifiedFinal);
}
}
});
}
if (removed != null) {
final boolean permanent = mOp != OP_UNAVAILABLE;
final ArrayList<ApplicationInfo> removedFinal = removed;
mHandler.post(new Runnable() {
public void run() {
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == cb && cb != null) {
callbacks.bindAppsRemoved(removedFinal, permanent);
}
}
});
}
mHandler.post(new Runnable() {
@Override
public void run() {
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == cb && cb != null) {
callbacks.bindPackagesUpdated();
}
}
});
}
}
/**
* Returns all the Workspace ShortcutInfos associated with a particular package.
* @param intent
* @return
*/
ArrayList<ShortcutInfo> getShortcutInfosForPackage(String packageName) {
ArrayList<ShortcutInfo> infos = new ArrayList<ShortcutInfo>();
for (ItemInfo i : sWorkspaceItems) {
if (i instanceof ShortcutInfo) {
ShortcutInfo info = (ShortcutInfo) i;
if (packageName.equals(info.getPackageName())) {
infos.add(info);
}
}
}
return infos;
}
/**
* This is called from the code that adds shortcuts from the intent receiver. This
* doesn't have a Cursor, but
*/
public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) {
return getShortcutInfo(manager, intent, context, null, -1, -1, null);
}
/**
* Make an ShortcutInfo object for a shortcut that is an application.
*
* If c is not null, then it will be used to fill in missing data like the title and icon.
*/
public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context,
Cursor c, int iconIndex, int titleIndex, HashMap<Object, CharSequence> labelCache) {
Bitmap icon = null;
final ShortcutInfo info = new ShortcutInfo();
ComponentName componentName = intent.getComponent();
if (componentName == null) {
return null;
}
try {
PackageInfo pi = manager.getPackageInfo(componentName.getPackageName(), 0);
if (!pi.applicationInfo.enabled) {
// If we return null here, the corresponding item will be removed from the launcher
// db and will not appear in the workspace.
return null;
}
} catch (NameNotFoundException e) {
Log.d(TAG, "getPackInfo failed for package " + componentName.getPackageName());
}
// TODO: See if the PackageManager knows about this case. If it doesn't
// then return null & delete this.
// the resource -- This may implicitly give us back the fallback icon,
// but don't worry about that. All we're doing with usingFallbackIcon is
// to avoid saving lots of copies of that in the database, and most apps
// have icons anyway.
// Attempt to use queryIntentActivities to get the ResolveInfo (with IntentFilter info) and
// if that fails, or is ambiguious, fallback to the standard way of getting the resolve info
// via resolveActivity().
ResolveInfo resolveInfo = null;
ComponentName oldComponent = intent.getComponent();
Intent newIntent = new Intent(intent.getAction(), null);
newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
newIntent.setPackage(oldComponent.getPackageName());
List<ResolveInfo> infos = manager.queryIntentActivities(newIntent, 0);
for (ResolveInfo i : infos) {
ComponentName cn = new ComponentName(i.activityInfo.packageName,
i.activityInfo.name);
if (cn.equals(oldComponent)) {
resolveInfo = i;
}
}
if (resolveInfo == null) {
resolveInfo = manager.resolveActivity(intent, 0);
}
if (resolveInfo != null) {
icon = mIconCache.getIcon(componentName, resolveInfo, labelCache);
}
// the db
if (icon == null) {
if (c != null) {
icon = getIconFromCursor(c, iconIndex, context);
}
}
// the fallback icon
if (icon == null) {
icon = getFallbackIcon();
info.usingFallbackIcon = true;
}
info.setIcon(icon);
// from the resource
if (resolveInfo != null) {
ComponentName key = LauncherModel.getComponentNameFromResolveInfo(resolveInfo);
if (labelCache != null && labelCache.containsKey(key)) {
info.title = labelCache.get(key);
} else {
info.title = resolveInfo.activityInfo.loadLabel(manager);
if (labelCache != null) {
labelCache.put(key, info.title);
}
}
}
// from the db
if (info.title == null) {
if (c != null) {
info.title = c.getString(titleIndex);
}
}
// fall back to the class name of the activity
if (info.title == null) {
info.title = componentName.getClassName();
}
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
return info;
}
/**
* Make an ShortcutInfo object for a shortcut that isn't an application.
*/
private ShortcutInfo getShortcutInfo(Cursor c, Context context,
int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
int titleIndex) {
Bitmap icon = null;
final ShortcutInfo info = new ShortcutInfo();
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
// TODO: If there's an explicit component and we can't install that, delete it.
info.title = c.getString(titleIndex);
int iconType = c.getInt(iconTypeIndex);
switch (iconType) {
case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
String packageName = c.getString(iconPackageIndex);
String resourceName = c.getString(iconResourceIndex);
PackageManager packageManager = context.getPackageManager();
info.customIcon = false;
// the resource
try {
Resources resources = packageManager.getResourcesForApplication(packageName);
if (resources != null) {
final int id = resources.getIdentifier(resourceName, null, null);
icon = Utilities.createIconBitmap(
mIconCache.getFullResIcon(resources, id), context);
}
} catch (Exception e) {
// drop this. we have other places to look for icons
}
// the db
if (icon == null) {
icon = getIconFromCursor(c, iconIndex, context);
}
// the fallback icon
if (icon == null) {
icon = getFallbackIcon();
info.usingFallbackIcon = true;
}
break;
case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
icon = getIconFromCursor(c, iconIndex, context);
if (icon == null) {
icon = getFallbackIcon();
info.customIcon = false;
info.usingFallbackIcon = true;
} else {
info.customIcon = true;
}
break;
default:
icon = getFallbackIcon();
info.usingFallbackIcon = true;
info.customIcon = false;
break;
}
info.setIcon(icon);
return info;
}
Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) {
@SuppressWarnings("all") // suppress dead code warning
final boolean debug = false;
if (debug) {
Log.d(TAG, "getIconFromCursor app="
+ c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE)));
}
byte[] data = c.getBlob(iconIndex);
try {
return Utilities.createIconBitmap(
BitmapFactory.decodeByteArray(data, 0, data.length), context);
} catch (Exception e) {
return null;
}
}
ShortcutInfo addShortcut(Context context, Intent data, long container, int screen,
int cellX, int cellY, boolean notify) {
final ShortcutInfo info = infoFromShortcutIntent(context, data, null);
if (info == null) {
return null;
}
addItemToDatabase(context, info, container, screen, cellX, cellY, notify);
return info;
}
/**
* Attempts to find an AppWidgetProviderInfo that matches the given component.
*/
AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context,
ComponentName component) {
List<AppWidgetProviderInfo> widgets =
AppWidgetManager.getInstance(context).getInstalledProviders();
for (AppWidgetProviderInfo info : widgets) {
if (info.provider.equals(component)) {
return info;
}
}
return null;
}
/**
* Returns a list of all the widgets that can handle configuration with a particular mimeType.
*/
List<WidgetMimeTypeHandlerData> resolveWidgetsForMimeType(Context context, String mimeType) {
final PackageManager packageManager = context.getPackageManager();
final List<WidgetMimeTypeHandlerData> supportedConfigurationActivities =
new ArrayList<WidgetMimeTypeHandlerData>();
final Intent supportsIntent =
new Intent(InstallWidgetReceiver.ACTION_SUPPORTS_CLIPDATA_MIMETYPE);
supportsIntent.setType(mimeType);
// Create a set of widget configuration components that we can test against
final List<AppWidgetProviderInfo> widgets =
AppWidgetManager.getInstance(context).getInstalledProviders();
final HashMap<ComponentName, AppWidgetProviderInfo> configurationComponentToWidget =
new HashMap<ComponentName, AppWidgetProviderInfo>();
for (AppWidgetProviderInfo info : widgets) {
configurationComponentToWidget.put(info.configure, info);
}
// Run through each of the intents that can handle this type of clip data, and cross
// reference them with the components that are actual configuration components
final List<ResolveInfo> activities = packageManager.queryIntentActivities(supportsIntent,
PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo info : activities) {
final ActivityInfo activityInfo = info.activityInfo;
final ComponentName infoComponent = new ComponentName(activityInfo.packageName,
activityInfo.name);
if (configurationComponentToWidget.containsKey(infoComponent)) {
supportedConfigurationActivities.add(
new InstallWidgetReceiver.WidgetMimeTypeHandlerData(info,
configurationComponentToWidget.get(infoComponent)));
}
}
return supportedConfigurationActivities;
}
ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) {
Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
if (intent == null) {
// If the intent is null, we can't construct a valid ShortcutInfo, so we return null
Log.e(TAG, "Can't construct ShorcutInfo with null intent");
return null;
}
Bitmap icon = null;
boolean customIcon = false;
ShortcutIconResource iconResource = null;
if (bitmap != null && bitmap instanceof Bitmap) {
icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context);
customIcon = true;
} else {
Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
if (extra != null && extra instanceof ShortcutIconResource) {
try {
iconResource = (ShortcutIconResource) extra;
final PackageManager packageManager = context.getPackageManager();
Resources resources = packageManager.getResourcesForApplication(
iconResource.packageName);
final int id = resources.getIdentifier(iconResource.resourceName, null, null);
icon = Utilities.createIconBitmap(
mIconCache.getFullResIcon(resources, id), context);
} catch (Exception e) {
Log.w(TAG, "Could not load shortcut icon: " + extra);
}
}
}
final ShortcutInfo info = new ShortcutInfo();
if (icon == null) {
if (fallbackIcon != null) {
icon = fallbackIcon;
} else {
icon = getFallbackIcon();
info.usingFallbackIcon = true;
}
}
info.setIcon(icon);
info.title = name;
info.intent = intent;
info.customIcon = customIcon;
info.iconResource = iconResource;
return info;
}
boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c,
int iconIndex) {
// If apps can't be on SD, don't even bother.
if (!mAppsCanBeOnExternalStorage) {
return false;
}
// If this icon doesn't have a custom icon, check to see
// what's stored in the DB, and if it doesn't match what
// we're going to show, store what we are going to show back
// into the DB. We do this so when we're loading, if the
// package manager can't find an icon (for example because
// the app is on SD) then we can use that instead.
if (!info.customIcon && !info.usingFallbackIcon) {
cache.put(info, c.getBlob(iconIndex));
return true;
}
return false;
}
void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) {
boolean needSave = false;
try {
if (data != null) {
Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length);
Bitmap loaded = info.getIcon(mIconCache);
needSave = !saved.sameAs(loaded);
} else {
needSave = true;
}
} catch (Exception e) {
needSave = true;
}
if (needSave) {
Log.d(TAG, "going to save icon bitmap for info=" + info);
// This is slower than is ideal, but this only happens once
// or when the app is updated with a new icon.
updateItemInDatabase(context, info);
}
}
/**
* Return an existing FolderInfo object if we have encountered this ID previously,
* or make a new one.
*/
private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
// See if a placeholder was created for us already
FolderInfo folderInfo = folders.get(id);
if (folderInfo == null) {
// No placeholder -- create a new instance
folderInfo = new FolderInfo();
folders.put(id, folderInfo);
}
return folderInfo;
}
private static final Collator sCollator = Collator.getInstance();
public static final Comparator<ApplicationInfo> APP_NAME_COMPARATOR
= new Comparator<ApplicationInfo>() {
public final int compare(ApplicationInfo a, ApplicationInfo b) {
int result = sCollator.compare(a.title.toString(), b.title.toString());
if (result == 0) {
result = a.componentName.compareTo(b.componentName);
}
return result;
}
};
public static final Comparator<ApplicationInfo> APP_INSTALL_TIME_COMPARATOR
= new Comparator<ApplicationInfo>() {
public final int compare(ApplicationInfo a, ApplicationInfo b) {
if (a.firstInstallTime < b.firstInstallTime) return 1;
if (a.firstInstallTime > b.firstInstallTime) return -1;
return 0;
}
};
public static final Comparator<AppWidgetProviderInfo> WIDGET_NAME_COMPARATOR
= new Comparator<AppWidgetProviderInfo>() {
public final int compare(AppWidgetProviderInfo a, AppWidgetProviderInfo b) {
return sCollator.compare(a.label.toString(), b.label.toString());
}
};
static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) {
if (info.activityInfo != null) {
return new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
} else {
return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name);
}
}
public static class ShortcutNameComparator implements Comparator<ResolveInfo> {
private PackageManager mPackageManager;
private HashMap<Object, CharSequence> mLabelCache;
ShortcutNameComparator(PackageManager pm) {
mPackageManager = pm;
mLabelCache = new HashMap<Object, CharSequence>();
}
ShortcutNameComparator(PackageManager pm, HashMap<Object, CharSequence> labelCache) {
mPackageManager = pm;
mLabelCache = labelCache;
}
public final int compare(ResolveInfo a, ResolveInfo b) {
CharSequence labelA, labelB;
ComponentName keyA = LauncherModel.getComponentNameFromResolveInfo(a);
ComponentName keyB = LauncherModel.getComponentNameFromResolveInfo(b);
if (mLabelCache.containsKey(keyA)) {
labelA = mLabelCache.get(keyA);
} else {
labelA = a.loadLabel(mPackageManager).toString();
mLabelCache.put(keyA, labelA);
}
if (mLabelCache.containsKey(keyB)) {
labelB = mLabelCache.get(keyB);
} else {
labelB = b.loadLabel(mPackageManager).toString();
mLabelCache.put(keyB, labelB);
}
return sCollator.compare(labelA, labelB);
}
};
public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
private PackageManager mPackageManager;
private HashMap<Object, String> mLabelCache;
WidgetAndShortcutNameComparator(PackageManager pm) {
mPackageManager = pm;
mLabelCache = new HashMap<Object, String>();
}
public final int compare(Object a, Object b) {
String labelA, labelB;
if (mLabelCache.containsKey(a)) {
labelA = mLabelCache.get(a);
} else {
labelA = (a instanceof AppWidgetProviderInfo) ?
((AppWidgetProviderInfo) a).label :
((ResolveInfo) a).loadLabel(mPackageManager).toString();
mLabelCache.put(a, labelA);
}
if (mLabelCache.containsKey(b)) {
labelB = mLabelCache.get(b);
} else {
labelB = (b instanceof AppWidgetProviderInfo) ?
((AppWidgetProviderInfo) b).label :
((ResolveInfo) b).loadLabel(mPackageManager).toString();
mLabelCache.put(b, labelB);
}
return sCollator.compare(labelA, labelB);
}
};
public void dumpState() {
Log.d(TAG, "mCallbacks=" + mCallbacks);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mAllAppsList.data);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mAllAppsList.added);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mAllAppsList.removed);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mAllAppsList.modified);
if (mLoaderTask != null) {
mLoaderTask.dumpState();
} else {
Log.d(TAG, "mLoaderTask=null");
}
}
}
| false | true | static boolean shortcutExists(Context context, String title, Intent intent) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
new String[] { "title", "intent" }, "title=? and intent=?",
new String[] { title, intent.toUri(0) }, null);
boolean result = false;
try {
result = c.moveToFirst();
} finally {
c.close();
}
return result;
}
/**
* Returns an ItemInfo array containing all the items in the LauncherModel.
* The ItemInfo.id is not set through this function.
*/
static ArrayList<ItemInfo> getItemsInLocalCoordinates(Context context) {
ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] {
LauncherSettings.Favorites.ITEM_TYPE, LauncherSettings.Favorites.CONTAINER,
LauncherSettings.Favorites.SCREEN, LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY,
LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY }, null, null, null);
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX);
final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY);
try {
while (c.moveToNext()) {
ItemInfo item = new ItemInfo();
item.cellX = c.getInt(cellXIndex);
item.cellY = c.getInt(cellYIndex);
item.spanX = c.getInt(spanXIndex);
item.spanY = c.getInt(spanYIndex);
item.container = c.getInt(containerIndex);
item.itemType = c.getInt(itemTypeIndex);
item.screen = c.getInt(screenIndex);
items.add(item);
}
} catch (Exception e) {
items.clear();
} finally {
c.close();
}
return items;
}
/**
* Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
*/
FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
"_id=? and (itemType=? or itemType=?)",
new String[] { String.valueOf(id),
String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null);
try {
if (c.moveToFirst()) {
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
FolderInfo folderInfo = null;
switch (c.getInt(itemTypeIndex)) {
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
folderInfo = findOrMakeFolder(folderList, id);
break;
}
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
folderInfo.container = c.getInt(containerIndex);
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
return folderInfo;
}
} finally {
c.close();
}
return null;
}
/**
* Add an item to the database in a specified container. Sets the container, screen, cellX and
* cellY fields of the item. Also assigns an ID to the item.
*/
static void addItemToDatabase(Context context, final ItemInfo item, final long container,
final int screen, final int cellX, final int cellY, final boolean notify) {
item.container = container;
item.cellX = cellX;
item.cellY = cellY;
// We store hotseat items in canonical form which is this orientation invariant position
// in the hotseat
if (context instanceof Launcher && screen < 0 &&
container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
item.screen = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
} else {
item.screen = screen;
}
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
LauncherApplication app = (LauncherApplication) context.getApplicationContext();
item.id = app.getLauncherProvider().generateNewId();
values.put(LauncherSettings.Favorites._ID, item.id);
item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
Runnable r = new Runnable() {
public void run() {
cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
if (sItemsIdMap.containsKey(item.id)) {
// we should not be adding new items in the db with the same id
throw new RuntimeException("Error: ItemInfo id (" + item.id + ") passed to " +
"addItemToDatabase already exists." + item.toString());
}
sItemsIdMap.put(item.id, item);
switch (item.itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
sFolders.put(item.id, (FolderInfo) item);
// Fall through
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
sWorkspaceItems.add(item);
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
sAppWidgets.add((LauncherAppWidgetInfo) item);
break;
}
}
};
if (sWorkerThread.getThreadId() == Process.myTid()) {
r.run();
} else {
sWorker.post(r);
}
}
/**
* Creates a new unique child id, for a given cell span across all layouts.
*/
static int getCellLayoutChildId(
long container, int screen, int localCellX, int localCellY, int spanX, int spanY) {
return (((int) container & 0xFF) << 24)
| (screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF);
}
static int getCellCountX() {
return mCellCountX;
}
static int getCellCountY() {
return mCellCountY;
}
/**
* Updates the model orientation helper to take into account the current layout dimensions
* when performing local/canonical coordinate transformations.
*/
static void updateWorkspaceLayoutCells(int shortAxisCellCount, int longAxisCellCount) {
mCellCountX = shortAxisCellCount;
mCellCountY = longAxisCellCount;
}
/**
* Removes the specified item from the database
* @param context
* @param item
*/
static void deleteItemFromDatabase(Context context, final ItemInfo item) {
final ContentResolver cr = context.getContentResolver();
final Uri uriToDelete = LauncherSettings.Favorites.getContentUri(item.id, false);
Runnable r = new Runnable() {
public void run() {
cr.delete(uriToDelete, null, null);
switch (item.itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
sFolders.remove(item.id);
sWorkspaceItems.remove(item);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
sWorkspaceItems.remove(item);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
sAppWidgets.remove((LauncherAppWidgetInfo) item);
break;
}
sItemsIdMap.remove(item.id);
sDbIconCache.remove(item);
}
};
if (sWorkerThread.getThreadId() == Process.myTid()) {
r.run();
} else {
sWorker.post(r);
}
}
/**
* Remove the contents of the specified folder from the database
*/
static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) {
final ContentResolver cr = context.getContentResolver();
Runnable r = new Runnable() {
public void run() {
cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
sItemsIdMap.remove(info.id);
sFolders.remove(info.id);
sDbIconCache.remove(info);
sWorkspaceItems.remove(info);
cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
for (ItemInfo childInfo : info.contents) {
sItemsIdMap.remove(childInfo.id);
sDbIconCache.remove(childInfo);
}
}
};
if (sWorkerThread.getThreadId() == Process.myTid()) {
r.run();
} else {
sWorker.post(r);
}
}
/**
* Set this as the current Launcher activity object for the loader.
*/
public void initialize(Callbacks callbacks) {
synchronized (mLock) {
mCallbacks = new WeakReference<Callbacks>(callbacks);
}
}
/**
* Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
* ACTION_PACKAGE_CHANGED.
*/
@Override
public void onReceive(Context context, Intent intent) {
if (DEBUG_LOADERS) Log.d(TAG, "onReceive intent=" + intent);
final String action = intent.getAction();
if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
|| Intent.ACTION_PACKAGE_REMOVED.equals(action)
|| Intent.ACTION_PACKAGE_ADDED.equals(action)) {
final String packageName = intent.getData().getSchemeSpecificPart();
final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
int op = PackageUpdatedTask.OP_NONE;
if (packageName == null || packageName.length() == 0) {
// they sent us a bad intent
return;
}
if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
op = PackageUpdatedTask.OP_UPDATE;
} else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
if (!replacing) {
op = PackageUpdatedTask.OP_REMOVE;
}
// else, we are replacing the package, so a PACKAGE_ADDED will be sent
// later, we will update the package at this time
} else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
if (!replacing) {
op = PackageUpdatedTask.OP_ADD;
} else {
op = PackageUpdatedTask.OP_UPDATE;
}
}
if (op != PackageUpdatedTask.OP_NONE) {
enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName }));
}
} else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
// First, schedule to add these apps back in.
String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packages));
// Then, rebind everything.
startLoaderFromBackground();
} else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
enqueuePackageUpdated(new PackageUpdatedTask(
PackageUpdatedTask.OP_UNAVAILABLE, packages));
} else if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
// If we have changed locale we need to clear out the labels in all apps/workspace.
forceReload();
} else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
// Check if configuration change was an mcc/mnc change which would affect app resources
// and we would need to clear out the labels in all apps/workspace. Same handling as
// above for ACTION_LOCALE_CHANGED
Configuration currentConfig = context.getResources().getConfiguration();
if (mPreviousConfigMcc != currentConfig.mcc) {
Log.d(TAG, "Reload apps on config change. curr_mcc:"
+ currentConfig.mcc + " prevmcc:" + mPreviousConfigMcc);
forceReload();
}
// Update previousConfig
mPreviousConfigMcc = currentConfig.mcc;
} else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) ||
SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) {
if (mCallbacks != null) {
Callbacks callbacks = mCallbacks.get();
if (callbacks != null) {
callbacks.bindSearchablesChanged();
}
}
}
}
private void forceReload() {
resetLoadedState(true, true);
// Do this here because if the launcher activity is running it will be restarted.
// If it's not running startLoaderFromBackground will merely tell it that it needs
// to reload.
startLoaderFromBackground();
}
public void resetLoadedState(boolean resetAllAppsLoaded, boolean resetWorkspaceLoaded) {
synchronized (mLock) {
// Stop any existing loaders first, so they don't set mAllAppsLoaded or
// mWorkspaceLoaded to true later
stopLoaderLocked();
if (resetAllAppsLoaded) mAllAppsLoaded = false;
if (resetWorkspaceLoaded) mWorkspaceLoaded = false;
}
}
/**
* When the launcher is in the background, it's possible for it to miss paired
* configuration changes. So whenever we trigger the loader from the background
* tell the launcher that it needs to re-run the loader when it comes back instead
* of doing it now.
*/
public void startLoaderFromBackground() {
boolean runLoader = false;
if (mCallbacks != null) {
Callbacks callbacks = mCallbacks.get();
if (callbacks != null) {
// Only actually run the loader if they're not paused.
if (!callbacks.setLoadOnResume()) {
runLoader = true;
}
}
}
if (runLoader) {
startLoader(false);
}
}
// If there is already a loader task running, tell it to stop.
// returns true if isLaunching() was true on the old task
private boolean stopLoaderLocked() {
boolean isLaunching = false;
LoaderTask oldTask = mLoaderTask;
if (oldTask != null) {
if (oldTask.isLaunching()) {
isLaunching = true;
}
oldTask.stopLocked();
}
return isLaunching;
}
public void startLoader(boolean isLaunching) {
synchronized (mLock) {
if (DEBUG_LOADERS) {
Log.d(TAG, "startLoader isLaunching=" + isLaunching);
}
// Don't bother to start the thread if we know it's not going to do anything
if (mCallbacks != null && mCallbacks.get() != null) {
// If there is already one running, tell it to stop.
// also, don't downgrade isLaunching if we're already running
isLaunching = isLaunching || stopLoaderLocked();
mLoaderTask = new LoaderTask(mApp, isLaunching);
sWorkerThread.setPriority(Thread.NORM_PRIORITY);
sWorker.post(mLoaderTask);
}
}
}
public void stopLoader() {
synchronized (mLock) {
if (mLoaderTask != null) {
mLoaderTask.stopLocked();
}
}
}
public boolean isAllAppsLoaded() {
return mAllAppsLoaded;
}
boolean isLoadingWorkspace() {
synchronized (mLock) {
if (mLoaderTask != null) {
return mLoaderTask.isLoadingWorkspace();
}
}
return false;
}
/**
* Runnable for the thread that loads the contents of the launcher:
* - workspace icons
* - widgets
* - all apps icons
*/
private class LoaderTask implements Runnable {
private Context mContext;
private Thread mWaitThread;
private boolean mIsLaunching;
private boolean mIsLoadingAndBindingWorkspace;
private boolean mStopped;
private boolean mLoadAndBindStepFinished;
private HashMap<Object, CharSequence> mLabelCache;
LoaderTask(Context context, boolean isLaunching) {
mContext = context;
mIsLaunching = isLaunching;
mLabelCache = new HashMap<Object, CharSequence>();
}
boolean isLaunching() {
return mIsLaunching;
}
boolean isLoadingWorkspace() {
return mIsLoadingAndBindingWorkspace;
}
private void loadAndBindWorkspace() {
mIsLoadingAndBindingWorkspace = true;
// Load the workspace
if (DEBUG_LOADERS) {
Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded);
}
if (!mWorkspaceLoaded) {
loadWorkspace();
synchronized (LoaderTask.this) {
if (mStopped) {
return;
}
mWorkspaceLoaded = true;
}
}
// Bind the workspace
bindWorkspace();
}
private void waitForIdle() {
// Wait until the either we're stopped or the other threads are done.
// This way we don't start loading all apps until the workspace has settled
// down.
synchronized (LoaderTask.this) {
final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
mHandler.postIdle(new Runnable() {
public void run() {
synchronized (LoaderTask.this) {
mLoadAndBindStepFinished = true;
if (DEBUG_LOADERS) {
Log.d(TAG, "done with previous binding step");
}
LoaderTask.this.notify();
}
}
});
while (!mStopped && !mLoadAndBindStepFinished) {
try {
this.wait();
} catch (InterruptedException ex) {
// Ignore
}
}
if (DEBUG_LOADERS) {
Log.d(TAG, "waited "
+ (SystemClock.uptimeMillis()-workspaceWaitTime)
+ "ms for previous step to finish binding");
}
}
}
public void run() {
// Optimize for end-user experience: if the Launcher is up and // running with the
// All Apps interface in the foreground, load All Apps first. Otherwise, load the
// workspace first (default).
final Callbacks cbk = mCallbacks.get();
final boolean loadWorkspaceFirst = cbk != null ? (!cbk.isAllAppsVisible()) : true;
keep_running: {
// Elevate priority when Home launches for the first time to avoid
// starving at boot time. Staring at a blank home is not cool.
synchronized (mLock) {
if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " +
(mIsLaunching ? "DEFAULT" : "BACKGROUND"));
android.os.Process.setThreadPriority(mIsLaunching
? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
}
if (loadWorkspaceFirst) {
if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace");
loadAndBindWorkspace();
} else {
if (DEBUG_LOADERS) Log.d(TAG, "step 1: special: loading all apps");
loadAndBindAllApps();
}
if (mStopped) {
break keep_running;
}
// Whew! Hard work done. Slow us down, and wait until the UI thread has
// settled down.
synchronized (mLock) {
if (mIsLaunching) {
if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND");
android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
}
}
waitForIdle();
// second step
if (loadWorkspaceFirst) {
if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps");
loadAndBindAllApps();
} else {
if (DEBUG_LOADERS) Log.d(TAG, "step 2: special: loading workspace");
loadAndBindWorkspace();
}
// Restore the default thread priority after we are done loading items
synchronized (mLock) {
android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
}
}
// Update the saved icons if necessary
if (DEBUG_LOADERS) Log.d(TAG, "Comparing loaded icons to database icons");
for (Object key : sDbIconCache.keySet()) {
updateSavedIcon(mContext, (ShortcutInfo) key, sDbIconCache.get(key));
}
sDbIconCache.clear();
// Clear out this reference, otherwise we end up holding it until all of the
// callback runnables are done.
mContext = null;
synchronized (mLock) {
// If we are still the last one to be scheduled, remove ourselves.
if (mLoaderTask == this) {
mLoaderTask = null;
}
}
}
public void stopLocked() {
synchronized (LoaderTask.this) {
mStopped = true;
this.notify();
}
}
/**
* Gets the callbacks object. If we've been stopped, or if the launcher object
* has somehow been garbage collected, return null instead. Pass in the Callbacks
* object that was around when the deferred message was scheduled, and if there's
* a new Callbacks object around then also return null. This will save us from
* calling onto it with data that will be ignored.
*/
Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
synchronized (mLock) {
if (mStopped) {
return null;
}
if (mCallbacks == null) {
return null;
}
final Callbacks callbacks = mCallbacks.get();
if (callbacks != oldCallbacks) {
return null;
}
if (callbacks == null) {
Log.w(TAG, "no mCallbacks");
return null;
}
return callbacks;
}
}
// check & update map of what's occupied; used to discard overlapping/invalid items
private boolean checkItemPlacement(ItemInfo occupied[][][], ItemInfo item) {
int containerIndex = item.screen;
if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
// Return early if we detect that an item is under the hotseat button
if (mCallbacks == null || mCallbacks.get().isAllAppsButtonRank(item.screen)) {
return false;
}
// We use the last index to refer to the hotseat and the screen as the rank, so
// test and update the occupied state accordingly
if (occupied[Launcher.SCREEN_COUNT][item.screen][0] != null) {
Log.e(TAG, "Error loading shortcut into hotseat " + item
+ " into position (" + item.screen + ":" + item.cellX + "," + item.cellY
+ ") occupied by " + occupied[Launcher.SCREEN_COUNT][item.screen][0]);
return false;
} else {
occupied[Launcher.SCREEN_COUNT][item.screen][0] = item;
return true;
}
} else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
// Skip further checking if it is not the hotseat or workspace container
return true;
}
// Check if any workspace icons overlap with each other
for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
if (occupied[containerIndex][x][y] != null) {
Log.e(TAG, "Error loading shortcut " + item
+ " into cell (" + containerIndex + "-" + item.screen + ":"
+ x + "," + y
+ ") occupied by "
+ occupied[containerIndex][x][y]);
return false;
}
}
}
for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
occupied[containerIndex][x][y] = item;
}
}
return true;
}
private void loadWorkspace() {
final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
final Context context = mContext;
final ContentResolver contentResolver = context.getContentResolver();
final PackageManager manager = context.getPackageManager();
final AppWidgetManager widgets = AppWidgetManager.getInstance(context);
final boolean isSafeMode = manager.isSafeMode();
// Make sure the default workspace is loaded, if needed
mApp.getLauncherProvider().loadDefaultFavoritesIfNecessary();
sWorkspaceItems.clear();
sAppWidgets.clear();
sFolders.clear();
sItemsIdMap.clear();
sDbIconCache.clear();
final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
final Cursor c = contentResolver.query(
LauncherSettings.Favorites.CONTENT_URI, null, null, null, null);
// +1 for the hotseat (it can be larger than the workspace)
// Load workspace in reverse order to ensure that latest items are loaded first (and
// before any earlier duplicates)
final ItemInfo occupied[][][] =
new ItemInfo[Launcher.SCREEN_COUNT + 1][mCellCountX + 1][mCellCountY + 1];
try {
final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
final int intentIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.INTENT);
final int titleIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.TITLE);
final int iconTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_TYPE);
final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
final int iconPackageIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_PACKAGE);
final int iconResourceIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_RESOURCE);
final int containerIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.CONTAINER);
final int itemTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ITEM_TYPE);
final int appWidgetIdIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.APPWIDGET_ID);
final int screenIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLY);
final int spanXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.SPANX);
final int spanYIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SPANY);
//final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
//final int displayModeIndex = c.getColumnIndexOrThrow(
// LauncherSettings.Favorites.DISPLAY_MODE);
ShortcutInfo info;
String intentDescription;
LauncherAppWidgetInfo appWidgetInfo;
int container;
long id;
Intent intent;
while (!mStopped && c.moveToNext()) {
try {
int itemType = c.getInt(itemTypeIndex);
switch (itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
intentDescription = c.getString(intentIndex);
try {
intent = Intent.parseUri(intentDescription, 0);
} catch (URISyntaxException e) {
continue;
}
if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
info = getShortcutInfo(manager, intent, context, c, iconIndex,
titleIndex, mLabelCache);
} else {
info = getShortcutInfo(c, context, iconTypeIndex,
iconPackageIndex, iconResourceIndex, iconIndex,
titleIndex);
// App shortcuts that used to be automatically added to Launcher
// didn't always have the correct intent flags set, so do that here
if (intent.getAction().equals(Intent.ACTION_MAIN) &&
intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
intent.addFlags(
Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
}
}
if (info != null) {
info.intent = intent;
info.id = c.getLong(idIndex);
container = c.getInt(containerIndex);
info.container = container;
info.screen = c.getInt(screenIndex);
info.cellX = c.getInt(cellXIndex);
info.cellY = c.getInt(cellYIndex);
// check & update map of what's occupied
if (!checkItemPlacement(occupied, info)) {
break;
}
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
sWorkspaceItems.add(info);
break;
default:
// Item is in a user folder
FolderInfo folderInfo =
findOrMakeFolder(sFolders, container);
folderInfo.add(info);
break;
}
sItemsIdMap.put(info.id, info);
// now that we've loaded everthing re-save it with the
// icon in case it disappears somehow.
queueIconToBeChecked(sDbIconCache, info, c, iconIndex);
} else {
// Failed to load the shortcut, probably because the
// activity manager couldn't resolve it (maybe the app
// was uninstalled), or the db row was somehow screwed up.
// Delete it.
id = c.getLong(idIndex);
Log.e(TAG, "Error loading shortcut " + id + ", removing it");
contentResolver.delete(LauncherSettings.Favorites.getContentUri(
id, false), null, null);
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
id = c.getLong(idIndex);
FolderInfo folderInfo = findOrMakeFolder(sFolders, id);
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
container = c.getInt(containerIndex);
folderInfo.container = container;
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
// check & update map of what's occupied
if (!checkItemPlacement(occupied, folderInfo)) {
break;
}
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
sWorkspaceItems.add(folderInfo);
break;
}
sItemsIdMap.put(folderInfo.id, folderInfo);
sFolders.put(folderInfo.id, folderInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
// Read all Launcher-specific widget details
int appWidgetId = c.getInt(appWidgetIdIndex);
id = c.getLong(idIndex);
final AppWidgetProviderInfo provider =
widgets.getAppWidgetInfo(appWidgetId);
if (!isSafeMode && (provider == null || provider.provider == null ||
provider.provider.getPackageName() == null)) {
String log = "Deleting widget that isn't installed anymore: id="
+ id + " appWidgetId=" + appWidgetId;
Log.e(TAG, log);
Launcher.sDumpLogs.add(log);
itemsToRemove.add(id);
} else {
appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
provider.provider);
appWidgetInfo.id = id;
appWidgetInfo.screen = c.getInt(screenIndex);
appWidgetInfo.cellX = c.getInt(cellXIndex);
appWidgetInfo.cellY = c.getInt(cellYIndex);
appWidgetInfo.spanX = c.getInt(spanXIndex);
appWidgetInfo.spanY = c.getInt(spanYIndex);
int[] minSpan = Launcher.getMinSpanForWidget(context, provider);
appWidgetInfo.minSpanX = minSpan[0];
appWidgetInfo.minSpanY = minSpan[1];
container = c.getInt(containerIndex);
if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Log.e(TAG, "Widget found where container "
+ "!= CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
continue;
}
appWidgetInfo.container = c.getInt(containerIndex);
// check & update map of what's occupied
if (!checkItemPlacement(occupied, appWidgetInfo)) {
break;
}
sItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
sAppWidgets.add(appWidgetInfo);
}
break;
}
} catch (Exception e) {
Log.w(TAG, "Desktop items loading interrupted:", e);
}
}
} finally {
c.close();
}
if (itemsToRemove.size() > 0) {
ContentProviderClient client = contentResolver.acquireContentProviderClient(
LauncherSettings.Favorites.CONTENT_URI);
// Remove dead items
for (long id : itemsToRemove) {
if (DEBUG_LOADERS) {
Log.d(TAG, "Removed id = " + id);
}
// Don't notify content observers
try {
client.delete(LauncherSettings.Favorites.getContentUri(id, false),
null, null);
} catch (RemoteException e) {
Log.w(TAG, "Could not remove id = " + id);
}
}
}
if (DEBUG_LOADERS) {
Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
Log.d(TAG, "workspace layout: ");
for (int y = 0; y < mCellCountY; y++) {
String line = "";
for (int s = 0; s < Launcher.SCREEN_COUNT; s++) {
if (s > 0) {
line += " | ";
}
for (int x = 0; x < mCellCountX; x++) {
line += ((occupied[s][x][y] != null) ? "#" : ".");
}
}
Log.d(TAG, "[ " + line + " ]");
}
}
}
/**
* Read everything out of our database.
*/
private void bindWorkspace() {
final long t = SystemClock.uptimeMillis();
// Don't use these two variables in any of the callback runnables.
// Otherwise we hold a reference to them.
final Callbacks oldCallbacks = mCallbacks.get();
if (oldCallbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderTask running with no launcher");
return;
}
// Get the list of workspace items to load and unbind the existing ShortcutInfos
// before we call startBinding() below.
final int currentScreen = oldCallbacks.getCurrentWorkspaceScreen();
final ArrayList<ItemInfo> tmpWorkspaceItems = unbindWorkspaceItemsOnMainThread();
// Order the items for loading as follows: current workspace, hotseat, everything else
Collections.sort(tmpWorkspaceItems, new Comparator<ItemInfo>() {
@Override
public int compare(ItemInfo lhs, ItemInfo rhs) {
int cellCountX = LauncherModel.getCellCountX();
int cellCountY = LauncherModel.getCellCountY();
int screenOffset = cellCountX * cellCountY;
int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat
long lr = (lhs.container * containerOffset + lhs.screen * screenOffset +
lhs.cellY * cellCountX + lhs.cellX);
long rr = (rhs.container * containerOffset + rhs.screen * screenOffset +
rhs.cellY * cellCountX + rhs.cellX);
return (int) (lr - rr);
}
});
// Precondition: the items are ordered by page, screen
final ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>();
for (ItemInfo ii : tmpWorkspaceItems) {
// Prepend the current items, hotseat items, append everything else
if (ii.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
ii.screen == currentScreen) {
workspaceItems.add(0, ii);
} else if (ii.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
workspaceItems.add(0, ii);
} else {
workspaceItems.add(ii);
}
}
// Tell the workspace that we're about to start firing items at it
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.startBinding();
}
}
});
// Add the items to the workspace.
int N = workspaceItems.size();
for (int i=0; i<N; i+=ITEMS_CHUNK) {
final int start = i;
final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindItems(workspaceItems, start, start+chunkSize);
}
}
});
}
// Ensure that we don't use the same folders data structure on the main thread
final HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>(sFolders);
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindFolders(folders);
}
}
});
// Wait until the queue goes empty.
mHandler.post(new Runnable() {
public void run() {
if (DEBUG_LOADERS) {
Log.d(TAG, "Going to start binding widgets soon.");
}
}
});
// Bind the widgets, one at a time.
// WARNING: this is calling into the workspace from the background thread,
// but since getCurrentScreen() just returns the int, we should be okay. This
// is just a hint for the order, and if it's wrong, we'll be okay.
// TODO: instead, we should have that push the current screen into here.
N = sAppWidgets.size();
// once for the current screen
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = sAppWidgets.get(i);
if (widget.screen == currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// once for the other screens
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = sAppWidgets.get(i);
if (widget.screen != currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// Tell the workspace that we're done.
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.finishBindingItems();
}
}
});
// If we're profiling, this is the last thing in the queue.
mHandler.post(new Runnable() {
public void run() {
if (DEBUG_LOADERS) {
Log.d(TAG, "bound workspace in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
mIsLoadingAndBindingWorkspace = false;
}
});
}
private void loadAndBindAllApps() {
if (DEBUG_LOADERS) {
Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
}
if (!mAllAppsLoaded) {
loadAllAppsByBatch();
synchronized (LoaderTask.this) {
if (mStopped) {
return;
}
mAllAppsLoaded = true;
}
} else {
onlyBindAllApps();
}
}
private void onlyBindAllApps() {
final Callbacks oldCallbacks = mCallbacks.get();
if (oldCallbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
return;
}
// shallow copy
@SuppressWarnings("unchecked")
final ArrayList<ApplicationInfo> list
= (ArrayList<ApplicationInfo>) mAllAppsList.data.clone();
mHandler.post(new Runnable() {
public void run() {
final long t = SystemClock.uptimeMillis();
final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindAllApplications(list);
}
if (DEBUG_LOADERS) {
Log.d(TAG, "bound all " + list.size() + " apps from cache in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
}
});
}
private void loadAllAppsByBatch() {
final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
// Don't use these two variables in any of the callback runnables.
// Otherwise we hold a reference to them.
final Callbacks oldCallbacks = mCallbacks.get();
if (oldCallbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderTask running with no launcher (loadAllAppsByBatch)");
return;
}
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
final PackageManager packageManager = mContext.getPackageManager();
List<ResolveInfo> apps = null;
int N = Integer.MAX_VALUE;
int startIndex;
int i=0;
int batchSize = -1;
while (i < N && !mStopped) {
if (i == 0) {
mAllAppsList.clear();
final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
apps = packageManager.queryIntentActivities(mainIntent, 0);
if (DEBUG_LOADERS) {
Log.d(TAG, "queryIntentActivities took "
+ (SystemClock.uptimeMillis()-qiaTime) + "ms");
}
if (apps == null) {
return;
}
N = apps.size();
if (DEBUG_LOADERS) {
Log.d(TAG, "queryIntentActivities got " + N + " apps");
}
if (N == 0) {
// There are no apps?!?
return;
}
if (mBatchSize == 0) {
batchSize = N;
} else {
batchSize = mBatchSize;
}
final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Collections.sort(apps,
new LauncherModel.ShortcutNameComparator(packageManager, mLabelCache));
if (DEBUG_LOADERS) {
Log.d(TAG, "sort took "
+ (SystemClock.uptimeMillis()-sortTime) + "ms");
}
}
final long t2 = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
startIndex = i;
for (int j=0; i<N && j<batchSize; j++) {
// This builds the icon bitmaps.
mAllAppsList.add(new ApplicationInfo(packageManager, apps.get(i),
mIconCache, mLabelCache));
i++;
}
final boolean first = i <= batchSize;
final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
final ArrayList<ApplicationInfo> added = mAllAppsList.added;
mAllAppsList.added = new ArrayList<ApplicationInfo>();
mHandler.post(new Runnable() {
public void run() {
final long t = SystemClock.uptimeMillis();
if (callbacks != null) {
if (first) {
callbacks.bindAllApplications(added);
} else {
callbacks.bindAppsAdded(added);
}
if (DEBUG_LOADERS) {
Log.d(TAG, "bound " + added.size() + " apps in "
+ (SystemClock.uptimeMillis() - t) + "ms");
}
} else {
Log.i(TAG, "not binding apps: no Launcher activity");
}
}
});
if (DEBUG_LOADERS) {
Log.d(TAG, "batch of " + (i-startIndex) + " icons processed in "
+ (SystemClock.uptimeMillis()-t2) + "ms");
}
if (mAllAppsLoadDelay > 0 && i < N) {
try {
if (DEBUG_LOADERS) {
Log.d(TAG, "sleeping for " + mAllAppsLoadDelay + "ms");
}
Thread.sleep(mAllAppsLoadDelay);
} catch (InterruptedException exc) { }
}
}
if (DEBUG_LOADERS) {
Log.d(TAG, "cached all " + N + " apps in "
+ (SystemClock.uptimeMillis()-t) + "ms"
+ (mAllAppsLoadDelay > 0 ? " (including delay)" : ""));
}
}
public void dumpState() {
Log.d(TAG, "mLoaderTask.mContext=" + mContext);
Log.d(TAG, "mLoaderTask.mWaitThread=" + mWaitThread);
Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
Log.d(TAG, "mItems size=" + sWorkspaceItems.size());
}
}
void enqueuePackageUpdated(PackageUpdatedTask task) {
sWorker.post(task);
}
private class PackageUpdatedTask implements Runnable {
int mOp;
String[] mPackages;
public static final int OP_NONE = 0;
public static final int OP_ADD = 1;
public static final int OP_UPDATE = 2;
public static final int OP_REMOVE = 3; // uninstlled
public static final int OP_UNAVAILABLE = 4; // external media unmounted
public PackageUpdatedTask(int op, String[] packages) {
mOp = op;
mPackages = packages;
}
public void run() {
final Context context = mApp;
final String[] packages = mPackages;
final int N = packages.length;
switch (mOp) {
case OP_ADD:
for (int i=0; i<N; i++) {
if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
mAllAppsList.addPackage(context, packages[i]);
}
break;
case OP_UPDATE:
for (int i=0; i<N; i++) {
if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
mAllAppsList.updatePackage(context, packages[i]);
}
break;
case OP_REMOVE:
case OP_UNAVAILABLE:
for (int i=0; i<N; i++) {
if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
mAllAppsList.removePackage(packages[i]);
}
break;
}
ArrayList<ApplicationInfo> added = null;
ArrayList<ApplicationInfo> removed = null;
ArrayList<ApplicationInfo> modified = null;
if (mAllAppsList.added.size() > 0) {
added = mAllAppsList.added;
mAllAppsList.added = new ArrayList<ApplicationInfo>();
}
if (mAllAppsList.removed.size() > 0) {
removed = mAllAppsList.removed;
mAllAppsList.removed = new ArrayList<ApplicationInfo>();
for (ApplicationInfo info: removed) {
mIconCache.remove(info.intent.getComponent());
}
}
if (mAllAppsList.modified.size() > 0) {
modified = mAllAppsList.modified;
mAllAppsList.modified = new ArrayList<ApplicationInfo>();
}
final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == null) {
Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
return;
}
if (added != null) {
final ArrayList<ApplicationInfo> addedFinal = added;
mHandler.post(new Runnable() {
public void run() {
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == cb && cb != null) {
callbacks.bindAppsAdded(addedFinal);
}
}
});
}
if (modified != null) {
final ArrayList<ApplicationInfo> modifiedFinal = modified;
mHandler.post(new Runnable() {
public void run() {
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == cb && cb != null) {
callbacks.bindAppsUpdated(modifiedFinal);
}
}
});
}
if (removed != null) {
final boolean permanent = mOp != OP_UNAVAILABLE;
final ArrayList<ApplicationInfo> removedFinal = removed;
mHandler.post(new Runnable() {
public void run() {
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == cb && cb != null) {
callbacks.bindAppsRemoved(removedFinal, permanent);
}
}
});
}
mHandler.post(new Runnable() {
@Override
public void run() {
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == cb && cb != null) {
callbacks.bindPackagesUpdated();
}
}
});
}
}
/**
* Returns all the Workspace ShortcutInfos associated with a particular package.
* @param intent
* @return
*/
ArrayList<ShortcutInfo> getShortcutInfosForPackage(String packageName) {
ArrayList<ShortcutInfo> infos = new ArrayList<ShortcutInfo>();
for (ItemInfo i : sWorkspaceItems) {
if (i instanceof ShortcutInfo) {
ShortcutInfo info = (ShortcutInfo) i;
if (packageName.equals(info.getPackageName())) {
infos.add(info);
}
}
}
return infos;
}
/**
* This is called from the code that adds shortcuts from the intent receiver. This
* doesn't have a Cursor, but
*/
public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) {
return getShortcutInfo(manager, intent, context, null, -1, -1, null);
}
/**
* Make an ShortcutInfo object for a shortcut that is an application.
*
* If c is not null, then it will be used to fill in missing data like the title and icon.
*/
public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context,
Cursor c, int iconIndex, int titleIndex, HashMap<Object, CharSequence> labelCache) {
Bitmap icon = null;
final ShortcutInfo info = new ShortcutInfo();
ComponentName componentName = intent.getComponent();
if (componentName == null) {
return null;
}
try {
PackageInfo pi = manager.getPackageInfo(componentName.getPackageName(), 0);
if (!pi.applicationInfo.enabled) {
// If we return null here, the corresponding item will be removed from the launcher
// db and will not appear in the workspace.
return null;
}
} catch (NameNotFoundException e) {
Log.d(TAG, "getPackInfo failed for package " + componentName.getPackageName());
}
// TODO: See if the PackageManager knows about this case. If it doesn't
// then return null & delete this.
// the resource -- This may implicitly give us back the fallback icon,
// but don't worry about that. All we're doing with usingFallbackIcon is
// to avoid saving lots of copies of that in the database, and most apps
// have icons anyway.
// Attempt to use queryIntentActivities to get the ResolveInfo (with IntentFilter info) and
// if that fails, or is ambiguious, fallback to the standard way of getting the resolve info
// via resolveActivity().
ResolveInfo resolveInfo = null;
ComponentName oldComponent = intent.getComponent();
Intent newIntent = new Intent(intent.getAction(), null);
newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
newIntent.setPackage(oldComponent.getPackageName());
List<ResolveInfo> infos = manager.queryIntentActivities(newIntent, 0);
for (ResolveInfo i : infos) {
ComponentName cn = new ComponentName(i.activityInfo.packageName,
i.activityInfo.name);
if (cn.equals(oldComponent)) {
resolveInfo = i;
}
}
if (resolveInfo == null) {
resolveInfo = manager.resolveActivity(intent, 0);
}
if (resolveInfo != null) {
icon = mIconCache.getIcon(componentName, resolveInfo, labelCache);
}
// the db
if (icon == null) {
if (c != null) {
icon = getIconFromCursor(c, iconIndex, context);
}
}
// the fallback icon
if (icon == null) {
icon = getFallbackIcon();
info.usingFallbackIcon = true;
}
info.setIcon(icon);
// from the resource
if (resolveInfo != null) {
ComponentName key = LauncherModel.getComponentNameFromResolveInfo(resolveInfo);
if (labelCache != null && labelCache.containsKey(key)) {
info.title = labelCache.get(key);
} else {
info.title = resolveInfo.activityInfo.loadLabel(manager);
if (labelCache != null) {
labelCache.put(key, info.title);
}
}
}
// from the db
if (info.title == null) {
if (c != null) {
info.title = c.getString(titleIndex);
}
}
// fall back to the class name of the activity
if (info.title == null) {
info.title = componentName.getClassName();
}
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
return info;
}
/**
* Make an ShortcutInfo object for a shortcut that isn't an application.
*/
private ShortcutInfo getShortcutInfo(Cursor c, Context context,
int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
int titleIndex) {
Bitmap icon = null;
final ShortcutInfo info = new ShortcutInfo();
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
// TODO: If there's an explicit component and we can't install that, delete it.
info.title = c.getString(titleIndex);
int iconType = c.getInt(iconTypeIndex);
switch (iconType) {
case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
String packageName = c.getString(iconPackageIndex);
String resourceName = c.getString(iconResourceIndex);
PackageManager packageManager = context.getPackageManager();
info.customIcon = false;
// the resource
try {
Resources resources = packageManager.getResourcesForApplication(packageName);
if (resources != null) {
final int id = resources.getIdentifier(resourceName, null, null);
icon = Utilities.createIconBitmap(
mIconCache.getFullResIcon(resources, id), context);
}
} catch (Exception e) {
// drop this. we have other places to look for icons
}
// the db
if (icon == null) {
icon = getIconFromCursor(c, iconIndex, context);
}
// the fallback icon
if (icon == null) {
icon = getFallbackIcon();
info.usingFallbackIcon = true;
}
break;
case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
icon = getIconFromCursor(c, iconIndex, context);
if (icon == null) {
icon = getFallbackIcon();
info.customIcon = false;
info.usingFallbackIcon = true;
} else {
info.customIcon = true;
}
break;
default:
icon = getFallbackIcon();
info.usingFallbackIcon = true;
info.customIcon = false;
break;
}
info.setIcon(icon);
return info;
}
Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) {
@SuppressWarnings("all") // suppress dead code warning
final boolean debug = false;
if (debug) {
Log.d(TAG, "getIconFromCursor app="
+ c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE)));
}
byte[] data = c.getBlob(iconIndex);
try {
return Utilities.createIconBitmap(
BitmapFactory.decodeByteArray(data, 0, data.length), context);
} catch (Exception e) {
return null;
}
}
ShortcutInfo addShortcut(Context context, Intent data, long container, int screen,
int cellX, int cellY, boolean notify) {
final ShortcutInfo info = infoFromShortcutIntent(context, data, null);
if (info == null) {
return null;
}
addItemToDatabase(context, info, container, screen, cellX, cellY, notify);
return info;
}
/**
* Attempts to find an AppWidgetProviderInfo that matches the given component.
*/
AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context,
ComponentName component) {
List<AppWidgetProviderInfo> widgets =
AppWidgetManager.getInstance(context).getInstalledProviders();
for (AppWidgetProviderInfo info : widgets) {
if (info.provider.equals(component)) {
return info;
}
}
return null;
}
/**
* Returns a list of all the widgets that can handle configuration with a particular mimeType.
*/
List<WidgetMimeTypeHandlerData> resolveWidgetsForMimeType(Context context, String mimeType) {
final PackageManager packageManager = context.getPackageManager();
final List<WidgetMimeTypeHandlerData> supportedConfigurationActivities =
new ArrayList<WidgetMimeTypeHandlerData>();
final Intent supportsIntent =
new Intent(InstallWidgetReceiver.ACTION_SUPPORTS_CLIPDATA_MIMETYPE);
supportsIntent.setType(mimeType);
// Create a set of widget configuration components that we can test against
final List<AppWidgetProviderInfo> widgets =
AppWidgetManager.getInstance(context).getInstalledProviders();
final HashMap<ComponentName, AppWidgetProviderInfo> configurationComponentToWidget =
new HashMap<ComponentName, AppWidgetProviderInfo>();
for (AppWidgetProviderInfo info : widgets) {
configurationComponentToWidget.put(info.configure, info);
}
// Run through each of the intents that can handle this type of clip data, and cross
// reference them with the components that are actual configuration components
final List<ResolveInfo> activities = packageManager.queryIntentActivities(supportsIntent,
PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo info : activities) {
final ActivityInfo activityInfo = info.activityInfo;
final ComponentName infoComponent = new ComponentName(activityInfo.packageName,
activityInfo.name);
if (configurationComponentToWidget.containsKey(infoComponent)) {
supportedConfigurationActivities.add(
new InstallWidgetReceiver.WidgetMimeTypeHandlerData(info,
configurationComponentToWidget.get(infoComponent)));
}
}
return supportedConfigurationActivities;
}
ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) {
Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
if (intent == null) {
// If the intent is null, we can't construct a valid ShortcutInfo, so we return null
Log.e(TAG, "Can't construct ShorcutInfo with null intent");
return null;
}
Bitmap icon = null;
boolean customIcon = false;
ShortcutIconResource iconResource = null;
if (bitmap != null && bitmap instanceof Bitmap) {
icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context);
customIcon = true;
} else {
Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
if (extra != null && extra instanceof ShortcutIconResource) {
try {
iconResource = (ShortcutIconResource) extra;
final PackageManager packageManager = context.getPackageManager();
Resources resources = packageManager.getResourcesForApplication(
iconResource.packageName);
final int id = resources.getIdentifier(iconResource.resourceName, null, null);
icon = Utilities.createIconBitmap(
mIconCache.getFullResIcon(resources, id), context);
} catch (Exception e) {
Log.w(TAG, "Could not load shortcut icon: " + extra);
}
}
}
final ShortcutInfo info = new ShortcutInfo();
if (icon == null) {
if (fallbackIcon != null) {
icon = fallbackIcon;
} else {
icon = getFallbackIcon();
info.usingFallbackIcon = true;
}
}
info.setIcon(icon);
info.title = name;
info.intent = intent;
info.customIcon = customIcon;
info.iconResource = iconResource;
return info;
}
boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c,
int iconIndex) {
// If apps can't be on SD, don't even bother.
if (!mAppsCanBeOnExternalStorage) {
return false;
}
// If this icon doesn't have a custom icon, check to see
// what's stored in the DB, and if it doesn't match what
// we're going to show, store what we are going to show back
// into the DB. We do this so when we're loading, if the
// package manager can't find an icon (for example because
// the app is on SD) then we can use that instead.
if (!info.customIcon && !info.usingFallbackIcon) {
cache.put(info, c.getBlob(iconIndex));
return true;
}
return false;
}
void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) {
boolean needSave = false;
try {
if (data != null) {
Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length);
Bitmap loaded = info.getIcon(mIconCache);
needSave = !saved.sameAs(loaded);
} else {
needSave = true;
}
} catch (Exception e) {
needSave = true;
}
if (needSave) {
Log.d(TAG, "going to save icon bitmap for info=" + info);
// This is slower than is ideal, but this only happens once
// or when the app is updated with a new icon.
updateItemInDatabase(context, info);
}
}
/**
* Return an existing FolderInfo object if we have encountered this ID previously,
* or make a new one.
*/
private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
// See if a placeholder was created for us already
FolderInfo folderInfo = folders.get(id);
if (folderInfo == null) {
// No placeholder -- create a new instance
folderInfo = new FolderInfo();
folders.put(id, folderInfo);
}
return folderInfo;
}
private static final Collator sCollator = Collator.getInstance();
public static final Comparator<ApplicationInfo> APP_NAME_COMPARATOR
= new Comparator<ApplicationInfo>() {
public final int compare(ApplicationInfo a, ApplicationInfo b) {
int result = sCollator.compare(a.title.toString(), b.title.toString());
if (result == 0) {
result = a.componentName.compareTo(b.componentName);
}
return result;
}
};
public static final Comparator<ApplicationInfo> APP_INSTALL_TIME_COMPARATOR
= new Comparator<ApplicationInfo>() {
public final int compare(ApplicationInfo a, ApplicationInfo b) {
if (a.firstInstallTime < b.firstInstallTime) return 1;
if (a.firstInstallTime > b.firstInstallTime) return -1;
return 0;
}
};
public static final Comparator<AppWidgetProviderInfo> WIDGET_NAME_COMPARATOR
= new Comparator<AppWidgetProviderInfo>() {
public final int compare(AppWidgetProviderInfo a, AppWidgetProviderInfo b) {
return sCollator.compare(a.label.toString(), b.label.toString());
}
};
static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) {
if (info.activityInfo != null) {
return new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
} else {
return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name);
}
}
public static class ShortcutNameComparator implements Comparator<ResolveInfo> {
private PackageManager mPackageManager;
private HashMap<Object, CharSequence> mLabelCache;
ShortcutNameComparator(PackageManager pm) {
mPackageManager = pm;
mLabelCache = new HashMap<Object, CharSequence>();
}
ShortcutNameComparator(PackageManager pm, HashMap<Object, CharSequence> labelCache) {
mPackageManager = pm;
mLabelCache = labelCache;
}
public final int compare(ResolveInfo a, ResolveInfo b) {
CharSequence labelA, labelB;
ComponentName keyA = LauncherModel.getComponentNameFromResolveInfo(a);
ComponentName keyB = LauncherModel.getComponentNameFromResolveInfo(b);
if (mLabelCache.containsKey(keyA)) {
labelA = mLabelCache.get(keyA);
} else {
labelA = a.loadLabel(mPackageManager).toString();
mLabelCache.put(keyA, labelA);
}
if (mLabelCache.containsKey(keyB)) {
labelB = mLabelCache.get(keyB);
} else {
labelB = b.loadLabel(mPackageManager).toString();
mLabelCache.put(keyB, labelB);
}
return sCollator.compare(labelA, labelB);
}
};
public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
private PackageManager mPackageManager;
private HashMap<Object, String> mLabelCache;
WidgetAndShortcutNameComparator(PackageManager pm) {
mPackageManager = pm;
mLabelCache = new HashMap<Object, String>();
}
public final int compare(Object a, Object b) {
String labelA, labelB;
if (mLabelCache.containsKey(a)) {
labelA = mLabelCache.get(a);
} else {
labelA = (a instanceof AppWidgetProviderInfo) ?
((AppWidgetProviderInfo) a).label :
((ResolveInfo) a).loadLabel(mPackageManager).toString();
mLabelCache.put(a, labelA);
}
if (mLabelCache.containsKey(b)) {
labelB = mLabelCache.get(b);
} else {
labelB = (b instanceof AppWidgetProviderInfo) ?
((AppWidgetProviderInfo) b).label :
((ResolveInfo) b).loadLabel(mPackageManager).toString();
mLabelCache.put(b, labelB);
}
return sCollator.compare(labelA, labelB);
}
};
public void dumpState() {
Log.d(TAG, "mCallbacks=" + mCallbacks);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mAllAppsList.data);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mAllAppsList.added);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mAllAppsList.removed);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mAllAppsList.modified);
if (mLoaderTask != null) {
mLoaderTask.dumpState();
} else {
Log.d(TAG, "mLoaderTask=null");
}
}
}
| static boolean shortcutExists(Context context, String title, Intent intent) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
new String[] { "title", "intent" }, "title=? and intent=?",
new String[] { title, intent.toUri(0) }, null);
boolean result = false;
try {
result = c.moveToFirst();
} finally {
c.close();
}
return result;
}
/**
* Returns an ItemInfo array containing all the items in the LauncherModel.
* The ItemInfo.id is not set through this function.
*/
static ArrayList<ItemInfo> getItemsInLocalCoordinates(Context context) {
ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] {
LauncherSettings.Favorites.ITEM_TYPE, LauncherSettings.Favorites.CONTAINER,
LauncherSettings.Favorites.SCREEN, LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY,
LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY }, null, null, null);
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX);
final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY);
try {
while (c.moveToNext()) {
ItemInfo item = new ItemInfo();
item.cellX = c.getInt(cellXIndex);
item.cellY = c.getInt(cellYIndex);
item.spanX = c.getInt(spanXIndex);
item.spanY = c.getInt(spanYIndex);
item.container = c.getInt(containerIndex);
item.itemType = c.getInt(itemTypeIndex);
item.screen = c.getInt(screenIndex);
items.add(item);
}
} catch (Exception e) {
items.clear();
} finally {
c.close();
}
return items;
}
/**
* Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
*/
FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
"_id=? and (itemType=? or itemType=?)",
new String[] { String.valueOf(id),
String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null);
try {
if (c.moveToFirst()) {
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
FolderInfo folderInfo = null;
switch (c.getInt(itemTypeIndex)) {
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
folderInfo = findOrMakeFolder(folderList, id);
break;
}
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
folderInfo.container = c.getInt(containerIndex);
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
return folderInfo;
}
} finally {
c.close();
}
return null;
}
/**
* Add an item to the database in a specified container. Sets the container, screen, cellX and
* cellY fields of the item. Also assigns an ID to the item.
*/
static void addItemToDatabase(Context context, final ItemInfo item, final long container,
final int screen, final int cellX, final int cellY, final boolean notify) {
item.container = container;
item.cellX = cellX;
item.cellY = cellY;
// We store hotseat items in canonical form which is this orientation invariant position
// in the hotseat
if (context instanceof Launcher && screen < 0 &&
container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
item.screen = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
} else {
item.screen = screen;
}
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
LauncherApplication app = (LauncherApplication) context.getApplicationContext();
item.id = app.getLauncherProvider().generateNewId();
values.put(LauncherSettings.Favorites._ID, item.id);
item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
Runnable r = new Runnable() {
public void run() {
cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
if (sItemsIdMap.containsKey(item.id)) {
// we should not be adding new items in the db with the same id
throw new RuntimeException("Error: ItemInfo id (" + item.id + ") passed to " +
"addItemToDatabase already exists." + item.toString());
}
sItemsIdMap.put(item.id, item);
switch (item.itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
sFolders.put(item.id, (FolderInfo) item);
// Fall through
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
sWorkspaceItems.add(item);
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
sAppWidgets.add((LauncherAppWidgetInfo) item);
break;
}
}
};
if (sWorkerThread.getThreadId() == Process.myTid()) {
r.run();
} else {
sWorker.post(r);
}
}
/**
* Creates a new unique child id, for a given cell span across all layouts.
*/
static int getCellLayoutChildId(
long container, int screen, int localCellX, int localCellY, int spanX, int spanY) {
return (((int) container & 0xFF) << 24)
| (screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF);
}
static int getCellCountX() {
return mCellCountX;
}
static int getCellCountY() {
return mCellCountY;
}
/**
* Updates the model orientation helper to take into account the current layout dimensions
* when performing local/canonical coordinate transformations.
*/
static void updateWorkspaceLayoutCells(int shortAxisCellCount, int longAxisCellCount) {
mCellCountX = shortAxisCellCount;
mCellCountY = longAxisCellCount;
}
/**
* Removes the specified item from the database
* @param context
* @param item
*/
static void deleteItemFromDatabase(Context context, final ItemInfo item) {
final ContentResolver cr = context.getContentResolver();
final Uri uriToDelete = LauncherSettings.Favorites.getContentUri(item.id, false);
Runnable r = new Runnable() {
public void run() {
cr.delete(uriToDelete, null, null);
switch (item.itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
sFolders.remove(item.id);
sWorkspaceItems.remove(item);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
sWorkspaceItems.remove(item);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
sAppWidgets.remove((LauncherAppWidgetInfo) item);
break;
}
sItemsIdMap.remove(item.id);
sDbIconCache.remove(item);
}
};
if (sWorkerThread.getThreadId() == Process.myTid()) {
r.run();
} else {
sWorker.post(r);
}
}
/**
* Remove the contents of the specified folder from the database
*/
static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) {
final ContentResolver cr = context.getContentResolver();
Runnable r = new Runnable() {
public void run() {
cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
sItemsIdMap.remove(info.id);
sFolders.remove(info.id);
sDbIconCache.remove(info);
sWorkspaceItems.remove(info);
cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
for (ItemInfo childInfo : info.contents) {
sItemsIdMap.remove(childInfo.id);
sDbIconCache.remove(childInfo);
}
}
};
if (sWorkerThread.getThreadId() == Process.myTid()) {
r.run();
} else {
sWorker.post(r);
}
}
/**
* Set this as the current Launcher activity object for the loader.
*/
public void initialize(Callbacks callbacks) {
synchronized (mLock) {
mCallbacks = new WeakReference<Callbacks>(callbacks);
}
}
/**
* Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
* ACTION_PACKAGE_CHANGED.
*/
@Override
public void onReceive(Context context, Intent intent) {
if (DEBUG_LOADERS) Log.d(TAG, "onReceive intent=" + intent);
final String action = intent.getAction();
if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
|| Intent.ACTION_PACKAGE_REMOVED.equals(action)
|| Intent.ACTION_PACKAGE_ADDED.equals(action)) {
final String packageName = intent.getData().getSchemeSpecificPart();
final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
int op = PackageUpdatedTask.OP_NONE;
if (packageName == null || packageName.length() == 0) {
// they sent us a bad intent
return;
}
if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
op = PackageUpdatedTask.OP_UPDATE;
} else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
if (!replacing) {
op = PackageUpdatedTask.OP_REMOVE;
}
// else, we are replacing the package, so a PACKAGE_ADDED will be sent
// later, we will update the package at this time
} else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
if (!replacing) {
op = PackageUpdatedTask.OP_ADD;
} else {
op = PackageUpdatedTask.OP_UPDATE;
}
}
if (op != PackageUpdatedTask.OP_NONE) {
enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName }));
}
} else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
// First, schedule to add these apps back in.
String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packages));
// Then, rebind everything.
startLoaderFromBackground();
} else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
enqueuePackageUpdated(new PackageUpdatedTask(
PackageUpdatedTask.OP_UNAVAILABLE, packages));
} else if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
// If we have changed locale we need to clear out the labels in all apps/workspace.
forceReload();
} else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
// Check if configuration change was an mcc/mnc change which would affect app resources
// and we would need to clear out the labels in all apps/workspace. Same handling as
// above for ACTION_LOCALE_CHANGED
Configuration currentConfig = context.getResources().getConfiguration();
if (mPreviousConfigMcc != currentConfig.mcc) {
Log.d(TAG, "Reload apps on config change. curr_mcc:"
+ currentConfig.mcc + " prevmcc:" + mPreviousConfigMcc);
forceReload();
}
// Update previousConfig
mPreviousConfigMcc = currentConfig.mcc;
} else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) ||
SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) {
if (mCallbacks != null) {
Callbacks callbacks = mCallbacks.get();
if (callbacks != null) {
callbacks.bindSearchablesChanged();
}
}
}
}
private void forceReload() {
resetLoadedState(true, true);
// Do this here because if the launcher activity is running it will be restarted.
// If it's not running startLoaderFromBackground will merely tell it that it needs
// to reload.
startLoaderFromBackground();
}
public void resetLoadedState(boolean resetAllAppsLoaded, boolean resetWorkspaceLoaded) {
synchronized (mLock) {
// Stop any existing loaders first, so they don't set mAllAppsLoaded or
// mWorkspaceLoaded to true later
stopLoaderLocked();
if (resetAllAppsLoaded) mAllAppsLoaded = false;
if (resetWorkspaceLoaded) mWorkspaceLoaded = false;
}
}
/**
* When the launcher is in the background, it's possible for it to miss paired
* configuration changes. So whenever we trigger the loader from the background
* tell the launcher that it needs to re-run the loader when it comes back instead
* of doing it now.
*/
public void startLoaderFromBackground() {
boolean runLoader = false;
if (mCallbacks != null) {
Callbacks callbacks = mCallbacks.get();
if (callbacks != null) {
// Only actually run the loader if they're not paused.
if (!callbacks.setLoadOnResume()) {
runLoader = true;
}
}
}
if (runLoader) {
startLoader(false);
}
}
// If there is already a loader task running, tell it to stop.
// returns true if isLaunching() was true on the old task
private boolean stopLoaderLocked() {
boolean isLaunching = false;
LoaderTask oldTask = mLoaderTask;
if (oldTask != null) {
if (oldTask.isLaunching()) {
isLaunching = true;
}
oldTask.stopLocked();
}
return isLaunching;
}
public void startLoader(boolean isLaunching) {
synchronized (mLock) {
if (DEBUG_LOADERS) {
Log.d(TAG, "startLoader isLaunching=" + isLaunching);
}
// Don't bother to start the thread if we know it's not going to do anything
if (mCallbacks != null && mCallbacks.get() != null) {
// If there is already one running, tell it to stop.
// also, don't downgrade isLaunching if we're already running
isLaunching = isLaunching || stopLoaderLocked();
mLoaderTask = new LoaderTask(mApp, isLaunching);
sWorkerThread.setPriority(Thread.NORM_PRIORITY);
sWorker.post(mLoaderTask);
}
}
}
public void stopLoader() {
synchronized (mLock) {
if (mLoaderTask != null) {
mLoaderTask.stopLocked();
}
}
}
public boolean isAllAppsLoaded() {
return mAllAppsLoaded;
}
boolean isLoadingWorkspace() {
synchronized (mLock) {
if (mLoaderTask != null) {
return mLoaderTask.isLoadingWorkspace();
}
}
return false;
}
/**
* Runnable for the thread that loads the contents of the launcher:
* - workspace icons
* - widgets
* - all apps icons
*/
private class LoaderTask implements Runnable {
private Context mContext;
private Thread mWaitThread;
private boolean mIsLaunching;
private boolean mIsLoadingAndBindingWorkspace;
private boolean mStopped;
private boolean mLoadAndBindStepFinished;
private HashMap<Object, CharSequence> mLabelCache;
LoaderTask(Context context, boolean isLaunching) {
mContext = context;
mIsLaunching = isLaunching;
mLabelCache = new HashMap<Object, CharSequence>();
}
boolean isLaunching() {
return mIsLaunching;
}
boolean isLoadingWorkspace() {
return mIsLoadingAndBindingWorkspace;
}
private void loadAndBindWorkspace() {
mIsLoadingAndBindingWorkspace = true;
// Load the workspace
if (DEBUG_LOADERS) {
Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded);
}
if (!mWorkspaceLoaded) {
loadWorkspace();
synchronized (LoaderTask.this) {
if (mStopped) {
return;
}
mWorkspaceLoaded = true;
}
}
// Bind the workspace
bindWorkspace();
}
private void waitForIdle() {
// Wait until the either we're stopped or the other threads are done.
// This way we don't start loading all apps until the workspace has settled
// down.
synchronized (LoaderTask.this) {
final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
mHandler.postIdle(new Runnable() {
public void run() {
synchronized (LoaderTask.this) {
mLoadAndBindStepFinished = true;
if (DEBUG_LOADERS) {
Log.d(TAG, "done with previous binding step");
}
LoaderTask.this.notify();
}
}
});
while (!mStopped && !mLoadAndBindStepFinished) {
try {
this.wait();
} catch (InterruptedException ex) {
// Ignore
}
}
if (DEBUG_LOADERS) {
Log.d(TAG, "waited "
+ (SystemClock.uptimeMillis()-workspaceWaitTime)
+ "ms for previous step to finish binding");
}
}
}
public void run() {
// Optimize for end-user experience: if the Launcher is up and // running with the
// All Apps interface in the foreground, load All Apps first. Otherwise, load the
// workspace first (default).
final Callbacks cbk = mCallbacks.get();
final boolean loadWorkspaceFirst = cbk != null ? (!cbk.isAllAppsVisible()) : true;
keep_running: {
// Elevate priority when Home launches for the first time to avoid
// starving at boot time. Staring at a blank home is not cool.
synchronized (mLock) {
if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " +
(mIsLaunching ? "DEFAULT" : "BACKGROUND"));
android.os.Process.setThreadPriority(mIsLaunching
? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
}
if (loadWorkspaceFirst) {
if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace");
loadAndBindWorkspace();
} else {
if (DEBUG_LOADERS) Log.d(TAG, "step 1: special: loading all apps");
loadAndBindAllApps();
}
if (mStopped) {
break keep_running;
}
// Whew! Hard work done. Slow us down, and wait until the UI thread has
// settled down.
synchronized (mLock) {
if (mIsLaunching) {
if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND");
android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
}
}
waitForIdle();
// second step
if (loadWorkspaceFirst) {
if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps");
loadAndBindAllApps();
} else {
if (DEBUG_LOADERS) Log.d(TAG, "step 2: special: loading workspace");
loadAndBindWorkspace();
}
// Restore the default thread priority after we are done loading items
synchronized (mLock) {
android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
}
}
// Update the saved icons if necessary
if (DEBUG_LOADERS) Log.d(TAG, "Comparing loaded icons to database icons");
for (Object key : sDbIconCache.keySet()) {
updateSavedIcon(mContext, (ShortcutInfo) key, sDbIconCache.get(key));
}
sDbIconCache.clear();
// Clear out this reference, otherwise we end up holding it until all of the
// callback runnables are done.
mContext = null;
synchronized (mLock) {
// If we are still the last one to be scheduled, remove ourselves.
if (mLoaderTask == this) {
mLoaderTask = null;
}
}
}
public void stopLocked() {
synchronized (LoaderTask.this) {
mStopped = true;
this.notify();
}
}
/**
* Gets the callbacks object. If we've been stopped, or if the launcher object
* has somehow been garbage collected, return null instead. Pass in the Callbacks
* object that was around when the deferred message was scheduled, and if there's
* a new Callbacks object around then also return null. This will save us from
* calling onto it with data that will be ignored.
*/
Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
synchronized (mLock) {
if (mStopped) {
return null;
}
if (mCallbacks == null) {
return null;
}
final Callbacks callbacks = mCallbacks.get();
if (callbacks != oldCallbacks) {
return null;
}
if (callbacks == null) {
Log.w(TAG, "no mCallbacks");
return null;
}
return callbacks;
}
}
// check & update map of what's occupied; used to discard overlapping/invalid items
private boolean checkItemPlacement(ItemInfo occupied[][][], ItemInfo item) {
int containerIndex = item.screen;
if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
// Return early if we detect that an item is under the hotseat button
if (mCallbacks == null || mCallbacks.get().isAllAppsButtonRank(item.screen)) {
return false;
}
// We use the last index to refer to the hotseat and the screen as the rank, so
// test and update the occupied state accordingly
if (occupied[Launcher.SCREEN_COUNT][item.screen][0] != null) {
Log.e(TAG, "Error loading shortcut into hotseat " + item
+ " into position (" + item.screen + ":" + item.cellX + "," + item.cellY
+ ") occupied by " + occupied[Launcher.SCREEN_COUNT][item.screen][0]);
return false;
} else {
occupied[Launcher.SCREEN_COUNT][item.screen][0] = item;
return true;
}
} else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
// Skip further checking if it is not the hotseat or workspace container
return true;
}
// Check if any workspace icons overlap with each other
for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
if (occupied[containerIndex][x][y] != null) {
Log.e(TAG, "Error loading shortcut " + item
+ " into cell (" + containerIndex + "-" + item.screen + ":"
+ x + "," + y
+ ") occupied by "
+ occupied[containerIndex][x][y]);
return false;
}
}
}
for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
occupied[containerIndex][x][y] = item;
}
}
return true;
}
private void loadWorkspace() {
final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
final Context context = mContext;
final ContentResolver contentResolver = context.getContentResolver();
final PackageManager manager = context.getPackageManager();
final AppWidgetManager widgets = AppWidgetManager.getInstance(context);
final boolean isSafeMode = manager.isSafeMode();
// Make sure the default workspace is loaded, if needed
mApp.getLauncherProvider().loadDefaultFavoritesIfNecessary();
sWorkspaceItems.clear();
sAppWidgets.clear();
sFolders.clear();
sItemsIdMap.clear();
sDbIconCache.clear();
final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
final Cursor c = contentResolver.query(
LauncherSettings.Favorites.CONTENT_URI, null, null, null, null);
// +1 for the hotseat (it can be larger than the workspace)
// Load workspace in reverse order to ensure that latest items are loaded first (and
// before any earlier duplicates)
final ItemInfo occupied[][][] =
new ItemInfo[Launcher.SCREEN_COUNT + 1][mCellCountX + 1][mCellCountY + 1];
try {
final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
final int intentIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.INTENT);
final int titleIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.TITLE);
final int iconTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_TYPE);
final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
final int iconPackageIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_PACKAGE);
final int iconResourceIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_RESOURCE);
final int containerIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.CONTAINER);
final int itemTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ITEM_TYPE);
final int appWidgetIdIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.APPWIDGET_ID);
final int screenIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLY);
final int spanXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.SPANX);
final int spanYIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SPANY);
//final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
//final int displayModeIndex = c.getColumnIndexOrThrow(
// LauncherSettings.Favorites.DISPLAY_MODE);
ShortcutInfo info;
String intentDescription;
LauncherAppWidgetInfo appWidgetInfo;
int container;
long id;
Intent intent;
while (!mStopped && c.moveToNext()) {
try {
int itemType = c.getInt(itemTypeIndex);
switch (itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
intentDescription = c.getString(intentIndex);
try {
intent = Intent.parseUri(intentDescription, 0);
} catch (URISyntaxException e) {
continue;
}
if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
info = getShortcutInfo(manager, intent, context, c, iconIndex,
titleIndex, mLabelCache);
} else {
info = getShortcutInfo(c, context, iconTypeIndex,
iconPackageIndex, iconResourceIndex, iconIndex,
titleIndex);
// App shortcuts that used to be automatically added to Launcher
// didn't always have the correct intent flags set, so do that here
if (intent.getAction().equals(Intent.ACTION_MAIN) &&
intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
intent.addFlags(
Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
}
}
if (info != null) {
info.intent = intent;
info.id = c.getLong(idIndex);
container = c.getInt(containerIndex);
info.container = container;
info.screen = c.getInt(screenIndex);
info.cellX = c.getInt(cellXIndex);
info.cellY = c.getInt(cellYIndex);
// check & update map of what's occupied
if (!checkItemPlacement(occupied, info)) {
break;
}
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
sWorkspaceItems.add(info);
break;
default:
// Item is in a user folder
FolderInfo folderInfo =
findOrMakeFolder(sFolders, container);
folderInfo.add(info);
break;
}
sItemsIdMap.put(info.id, info);
// now that we've loaded everthing re-save it with the
// icon in case it disappears somehow.
queueIconToBeChecked(sDbIconCache, info, c, iconIndex);
} else {
// Failed to load the shortcut, probably because the
// activity manager couldn't resolve it (maybe the app
// was uninstalled), or the db row was somehow screwed up.
// Delete it.
id = c.getLong(idIndex);
Log.e(TAG, "Error loading shortcut " + id + ", removing it");
contentResolver.delete(LauncherSettings.Favorites.getContentUri(
id, false), null, null);
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
id = c.getLong(idIndex);
FolderInfo folderInfo = findOrMakeFolder(sFolders, id);
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
container = c.getInt(containerIndex);
folderInfo.container = container;
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
// check & update map of what's occupied
if (!checkItemPlacement(occupied, folderInfo)) {
break;
}
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
sWorkspaceItems.add(folderInfo);
break;
}
sItemsIdMap.put(folderInfo.id, folderInfo);
sFolders.put(folderInfo.id, folderInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
// Read all Launcher-specific widget details
int appWidgetId = c.getInt(appWidgetIdIndex);
id = c.getLong(idIndex);
final AppWidgetProviderInfo provider =
widgets.getAppWidgetInfo(appWidgetId);
if (!isSafeMode && (provider == null || provider.provider == null ||
provider.provider.getPackageName() == null)) {
String log = "Deleting widget that isn't installed anymore: id="
+ id + " appWidgetId=" + appWidgetId;
Log.e(TAG, log);
Launcher.sDumpLogs.add(log);
itemsToRemove.add(id);
} else {
appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
provider.provider);
appWidgetInfo.id = id;
appWidgetInfo.screen = c.getInt(screenIndex);
appWidgetInfo.cellX = c.getInt(cellXIndex);
appWidgetInfo.cellY = c.getInt(cellYIndex);
appWidgetInfo.spanX = c.getInt(spanXIndex);
appWidgetInfo.spanY = c.getInt(spanYIndex);
int[] minSpan = Launcher.getMinSpanForWidget(context, provider);
appWidgetInfo.minSpanX = minSpan[0];
appWidgetInfo.minSpanY = minSpan[1];
container = c.getInt(containerIndex);
if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Log.e(TAG, "Widget found where container "
+ "!= CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
continue;
}
appWidgetInfo.container = c.getInt(containerIndex);
// check & update map of what's occupied
if (!checkItemPlacement(occupied, appWidgetInfo)) {
break;
}
sItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
sAppWidgets.add(appWidgetInfo);
}
break;
}
} catch (Exception e) {
Log.w(TAG, "Desktop items loading interrupted:", e);
}
}
} finally {
c.close();
}
if (itemsToRemove.size() > 0) {
ContentProviderClient client = contentResolver.acquireContentProviderClient(
LauncherSettings.Favorites.CONTENT_URI);
// Remove dead items
for (long id : itemsToRemove) {
if (DEBUG_LOADERS) {
Log.d(TAG, "Removed id = " + id);
}
// Don't notify content observers
try {
client.delete(LauncherSettings.Favorites.getContentUri(id, false),
null, null);
} catch (RemoteException e) {
Log.w(TAG, "Could not remove id = " + id);
}
}
}
if (DEBUG_LOADERS) {
Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
Log.d(TAG, "workspace layout: ");
for (int y = 0; y < mCellCountY; y++) {
String line = "";
for (int s = 0; s < Launcher.SCREEN_COUNT; s++) {
if (s > 0) {
line += " | ";
}
for (int x = 0; x < mCellCountX; x++) {
line += ((occupied[s][x][y] != null) ? "#" : ".");
}
}
Log.d(TAG, "[ " + line + " ]");
}
}
}
/**
* Read everything out of our database.
*/
private void bindWorkspace() {
final long t = SystemClock.uptimeMillis();
// Don't use these two variables in any of the callback runnables.
// Otherwise we hold a reference to them.
final Callbacks oldCallbacks = mCallbacks.get();
if (oldCallbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderTask running with no launcher");
return;
}
// Get the list of workspace items to load and unbind the existing ShortcutInfos
// before we call startBinding() below.
final int currentScreen = oldCallbacks.getCurrentWorkspaceScreen();
final ArrayList<ItemInfo> tmpWorkspaceItems = unbindWorkspaceItemsOnMainThread();
// Order the items for loading as follows: current workspace, hotseat, everything else
Collections.sort(tmpWorkspaceItems, new Comparator<ItemInfo>() {
@Override
public int compare(ItemInfo lhs, ItemInfo rhs) {
int cellCountX = LauncherModel.getCellCountX();
int cellCountY = LauncherModel.getCellCountY();
int screenOffset = cellCountX * cellCountY;
int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat
long lr = (lhs.container * containerOffset + lhs.screen * screenOffset +
lhs.cellY * cellCountX + lhs.cellX);
long rr = (rhs.container * containerOffset + rhs.screen * screenOffset +
rhs.cellY * cellCountX + rhs.cellX);
return (int) (lr - rr);
}
});
// Precondition: the items are ordered by page, screen
final ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>();
for (ItemInfo ii : tmpWorkspaceItems) {
// Prepend the current items, hotseat items, append everything else
if (ii.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
ii.screen == currentScreen) {
workspaceItems.add(0, ii);
} else if (ii.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
workspaceItems.add(0, ii);
} else {
workspaceItems.add(ii);
}
}
// Tell the workspace that we're about to start firing items at it
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.startBinding();
}
}
});
// Add the items to the workspace.
int N = workspaceItems.size();
for (int i=0; i<N; i+=ITEMS_CHUNK) {
final int start = i;
final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindItems(workspaceItems, start, start+chunkSize);
}
}
});
}
// Ensure that we don't use the same folders data structure on the main thread
final HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>(sFolders);
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindFolders(folders);
}
}
});
// Wait until the queue goes empty.
mHandler.post(new Runnable() {
public void run() {
if (DEBUG_LOADERS) {
Log.d(TAG, "Going to start binding widgets soon.");
}
}
});
// Bind the widgets, one at a time.
// WARNING: this is calling into the workspace from the background thread,
// but since getCurrentScreen() just returns the int, we should be okay. This
// is just a hint for the order, and if it's wrong, we'll be okay.
// TODO: instead, we should have that push the current screen into here.
N = sAppWidgets.size();
// once for the current screen
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = sAppWidgets.get(i);
if (widget.screen == currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// once for the other screens
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = sAppWidgets.get(i);
if (widget.screen != currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// Tell the workspace that we're done.
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.finishBindingItems();
}
}
});
// Cleanup
mHandler.post(new Runnable() {
public void run() {
// If we're profiling, ensure this is the last thing in the queue.
if (DEBUG_LOADERS) {
Log.d(TAG, "bound workspace in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
mIsLoadingAndBindingWorkspace = false;
}
});
}
private void loadAndBindAllApps() {
if (DEBUG_LOADERS) {
Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
}
if (!mAllAppsLoaded) {
loadAllAppsByBatch();
synchronized (LoaderTask.this) {
if (mStopped) {
return;
}
mAllAppsLoaded = true;
}
} else {
onlyBindAllApps();
}
}
private void onlyBindAllApps() {
final Callbacks oldCallbacks = mCallbacks.get();
if (oldCallbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
return;
}
// shallow copy
@SuppressWarnings("unchecked")
final ArrayList<ApplicationInfo> list
= (ArrayList<ApplicationInfo>) mAllAppsList.data.clone();
mHandler.post(new Runnable() {
public void run() {
final long t = SystemClock.uptimeMillis();
final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindAllApplications(list);
}
if (DEBUG_LOADERS) {
Log.d(TAG, "bound all " + list.size() + " apps from cache in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
}
});
}
private void loadAllAppsByBatch() {
final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
// Don't use these two variables in any of the callback runnables.
// Otherwise we hold a reference to them.
final Callbacks oldCallbacks = mCallbacks.get();
if (oldCallbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderTask running with no launcher (loadAllAppsByBatch)");
return;
}
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
final PackageManager packageManager = mContext.getPackageManager();
List<ResolveInfo> apps = null;
int N = Integer.MAX_VALUE;
int startIndex;
int i=0;
int batchSize = -1;
while (i < N && !mStopped) {
if (i == 0) {
mAllAppsList.clear();
final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
apps = packageManager.queryIntentActivities(mainIntent, 0);
if (DEBUG_LOADERS) {
Log.d(TAG, "queryIntentActivities took "
+ (SystemClock.uptimeMillis()-qiaTime) + "ms");
}
if (apps == null) {
return;
}
N = apps.size();
if (DEBUG_LOADERS) {
Log.d(TAG, "queryIntentActivities got " + N + " apps");
}
if (N == 0) {
// There are no apps?!?
return;
}
if (mBatchSize == 0) {
batchSize = N;
} else {
batchSize = mBatchSize;
}
final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Collections.sort(apps,
new LauncherModel.ShortcutNameComparator(packageManager, mLabelCache));
if (DEBUG_LOADERS) {
Log.d(TAG, "sort took "
+ (SystemClock.uptimeMillis()-sortTime) + "ms");
}
}
final long t2 = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
startIndex = i;
for (int j=0; i<N && j<batchSize; j++) {
// This builds the icon bitmaps.
mAllAppsList.add(new ApplicationInfo(packageManager, apps.get(i),
mIconCache, mLabelCache));
i++;
}
final boolean first = i <= batchSize;
final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
final ArrayList<ApplicationInfo> added = mAllAppsList.added;
mAllAppsList.added = new ArrayList<ApplicationInfo>();
mHandler.post(new Runnable() {
public void run() {
final long t = SystemClock.uptimeMillis();
if (callbacks != null) {
if (first) {
callbacks.bindAllApplications(added);
} else {
callbacks.bindAppsAdded(added);
}
if (DEBUG_LOADERS) {
Log.d(TAG, "bound " + added.size() + " apps in "
+ (SystemClock.uptimeMillis() - t) + "ms");
}
} else {
Log.i(TAG, "not binding apps: no Launcher activity");
}
}
});
if (DEBUG_LOADERS) {
Log.d(TAG, "batch of " + (i-startIndex) + " icons processed in "
+ (SystemClock.uptimeMillis()-t2) + "ms");
}
if (mAllAppsLoadDelay > 0 && i < N) {
try {
if (DEBUG_LOADERS) {
Log.d(TAG, "sleeping for " + mAllAppsLoadDelay + "ms");
}
Thread.sleep(mAllAppsLoadDelay);
} catch (InterruptedException exc) { }
}
}
if (DEBUG_LOADERS) {
Log.d(TAG, "cached all " + N + " apps in "
+ (SystemClock.uptimeMillis()-t) + "ms"
+ (mAllAppsLoadDelay > 0 ? " (including delay)" : ""));
}
}
public void dumpState() {
Log.d(TAG, "mLoaderTask.mContext=" + mContext);
Log.d(TAG, "mLoaderTask.mWaitThread=" + mWaitThread);
Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
Log.d(TAG, "mItems size=" + sWorkspaceItems.size());
}
}
void enqueuePackageUpdated(PackageUpdatedTask task) {
sWorker.post(task);
}
private class PackageUpdatedTask implements Runnable {
int mOp;
String[] mPackages;
public static final int OP_NONE = 0;
public static final int OP_ADD = 1;
public static final int OP_UPDATE = 2;
public static final int OP_REMOVE = 3; // uninstlled
public static final int OP_UNAVAILABLE = 4; // external media unmounted
public PackageUpdatedTask(int op, String[] packages) {
mOp = op;
mPackages = packages;
}
public void run() {
final Context context = mApp;
final String[] packages = mPackages;
final int N = packages.length;
switch (mOp) {
case OP_ADD:
for (int i=0; i<N; i++) {
if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
mAllAppsList.addPackage(context, packages[i]);
}
break;
case OP_UPDATE:
for (int i=0; i<N; i++) {
if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
mAllAppsList.updatePackage(context, packages[i]);
}
break;
case OP_REMOVE:
case OP_UNAVAILABLE:
for (int i=0; i<N; i++) {
if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
mAllAppsList.removePackage(packages[i]);
}
break;
}
ArrayList<ApplicationInfo> added = null;
ArrayList<ApplicationInfo> removed = null;
ArrayList<ApplicationInfo> modified = null;
if (mAllAppsList.added.size() > 0) {
added = mAllAppsList.added;
mAllAppsList.added = new ArrayList<ApplicationInfo>();
}
if (mAllAppsList.removed.size() > 0) {
removed = mAllAppsList.removed;
mAllAppsList.removed = new ArrayList<ApplicationInfo>();
for (ApplicationInfo info: removed) {
mIconCache.remove(info.intent.getComponent());
}
}
if (mAllAppsList.modified.size() > 0) {
modified = mAllAppsList.modified;
mAllAppsList.modified = new ArrayList<ApplicationInfo>();
}
final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == null) {
Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
return;
}
if (added != null) {
final ArrayList<ApplicationInfo> addedFinal = added;
mHandler.post(new Runnable() {
public void run() {
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == cb && cb != null) {
callbacks.bindAppsAdded(addedFinal);
}
}
});
}
if (modified != null) {
final ArrayList<ApplicationInfo> modifiedFinal = modified;
mHandler.post(new Runnable() {
public void run() {
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == cb && cb != null) {
callbacks.bindAppsUpdated(modifiedFinal);
}
}
});
}
if (removed != null) {
final boolean permanent = mOp != OP_UNAVAILABLE;
final ArrayList<ApplicationInfo> removedFinal = removed;
mHandler.post(new Runnable() {
public void run() {
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == cb && cb != null) {
callbacks.bindAppsRemoved(removedFinal, permanent);
}
}
});
}
mHandler.post(new Runnable() {
@Override
public void run() {
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == cb && cb != null) {
callbacks.bindPackagesUpdated();
}
}
});
}
}
/**
* Returns all the Workspace ShortcutInfos associated with a particular package.
* @param intent
* @return
*/
ArrayList<ShortcutInfo> getShortcutInfosForPackage(String packageName) {
ArrayList<ShortcutInfo> infos = new ArrayList<ShortcutInfo>();
for (ItemInfo i : sWorkspaceItems) {
if (i instanceof ShortcutInfo) {
ShortcutInfo info = (ShortcutInfo) i;
if (packageName.equals(info.getPackageName())) {
infos.add(info);
}
}
}
return infos;
}
/**
* This is called from the code that adds shortcuts from the intent receiver. This
* doesn't have a Cursor, but
*/
public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) {
return getShortcutInfo(manager, intent, context, null, -1, -1, null);
}
/**
* Make an ShortcutInfo object for a shortcut that is an application.
*
* If c is not null, then it will be used to fill in missing data like the title and icon.
*/
public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context,
Cursor c, int iconIndex, int titleIndex, HashMap<Object, CharSequence> labelCache) {
Bitmap icon = null;
final ShortcutInfo info = new ShortcutInfo();
ComponentName componentName = intent.getComponent();
if (componentName == null) {
return null;
}
try {
PackageInfo pi = manager.getPackageInfo(componentName.getPackageName(), 0);
if (!pi.applicationInfo.enabled) {
// If we return null here, the corresponding item will be removed from the launcher
// db and will not appear in the workspace.
return null;
}
} catch (NameNotFoundException e) {
Log.d(TAG, "getPackInfo failed for package " + componentName.getPackageName());
}
// TODO: See if the PackageManager knows about this case. If it doesn't
// then return null & delete this.
// the resource -- This may implicitly give us back the fallback icon,
// but don't worry about that. All we're doing with usingFallbackIcon is
// to avoid saving lots of copies of that in the database, and most apps
// have icons anyway.
// Attempt to use queryIntentActivities to get the ResolveInfo (with IntentFilter info) and
// if that fails, or is ambiguious, fallback to the standard way of getting the resolve info
// via resolveActivity().
ResolveInfo resolveInfo = null;
ComponentName oldComponent = intent.getComponent();
Intent newIntent = new Intent(intent.getAction(), null);
newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
newIntent.setPackage(oldComponent.getPackageName());
List<ResolveInfo> infos = manager.queryIntentActivities(newIntent, 0);
for (ResolveInfo i : infos) {
ComponentName cn = new ComponentName(i.activityInfo.packageName,
i.activityInfo.name);
if (cn.equals(oldComponent)) {
resolveInfo = i;
}
}
if (resolveInfo == null) {
resolveInfo = manager.resolveActivity(intent, 0);
}
if (resolveInfo != null) {
icon = mIconCache.getIcon(componentName, resolveInfo, labelCache);
}
// the db
if (icon == null) {
if (c != null) {
icon = getIconFromCursor(c, iconIndex, context);
}
}
// the fallback icon
if (icon == null) {
icon = getFallbackIcon();
info.usingFallbackIcon = true;
}
info.setIcon(icon);
// from the resource
if (resolveInfo != null) {
ComponentName key = LauncherModel.getComponentNameFromResolveInfo(resolveInfo);
if (labelCache != null && labelCache.containsKey(key)) {
info.title = labelCache.get(key);
} else {
info.title = resolveInfo.activityInfo.loadLabel(manager);
if (labelCache != null) {
labelCache.put(key, info.title);
}
}
}
// from the db
if (info.title == null) {
if (c != null) {
info.title = c.getString(titleIndex);
}
}
// fall back to the class name of the activity
if (info.title == null) {
info.title = componentName.getClassName();
}
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
return info;
}
/**
* Make an ShortcutInfo object for a shortcut that isn't an application.
*/
private ShortcutInfo getShortcutInfo(Cursor c, Context context,
int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
int titleIndex) {
Bitmap icon = null;
final ShortcutInfo info = new ShortcutInfo();
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
// TODO: If there's an explicit component and we can't install that, delete it.
info.title = c.getString(titleIndex);
int iconType = c.getInt(iconTypeIndex);
switch (iconType) {
case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
String packageName = c.getString(iconPackageIndex);
String resourceName = c.getString(iconResourceIndex);
PackageManager packageManager = context.getPackageManager();
info.customIcon = false;
// the resource
try {
Resources resources = packageManager.getResourcesForApplication(packageName);
if (resources != null) {
final int id = resources.getIdentifier(resourceName, null, null);
icon = Utilities.createIconBitmap(
mIconCache.getFullResIcon(resources, id), context);
}
} catch (Exception e) {
// drop this. we have other places to look for icons
}
// the db
if (icon == null) {
icon = getIconFromCursor(c, iconIndex, context);
}
// the fallback icon
if (icon == null) {
icon = getFallbackIcon();
info.usingFallbackIcon = true;
}
break;
case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
icon = getIconFromCursor(c, iconIndex, context);
if (icon == null) {
icon = getFallbackIcon();
info.customIcon = false;
info.usingFallbackIcon = true;
} else {
info.customIcon = true;
}
break;
default:
icon = getFallbackIcon();
info.usingFallbackIcon = true;
info.customIcon = false;
break;
}
info.setIcon(icon);
return info;
}
Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) {
@SuppressWarnings("all") // suppress dead code warning
final boolean debug = false;
if (debug) {
Log.d(TAG, "getIconFromCursor app="
+ c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE)));
}
byte[] data = c.getBlob(iconIndex);
try {
return Utilities.createIconBitmap(
BitmapFactory.decodeByteArray(data, 0, data.length), context);
} catch (Exception e) {
return null;
}
}
ShortcutInfo addShortcut(Context context, Intent data, long container, int screen,
int cellX, int cellY, boolean notify) {
final ShortcutInfo info = infoFromShortcutIntent(context, data, null);
if (info == null) {
return null;
}
addItemToDatabase(context, info, container, screen, cellX, cellY, notify);
return info;
}
/**
* Attempts to find an AppWidgetProviderInfo that matches the given component.
*/
AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context,
ComponentName component) {
List<AppWidgetProviderInfo> widgets =
AppWidgetManager.getInstance(context).getInstalledProviders();
for (AppWidgetProviderInfo info : widgets) {
if (info.provider.equals(component)) {
return info;
}
}
return null;
}
/**
* Returns a list of all the widgets that can handle configuration with a particular mimeType.
*/
List<WidgetMimeTypeHandlerData> resolveWidgetsForMimeType(Context context, String mimeType) {
final PackageManager packageManager = context.getPackageManager();
final List<WidgetMimeTypeHandlerData> supportedConfigurationActivities =
new ArrayList<WidgetMimeTypeHandlerData>();
final Intent supportsIntent =
new Intent(InstallWidgetReceiver.ACTION_SUPPORTS_CLIPDATA_MIMETYPE);
supportsIntent.setType(mimeType);
// Create a set of widget configuration components that we can test against
final List<AppWidgetProviderInfo> widgets =
AppWidgetManager.getInstance(context).getInstalledProviders();
final HashMap<ComponentName, AppWidgetProviderInfo> configurationComponentToWidget =
new HashMap<ComponentName, AppWidgetProviderInfo>();
for (AppWidgetProviderInfo info : widgets) {
configurationComponentToWidget.put(info.configure, info);
}
// Run through each of the intents that can handle this type of clip data, and cross
// reference them with the components that are actual configuration components
final List<ResolveInfo> activities = packageManager.queryIntentActivities(supportsIntent,
PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo info : activities) {
final ActivityInfo activityInfo = info.activityInfo;
final ComponentName infoComponent = new ComponentName(activityInfo.packageName,
activityInfo.name);
if (configurationComponentToWidget.containsKey(infoComponent)) {
supportedConfigurationActivities.add(
new InstallWidgetReceiver.WidgetMimeTypeHandlerData(info,
configurationComponentToWidget.get(infoComponent)));
}
}
return supportedConfigurationActivities;
}
ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) {
Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
if (intent == null) {
// If the intent is null, we can't construct a valid ShortcutInfo, so we return null
Log.e(TAG, "Can't construct ShorcutInfo with null intent");
return null;
}
Bitmap icon = null;
boolean customIcon = false;
ShortcutIconResource iconResource = null;
if (bitmap != null && bitmap instanceof Bitmap) {
icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context);
customIcon = true;
} else {
Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
if (extra != null && extra instanceof ShortcutIconResource) {
try {
iconResource = (ShortcutIconResource) extra;
final PackageManager packageManager = context.getPackageManager();
Resources resources = packageManager.getResourcesForApplication(
iconResource.packageName);
final int id = resources.getIdentifier(iconResource.resourceName, null, null);
icon = Utilities.createIconBitmap(
mIconCache.getFullResIcon(resources, id), context);
} catch (Exception e) {
Log.w(TAG, "Could not load shortcut icon: " + extra);
}
}
}
final ShortcutInfo info = new ShortcutInfo();
if (icon == null) {
if (fallbackIcon != null) {
icon = fallbackIcon;
} else {
icon = getFallbackIcon();
info.usingFallbackIcon = true;
}
}
info.setIcon(icon);
info.title = name;
info.intent = intent;
info.customIcon = customIcon;
info.iconResource = iconResource;
return info;
}
boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c,
int iconIndex) {
// If apps can't be on SD, don't even bother.
if (!mAppsCanBeOnExternalStorage) {
return false;
}
// If this icon doesn't have a custom icon, check to see
// what's stored in the DB, and if it doesn't match what
// we're going to show, store what we are going to show back
// into the DB. We do this so when we're loading, if the
// package manager can't find an icon (for example because
// the app is on SD) then we can use that instead.
if (!info.customIcon && !info.usingFallbackIcon) {
cache.put(info, c.getBlob(iconIndex));
return true;
}
return false;
}
void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) {
boolean needSave = false;
try {
if (data != null) {
Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length);
Bitmap loaded = info.getIcon(mIconCache);
needSave = !saved.sameAs(loaded);
} else {
needSave = true;
}
} catch (Exception e) {
needSave = true;
}
if (needSave) {
Log.d(TAG, "going to save icon bitmap for info=" + info);
// This is slower than is ideal, but this only happens once
// or when the app is updated with a new icon.
updateItemInDatabase(context, info);
}
}
/**
* Return an existing FolderInfo object if we have encountered this ID previously,
* or make a new one.
*/
private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
// See if a placeholder was created for us already
FolderInfo folderInfo = folders.get(id);
if (folderInfo == null) {
// No placeholder -- create a new instance
folderInfo = new FolderInfo();
folders.put(id, folderInfo);
}
return folderInfo;
}
private static final Collator sCollator = Collator.getInstance();
public static final Comparator<ApplicationInfo> APP_NAME_COMPARATOR
= new Comparator<ApplicationInfo>() {
public final int compare(ApplicationInfo a, ApplicationInfo b) {
int result = sCollator.compare(a.title.toString(), b.title.toString());
if (result == 0) {
result = a.componentName.compareTo(b.componentName);
}
return result;
}
};
public static final Comparator<ApplicationInfo> APP_INSTALL_TIME_COMPARATOR
= new Comparator<ApplicationInfo>() {
public final int compare(ApplicationInfo a, ApplicationInfo b) {
if (a.firstInstallTime < b.firstInstallTime) return 1;
if (a.firstInstallTime > b.firstInstallTime) return -1;
return 0;
}
};
public static final Comparator<AppWidgetProviderInfo> WIDGET_NAME_COMPARATOR
= new Comparator<AppWidgetProviderInfo>() {
public final int compare(AppWidgetProviderInfo a, AppWidgetProviderInfo b) {
return sCollator.compare(a.label.toString(), b.label.toString());
}
};
static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) {
if (info.activityInfo != null) {
return new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
} else {
return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name);
}
}
public static class ShortcutNameComparator implements Comparator<ResolveInfo> {
private PackageManager mPackageManager;
private HashMap<Object, CharSequence> mLabelCache;
ShortcutNameComparator(PackageManager pm) {
mPackageManager = pm;
mLabelCache = new HashMap<Object, CharSequence>();
}
ShortcutNameComparator(PackageManager pm, HashMap<Object, CharSequence> labelCache) {
mPackageManager = pm;
mLabelCache = labelCache;
}
public final int compare(ResolveInfo a, ResolveInfo b) {
CharSequence labelA, labelB;
ComponentName keyA = LauncherModel.getComponentNameFromResolveInfo(a);
ComponentName keyB = LauncherModel.getComponentNameFromResolveInfo(b);
if (mLabelCache.containsKey(keyA)) {
labelA = mLabelCache.get(keyA);
} else {
labelA = a.loadLabel(mPackageManager).toString();
mLabelCache.put(keyA, labelA);
}
if (mLabelCache.containsKey(keyB)) {
labelB = mLabelCache.get(keyB);
} else {
labelB = b.loadLabel(mPackageManager).toString();
mLabelCache.put(keyB, labelB);
}
return sCollator.compare(labelA, labelB);
}
};
public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
private PackageManager mPackageManager;
private HashMap<Object, String> mLabelCache;
WidgetAndShortcutNameComparator(PackageManager pm) {
mPackageManager = pm;
mLabelCache = new HashMap<Object, String>();
}
public final int compare(Object a, Object b) {
String labelA, labelB;
if (mLabelCache.containsKey(a)) {
labelA = mLabelCache.get(a);
} else {
labelA = (a instanceof AppWidgetProviderInfo) ?
((AppWidgetProviderInfo) a).label :
((ResolveInfo) a).loadLabel(mPackageManager).toString();
mLabelCache.put(a, labelA);
}
if (mLabelCache.containsKey(b)) {
labelB = mLabelCache.get(b);
} else {
labelB = (b instanceof AppWidgetProviderInfo) ?
((AppWidgetProviderInfo) b).label :
((ResolveInfo) b).loadLabel(mPackageManager).toString();
mLabelCache.put(b, labelB);
}
return sCollator.compare(labelA, labelB);
}
};
public void dumpState() {
Log.d(TAG, "mCallbacks=" + mCallbacks);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mAllAppsList.data);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mAllAppsList.added);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mAllAppsList.removed);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mAllAppsList.modified);
if (mLoaderTask != null) {
mLoaderTask.dumpState();
} else {
Log.d(TAG, "mLoaderTask=null");
}
}
}
|
diff --git a/src/com/wehuibao/json/Doc.java b/src/com/wehuibao/json/Doc.java
index 4f99170..fb6767b 100644
--- a/src/com/wehuibao/json/Doc.java
+++ b/src/com/wehuibao/json/Doc.java
@@ -1,25 +1,26 @@
package com.wehuibao.json;
import java.util.List;
import com.google.gson.annotations.SerializedName;
public class Doc {
public String abbrev_text;
public String abbrev;
public String absolute_url;
public int cnt_follower;
@SerializedName("id")
public String docId;
public String major_title;
public int seqid;
public Thumbnail thumb;
public String title;
public String url;
public int vote_count;
public List<User> sharers;
public String get_absolute_url() {
- return "http://wehuibao.com/api/doc" + this.docId;
+ //TODO: should use absolute_url, like http://wehuibao.com/docr/ISG71x
+ return "http://wehuibao.com/doc/" + this.docId;
}
}
| true | true | public String get_absolute_url() {
return "http://wehuibao.com/api/doc" + this.docId;
}
| public String get_absolute_url() {
//TODO: should use absolute_url, like http://wehuibao.com/docr/ISG71x
return "http://wehuibao.com/doc/" + this.docId;
}
|
diff --git a/examples/index/Program.java b/examples/index/Program.java
index c14e83a..a02b6b8 100644
--- a/examples/index/Program.java
+++ b/examples/index/Program.java
@@ -1,96 +1,95 @@
/*
* Copyright 2011 Splunk, 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.
*/
import com.splunk.EntityCollection;
import com.splunk.Service;
import com.splunk.Index;
import java.util.Properties;
public class Program extends com.splunk.sdk.Program {
private void listAllIndexes(Service service) {
EntityCollection<Index> indexes = service.getIndexes();
for (Index entity: indexes.values()) {
System.out.println(
entity.getTitle() +
" (" + entity.getContent().get("totalEventCount") + ")");
}
}
public static void main(String[] args) {
Program program = new Program();
try {
program.init(args).run();
}
catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
public void run() throws Exception {
- Service service = new Service(this.host, this.port, this.scheme,
- this.proxyhost, this.proxyport);
+ Service service = new Service(this.host, this.port, this.scheme);
service.login(this.username, this.password);
// This example takes optional arguments:
// [action index-name]
//
// without cli arguments, all indexes and their totalEventCount
// is displayed
if (this.args.length == 0) {
listAllIndexes(service);
return;
} else {
if (this.args.length != 2) {
System.out.println("You must provide action and index name");
}
}
String action = this.args[0];
String name = this.args[1];
EntityCollection indexes = service.getIndexes();
if (this.args[0].equals("clean")) {
if (!indexes.containsKey(name)) {
System.out.println("Index " + name + " does not exists");
return;
}
service.getIndexes().get(name).clean();
} else if (action.equals("create")) {
if (indexes.containsKey(name)) {
System.out.println("Index " + name + " already exists");
return;
}
service.getIndexes().create(name);
} else if (action.equals("disable")) {
if (!indexes.containsKey(name)) {
System.out.println("Index " + name + " does not exists");
return;
}
service.getIndexes().get(name).disable();
} else if (action.equals("enable")) {
if (!indexes.containsKey(name)) {
System.out.println("Index " + name + " does not exists");
return;
}
service.getIndexes().get(name).disable();
} else {
System.out.println("Unknown action: " + action);
}
}
}
| true | true | public void run() throws Exception {
Service service = new Service(this.host, this.port, this.scheme,
this.proxyhost, this.proxyport);
service.login(this.username, this.password);
// This example takes optional arguments:
// [action index-name]
//
// without cli arguments, all indexes and their totalEventCount
// is displayed
if (this.args.length == 0) {
listAllIndexes(service);
return;
} else {
if (this.args.length != 2) {
System.out.println("You must provide action and index name");
}
}
String action = this.args[0];
String name = this.args[1];
EntityCollection indexes = service.getIndexes();
if (this.args[0].equals("clean")) {
if (!indexes.containsKey(name)) {
System.out.println("Index " + name + " does not exists");
return;
}
service.getIndexes().get(name).clean();
} else if (action.equals("create")) {
if (indexes.containsKey(name)) {
System.out.println("Index " + name + " already exists");
return;
}
service.getIndexes().create(name);
} else if (action.equals("disable")) {
if (!indexes.containsKey(name)) {
System.out.println("Index " + name + " does not exists");
return;
}
service.getIndexes().get(name).disable();
} else if (action.equals("enable")) {
if (!indexes.containsKey(name)) {
System.out.println("Index " + name + " does not exists");
return;
}
service.getIndexes().get(name).disable();
} else {
System.out.println("Unknown action: " + action);
}
}
| public void run() throws Exception {
Service service = new Service(this.host, this.port, this.scheme);
service.login(this.username, this.password);
// This example takes optional arguments:
// [action index-name]
//
// without cli arguments, all indexes and their totalEventCount
// is displayed
if (this.args.length == 0) {
listAllIndexes(service);
return;
} else {
if (this.args.length != 2) {
System.out.println("You must provide action and index name");
}
}
String action = this.args[0];
String name = this.args[1];
EntityCollection indexes = service.getIndexes();
if (this.args[0].equals("clean")) {
if (!indexes.containsKey(name)) {
System.out.println("Index " + name + " does not exists");
return;
}
service.getIndexes().get(name).clean();
} else if (action.equals("create")) {
if (indexes.containsKey(name)) {
System.out.println("Index " + name + " already exists");
return;
}
service.getIndexes().create(name);
} else if (action.equals("disable")) {
if (!indexes.containsKey(name)) {
System.out.println("Index " + name + " does not exists");
return;
}
service.getIndexes().get(name).disable();
} else if (action.equals("enable")) {
if (!indexes.containsKey(name)) {
System.out.println("Index " + name + " does not exists");
return;
}
service.getIndexes().get(name).disable();
} else {
System.out.println("Unknown action: " + action);
}
}
|
diff --git a/app/controllers/Security.java b/app/controllers/Security.java
index 0a22d3a..6639f33 100644
--- a/app/controllers/Security.java
+++ b/app/controllers/Security.java
@@ -1,127 +1,126 @@
package controllers;
import models.Profile;
import models.User;
import play.Logger;
import play.Play;
import play.libs.WS;
import play.libs.WS.WSRequest;
import play.mvc.Router;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
/**
* Checks user login pass
*
* @author anthonjp
*
*/
public class Security extends controllers.Secure.Security {
static boolean authenticate(String username, String password) {
//return User.connect(username, password) != null;
// authenticate with rollcall
String rollcallUrl = Play.configuration.getProperty("sail.rollcall.url");
WSRequest req = WS.url(rollcallUrl+"/login.json");
req.setParameter("session[login]", username);
req.setParameter("session[password]", password);
WS.HttpResponse sessionRes = req.post();
JsonElement sessionJson = sessionRes.getJson();
if (sessionRes.getStatus() == 201) { // session created successfully
JsonObject session = sessionJson.getAsJsonObject().getAsJsonObject("session");
JsonObject account = session.getAsJsonObject("account");
String token = session.get("token").getAsString();
String encryptedPassword = account.get("encrypted_password").getAsString();
// now check if we already have this user in the local database
if (User.findUserByUsername(username) == null) { // user doesn't yet exist
new User(username, encryptedPassword).save();
Logger.info("User '"+username+"' created and authenticated.");
return true;
} else { // user exists
Logger.info("User '"+username+"' successfuly authenticated.");
return true;
}
} else { // some error during session creation
Logger.warn("Authentication for '"+username+"' failed because: "+sessionJson.toString());
flash.put("error", "Rollcall authentication failed: "+sessionJson.toString());
return false;
}
}
static void onAuthenticated() {
// String username = Security.connected();
// User user = User.findUserByUsername(username);
// Profile profile = Profile.findProfileByUser(user);
//
// if( profile == null ) {
// profile = new Profile(user, null, null).save();
// }
//
// //profile.isComplete = false;
//
// session.put("profile.id", profile.id);
//
// if( profile.isComplete ) {
// Application.index();
// } else {
// Profiles.form();
// }
String username = Security.connected();
User user = User.findUserByUsername(username);
Profile profile = Profile.findProfileByUser(user);
if( profile == null ) {
profile = new Profile(user, null, null).save();
}
- profile.isComplete = false;
session.put("profile.id", profile.id);
// figure out what kind of user this is based on data in Rollcall
String rollcallUrl = Play.configuration.getProperty("sail.rollcall.url");
WS.HttpResponse userRes = WS.url(rollcallUrl+"/users/"+username+".json").get();
String userKind;
if (userRes.getStatus() == 200) {
userKind = userRes.getJson().getAsJsonObject().getAsJsonObject("user").get("kind").getAsString();
if (userKind.equals("Instructor")) {
// redirect to the teacher dashboard
redirect(Router.reverse("TeacherDashboard.show").url);
} else if (userKind.equals("Student")) {
if( profile.isComplete == true ) {
Application.index();
} else {
Profiles.form();
}
} else if (userKind.equals("Admin")) {
if( profile.isComplete ) {
Application.index();
} else {
Profiles.form();
}
} else {
throw new RuntimeException("This kind of user cannot log in to this service: '"+userKind+"'");
}
} else if (userRes.getStatus() == 404) {
throw new RuntimeException("'"+username+"' is not a user (maybe a group account?)");
} else {
throw new RuntimeException("Couldn't retrieve User data for '"+username+"' from "+rollcallUrl+". Response status: "+userRes.getStatus());
}
}
}
| true | true | static void onAuthenticated() {
// String username = Security.connected();
// User user = User.findUserByUsername(username);
// Profile profile = Profile.findProfileByUser(user);
//
// if( profile == null ) {
// profile = new Profile(user, null, null).save();
// }
//
// //profile.isComplete = false;
//
// session.put("profile.id", profile.id);
//
// if( profile.isComplete ) {
// Application.index();
// } else {
// Profiles.form();
// }
String username = Security.connected();
User user = User.findUserByUsername(username);
Profile profile = Profile.findProfileByUser(user);
if( profile == null ) {
profile = new Profile(user, null, null).save();
}
profile.isComplete = false;
session.put("profile.id", profile.id);
// figure out what kind of user this is based on data in Rollcall
String rollcallUrl = Play.configuration.getProperty("sail.rollcall.url");
WS.HttpResponse userRes = WS.url(rollcallUrl+"/users/"+username+".json").get();
String userKind;
if (userRes.getStatus() == 200) {
userKind = userRes.getJson().getAsJsonObject().getAsJsonObject("user").get("kind").getAsString();
if (userKind.equals("Instructor")) {
// redirect to the teacher dashboard
redirect(Router.reverse("TeacherDashboard.show").url);
} else if (userKind.equals("Student")) {
if( profile.isComplete == true ) {
Application.index();
} else {
Profiles.form();
}
} else if (userKind.equals("Admin")) {
if( profile.isComplete ) {
Application.index();
} else {
Profiles.form();
}
} else {
throw new RuntimeException("This kind of user cannot log in to this service: '"+userKind+"'");
}
} else if (userRes.getStatus() == 404) {
throw new RuntimeException("'"+username+"' is not a user (maybe a group account?)");
} else {
throw new RuntimeException("Couldn't retrieve User data for '"+username+"' from "+rollcallUrl+". Response status: "+userRes.getStatus());
}
}
| static void onAuthenticated() {
// String username = Security.connected();
// User user = User.findUserByUsername(username);
// Profile profile = Profile.findProfileByUser(user);
//
// if( profile == null ) {
// profile = new Profile(user, null, null).save();
// }
//
// //profile.isComplete = false;
//
// session.put("profile.id", profile.id);
//
// if( profile.isComplete ) {
// Application.index();
// } else {
// Profiles.form();
// }
String username = Security.connected();
User user = User.findUserByUsername(username);
Profile profile = Profile.findProfileByUser(user);
if( profile == null ) {
profile = new Profile(user, null, null).save();
}
session.put("profile.id", profile.id);
// figure out what kind of user this is based on data in Rollcall
String rollcallUrl = Play.configuration.getProperty("sail.rollcall.url");
WS.HttpResponse userRes = WS.url(rollcallUrl+"/users/"+username+".json").get();
String userKind;
if (userRes.getStatus() == 200) {
userKind = userRes.getJson().getAsJsonObject().getAsJsonObject("user").get("kind").getAsString();
if (userKind.equals("Instructor")) {
// redirect to the teacher dashboard
redirect(Router.reverse("TeacherDashboard.show").url);
} else if (userKind.equals("Student")) {
if( profile.isComplete == true ) {
Application.index();
} else {
Profiles.form();
}
} else if (userKind.equals("Admin")) {
if( profile.isComplete ) {
Application.index();
} else {
Profiles.form();
}
} else {
throw new RuntimeException("This kind of user cannot log in to this service: '"+userKind+"'");
}
} else if (userRes.getStatus() == 404) {
throw new RuntimeException("'"+username+"' is not a user (maybe a group account?)");
} else {
throw new RuntimeException("Couldn't retrieve User data for '"+username+"' from "+rollcallUrl+". Response status: "+userRes.getStatus());
}
}
|
diff --git a/entitlement/src/main/java/com/ning/billing/entitlement/api/user/SubscriptionData.java b/entitlement/src/main/java/com/ning/billing/entitlement/api/user/SubscriptionData.java
index 71ac2f289..33991b076 100644
--- a/entitlement/src/main/java/com/ning/billing/entitlement/api/user/SubscriptionData.java
+++ b/entitlement/src/main/java/com/ning/billing/entitlement/api/user/SubscriptionData.java
@@ -1,421 +1,421 @@
/*
* Copyright 2010-2011 Ning, Inc.
*
* Ning 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.ning.billing.entitlement.api.user;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ning.billing.ErrorCode;
import com.ning.billing.catalog.api.ActionPolicy;
import com.ning.billing.catalog.api.BillingPeriod;
import com.ning.billing.catalog.api.CatalogApiException;
import com.ning.billing.catalog.api.ICatalog;
import com.ning.billing.catalog.api.IPlan;
import com.ning.billing.catalog.api.IPlanPhase;
import com.ning.billing.catalog.api.ProductCategory;
import com.ning.billing.entitlement.api.user.SubscriptionFactory.SubscriptionBuilder;
import com.ning.billing.entitlement.events.EntitlementEvent;
import com.ning.billing.entitlement.events.EntitlementEvent.EventType;
import com.ning.billing.entitlement.events.phase.PhaseEvent;
import com.ning.billing.entitlement.events.user.ApiEventType;
import com.ning.billing.entitlement.events.user.ApiEvent;
import com.ning.billing.entitlement.exceptions.EntitlementError;
import com.ning.billing.util.clock.Clock;
public class SubscriptionData implements Subscription {
private final static Logger log = LoggerFactory.getLogger(SubscriptionData.class);
private final Clock clock;
private final SubscriptionApiService apiService;
//
// Final subscription fields
//
private final UUID id;
private final UUID bundleId;
private final DateTime startDate;
private final DateTime bundleStartDate;
private final ProductCategory category;
//
// Those can be modified through non User APIs, and a new Subscription object would be created
//
private final long activeVersion;
private final DateTime chargedThroughDate;
private final DateTime paidThroughDate;
//
// User APIs (create, change, cancel,...) will recompute those each time,
// so the user holding that subscription object get the correct state when
// the call completes
//
private List<SubscriptionTransitionData> transitions;
// Transient object never returned at the API
public SubscriptionData(SubscriptionBuilder builder) {
this(builder, null, null);
}
public SubscriptionData(SubscriptionBuilder builder, SubscriptionApiService apiService, Clock clock) {
super();
this.apiService = apiService;
this.clock = clock;
this.id = builder.getId();
this.bundleId = builder.getBundleId();
this.startDate = builder.getStartDate();
this.bundleStartDate = builder.getBundleStartDate();
this.category = builder.getCategory();
this.activeVersion = builder.getActiveVersion();
this.chargedThroughDate = builder.getChargedThroughDate();
this.paidThroughDate = builder.getPaidThroughDate();
}
@Override
public UUID getId() {
return id;
}
@Override
public UUID getBundleId() {
return bundleId;
}
@Override
public DateTime getStartDate() {
return startDate;
}
@Override
public SubscriptionState getState() {
return (transitions == null) ? null : getLatestTranstion().getNextState();
}
@Override
public IPlanPhase getCurrentPhase() {
return (transitions == null) ? null : getLatestTranstion().getNextPhase();
}
@Override
public IPlan getCurrentPlan() {
return (transitions == null) ? null : getLatestTranstion().getNextPlan();
}
@Override
public String getCurrentPriceList() {
return (transitions == null) ? null : getLatestTranstion().getNextPriceList();
}
@Override
public DateTime getEndDate() {
SubscriptionTransition latestTransition = getLatestTranstion();
if (latestTransition.getNextState() == SubscriptionState.CANCELLED) {
return latestTransition.getEffectiveTransitionTime();
}
return null;
}
@Override
public void cancel(DateTime requestedDate, boolean eot) throws EntitlementUserApiException {
apiService.cancel(this, requestedDate, eot);
}
@Override
public void uncancel() throws EntitlementUserApiException {
apiService.uncancel(this);
}
@Override
public void changePlan(String productName, BillingPeriod term,
String priceList, DateTime requestedDate) throws EntitlementUserApiException {
apiService.changePlan(this, productName, term, priceList, requestedDate);
}
@Override
public void pause() throws EntitlementUserApiException {
throw new EntitlementUserApiException(ErrorCode.NOT_IMPLEMENTED);
}
@Override
public void resume() throws EntitlementUserApiException {
throw new EntitlementUserApiException(ErrorCode.NOT_IMPLEMENTED);
}
public SubscriptionTransition getLatestTranstion() {
if (transitions == null) {
return null;
}
SubscriptionTransition latestSubscription = null;
for (SubscriptionTransition cur : transitions) {
if (cur.getEffectiveTransitionTime().isAfter(clock.getUTCNow())) {
break;
}
latestSubscription = cur;
}
return latestSubscription;
}
public SubscriptionTransition getTransitionFromEvent(EntitlementEvent event) {
if (transitions == null || event == null) {
return null;
}
for (SubscriptionTransition cur : transitions) {
if (cur.getId().equals(event.getId())) {
return cur;
}
}
return null;
}
public long getActiveVersion() {
return activeVersion;
}
public ProductCategory getCategory() {
return category;
}
public DateTime getBundleStartDate() {
return bundleStartDate;
}
public DateTime getChargedThroughDate() {
return chargedThroughDate;
}
public DateTime getPaidThroughDate() {
return paidThroughDate;
}
public DateTime getCurrentPlanStart() {
if (transitions == null) {
throw new EntitlementError(String.format("No transitions for subscription %s", getId()));
}
Iterator<SubscriptionTransitionData> it = ((LinkedList<SubscriptionTransitionData>) transitions).descendingIterator();
while (it.hasNext()) {
SubscriptionTransitionData cur = it.next();
if (cur.getEffectiveTransitionTime().isAfter(clock.getUTCNow())) {
// Skip future events
continue;
}
if (cur.getEventType() == EventType.API_USER &&
cur.getApiEventType() == ApiEventType.CHANGE) {
return cur.getEffectiveTransitionTime();
}
}
// CREATE event
return transitions.get(0).getEffectiveTransitionTime();
}
public List<SubscriptionTransition> getActiveTransitions() {
if (transitions == null) {
return Collections.emptyList();
}
List<SubscriptionTransition> activeTransitions = new ArrayList<SubscriptionTransition>();
for (SubscriptionTransition cur : transitions) {
if (cur.getEffectiveTransitionTime().isAfter(clock.getUTCNow())) {
activeTransitions.add(cur);
}
}
return activeTransitions;
}
public boolean isSubscriptionFutureCancelled() {
if (transitions == null) {
return false;
}
for (SubscriptionTransitionData cur : transitions) {
if (cur.getEffectiveTransitionTime().isBefore(clock.getUTCNow()) ||
cur.getEventType() == EventType.PHASE ||
cur.getApiEventType() != ApiEventType.CANCEL) {
continue;
}
return true;
}
return false;
}
public DateTime getPlanChangeEffectiveDate(ActionPolicy policy, DateTime now) {
if (policy == ActionPolicy.IMMEDIATE) {
return now;
}
if (policy != ActionPolicy.END_OF_TERM) {
throw new EntitlementError(String.format("Unexpected policy type %s", policy.toString()));
}
//
// If CTD is null or CTD in the past, we default to the start date of the current phase
//
DateTime effectiveDate = chargedThroughDate;
if (chargedThroughDate == null || chargedThroughDate.isBefore(clock.getUTCNow())) {
effectiveDate = getCurrentPhaseStart();
}
return effectiveDate;
}
public DateTime getCurrentPhaseStart() {
if (transitions == null) {
throw new EntitlementError(String.format("No transitions for subscription %s", getId()));
}
Iterator<SubscriptionTransitionData> it = ((LinkedList<SubscriptionTransitionData>) transitions).descendingIterator();
while (it.hasNext()) {
SubscriptionTransitionData cur = it.next();
if (cur.getEffectiveTransitionTime().isAfter(clock.getUTCNow())) {
// Skip future events
continue;
}
if (cur.getEventType() == EventType.PHASE) {
return cur.getEffectiveTransitionTime();
}
}
// CREATE event
return transitions.get(0).getEffectiveTransitionTime();
}
public void rebuildTransitions(final List<EntitlementEvent> events, final ICatalog catalog) {
if (events == null) {
return;
}
SubscriptionState nextState = null;
String nextPlanName = null;
String nextPhaseName = null;
String nextPriceList = null;
SubscriptionState previousState = null;
String previousPlanName = null;
String previousPhaseName = null;
String previousPriceList = null;
transitions = new LinkedList<SubscriptionTransitionData>();
for (final EntitlementEvent cur : events) {
if (!cur.isActive() || cur.getActiveVersion() < activeVersion) {
continue;
}
ApiEventType apiEventType = null;
switch (cur.getType()) {
case PHASE:
PhaseEvent phaseEV = (PhaseEvent) cur;
nextPhaseName = phaseEV.getPhase();
break;
case API_USER:
ApiEvent userEV = (ApiEvent) cur;
apiEventType = userEV.getEventType();
switch(apiEventType) {
case CREATE:
nextState = SubscriptionState.ACTIVE;
nextPlanName = userEV.getEventPlan();
nextPhaseName = userEV.getEventPlanPhase();
nextPriceList = userEV.getPriceList();
break;
case CHANGE:
nextPlanName = userEV.getEventPlan();
nextPhaseName = userEV.getEventPlanPhase();
nextPriceList = userEV.getPriceList();
break;
case PAUSE:
nextState = SubscriptionState.PAUSED;
break;
case RESUME:
nextState = SubscriptionState.ACTIVE;
break;
case CANCEL:
nextState = SubscriptionState.CANCELLED;
nextPlanName = null;
nextPhaseName = null;
break;
case UNCANCEL:
break;
default:
throw new EntitlementError(String.format("Unexpected UserEvent type = %s",
userEV.getEventType().toString()));
}
break;
default:
throw new EntitlementError(String.format("Unexpected Event type = %s",
cur.getType()));
}
IPlan previousPlan = null;
IPlanPhase previousPhase = null;
IPlan nextPlan = null;
IPlanPhase nextPhase = null;
try {
previousPlan = (previousPlanName != null) ? catalog.findPlan(previousPlanName) : null;
- previousPhase = (previousPhase != null) ? catalog.findPhase(previousPhaseName) : null;
+ previousPhase = (previousPhaseName != null) ? catalog.findPhase(previousPhaseName) : null;
nextPlan = (nextPlanName != null) ? catalog.findPlan(nextPlanName) : null;
nextPhase = (nextPhaseName != null) ? catalog.findPhase(nextPhaseName) : null;
} catch (CatalogApiException e) {
log.error(String.format("Failed to build transition for subscription %s", id), e);
}
SubscriptionTransitionData transition =
new SubscriptionTransitionData(cur.getId(),
id,
bundleId,
cur.getType(),
apiEventType,
cur.getRequestedDate(),
cur.getEffectiveDate(),
previousState,
previousPlan,
previousPhase,
previousPriceList,
nextState,
nextPlan,
nextPhase,
nextPriceList);
transitions.add(transition);
previousState = nextState;
previousPlanName = nextPlanName;
previousPhaseName = nextPhaseName;
previousPriceList = nextPriceList;
}
}
}
| true | true | public void rebuildTransitions(final List<EntitlementEvent> events, final ICatalog catalog) {
if (events == null) {
return;
}
SubscriptionState nextState = null;
String nextPlanName = null;
String nextPhaseName = null;
String nextPriceList = null;
SubscriptionState previousState = null;
String previousPlanName = null;
String previousPhaseName = null;
String previousPriceList = null;
transitions = new LinkedList<SubscriptionTransitionData>();
for (final EntitlementEvent cur : events) {
if (!cur.isActive() || cur.getActiveVersion() < activeVersion) {
continue;
}
ApiEventType apiEventType = null;
switch (cur.getType()) {
case PHASE:
PhaseEvent phaseEV = (PhaseEvent) cur;
nextPhaseName = phaseEV.getPhase();
break;
case API_USER:
ApiEvent userEV = (ApiEvent) cur;
apiEventType = userEV.getEventType();
switch(apiEventType) {
case CREATE:
nextState = SubscriptionState.ACTIVE;
nextPlanName = userEV.getEventPlan();
nextPhaseName = userEV.getEventPlanPhase();
nextPriceList = userEV.getPriceList();
break;
case CHANGE:
nextPlanName = userEV.getEventPlan();
nextPhaseName = userEV.getEventPlanPhase();
nextPriceList = userEV.getPriceList();
break;
case PAUSE:
nextState = SubscriptionState.PAUSED;
break;
case RESUME:
nextState = SubscriptionState.ACTIVE;
break;
case CANCEL:
nextState = SubscriptionState.CANCELLED;
nextPlanName = null;
nextPhaseName = null;
break;
case UNCANCEL:
break;
default:
throw new EntitlementError(String.format("Unexpected UserEvent type = %s",
userEV.getEventType().toString()));
}
break;
default:
throw new EntitlementError(String.format("Unexpected Event type = %s",
cur.getType()));
}
IPlan previousPlan = null;
IPlanPhase previousPhase = null;
IPlan nextPlan = null;
IPlanPhase nextPhase = null;
try {
previousPlan = (previousPlanName != null) ? catalog.findPlan(previousPlanName) : null;
previousPhase = (previousPhase != null) ? catalog.findPhase(previousPhaseName) : null;
nextPlan = (nextPlanName != null) ? catalog.findPlan(nextPlanName) : null;
nextPhase = (nextPhaseName != null) ? catalog.findPhase(nextPhaseName) : null;
} catch (CatalogApiException e) {
log.error(String.format("Failed to build transition for subscription %s", id), e);
}
SubscriptionTransitionData transition =
new SubscriptionTransitionData(cur.getId(),
id,
bundleId,
cur.getType(),
apiEventType,
cur.getRequestedDate(),
cur.getEffectiveDate(),
previousState,
previousPlan,
previousPhase,
previousPriceList,
nextState,
nextPlan,
nextPhase,
nextPriceList);
transitions.add(transition);
previousState = nextState;
previousPlanName = nextPlanName;
previousPhaseName = nextPhaseName;
previousPriceList = nextPriceList;
}
}
| public void rebuildTransitions(final List<EntitlementEvent> events, final ICatalog catalog) {
if (events == null) {
return;
}
SubscriptionState nextState = null;
String nextPlanName = null;
String nextPhaseName = null;
String nextPriceList = null;
SubscriptionState previousState = null;
String previousPlanName = null;
String previousPhaseName = null;
String previousPriceList = null;
transitions = new LinkedList<SubscriptionTransitionData>();
for (final EntitlementEvent cur : events) {
if (!cur.isActive() || cur.getActiveVersion() < activeVersion) {
continue;
}
ApiEventType apiEventType = null;
switch (cur.getType()) {
case PHASE:
PhaseEvent phaseEV = (PhaseEvent) cur;
nextPhaseName = phaseEV.getPhase();
break;
case API_USER:
ApiEvent userEV = (ApiEvent) cur;
apiEventType = userEV.getEventType();
switch(apiEventType) {
case CREATE:
nextState = SubscriptionState.ACTIVE;
nextPlanName = userEV.getEventPlan();
nextPhaseName = userEV.getEventPlanPhase();
nextPriceList = userEV.getPriceList();
break;
case CHANGE:
nextPlanName = userEV.getEventPlan();
nextPhaseName = userEV.getEventPlanPhase();
nextPriceList = userEV.getPriceList();
break;
case PAUSE:
nextState = SubscriptionState.PAUSED;
break;
case RESUME:
nextState = SubscriptionState.ACTIVE;
break;
case CANCEL:
nextState = SubscriptionState.CANCELLED;
nextPlanName = null;
nextPhaseName = null;
break;
case UNCANCEL:
break;
default:
throw new EntitlementError(String.format("Unexpected UserEvent type = %s",
userEV.getEventType().toString()));
}
break;
default:
throw new EntitlementError(String.format("Unexpected Event type = %s",
cur.getType()));
}
IPlan previousPlan = null;
IPlanPhase previousPhase = null;
IPlan nextPlan = null;
IPlanPhase nextPhase = null;
try {
previousPlan = (previousPlanName != null) ? catalog.findPlan(previousPlanName) : null;
previousPhase = (previousPhaseName != null) ? catalog.findPhase(previousPhaseName) : null;
nextPlan = (nextPlanName != null) ? catalog.findPlan(nextPlanName) : null;
nextPhase = (nextPhaseName != null) ? catalog.findPhase(nextPhaseName) : null;
} catch (CatalogApiException e) {
log.error(String.format("Failed to build transition for subscription %s", id), e);
}
SubscriptionTransitionData transition =
new SubscriptionTransitionData(cur.getId(),
id,
bundleId,
cur.getType(),
apiEventType,
cur.getRequestedDate(),
cur.getEffectiveDate(),
previousState,
previousPlan,
previousPhase,
previousPriceList,
nextState,
nextPlan,
nextPhase,
nextPriceList);
transitions.add(transition);
previousState = nextState;
previousPlanName = nextPlanName;
previousPhaseName = nextPhaseName;
previousPriceList = nextPriceList;
}
}
|
diff --git a/twitter-web/src/main/java/com/nelsonjrodrigues/twitter/web/rest/exceptionhandler/RestApiExceptionHandler.java b/twitter-web/src/main/java/com/nelsonjrodrigues/twitter/web/rest/exceptionhandler/RestApiExceptionHandler.java
index dbb0ed1..186a71a 100644
--- a/twitter-web/src/main/java/com/nelsonjrodrigues/twitter/web/rest/exceptionhandler/RestApiExceptionHandler.java
+++ b/twitter-web/src/main/java/com/nelsonjrodrigues/twitter/web/rest/exceptionhandler/RestApiExceptionHandler.java
@@ -1,26 +1,27 @@
package com.nelsonjrodrigues.twitter.web.rest.exceptionhandler;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver;
public class RestApiExceptionHandler extends AbstractHandlerExceptionResolver {
@Override
protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
if (ex instanceof EmptyResultDataAccessException) {
try {
response.sendError(HttpStatus.NOT_FOUND.value());
} catch (Exception e) {
logger.warn("Handling of exception threw exception", e);
}
}
- return null;
+ // return empty model and view to signal handled exception
+ return new ModelAndView();
}
}
| true | true | protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
if (ex instanceof EmptyResultDataAccessException) {
try {
response.sendError(HttpStatus.NOT_FOUND.value());
} catch (Exception e) {
logger.warn("Handling of exception threw exception", e);
}
}
return null;
}
| protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
if (ex instanceof EmptyResultDataAccessException) {
try {
response.sendError(HttpStatus.NOT_FOUND.value());
} catch (Exception e) {
logger.warn("Handling of exception threw exception", e);
}
}
// return empty model and view to signal handled exception
return new ModelAndView();
}
|
diff --git a/src/com/gitblit/wicket/pages/ChangePasswordPage.java b/src/com/gitblit/wicket/pages/ChangePasswordPage.java
index 2738a5f..d7c774d 100644
--- a/src/com/gitblit/wicket/pages/ChangePasswordPage.java
+++ b/src/com/gitblit/wicket/pages/ChangePasswordPage.java
@@ -1,131 +1,133 @@
/*
* Copyright 2011 gitblit.com.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gitblit.wicket.pages;
import java.text.MessageFormat;
import org.apache.wicket.RestartResponseException;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.StatelessForm;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.protocol.http.WebResponse;
import com.gitblit.GitBlit;
import com.gitblit.GitBlitException;
import com.gitblit.Keys;
import com.gitblit.models.UserModel;
import com.gitblit.utils.StringUtils;
import com.gitblit.wicket.GitBlitWebSession;
public class ChangePasswordPage extends RootSubPage {
IModel<String> password = new Model<String>("");
IModel<String> confirmPassword = new Model<String>("");
public ChangePasswordPage() {
super();
if (!GitBlitWebSession.get().isLoggedIn()) {
// Change password requires a login
throw new RestartResponseException(getApplication().getHomePage());
}
if (!GitBlit.getBoolean(Keys.web.authenticateAdminPages, true)
&& !GitBlit.getBoolean(Keys.web.authenticateViewPages, false)) {
// no authentication enabled
throw new RestartResponseException(getApplication().getHomePage());
}
setupPage(getString("gb.changePassword"), GitBlitWebSession.get().getUser().username);
StatelessForm<Void> form = new StatelessForm<Void>("passwordForm") {
private static final long serialVersionUID = 1L;
@Override
public void onSubmit() {
String password = ChangePasswordPage.this.password.getObject();
String confirmPassword = ChangePasswordPage.this.confirmPassword.getObject();
// ensure passwords match
if (!password.equals(confirmPassword)) {
error("Passwords do not match!");
return;
}
// ensure password satisfies minimum length requirement
int minLength = GitBlit.getInteger(Keys.realm.minPasswordLength, 5);
if (minLength < 4) {
minLength = 4;
}
if (password.length() < minLength) {
error(MessageFormat.format(
"Password is too short. Minimum length is {0} characters.", minLength));
return;
}
UserModel user = GitBlitWebSession.get().getUser();
// convert to MD5 digest, if appropriate
String type = GitBlit.getString(Keys.realm.passwordStorage, "md5");
if (type.equalsIgnoreCase("md5")) {
// store MD5 digest of password
password = StringUtils.MD5_TYPE + StringUtils.getMD5(password);
} else if (type.equalsIgnoreCase("combined-md5")) {
// store MD5 digest of username+password
password = StringUtils.COMBINED_MD5_TYPE
+ StringUtils.getMD5(user.username.toLowerCase() + password);
}
user.password = password;
try {
GitBlit.self().updateUserModel(user.username, user, false);
if (GitBlit.getBoolean(Keys.web.allowCookieAuthentication, false)) {
WebResponse response = (WebResponse) getRequestCycle().getResponse();
GitBlit.self().setCookie(response, user);
}
} catch (GitBlitException e) {
error(e.getMessage());
return;
}
setRedirect(false);
info("Password successfully changed.");
setResponsePage(RepositoriesPage.class);
}
};
PasswordTextField passwordField = new PasswordTextField("password", password);
passwordField.setResetPassword(false);
form.add(passwordField);
PasswordTextField confirmPasswordField = new PasswordTextField("confirmPassword",
confirmPassword);
confirmPasswordField.setResetPassword(false);
form.add(confirmPasswordField);
form.add(new Button("save"));
Button cancel = new Button("cancel") {
private static final long serialVersionUID = 1L;
@Override
public void onSubmit() {
+ setRedirect(false);
+ error("Password change aborted.");
setResponsePage(RepositoriesPage.class);
}
};
cancel.setDefaultFormProcessing(false);
form.add(cancel);
add(form);
}
}
| true | true | public ChangePasswordPage() {
super();
if (!GitBlitWebSession.get().isLoggedIn()) {
// Change password requires a login
throw new RestartResponseException(getApplication().getHomePage());
}
if (!GitBlit.getBoolean(Keys.web.authenticateAdminPages, true)
&& !GitBlit.getBoolean(Keys.web.authenticateViewPages, false)) {
// no authentication enabled
throw new RestartResponseException(getApplication().getHomePage());
}
setupPage(getString("gb.changePassword"), GitBlitWebSession.get().getUser().username);
StatelessForm<Void> form = new StatelessForm<Void>("passwordForm") {
private static final long serialVersionUID = 1L;
@Override
public void onSubmit() {
String password = ChangePasswordPage.this.password.getObject();
String confirmPassword = ChangePasswordPage.this.confirmPassword.getObject();
// ensure passwords match
if (!password.equals(confirmPassword)) {
error("Passwords do not match!");
return;
}
// ensure password satisfies minimum length requirement
int minLength = GitBlit.getInteger(Keys.realm.minPasswordLength, 5);
if (minLength < 4) {
minLength = 4;
}
if (password.length() < minLength) {
error(MessageFormat.format(
"Password is too short. Minimum length is {0} characters.", minLength));
return;
}
UserModel user = GitBlitWebSession.get().getUser();
// convert to MD5 digest, if appropriate
String type = GitBlit.getString(Keys.realm.passwordStorage, "md5");
if (type.equalsIgnoreCase("md5")) {
// store MD5 digest of password
password = StringUtils.MD5_TYPE + StringUtils.getMD5(password);
} else if (type.equalsIgnoreCase("combined-md5")) {
// store MD5 digest of username+password
password = StringUtils.COMBINED_MD5_TYPE
+ StringUtils.getMD5(user.username.toLowerCase() + password);
}
user.password = password;
try {
GitBlit.self().updateUserModel(user.username, user, false);
if (GitBlit.getBoolean(Keys.web.allowCookieAuthentication, false)) {
WebResponse response = (WebResponse) getRequestCycle().getResponse();
GitBlit.self().setCookie(response, user);
}
} catch (GitBlitException e) {
error(e.getMessage());
return;
}
setRedirect(false);
info("Password successfully changed.");
setResponsePage(RepositoriesPage.class);
}
};
PasswordTextField passwordField = new PasswordTextField("password", password);
passwordField.setResetPassword(false);
form.add(passwordField);
PasswordTextField confirmPasswordField = new PasswordTextField("confirmPassword",
confirmPassword);
confirmPasswordField.setResetPassword(false);
form.add(confirmPasswordField);
form.add(new Button("save"));
Button cancel = new Button("cancel") {
private static final long serialVersionUID = 1L;
@Override
public void onSubmit() {
setResponsePage(RepositoriesPage.class);
}
};
cancel.setDefaultFormProcessing(false);
form.add(cancel);
add(form);
}
| public ChangePasswordPage() {
super();
if (!GitBlitWebSession.get().isLoggedIn()) {
// Change password requires a login
throw new RestartResponseException(getApplication().getHomePage());
}
if (!GitBlit.getBoolean(Keys.web.authenticateAdminPages, true)
&& !GitBlit.getBoolean(Keys.web.authenticateViewPages, false)) {
// no authentication enabled
throw new RestartResponseException(getApplication().getHomePage());
}
setupPage(getString("gb.changePassword"), GitBlitWebSession.get().getUser().username);
StatelessForm<Void> form = new StatelessForm<Void>("passwordForm") {
private static final long serialVersionUID = 1L;
@Override
public void onSubmit() {
String password = ChangePasswordPage.this.password.getObject();
String confirmPassword = ChangePasswordPage.this.confirmPassword.getObject();
// ensure passwords match
if (!password.equals(confirmPassword)) {
error("Passwords do not match!");
return;
}
// ensure password satisfies minimum length requirement
int minLength = GitBlit.getInteger(Keys.realm.minPasswordLength, 5);
if (minLength < 4) {
minLength = 4;
}
if (password.length() < minLength) {
error(MessageFormat.format(
"Password is too short. Minimum length is {0} characters.", minLength));
return;
}
UserModel user = GitBlitWebSession.get().getUser();
// convert to MD5 digest, if appropriate
String type = GitBlit.getString(Keys.realm.passwordStorage, "md5");
if (type.equalsIgnoreCase("md5")) {
// store MD5 digest of password
password = StringUtils.MD5_TYPE + StringUtils.getMD5(password);
} else if (type.equalsIgnoreCase("combined-md5")) {
// store MD5 digest of username+password
password = StringUtils.COMBINED_MD5_TYPE
+ StringUtils.getMD5(user.username.toLowerCase() + password);
}
user.password = password;
try {
GitBlit.self().updateUserModel(user.username, user, false);
if (GitBlit.getBoolean(Keys.web.allowCookieAuthentication, false)) {
WebResponse response = (WebResponse) getRequestCycle().getResponse();
GitBlit.self().setCookie(response, user);
}
} catch (GitBlitException e) {
error(e.getMessage());
return;
}
setRedirect(false);
info("Password successfully changed.");
setResponsePage(RepositoriesPage.class);
}
};
PasswordTextField passwordField = new PasswordTextField("password", password);
passwordField.setResetPassword(false);
form.add(passwordField);
PasswordTextField confirmPasswordField = new PasswordTextField("confirmPassword",
confirmPassword);
confirmPasswordField.setResetPassword(false);
form.add(confirmPasswordField);
form.add(new Button("save"));
Button cancel = new Button("cancel") {
private static final long serialVersionUID = 1L;
@Override
public void onSubmit() {
setRedirect(false);
error("Password change aborted.");
setResponsePage(RepositoriesPage.class);
}
};
cancel.setDefaultFormProcessing(false);
form.add(cancel);
add(form);
}
|
diff --git a/support/org/intellij/jflex/editor/JFlexAnnotator.java b/support/org/intellij/jflex/editor/JFlexAnnotator.java
index 459e6c3..3e38301 100644
--- a/support/org/intellij/jflex/editor/JFlexAnnotator.java
+++ b/support/org/intellij/jflex/editor/JFlexAnnotator.java
@@ -1,61 +1,61 @@
/*
* Copyright 2011-2013 Gregory Shrago
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.intellij.jflex.editor;
import com.intellij.lang.annotation.AnnotationHolder;
import com.intellij.lang.annotation.Annotator;
import com.intellij.openapi.project.DumbAware;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiReference;
import org.intellij.jflex.psi.*;
import org.intellij.jflex.psi.impl.JFlexPsiImplUtil;
import org.jetbrains.annotations.NotNull;
/**
* @author gregsh
*/
public class JFlexAnnotator implements Annotator, DumbAware {
@Override
public void annotate(@NotNull PsiElement element, @NotNull AnnotationHolder holder) {
if (element instanceof JFlexMacroDefinition) {
holder.createInfoAnnotation(((JFlexMacroDefinition)element).getNameIdentifier(), null).setTextAttributes(JFlexSyntaxHighlighterFactory.MACRO);
}
else if (element instanceof JFlexMacroReference) {
PsiReference reference = element.getReference();
PsiElement resolve = reference == null ? null : reference.resolve();
holder.createInfoAnnotation(element.getParent(), null).setTextAttributes(JFlexSyntaxHighlighterFactory.MACRO);
if (resolve == null) {
holder.createWarningAnnotation(element, "Unresolved macro reference");
}
}
else if (element instanceof JFlexStateDefinition) {
holder.createInfoAnnotation(((JFlexStateDefinition)element).getNameIdentifier(), null).setTextAttributes(JFlexSyntaxHighlighterFactory.STATE);
}
else if (element instanceof JFlexStateReference) {
boolean isYYINITIAL = JFlexPsiImplUtil.isYYINITIAL((JFlexStateReference)element);
PsiReference reference = isYYINITIAL ? null : element.getReference();
PsiElement resolve = reference == null ? null : reference.resolve();
- holder.createInfoAnnotation(element.getParent(), null).setTextAttributes(JFlexSyntaxHighlighterFactory.MACRO);
+ holder.createInfoAnnotation(element, null).setTextAttributes(JFlexSyntaxHighlighterFactory.STATE);
if (!isYYINITIAL && resolve == null) {
holder.createWarningAnnotation(element, "Unresolved state reference");
}
}
else if (element instanceof JFlexClassExpression) {
holder.createInfoAnnotation(element, null).setTextAttributes(JFlexSyntaxHighlighterFactory.CLASS);
}
}
}
| true | true | public void annotate(@NotNull PsiElement element, @NotNull AnnotationHolder holder) {
if (element instanceof JFlexMacroDefinition) {
holder.createInfoAnnotation(((JFlexMacroDefinition)element).getNameIdentifier(), null).setTextAttributes(JFlexSyntaxHighlighterFactory.MACRO);
}
else if (element instanceof JFlexMacroReference) {
PsiReference reference = element.getReference();
PsiElement resolve = reference == null ? null : reference.resolve();
holder.createInfoAnnotation(element.getParent(), null).setTextAttributes(JFlexSyntaxHighlighterFactory.MACRO);
if (resolve == null) {
holder.createWarningAnnotation(element, "Unresolved macro reference");
}
}
else if (element instanceof JFlexStateDefinition) {
holder.createInfoAnnotation(((JFlexStateDefinition)element).getNameIdentifier(), null).setTextAttributes(JFlexSyntaxHighlighterFactory.STATE);
}
else if (element instanceof JFlexStateReference) {
boolean isYYINITIAL = JFlexPsiImplUtil.isYYINITIAL((JFlexStateReference)element);
PsiReference reference = isYYINITIAL ? null : element.getReference();
PsiElement resolve = reference == null ? null : reference.resolve();
holder.createInfoAnnotation(element.getParent(), null).setTextAttributes(JFlexSyntaxHighlighterFactory.MACRO);
if (!isYYINITIAL && resolve == null) {
holder.createWarningAnnotation(element, "Unresolved state reference");
}
}
else if (element instanceof JFlexClassExpression) {
holder.createInfoAnnotation(element, null).setTextAttributes(JFlexSyntaxHighlighterFactory.CLASS);
}
}
| public void annotate(@NotNull PsiElement element, @NotNull AnnotationHolder holder) {
if (element instanceof JFlexMacroDefinition) {
holder.createInfoAnnotation(((JFlexMacroDefinition)element).getNameIdentifier(), null).setTextAttributes(JFlexSyntaxHighlighterFactory.MACRO);
}
else if (element instanceof JFlexMacroReference) {
PsiReference reference = element.getReference();
PsiElement resolve = reference == null ? null : reference.resolve();
holder.createInfoAnnotation(element.getParent(), null).setTextAttributes(JFlexSyntaxHighlighterFactory.MACRO);
if (resolve == null) {
holder.createWarningAnnotation(element, "Unresolved macro reference");
}
}
else if (element instanceof JFlexStateDefinition) {
holder.createInfoAnnotation(((JFlexStateDefinition)element).getNameIdentifier(), null).setTextAttributes(JFlexSyntaxHighlighterFactory.STATE);
}
else if (element instanceof JFlexStateReference) {
boolean isYYINITIAL = JFlexPsiImplUtil.isYYINITIAL((JFlexStateReference)element);
PsiReference reference = isYYINITIAL ? null : element.getReference();
PsiElement resolve = reference == null ? null : reference.resolve();
holder.createInfoAnnotation(element, null).setTextAttributes(JFlexSyntaxHighlighterFactory.STATE);
if (!isYYINITIAL && resolve == null) {
holder.createWarningAnnotation(element, "Unresolved state reference");
}
}
else if (element instanceof JFlexClassExpression) {
holder.createInfoAnnotation(element, null).setTextAttributes(JFlexSyntaxHighlighterFactory.CLASS);
}
}
|
diff --git a/everest-core/src/main/java/org/apache/felix/ipojo/everest/impl/DefaultResource.java b/everest-core/src/main/java/org/apache/felix/ipojo/everest/impl/DefaultResource.java
index 0a7a16a..eebbb98 100644
--- a/everest-core/src/main/java/org/apache/felix/ipojo/everest/impl/DefaultResource.java
+++ b/everest-core/src/main/java/org/apache/felix/ipojo/everest/impl/DefaultResource.java
@@ -1,297 +1,291 @@
package org.apache.felix.ipojo.everest.impl;
import org.apache.felix.ipojo.everest.filters.Filters;
import org.apache.felix.ipojo.everest.services.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* Default resource implementation
*/
public class DefaultResource implements Resource {
private final Path path;
private final Resource[] resources;
private final ResourceMetadata metadata;
private Relation[] relations;
public DefaultResource(Path path) {
this(path, null);
}
public DefaultResource(String path) {
this(Path.from(path), null);
}
public DefaultResource(Resource parent, String name) {
this(parent.getPath() + Paths.PATH_SEPARATOR + name);
}
public DefaultResource(Path path, ResourceMetadata metadata, Resource... resources) {
this.path = path;
this.resources = resources;
this.metadata = metadata;
}
public DefaultResource setRelations(Relation... relations) {
this.relations = relations;
return this;
}
public Path getPath() {
return path;
}
public Path getCanonicalPath() {
return path;
}
public List<Resource> getResources() {
if (resources == null) {
return Collections.emptyList();
}
return new ArrayList<Resource>(Arrays.asList(resources));
}
public ResourceMetadata getMetadata() {
if (metadata != null) {
return ImmutableResourceMetadata.of(metadata);
} else {
return ImmutableResourceMetadata.of(Collections.<String, Object>emptyMap());
}
}
public List<Relation> getRelations() {
if (relations == null) {
return Collections.emptyList();
}
return new ArrayList<Relation>(Arrays.asList(relations));
}
public DefaultResource setRelations(List<Relation> relations) {
this.relations = relations.toArray(new Relation[relations.size()]);
return this;
}
public List<Resource> getResources(ResourceFilter filter) {
List<Resource> resources = new ArrayList<Resource>();
for (Resource res : all()) {
if (filter.accept(res)) {
resources.add(res);
}
}
return resources;
}
public Resource getResource(String path) {
List<Resource> list = getResources(Filters.hasPath(path));
if (! list.isEmpty()) {
return list.get(0);
} else {
return null;
}
}
public void traverse(Resource resource, List<Resource> list) {
list.add(resource);
for (Resource res : resource.getResources()) {
traverse(res, list);
}
}
public List<Resource> all() {
List<Resource> all = new ArrayList<Resource>();
traverse(this, all);
return all;
}
/**
* A request was emitted on the current request.
* This method handles the request.
*
* @param request the request.
* @return the updated resource
* @throws IllegalActionOnResourceException
*
* @throws ResourceNotFoundException
*/
public Resource process(Request request) throws IllegalActionOnResourceException, ResourceNotFoundException {
//Trace
System.out.println("Processing request " + request.action() + " " + request.path() + " by " +
getCanonicalPath());
//End Trace
// 1) Substract our path from the request path.
Path rel = request.path().subtract(this.getPath());
// 2) The request is targeting us...
if (request.path().equals(getPath())) {
switch (request.action()) {
case GET:
return get(request);
case DELETE:
return delete(request);
case PUT:
return put(request);
case POST:
return post(request);
}
return null;
}
// 3) The request is targeting one of our child.
- Path path;
- if (getPath().toString().equals("/")) {
- path = Path.from(Path.SEPARATOR + rel.getFirst());
- } else {
- path = getPath().add(Path.from(Path.SEPARATOR + rel.getFirst()));
- }
+ Path path = getPath().add(Path.fromElements(rel.getFirst()));
for (Resource resource : getResources()) {
- System.out.println("Lookup to handle " + path + " by resource " + resource.getPath());
if (resource.getPath().equals(path)) {
return resource.process(request);
}
}
throw new ResourceNotFoundException(request);
}
/**
* Default get action : return the current resource.
*
* @param request the request
* @return the current resource
*/
public Resource get(Request request) {
return this;
}
/**
* Method to override to support resource deletion. By default it returns the current resource, unchanged.
*
* @param request the request
* @return the current resource (unchanged by default).
*/
public Resource delete(Request request) throws IllegalActionOnResourceException {
return this;
}
/**
* Method to override to support explicit resource creation. By default it returns {@literal null}.
*
* @param request the request
* @return {@literal null}
*/
public Resource put(Request request) throws IllegalActionOnResourceException {
return null;
}
/**
* Method to override to support resource update. By default it returns the current resource, unchanged.
*
* @param request the request
* @return the current resource (unchanged)
*/
public Resource post(Request request) throws IllegalActionOnResourceException {
return this;
}
public static interface ResourceFactory<T extends DefaultResource> {
T create(Path path, ResourceMetadata metadata, List<Resource> resources) throws IllegalResourceException;
}
public static class DefaultResourceFactory implements ResourceFactory<DefaultResource> {
public DefaultResource create(Path path, ResourceMetadata metadata, List<Resource> resources) {
if (resources != null) {
return new DefaultResource(path, metadata, resources.toArray(new Resource[resources.size()]));
} else {
return new DefaultResource(path, metadata);
}
}
}
public static class Builder {
private final ResourceFactory<? extends Resource> factory;
private Path path;
private ResourceMetadata metadata;
private List<Relation> relations;
private List<Resource> resources;
public Builder() {
factory = new DefaultResourceFactory();
}
public Builder(ResourceFactory<? extends Resource> factory) {
this.factory = factory;
}
public Builder(String path) {
this();
fromPath(path);
}
public Builder(Resource resource) {
this();
this.path = resource.getPath();
this.metadata = resource.getMetadata();
this.relations = resource.getRelations();
this.resources = resource.getResources();
}
public Builder(Resource resource, ResourceFactory factory) {
this(factory);
this.path = resource.getPath();
this.metadata = resource.getMetadata();
this.relations = resource.getRelations();
this.resources = resource.getResources();
}
public Builder fromPath(String path) {
this.path = Path.from(path);
return this;
}
public Builder fromPath(Path path) {
this.path = path;
return this;
}
public Builder with(ResourceMetadata resourceMetadata) {
this.metadata = resourceMetadata;
return this;
}
public Builder with(Resource resource) {
if (this.resources == null) {
this.resources = new ArrayList<Resource>();
}
resources.add(resource);
return this;
}
public Builder with(Relation relation) {
if (this.relations == null) {
this.relations = new ArrayList<Relation>();
}
relations.add(relation);
return this;
}
public DefaultResource build() throws IllegalResourceException {
DefaultResource res = factory.create(path, metadata, resources);
res.setRelations(relations);
return res;
}
}
}
| false | true | public Resource process(Request request) throws IllegalActionOnResourceException, ResourceNotFoundException {
//Trace
System.out.println("Processing request " + request.action() + " " + request.path() + " by " +
getCanonicalPath());
//End Trace
// 1) Substract our path from the request path.
Path rel = request.path().subtract(this.getPath());
// 2) The request is targeting us...
if (request.path().equals(getPath())) {
switch (request.action()) {
case GET:
return get(request);
case DELETE:
return delete(request);
case PUT:
return put(request);
case POST:
return post(request);
}
return null;
}
// 3) The request is targeting one of our child.
Path path;
if (getPath().toString().equals("/")) {
path = Path.from(Path.SEPARATOR + rel.getFirst());
} else {
path = getPath().add(Path.from(Path.SEPARATOR + rel.getFirst()));
}
for (Resource resource : getResources()) {
System.out.println("Lookup to handle " + path + " by resource " + resource.getPath());
if (resource.getPath().equals(path)) {
return resource.process(request);
}
}
throw new ResourceNotFoundException(request);
}
| public Resource process(Request request) throws IllegalActionOnResourceException, ResourceNotFoundException {
//Trace
System.out.println("Processing request " + request.action() + " " + request.path() + " by " +
getCanonicalPath());
//End Trace
// 1) Substract our path from the request path.
Path rel = request.path().subtract(this.getPath());
// 2) The request is targeting us...
if (request.path().equals(getPath())) {
switch (request.action()) {
case GET:
return get(request);
case DELETE:
return delete(request);
case PUT:
return put(request);
case POST:
return post(request);
}
return null;
}
// 3) The request is targeting one of our child.
Path path = getPath().add(Path.fromElements(rel.getFirst()));
for (Resource resource : getResources()) {
if (resource.getPath().equals(path)) {
return resource.process(request);
}
}
throw new ResourceNotFoundException(request);
}
|
diff --git a/org.eclipse.riena.navigation.ui.swt/src/org/eclipse/riena/navigation/ui/swt/views/ApplicationViewAdvisor.java b/org.eclipse.riena.navigation.ui.swt/src/org/eclipse/riena/navigation/ui/swt/views/ApplicationViewAdvisor.java
index 72def441e..d468f3480 100644
--- a/org.eclipse.riena.navigation.ui.swt/src/org/eclipse/riena/navigation/ui/swt/views/ApplicationViewAdvisor.java
+++ b/org.eclipse.riena.navigation.ui.swt/src/org/eclipse/riena/navigation/ui/swt/views/ApplicationViewAdvisor.java
@@ -1,818 +1,819 @@
/*******************************************************************************
* Copyright (c) 2007, 2010 compeople AG 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:
* compeople AG - initial API and implementation
*******************************************************************************/
package org.eclipse.riena.navigation.ui.swt.views;
import java.util.ArrayList;
import java.util.List;
import org.osgi.service.log.LogService;
import org.eclipse.core.runtime.Assert;
import org.eclipse.equinox.log.Logger;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.CoolBar;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IPerspectiveDescriptor;
import org.eclipse.ui.IPerspectiveRegistry;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IViewReference;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.WorkbenchException;
import org.eclipse.ui.application.ActionBarAdvisor;
import org.eclipse.ui.application.IActionBarConfigurer;
import org.eclipse.ui.application.IWorkbenchWindowConfigurer;
import org.eclipse.ui.application.WorkbenchWindowAdvisor;
import org.eclipse.riena.core.Log4r;
import org.eclipse.riena.core.wire.InjectExtension;
import org.eclipse.riena.internal.navigation.ui.swt.Activator;
import org.eclipse.riena.internal.navigation.ui.swt.CoolbarUtils;
import org.eclipse.riena.internal.navigation.ui.swt.IAdvisorHelper;
import org.eclipse.riena.internal.navigation.ui.swt.RestoreFocusOnEscListener;
import org.eclipse.riena.navigation.IApplicationNode;
import org.eclipse.riena.navigation.IModuleGroupNode;
import org.eclipse.riena.navigation.IModuleNode;
import org.eclipse.riena.navigation.INavigationNode;
import org.eclipse.riena.navigation.ISubApplicationNode;
import org.eclipse.riena.navigation.ISubModuleNode;
import org.eclipse.riena.navigation.listener.ApplicationNodeListener;
import org.eclipse.riena.navigation.listener.ModuleGroupNodeListener;
import org.eclipse.riena.navigation.listener.ModuleNodeListener;
import org.eclipse.riena.navigation.listener.NavigationTreeObserver;
import org.eclipse.riena.navigation.listener.SubApplicationNodeListener;
import org.eclipse.riena.navigation.listener.SubModuleNodeListener;
import org.eclipse.riena.navigation.model.ApplicationNode;
import org.eclipse.riena.navigation.ui.controllers.ApplicationController;
import org.eclipse.riena.navigation.ui.swt.binding.InjectSwtViewBindingDelegate;
import org.eclipse.riena.navigation.ui.swt.component.MenuCoolBarComposite;
import org.eclipse.riena.navigation.ui.swt.component.TitleComposite;
import org.eclipse.riena.navigation.ui.swt.lnf.renderer.EmbeddedBorderRenderer;
import org.eclipse.riena.navigation.ui.swt.lnf.renderer.ModuleGroupRenderer;
import org.eclipse.riena.navigation.ui.swt.lnf.renderer.ShellBorderRenderer;
import org.eclipse.riena.navigation.ui.swt.lnf.renderer.ShellRenderer;
import org.eclipse.riena.navigation.ui.swt.presentation.SwtViewProvider;
import org.eclipse.riena.navigation.ui.swt.presentation.stack.TitlelessStackPresentation;
import org.eclipse.riena.navigation.ui.swt.statusline.IStatuslineContentFactoryExtension;
import org.eclipse.riena.ui.filter.IUIFilter;
import org.eclipse.riena.ui.ridgets.swt.uibinding.AbstractViewBindingDelegate;
import org.eclipse.riena.ui.swt.DefaultStatuslineContentFactory;
import org.eclipse.riena.ui.swt.IStatusLineContentFactory;
import org.eclipse.riena.ui.swt.InfoFlyout;
import org.eclipse.riena.ui.swt.Statusline;
import org.eclipse.riena.ui.swt.StatuslineSpacer;
import org.eclipse.riena.ui.swt.lnf.ILnfRenderer;
import org.eclipse.riena.ui.swt.lnf.LnFUpdater;
import org.eclipse.riena.ui.swt.lnf.LnfKeyConstants;
import org.eclipse.riena.ui.swt.lnf.LnfManager;
import org.eclipse.riena.ui.swt.lnf.rienadefault.RienaDefaultLnf;
import org.eclipse.riena.ui.swt.utils.ImageStore;
import org.eclipse.riena.ui.swt.utils.TestingSupport;
import org.eclipse.riena.ui.swt.utils.UIControlsFactory;
import org.eclipse.riena.ui.swt.utils.WidgetIdentificationSupport;
import org.eclipse.riena.ui.workarea.IWorkareaDefinition;
import org.eclipse.riena.ui.workarea.WorkareaManager;
public class ApplicationViewAdvisor extends WorkbenchWindowAdvisor {
private static final Logger LOGGER = Log4r.getLogger(Activator.getDefault(), ApplicationViewAdvisor.class);
/**
* System property defining the initial width of the application window.
*/
private static final String PROPERTY_RIENA_APPLICATION_WIDTH = "riena.application.width"; //$NON-NLS-1$
/**
* System property defining the initial height of the application window.
*/
private static final String PROPERTY_RIENA_APPLICATION_HEIGHT = "riena.application.height"; //$NON-NLS-1$
/**
* System property defining the minimum width of the application window.
*/
private static final String PROPERTY_RIENA_APPLICATION_MINIMUM_WIDTH = "riena.application.minimum.width"; //$NON-NLS-1$
/**
* System property defining the minimum height of the application window.
*/
private static final String PROPERTY_RIENA_APPLICATION_MINIMUM_HEIGHT = "riena.application.minimum.height"; //$NON-NLS-1$
private static final int DEFAULT_COOLBAR_TOP_MARGIN = 2;
public static final String SHELL_RIDGET_PROPERTY = "applicationWindow"; //$NON-NLS-1$
enum BtnState {
NONE, HOVER, HOVER_SELECTED;
}
private final ApplicationController controller;
private final AbstractViewBindingDelegate binding;
private final IAdvisorHelper advisorHelper;
private TitleComposite titleComposite;
// content factory for delegation of content creation from the statusline
private IStatusLineContentFactory statuslineContentFactory;
/**
* The application window size minimum.
*/
private Point applicationSizeMinimum;
/**
* @noreference This constructor is not intended to be referenced by
* clients.
*/
public ApplicationViewAdvisor(final IWorkbenchWindowConfigurer configurer, final ApplicationController pController,
final IAdvisorHelper helper) {
super(configurer);
controller = pController;
binding = createBinding();
advisorHelper = helper;
initializeListener();
}
public void addUIControl(final Composite control, final String propertyName) {
binding.addUIControl(control, propertyName);
}
@InjectExtension()
public void bindStatuslineContentFactory(
final IStatuslineContentFactoryExtension[] statuslineContentFactoryExtensions) {
if (statuslineContentFactoryExtensions.length > 0) {
this.statuslineContentFactory = statuslineContentFactoryExtensions[0].createFactory();
}
}
@Override
public final ActionBarAdvisor createActionBarAdvisor(final IActionBarConfigurer configurer) {
return advisorHelper.createActionBarAdvisor(configurer);
}
@Override
public void createWindowContents(final Shell shell) {
initShell(shell);
// create and layouts the composite of switcher, menu, tool bar etc.
shell.setLayout(new FormLayout());
final Composite grabCorner = createGrabCorner(shell);
createStatusLine(shell, grabCorner);
titleComposite = createTitleComposite(shell);
final Composite menuBarComposite = createMenuBarComposite(shell, titleComposite);
final Composite coolBarComposite = createCoolBarComposite(shell, menuBarComposite);
final Composite mainComposite = createMainComposite(shell, coolBarComposite);
createInfoFlyout(mainComposite);
final RestoreFocusOnEscListener focusListener = new RestoreFocusOnEscListener(shell);
focusListener.addControl(RestoreFocusOnEscListener.findCoolBar(menuBarComposite));
focusListener.addControl(RestoreFocusOnEscListener.findCoolBar(coolBarComposite));
}
private void createInfoFlyout(final Composite mainComposite) {
final InfoFlyout flyout = new InfoFlyout(mainComposite);
binding.addUIControl(flyout, "infoFlyout"); //$NON-NLS-1$
}
@Override
public void dispose() {
super.dispose();
if (titleComposite != null) {
titleComposite.dispose();
titleComposite = null;
}
}
@Override
public void preWindowOpen() {
configureWindow();
}
@Override
public void postWindowOpen() {
super.postWindowOpen();
doInitialBinding();
if (titleComposite != null) {
// Redraw so that the active tab is displayed correct
titleComposite.setRedraw(false);
titleComposite.setRedraw(true);
}
}
/**
* Creates a delegate for the binding of view and controller.
*
* @return delegate for binding
*/
protected AbstractViewBindingDelegate createBinding() {
return new InjectSwtViewBindingDelegate();
}
// helping methods
//////////////////
private void initializeListener() {
final NavigationTreeObserver navigationTreeObserver = new NavigationTreeObserver();
navigationTreeObserver.addListener(new MyApplicationNodeListener());
navigationTreeObserver.addListener(new MySubApplicationNodeListener());
navigationTreeObserver.addListener(new MyModuleGroupNodeListener());
navigationTreeObserver.addListener(new MyModuleNodeListener());
navigationTreeObserver.addListener(new MySubModuleNodeListener());
navigationTreeObserver.addListenerTo(controller.getNavigationNode());
}
/**
* Configures the window of the application.
*/
private void configureWindow() {
final IWorkbenchWindowConfigurer configurer = getWindowConfigurer();
final String label = controller.getNavigationNode().getLabel();
if (label != null) {
configurer.setTitle(label);
}
initApplicationSize(configurer);
if (LnfManager.getLnf().getBooleanSetting(LnfKeyConstants.SHELL_HIDE_OS_BORDER)
&& !TestingSupport.isTestingEnabled()) { // some testing UI tools might not work with windows w/o real decorations(menu, border, etc){
// don't show the shell border (with the minimize, maximize and
// close buttons) of the operation system
configurer.setShellStyle(SWT.NO_TRIM | SWT.DOUBLE_BUFFERED);
}
}
/**
* Reads the two properties for the initial width and the initial height of
* the application.
*
* @param configurer
*/
private void initApplicationSize(final IWorkbenchWindowConfigurer configurer) {
int width = Integer.getInteger(PROPERTY_RIENA_APPLICATION_WIDTH, getApplicationSizeMinimum().x);
if (width < getApplicationSizeMinimum().x) {
width = getApplicationSizeMinimum().x;
LOGGER.log(LogService.LOG_WARNING,
"The initial width of the application is less than the minimum width which is " //$NON-NLS-1$
+ getApplicationSizeMinimum().x);
}
int height = Integer.getInteger(PROPERTY_RIENA_APPLICATION_HEIGHT, getApplicationSizeMinimum().y);
if (height < getApplicationSizeMinimum().y) {
height = getApplicationSizeMinimum().y;
LOGGER.log(LogService.LOG_WARNING,
"The initial height of the application is less than the minimum height which is " //$NON-NLS-1$
+ getApplicationSizeMinimum().y);
}
configurer.setInitialSize(new Point(width, height));
}
private void initApplicationSizeMinimum() {
final int widthMinimum = Integer.getInteger(PROPERTY_RIENA_APPLICATION_MINIMUM_WIDTH,
getApplicationDefaultSizeMinimum().x);
final int heightMinimum = Integer.getInteger(PROPERTY_RIENA_APPLICATION_MINIMUM_HEIGHT,
getApplicationDefaultSizeMinimum().y);
applicationSizeMinimum = new Point(widthMinimum, heightMinimum);
}
private Point getApplicationSizeMinimum() {
if (applicationSizeMinimum == null) {
initApplicationSizeMinimum();
}
return applicationSizeMinimum;
}
private Point getApplicationDefaultSizeMinimum() {
return (Point) LnfManager.getLnf().getSetting(LnfKeyConstants.APPLICATION_MIN_SIZE);
}
private void doInitialBinding() {
binding.injectAndBind(controller);
controller.afterBind();
controller.getNavigationNode().activate();
}
private void createStatusLine(final Composite shell, final Composite grabCorner) {
IStatusLineContentFactory statusLineFactory = getStatuslineContentFactory();
if (statusLineFactory == null) {
statusLineFactory = new DefaultStatuslineContentFactory();
}
final Statusline statusLine = new Statusline(shell, SWT.None, StatuslineSpacer.class, statusLineFactory);
final FormData fd = new FormData();
fd.height = LnfManager.getLnf().getIntegerSetting(LnfKeyConstants.STATUSLINE_HEIGHT);
final Rectangle navigationBounds = TitlelessStackPresentation.calcNavigationBounds(shell);
fd.left = new FormAttachment(0, navigationBounds.x);
if (grabCorner != null) {
fd.right = new FormAttachment(grabCorner, 0);
} else {
final int padding = getShellPadding();
fd.right = new FormAttachment(100, -padding);
}
fd.bottom = new FormAttachment(100, -5);
statusLine.setLayoutData(fd);
addUIControl(statusLine, "statusline"); //$NON-NLS-1$
new LnFUpdater().updateUIControls(statusLine, true);
}
/**
* Initializes the given shell.
*
* @param shell
* shell to initialize
*/
private void initShell(final Shell shell) {
shell.setBackground(LnfManager.getLnf().getColor(LnfKeyConstants.TITLELESS_SHELL_BACKGROUND));
shell.addPaintListener(new ShellPaintListener());
final String iconName = controller.getNavigationNode().getIcon();
shell.setImage(ImageStore.getInstance().getImage(iconName));
shell.setMinimumSize(getApplicationSizeMinimum());
// prepare shell for binding
addUIControl(shell, SHELL_RIDGET_PROPERTY);
if (getShellRenderer() != null) {
getShellRenderer().setShell(shell);
}
// TODO check if this is the main window. maybe support more then one workbench window.
WidgetIdentificationSupport.setIdentification(shell);
}
/**
* Create the composite that contains the:
* <ul>
* <li>shell title and title buttons</li>
* <li>the logo</li>
* <li>the sub application switcher</li>
* </ul>
*
* @param parentShell
* the parent shell (non null)
* @return the title composite (never null)
*/
private TitleComposite createTitleComposite(final Shell parentShell) {
final ApplicationNode node = (ApplicationNode) controller.getNavigationNode();
return new TitleComposite(parentShell, node);
}
/**
* Creates and positions the corner to grab.
*
* @param shell
*/
private org.eclipse.riena.ui.swt.GrabCorner createGrabCorner(final Shell shell) {
if (org.eclipse.riena.ui.swt.GrabCorner.isResizeable()
&& LnfManager.getLnf().getBooleanSetting(LnfKeyConstants.SHELL_HIDE_OS_BORDER)) {
return new org.eclipse.riena.ui.swt.GrabCorner(shell, SWT.DOUBLE_BUFFERED);
}
return null;
}
/**
* Creates and positions the composite for the menu bar.
*
* @param parent
* parent of composite
* @param previous
* previous composite in the layout
* @return composite
*/
private Composite createMenuBarComposite(final Composite parent, final Composite previous) {
Assert.isTrue(parent.getLayout() instanceof FormLayout);
final int padding = getShellPadding();
// menu bar
final IWorkbenchWindow window = getWindowConfigurer().getWindow();
final MenuCoolBarComposite composite = new MenuCoolBarComposite(parent, SWT.NONE, window);
final FormData formData = new FormData();
formData.top = new FormAttachment(previous, getMenuBarTopMargin());
formData.left = new FormAttachment(0, padding);
formData.right = new FormAttachment(100, -padding);
composite.setLayoutData(formData);
return composite;
}
/**
* Creates and positions the composite for the cool bar.
*
* @param parent
* parent of composite
* @param previous
* previous composite in the layout
* @return composite
*/
- private Composite createCoolBarComposite(final Composite parent, final Composite previous) {
+ private Composite createCoolBarComposite(final Composite parent, Composite previous) {
Assert.isTrue(parent.getLayout() instanceof FormLayout);
int padding = getCoolBarSeparatorPadding();
final Composite separator = UIControlsFactory.createSeparator(parent, SWT.HORIZONTAL);
FormData formData = new FormData();
formData.top = new FormAttachment(previous);
- formData.left = new FormAttachment(0, padding);
- formData.right = new FormAttachment(100, -padding);
+ formData.left = new FormAttachment(0, 2);
+ formData.right = new FormAttachment(100, -2);
formData.height = 2;
separator.setLayoutData(formData);
+ previous = separator;
padding = getShellPadding();
final Composite result = new Composite(parent, SWT.NONE);
result.setLayout(new FillLayout());
formData = new FormData();
formData.top = new FormAttachment(previous, getToolBarTopMargin());
formData.left = new FormAttachment(0, padding);
formData.right = new FormAttachment(100, -padding);
result.setLayoutData(formData);
final Control control = getWindowConfigurer().createCoolBarControl(result);
if (control instanceof CoolBar) {
final CoolBar coolbar = (CoolBar) control;
CoolbarUtils.initCoolBar(coolbar, getToolbarFont());
}
return result;
}
private static Font getToolbarFont() {
return LnfManager.getLnf().getFont(LnfKeyConstants.TOOLBAR_FONT);
}
private int getCoolBarSeparatorPadding() {
ModuleGroupRenderer mgRenderer = (ModuleGroupRenderer) LnfManager.getLnf().getRenderer(
LnfKeyConstants.MODULE_GROUP_RENDERER);
if (mgRenderer == null) {
mgRenderer = new ModuleGroupRenderer();
}
int padding = mgRenderer.getModuleGroupPadding();
EmbeddedBorderRenderer borderRenderer = (EmbeddedBorderRenderer) LnfManager.getLnf().getRenderer(
LnfKeyConstants.SUB_MODULE_VIEW_BORDER_RENDERER);
if (borderRenderer == null) {
borderRenderer = new EmbeddedBorderRenderer();
}
padding += borderRenderer.getBorderWidth();
padding += getShellPadding();
return padding;
}
/**
* Creates the main composite.
*
* @param parent
* parent of composite
* @param previous
* previous composite in the layout
* @return composite
*/
private Composite createMainComposite(final Composite parent, final Composite previous) {
Assert.isTrue(parent.getLayout() instanceof FormLayout);
final int padding = getShellPadding();
final Composite composite = new Composite(parent, SWT.DOUBLE_BUFFERED);
composite.setLayout(new FillLayout());
final FormData formData = new FormData();
formData.top = new FormAttachment(previous, LnfManager.getLnf().getIntegerSetting(
LnfKeyConstants.TOOLBAR_WORK_AREA_VERTICAL_GAP), 0);
formData.bottom = new FormAttachment(100, -padding);
formData.left = new FormAttachment(0, padding);
formData.right = new FormAttachment(100, -padding);
composite.setLayoutData(formData);
getWindowConfigurer().createPageComposite(composite);
return composite;
}
/**
* Returns the padding between shell border and content.
*
* @return padding
*/
private int getShellPadding() {
final ShellBorderRenderer borderRenderer = (ShellBorderRenderer) LnfManager.getLnf().getRenderer(
LnfKeyConstants.TITLELESS_SHELL_BORDER_RENDERER);
return borderRenderer.getCompleteBorderWidth();
}
/**
* Returns the renderer of the shell.
*
* @return renderer
*/
private ShellRenderer getShellRenderer() {
final ShellRenderer shellRenderer = (ShellRenderer) LnfManager.getLnf().getRenderer(
LnfKeyConstants.TITLELESS_SHELL_RENDERER);
return shellRenderer;
}
/**
* Returns the margin above the menu bar.
*
* @return top margin
*/
private int getMenuBarTopMargin() {
final RienaDefaultLnf lnf = LnfManager.getLnf();
return lnf.getIntegerSetting(LnfKeyConstants.MENUBAR_TOP_MARGIN, DEFAULT_COOLBAR_TOP_MARGIN);
}
/**
* Returns the margin above the tool bar.
*
* @return top margin
*/
private int getToolBarTopMargin() {
final RienaDefaultLnf lnf = LnfManager.getLnf();
return lnf.getIntegerSetting(LnfKeyConstants.TOOLBAR_TOP_MARGIN, DEFAULT_COOLBAR_TOP_MARGIN);
}
// helping classes
//////////////////
private class MyApplicationNodeListener extends ApplicationNodeListener {
@Override
public void filterAdded(final IApplicationNode source, final IUIFilter filter) {
show();
}
@Override
public void filterRemoved(final IApplicationNode source, final IUIFilter filter) {
show();
}
private void show() {
if (controller == null || controller.getNavigationNode() == null
|| controller.getNavigationNode().isDisposed()) {
return;
}
try {
final IViewPart vp = getNavigationViewPart();
if (vp == null) {
final NavigationViewPart navi = (NavigationViewPart) getActivePage()
.showView(NavigationViewPart.ID);
navi.updateNavigationSize();
}
} catch (final PartInitException e) {
throw new UIViewFailure(e.getMessage(), e);
}
}
private IWorkbenchPage getActivePage() {
return PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
}
/**
* Returns the view part of the navigation.
*
* @return view part of the navigation or
*/
private IViewPart getNavigationViewPart() {
final IViewReference[] references = getActivePage().getViewReferences();
for (final IViewReference viewReference : references) {
if (viewReference.getId().equals(NavigationViewPart.ID)) {
return viewReference.getView(true);
}
}
return null;
}
}
private class MySubApplicationNodeListener extends SubApplicationNodeListener {
/**
* {@inheritDoc}
* <p>
* Shows the specified perspective (sub-application).
*/
@Override
public void activated(final ISubApplicationNode source) {
if (source != null) {
showPerspective(source);
if (titleComposite != null) {
// Redraw so that the active tab is displayed correct
titleComposite.setRedraw(false);
titleComposite.setRedraw(true);
}
prepare(source);
}
super.activated(source);
}
private void showPerspective(final ISubApplicationNode source) {
try {
PlatformUI.getWorkbench().showPerspective(SwtViewProvider.getInstance().getSwtViewId(source).getId(),
PlatformUI.getWorkbench().getActiveWorkbenchWindow());
} catch (final WorkbenchException e) {
throw new UIViewFailure(e.getMessage(), e);
}
}
@Override
public void disposed(final ISubApplicationNode source) {
final SwtViewProvider viewProvider = SwtViewProvider.getInstance();
final String id = viewProvider.getSwtViewId(source).getId();
final IWorkbench workbench = PlatformUI.getWorkbench();
final IPerspectiveRegistry registry = workbench.getPerspectiveRegistry();
final IPerspectiveDescriptor perspDesc = registry.findPerspectiveWithId(id);
workbench.getActiveWorkbenchWindow().getActivePage().closePerspective(perspDesc, false, false);
viewProvider.unregisterSwtViewId(source);
}
}
/**
* This listener of a module group ensures the preparation of nodes (if
* necessary).
*/
private class MyModuleGroupNodeListener extends ModuleGroupNodeListener {
/**
* {@inheritDoc}
* <p>
* After activation of a module group prepare - if necessary - every
* child (sub module) node.
*/
@Override
public void activated(final IModuleGroupNode source) {
prepare(source);
super.activated(source);
}
/**
* {@inheritDoc}
* <p>
* After the parent of a module group changed prepare - if necessary -
* every child node.
*/
@Override
public void parentChanged(final IModuleGroupNode source) {
super.parentChanged(source);
prepare(source);
}
}
/**
* This listener of a module ensures the preparation of nodes (if
* necessary).
*/
private class MyModuleNodeListener extends ModuleNodeListener {
/**
* {@inheritDoc}
* <p>
* After activation of a module prepare - if necessary - every child
* (sub module) node.
*/
@Override
public void activated(final IModuleNode source) {
prepare(source);
super.activated(source);
}
/**
* {@inheritDoc}
* <p>
* After the parent of a module changed prepare - if necessary - every
* child node.
*/
@Override
public void parentChanged(final IModuleNode source) {
super.parentChanged(source);
prepare(source);
}
}
/**
* This listener of a sub module ensures the preparation of nodes (if
* necessary).
*/
private class MySubModuleNodeListener extends SubModuleNodeListener {
/**
* {@inheritDoc}
* <p>
* After activation of a sub module prepare - if necessary - every child
* node.
*/
@Override
public void activated(final ISubModuleNode source) {
prepare(source);
super.activated(source);
}
/**
* {@inheritDoc}
* <p>
* After the parent of a sub module changed prepare - if necessary -
* every child node.
*/
@Override
public void parentChanged(final ISubModuleNode source) {
super.parentChanged(source);
prepare(source);
}
}
/**
* Prepares every sub-module whose definition requires preparation.
*
* @param node
* navigation node
*/
private void prepare(final INavigationNode<?> node) {
if ((node == null) || (node.getParent() == null)) {
return;
}
if (node instanceof ISubModuleNode) {
final ISubModuleNode subModuleNode = (ISubModuleNode) node;
final IWorkareaDefinition definition = WorkareaManager.getInstance().getDefinition(subModuleNode);
if ((definition != null) && definition.isRequiredPreparation() && subModuleNode.isCreated()) {
subModuleNode.prepare();
}
}
/*
* The number of children can change while iterating. Only observe the
* node children !before! the iteration begins. Any child added while
* iterating will be handled automatically if preparation is required.
* Just ensure that there will be no concurrent modification of the
* children list while iterating over it. Conclusion is a copy..
*/
final List<INavigationNode<?>> children = new ArrayList<INavigationNode<?>>(node.getChildren());
for (final INavigationNode<?> child : children) {
prepare(child);
}
}
/**
* This listener paints the shell (the border of the shell).
*/
private static class ShellPaintListener implements PaintListener {
public void paintControl(final PaintEvent e) {
onPaint(e);
}
/**
* Paints the border of the (titleless) shell.
*
* @param e
* event
*/
private void onPaint(final PaintEvent e) {
if (e.getSource() instanceof Control) {
final Control shell = (Control) e.getSource();
final Rectangle shellBounds = shell.getBounds();
final Rectangle bounds = new Rectangle(0, 0, shellBounds.width, shellBounds.height);
final ILnfRenderer borderRenderer = LnfManager.getLnf().getRenderer(
LnfKeyConstants.TITLELESS_SHELL_BORDER_RENDERER);
borderRenderer.setBounds(bounds);
borderRenderer.paint(e.gc, null);
}
}
}
public IStatusLineContentFactory getStatuslineContentFactory() {
return statuslineContentFactory;
}
}
| false | true | private void configureWindow() {
final IWorkbenchWindowConfigurer configurer = getWindowConfigurer();
final String label = controller.getNavigationNode().getLabel();
if (label != null) {
configurer.setTitle(label);
}
initApplicationSize(configurer);
if (LnfManager.getLnf().getBooleanSetting(LnfKeyConstants.SHELL_HIDE_OS_BORDER)
&& !TestingSupport.isTestingEnabled()) { // some testing UI tools might not work with windows w/o real decorations(menu, border, etc){
// don't show the shell border (with the minimize, maximize and
// close buttons) of the operation system
configurer.setShellStyle(SWT.NO_TRIM | SWT.DOUBLE_BUFFERED);
}
}
/**
* Reads the two properties for the initial width and the initial height of
* the application.
*
* @param configurer
*/
private void initApplicationSize(final IWorkbenchWindowConfigurer configurer) {
int width = Integer.getInteger(PROPERTY_RIENA_APPLICATION_WIDTH, getApplicationSizeMinimum().x);
if (width < getApplicationSizeMinimum().x) {
width = getApplicationSizeMinimum().x;
LOGGER.log(LogService.LOG_WARNING,
"The initial width of the application is less than the minimum width which is " //$NON-NLS-1$
+ getApplicationSizeMinimum().x);
}
int height = Integer.getInteger(PROPERTY_RIENA_APPLICATION_HEIGHT, getApplicationSizeMinimum().y);
if (height < getApplicationSizeMinimum().y) {
height = getApplicationSizeMinimum().y;
LOGGER.log(LogService.LOG_WARNING,
"The initial height of the application is less than the minimum height which is " //$NON-NLS-1$
+ getApplicationSizeMinimum().y);
}
configurer.setInitialSize(new Point(width, height));
}
private void initApplicationSizeMinimum() {
final int widthMinimum = Integer.getInteger(PROPERTY_RIENA_APPLICATION_MINIMUM_WIDTH,
getApplicationDefaultSizeMinimum().x);
final int heightMinimum = Integer.getInteger(PROPERTY_RIENA_APPLICATION_MINIMUM_HEIGHT,
getApplicationDefaultSizeMinimum().y);
applicationSizeMinimum = new Point(widthMinimum, heightMinimum);
}
private Point getApplicationSizeMinimum() {
if (applicationSizeMinimum == null) {
initApplicationSizeMinimum();
}
return applicationSizeMinimum;
}
private Point getApplicationDefaultSizeMinimum() {
return (Point) LnfManager.getLnf().getSetting(LnfKeyConstants.APPLICATION_MIN_SIZE);
}
private void doInitialBinding() {
binding.injectAndBind(controller);
controller.afterBind();
controller.getNavigationNode().activate();
}
private void createStatusLine(final Composite shell, final Composite grabCorner) {
IStatusLineContentFactory statusLineFactory = getStatuslineContentFactory();
if (statusLineFactory == null) {
statusLineFactory = new DefaultStatuslineContentFactory();
}
final Statusline statusLine = new Statusline(shell, SWT.None, StatuslineSpacer.class, statusLineFactory);
final FormData fd = new FormData();
fd.height = LnfManager.getLnf().getIntegerSetting(LnfKeyConstants.STATUSLINE_HEIGHT);
final Rectangle navigationBounds = TitlelessStackPresentation.calcNavigationBounds(shell);
fd.left = new FormAttachment(0, navigationBounds.x);
if (grabCorner != null) {
fd.right = new FormAttachment(grabCorner, 0);
} else {
final int padding = getShellPadding();
fd.right = new FormAttachment(100, -padding);
}
fd.bottom = new FormAttachment(100, -5);
statusLine.setLayoutData(fd);
addUIControl(statusLine, "statusline"); //$NON-NLS-1$
new LnFUpdater().updateUIControls(statusLine, true);
}
/**
* Initializes the given shell.
*
* @param shell
* shell to initialize
*/
private void initShell(final Shell shell) {
shell.setBackground(LnfManager.getLnf().getColor(LnfKeyConstants.TITLELESS_SHELL_BACKGROUND));
shell.addPaintListener(new ShellPaintListener());
final String iconName = controller.getNavigationNode().getIcon();
shell.setImage(ImageStore.getInstance().getImage(iconName));
shell.setMinimumSize(getApplicationSizeMinimum());
// prepare shell for binding
addUIControl(shell, SHELL_RIDGET_PROPERTY);
if (getShellRenderer() != null) {
getShellRenderer().setShell(shell);
}
// TODO check if this is the main window. maybe support more then one workbench window.
WidgetIdentificationSupport.setIdentification(shell);
}
/**
* Create the composite that contains the:
* <ul>
* <li>shell title and title buttons</li>
* <li>the logo</li>
* <li>the sub application switcher</li>
* </ul>
*
* @param parentShell
* the parent shell (non null)
* @return the title composite (never null)
*/
private TitleComposite createTitleComposite(final Shell parentShell) {
final ApplicationNode node = (ApplicationNode) controller.getNavigationNode();
return new TitleComposite(parentShell, node);
}
/**
* Creates and positions the corner to grab.
*
* @param shell
*/
private org.eclipse.riena.ui.swt.GrabCorner createGrabCorner(final Shell shell) {
if (org.eclipse.riena.ui.swt.GrabCorner.isResizeable()
&& LnfManager.getLnf().getBooleanSetting(LnfKeyConstants.SHELL_HIDE_OS_BORDER)) {
return new org.eclipse.riena.ui.swt.GrabCorner(shell, SWT.DOUBLE_BUFFERED);
}
return null;
}
/**
* Creates and positions the composite for the menu bar.
*
* @param parent
* parent of composite
* @param previous
* previous composite in the layout
* @return composite
*/
private Composite createMenuBarComposite(final Composite parent, final Composite previous) {
Assert.isTrue(parent.getLayout() instanceof FormLayout);
final int padding = getShellPadding();
// menu bar
final IWorkbenchWindow window = getWindowConfigurer().getWindow();
final MenuCoolBarComposite composite = new MenuCoolBarComposite(parent, SWT.NONE, window);
final FormData formData = new FormData();
formData.top = new FormAttachment(previous, getMenuBarTopMargin());
formData.left = new FormAttachment(0, padding);
formData.right = new FormAttachment(100, -padding);
composite.setLayoutData(formData);
return composite;
}
/**
* Creates and positions the composite for the cool bar.
*
* @param parent
* parent of composite
* @param previous
* previous composite in the layout
* @return composite
*/
private Composite createCoolBarComposite(final Composite parent, final Composite previous) {
Assert.isTrue(parent.getLayout() instanceof FormLayout);
int padding = getCoolBarSeparatorPadding();
final Composite separator = UIControlsFactory.createSeparator(parent, SWT.HORIZONTAL);
FormData formData = new FormData();
formData.top = new FormAttachment(previous);
formData.left = new FormAttachment(0, padding);
formData.right = new FormAttachment(100, -padding);
formData.height = 2;
separator.setLayoutData(formData);
padding = getShellPadding();
final Composite result = new Composite(parent, SWT.NONE);
result.setLayout(new FillLayout());
formData = new FormData();
formData.top = new FormAttachment(previous, getToolBarTopMargin());
formData.left = new FormAttachment(0, padding);
formData.right = new FormAttachment(100, -padding);
result.setLayoutData(formData);
final Control control = getWindowConfigurer().createCoolBarControl(result);
if (control instanceof CoolBar) {
final CoolBar coolbar = (CoolBar) control;
CoolbarUtils.initCoolBar(coolbar, getToolbarFont());
}
return result;
}
private static Font getToolbarFont() {
return LnfManager.getLnf().getFont(LnfKeyConstants.TOOLBAR_FONT);
}
private int getCoolBarSeparatorPadding() {
ModuleGroupRenderer mgRenderer = (ModuleGroupRenderer) LnfManager.getLnf().getRenderer(
LnfKeyConstants.MODULE_GROUP_RENDERER);
if (mgRenderer == null) {
mgRenderer = new ModuleGroupRenderer();
}
int padding = mgRenderer.getModuleGroupPadding();
EmbeddedBorderRenderer borderRenderer = (EmbeddedBorderRenderer) LnfManager.getLnf().getRenderer(
LnfKeyConstants.SUB_MODULE_VIEW_BORDER_RENDERER);
if (borderRenderer == null) {
borderRenderer = new EmbeddedBorderRenderer();
}
padding += borderRenderer.getBorderWidth();
padding += getShellPadding();
return padding;
}
/**
* Creates the main composite.
*
* @param parent
* parent of composite
* @param previous
* previous composite in the layout
* @return composite
*/
private Composite createMainComposite(final Composite parent, final Composite previous) {
Assert.isTrue(parent.getLayout() instanceof FormLayout);
final int padding = getShellPadding();
final Composite composite = new Composite(parent, SWT.DOUBLE_BUFFERED);
composite.setLayout(new FillLayout());
final FormData formData = new FormData();
formData.top = new FormAttachment(previous, LnfManager.getLnf().getIntegerSetting(
LnfKeyConstants.TOOLBAR_WORK_AREA_VERTICAL_GAP), 0);
formData.bottom = new FormAttachment(100, -padding);
formData.left = new FormAttachment(0, padding);
formData.right = new FormAttachment(100, -padding);
composite.setLayoutData(formData);
getWindowConfigurer().createPageComposite(composite);
return composite;
}
/**
* Returns the padding between shell border and content.
*
* @return padding
*/
private int getShellPadding() {
final ShellBorderRenderer borderRenderer = (ShellBorderRenderer) LnfManager.getLnf().getRenderer(
LnfKeyConstants.TITLELESS_SHELL_BORDER_RENDERER);
return borderRenderer.getCompleteBorderWidth();
}
/**
* Returns the renderer of the shell.
*
* @return renderer
*/
private ShellRenderer getShellRenderer() {
final ShellRenderer shellRenderer = (ShellRenderer) LnfManager.getLnf().getRenderer(
LnfKeyConstants.TITLELESS_SHELL_RENDERER);
return shellRenderer;
}
/**
* Returns the margin above the menu bar.
*
* @return top margin
*/
private int getMenuBarTopMargin() {
final RienaDefaultLnf lnf = LnfManager.getLnf();
return lnf.getIntegerSetting(LnfKeyConstants.MENUBAR_TOP_MARGIN, DEFAULT_COOLBAR_TOP_MARGIN);
}
/**
* Returns the margin above the tool bar.
*
* @return top margin
*/
private int getToolBarTopMargin() {
final RienaDefaultLnf lnf = LnfManager.getLnf();
return lnf.getIntegerSetting(LnfKeyConstants.TOOLBAR_TOP_MARGIN, DEFAULT_COOLBAR_TOP_MARGIN);
}
// helping classes
//////////////////
private class MyApplicationNodeListener extends ApplicationNodeListener {
@Override
public void filterAdded(final IApplicationNode source, final IUIFilter filter) {
show();
}
@Override
public void filterRemoved(final IApplicationNode source, final IUIFilter filter) {
show();
}
private void show() {
if (controller == null || controller.getNavigationNode() == null
|| controller.getNavigationNode().isDisposed()) {
return;
}
try {
final IViewPart vp = getNavigationViewPart();
if (vp == null) {
final NavigationViewPart navi = (NavigationViewPart) getActivePage()
.showView(NavigationViewPart.ID);
navi.updateNavigationSize();
}
} catch (final PartInitException e) {
throw new UIViewFailure(e.getMessage(), e);
}
}
private IWorkbenchPage getActivePage() {
return PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
}
/**
* Returns the view part of the navigation.
*
* @return view part of the navigation or
*/
private IViewPart getNavigationViewPart() {
final IViewReference[] references = getActivePage().getViewReferences();
for (final IViewReference viewReference : references) {
if (viewReference.getId().equals(NavigationViewPart.ID)) {
return viewReference.getView(true);
}
}
return null;
}
}
private class MySubApplicationNodeListener extends SubApplicationNodeListener {
/**
* {@inheritDoc}
* <p>
* Shows the specified perspective (sub-application).
*/
@Override
public void activated(final ISubApplicationNode source) {
if (source != null) {
showPerspective(source);
if (titleComposite != null) {
// Redraw so that the active tab is displayed correct
titleComposite.setRedraw(false);
titleComposite.setRedraw(true);
}
prepare(source);
}
super.activated(source);
}
private void showPerspective(final ISubApplicationNode source) {
try {
PlatformUI.getWorkbench().showPerspective(SwtViewProvider.getInstance().getSwtViewId(source).getId(),
PlatformUI.getWorkbench().getActiveWorkbenchWindow());
} catch (final WorkbenchException e) {
throw new UIViewFailure(e.getMessage(), e);
}
}
@Override
public void disposed(final ISubApplicationNode source) {
final SwtViewProvider viewProvider = SwtViewProvider.getInstance();
final String id = viewProvider.getSwtViewId(source).getId();
final IWorkbench workbench = PlatformUI.getWorkbench();
final IPerspectiveRegistry registry = workbench.getPerspectiveRegistry();
final IPerspectiveDescriptor perspDesc = registry.findPerspectiveWithId(id);
workbench.getActiveWorkbenchWindow().getActivePage().closePerspective(perspDesc, false, false);
viewProvider.unregisterSwtViewId(source);
}
}
/**
* This listener of a module group ensures the preparation of nodes (if
* necessary).
*/
private class MyModuleGroupNodeListener extends ModuleGroupNodeListener {
/**
* {@inheritDoc}
* <p>
* After activation of a module group prepare - if necessary - every
* child (sub module) node.
*/
@Override
public void activated(final IModuleGroupNode source) {
prepare(source);
super.activated(source);
}
/**
* {@inheritDoc}
* <p>
* After the parent of a module group changed prepare - if necessary -
* every child node.
*/
@Override
public void parentChanged(final IModuleGroupNode source) {
super.parentChanged(source);
prepare(source);
}
}
/**
* This listener of a module ensures the preparation of nodes (if
* necessary).
*/
private class MyModuleNodeListener extends ModuleNodeListener {
/**
* {@inheritDoc}
* <p>
* After activation of a module prepare - if necessary - every child
* (sub module) node.
*/
@Override
public void activated(final IModuleNode source) {
prepare(source);
super.activated(source);
}
/**
* {@inheritDoc}
* <p>
* After the parent of a module changed prepare - if necessary - every
* child node.
*/
@Override
public void parentChanged(final IModuleNode source) {
super.parentChanged(source);
prepare(source);
}
}
/**
* This listener of a sub module ensures the preparation of nodes (if
* necessary).
*/
private class MySubModuleNodeListener extends SubModuleNodeListener {
/**
* {@inheritDoc}
* <p>
* After activation of a sub module prepare - if necessary - every child
* node.
*/
@Override
public void activated(final ISubModuleNode source) {
prepare(source);
super.activated(source);
}
/**
* {@inheritDoc}
* <p>
* After the parent of a sub module changed prepare - if necessary -
* every child node.
*/
@Override
public void parentChanged(final ISubModuleNode source) {
super.parentChanged(source);
prepare(source);
}
}
/**
* Prepares every sub-module whose definition requires preparation.
*
* @param node
* navigation node
*/
private void prepare(final INavigationNode<?> node) {
if ((node == null) || (node.getParent() == null)) {
return;
}
if (node instanceof ISubModuleNode) {
final ISubModuleNode subModuleNode = (ISubModuleNode) node;
final IWorkareaDefinition definition = WorkareaManager.getInstance().getDefinition(subModuleNode);
if ((definition != null) && definition.isRequiredPreparation() && subModuleNode.isCreated()) {
subModuleNode.prepare();
}
}
/*
* The number of children can change while iterating. Only observe the
* node children !before! the iteration begins. Any child added while
* iterating will be handled automatically if preparation is required.
* Just ensure that there will be no concurrent modification of the
* children list while iterating over it. Conclusion is a copy..
*/
final List<INavigationNode<?>> children = new ArrayList<INavigationNode<?>>(node.getChildren());
for (final INavigationNode<?> child : children) {
prepare(child);
}
}
/**
* This listener paints the shell (the border of the shell).
*/
private static class ShellPaintListener implements PaintListener {
public void paintControl(final PaintEvent e) {
onPaint(e);
}
/**
* Paints the border of the (titleless) shell.
*
* @param e
* event
*/
private void onPaint(final PaintEvent e) {
if (e.getSource() instanceof Control) {
final Control shell = (Control) e.getSource();
final Rectangle shellBounds = shell.getBounds();
final Rectangle bounds = new Rectangle(0, 0, shellBounds.width, shellBounds.height);
final ILnfRenderer borderRenderer = LnfManager.getLnf().getRenderer(
LnfKeyConstants.TITLELESS_SHELL_BORDER_RENDERER);
borderRenderer.setBounds(bounds);
borderRenderer.paint(e.gc, null);
}
}
}
public IStatusLineContentFactory getStatuslineContentFactory() {
return statuslineContentFactory;
}
}
| private void configureWindow() {
final IWorkbenchWindowConfigurer configurer = getWindowConfigurer();
final String label = controller.getNavigationNode().getLabel();
if (label != null) {
configurer.setTitle(label);
}
initApplicationSize(configurer);
if (LnfManager.getLnf().getBooleanSetting(LnfKeyConstants.SHELL_HIDE_OS_BORDER)
&& !TestingSupport.isTestingEnabled()) { // some testing UI tools might not work with windows w/o real decorations(menu, border, etc){
// don't show the shell border (with the minimize, maximize and
// close buttons) of the operation system
configurer.setShellStyle(SWT.NO_TRIM | SWT.DOUBLE_BUFFERED);
}
}
/**
* Reads the two properties for the initial width and the initial height of
* the application.
*
* @param configurer
*/
private void initApplicationSize(final IWorkbenchWindowConfigurer configurer) {
int width = Integer.getInteger(PROPERTY_RIENA_APPLICATION_WIDTH, getApplicationSizeMinimum().x);
if (width < getApplicationSizeMinimum().x) {
width = getApplicationSizeMinimum().x;
LOGGER.log(LogService.LOG_WARNING,
"The initial width of the application is less than the minimum width which is " //$NON-NLS-1$
+ getApplicationSizeMinimum().x);
}
int height = Integer.getInteger(PROPERTY_RIENA_APPLICATION_HEIGHT, getApplicationSizeMinimum().y);
if (height < getApplicationSizeMinimum().y) {
height = getApplicationSizeMinimum().y;
LOGGER.log(LogService.LOG_WARNING,
"The initial height of the application is less than the minimum height which is " //$NON-NLS-1$
+ getApplicationSizeMinimum().y);
}
configurer.setInitialSize(new Point(width, height));
}
private void initApplicationSizeMinimum() {
final int widthMinimum = Integer.getInteger(PROPERTY_RIENA_APPLICATION_MINIMUM_WIDTH,
getApplicationDefaultSizeMinimum().x);
final int heightMinimum = Integer.getInteger(PROPERTY_RIENA_APPLICATION_MINIMUM_HEIGHT,
getApplicationDefaultSizeMinimum().y);
applicationSizeMinimum = new Point(widthMinimum, heightMinimum);
}
private Point getApplicationSizeMinimum() {
if (applicationSizeMinimum == null) {
initApplicationSizeMinimum();
}
return applicationSizeMinimum;
}
private Point getApplicationDefaultSizeMinimum() {
return (Point) LnfManager.getLnf().getSetting(LnfKeyConstants.APPLICATION_MIN_SIZE);
}
private void doInitialBinding() {
binding.injectAndBind(controller);
controller.afterBind();
controller.getNavigationNode().activate();
}
private void createStatusLine(final Composite shell, final Composite grabCorner) {
IStatusLineContentFactory statusLineFactory = getStatuslineContentFactory();
if (statusLineFactory == null) {
statusLineFactory = new DefaultStatuslineContentFactory();
}
final Statusline statusLine = new Statusline(shell, SWT.None, StatuslineSpacer.class, statusLineFactory);
final FormData fd = new FormData();
fd.height = LnfManager.getLnf().getIntegerSetting(LnfKeyConstants.STATUSLINE_HEIGHT);
final Rectangle navigationBounds = TitlelessStackPresentation.calcNavigationBounds(shell);
fd.left = new FormAttachment(0, navigationBounds.x);
if (grabCorner != null) {
fd.right = new FormAttachment(grabCorner, 0);
} else {
final int padding = getShellPadding();
fd.right = new FormAttachment(100, -padding);
}
fd.bottom = new FormAttachment(100, -5);
statusLine.setLayoutData(fd);
addUIControl(statusLine, "statusline"); //$NON-NLS-1$
new LnFUpdater().updateUIControls(statusLine, true);
}
/**
* Initializes the given shell.
*
* @param shell
* shell to initialize
*/
private void initShell(final Shell shell) {
shell.setBackground(LnfManager.getLnf().getColor(LnfKeyConstants.TITLELESS_SHELL_BACKGROUND));
shell.addPaintListener(new ShellPaintListener());
final String iconName = controller.getNavigationNode().getIcon();
shell.setImage(ImageStore.getInstance().getImage(iconName));
shell.setMinimumSize(getApplicationSizeMinimum());
// prepare shell for binding
addUIControl(shell, SHELL_RIDGET_PROPERTY);
if (getShellRenderer() != null) {
getShellRenderer().setShell(shell);
}
// TODO check if this is the main window. maybe support more then one workbench window.
WidgetIdentificationSupport.setIdentification(shell);
}
/**
* Create the composite that contains the:
* <ul>
* <li>shell title and title buttons</li>
* <li>the logo</li>
* <li>the sub application switcher</li>
* </ul>
*
* @param parentShell
* the parent shell (non null)
* @return the title composite (never null)
*/
private TitleComposite createTitleComposite(final Shell parentShell) {
final ApplicationNode node = (ApplicationNode) controller.getNavigationNode();
return new TitleComposite(parentShell, node);
}
/**
* Creates and positions the corner to grab.
*
* @param shell
*/
private org.eclipse.riena.ui.swt.GrabCorner createGrabCorner(final Shell shell) {
if (org.eclipse.riena.ui.swt.GrabCorner.isResizeable()
&& LnfManager.getLnf().getBooleanSetting(LnfKeyConstants.SHELL_HIDE_OS_BORDER)) {
return new org.eclipse.riena.ui.swt.GrabCorner(shell, SWT.DOUBLE_BUFFERED);
}
return null;
}
/**
* Creates and positions the composite for the menu bar.
*
* @param parent
* parent of composite
* @param previous
* previous composite in the layout
* @return composite
*/
private Composite createMenuBarComposite(final Composite parent, final Composite previous) {
Assert.isTrue(parent.getLayout() instanceof FormLayout);
final int padding = getShellPadding();
// menu bar
final IWorkbenchWindow window = getWindowConfigurer().getWindow();
final MenuCoolBarComposite composite = new MenuCoolBarComposite(parent, SWT.NONE, window);
final FormData formData = new FormData();
formData.top = new FormAttachment(previous, getMenuBarTopMargin());
formData.left = new FormAttachment(0, padding);
formData.right = new FormAttachment(100, -padding);
composite.setLayoutData(formData);
return composite;
}
/**
* Creates and positions the composite for the cool bar.
*
* @param parent
* parent of composite
* @param previous
* previous composite in the layout
* @return composite
*/
private Composite createCoolBarComposite(final Composite parent, Composite previous) {
Assert.isTrue(parent.getLayout() instanceof FormLayout);
int padding = getCoolBarSeparatorPadding();
final Composite separator = UIControlsFactory.createSeparator(parent, SWT.HORIZONTAL);
FormData formData = new FormData();
formData.top = new FormAttachment(previous);
formData.left = new FormAttachment(0, 2);
formData.right = new FormAttachment(100, -2);
formData.height = 2;
separator.setLayoutData(formData);
previous = separator;
padding = getShellPadding();
final Composite result = new Composite(parent, SWT.NONE);
result.setLayout(new FillLayout());
formData = new FormData();
formData.top = new FormAttachment(previous, getToolBarTopMargin());
formData.left = new FormAttachment(0, padding);
formData.right = new FormAttachment(100, -padding);
result.setLayoutData(formData);
final Control control = getWindowConfigurer().createCoolBarControl(result);
if (control instanceof CoolBar) {
final CoolBar coolbar = (CoolBar) control;
CoolbarUtils.initCoolBar(coolbar, getToolbarFont());
}
return result;
}
private static Font getToolbarFont() {
return LnfManager.getLnf().getFont(LnfKeyConstants.TOOLBAR_FONT);
}
private int getCoolBarSeparatorPadding() {
ModuleGroupRenderer mgRenderer = (ModuleGroupRenderer) LnfManager.getLnf().getRenderer(
LnfKeyConstants.MODULE_GROUP_RENDERER);
if (mgRenderer == null) {
mgRenderer = new ModuleGroupRenderer();
}
int padding = mgRenderer.getModuleGroupPadding();
EmbeddedBorderRenderer borderRenderer = (EmbeddedBorderRenderer) LnfManager.getLnf().getRenderer(
LnfKeyConstants.SUB_MODULE_VIEW_BORDER_RENDERER);
if (borderRenderer == null) {
borderRenderer = new EmbeddedBorderRenderer();
}
padding += borderRenderer.getBorderWidth();
padding += getShellPadding();
return padding;
}
/**
* Creates the main composite.
*
* @param parent
* parent of composite
* @param previous
* previous composite in the layout
* @return composite
*/
private Composite createMainComposite(final Composite parent, final Composite previous) {
Assert.isTrue(parent.getLayout() instanceof FormLayout);
final int padding = getShellPadding();
final Composite composite = new Composite(parent, SWT.DOUBLE_BUFFERED);
composite.setLayout(new FillLayout());
final FormData formData = new FormData();
formData.top = new FormAttachment(previous, LnfManager.getLnf().getIntegerSetting(
LnfKeyConstants.TOOLBAR_WORK_AREA_VERTICAL_GAP), 0);
formData.bottom = new FormAttachment(100, -padding);
formData.left = new FormAttachment(0, padding);
formData.right = new FormAttachment(100, -padding);
composite.setLayoutData(formData);
getWindowConfigurer().createPageComposite(composite);
return composite;
}
/**
* Returns the padding between shell border and content.
*
* @return padding
*/
private int getShellPadding() {
final ShellBorderRenderer borderRenderer = (ShellBorderRenderer) LnfManager.getLnf().getRenderer(
LnfKeyConstants.TITLELESS_SHELL_BORDER_RENDERER);
return borderRenderer.getCompleteBorderWidth();
}
/**
* Returns the renderer of the shell.
*
* @return renderer
*/
private ShellRenderer getShellRenderer() {
final ShellRenderer shellRenderer = (ShellRenderer) LnfManager.getLnf().getRenderer(
LnfKeyConstants.TITLELESS_SHELL_RENDERER);
return shellRenderer;
}
/**
* Returns the margin above the menu bar.
*
* @return top margin
*/
private int getMenuBarTopMargin() {
final RienaDefaultLnf lnf = LnfManager.getLnf();
return lnf.getIntegerSetting(LnfKeyConstants.MENUBAR_TOP_MARGIN, DEFAULT_COOLBAR_TOP_MARGIN);
}
/**
* Returns the margin above the tool bar.
*
* @return top margin
*/
private int getToolBarTopMargin() {
final RienaDefaultLnf lnf = LnfManager.getLnf();
return lnf.getIntegerSetting(LnfKeyConstants.TOOLBAR_TOP_MARGIN, DEFAULT_COOLBAR_TOP_MARGIN);
}
// helping classes
//////////////////
private class MyApplicationNodeListener extends ApplicationNodeListener {
@Override
public void filterAdded(final IApplicationNode source, final IUIFilter filter) {
show();
}
@Override
public void filterRemoved(final IApplicationNode source, final IUIFilter filter) {
show();
}
private void show() {
if (controller == null || controller.getNavigationNode() == null
|| controller.getNavigationNode().isDisposed()) {
return;
}
try {
final IViewPart vp = getNavigationViewPart();
if (vp == null) {
final NavigationViewPart navi = (NavigationViewPart) getActivePage()
.showView(NavigationViewPart.ID);
navi.updateNavigationSize();
}
} catch (final PartInitException e) {
throw new UIViewFailure(e.getMessage(), e);
}
}
private IWorkbenchPage getActivePage() {
return PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
}
/**
* Returns the view part of the navigation.
*
* @return view part of the navigation or
*/
private IViewPart getNavigationViewPart() {
final IViewReference[] references = getActivePage().getViewReferences();
for (final IViewReference viewReference : references) {
if (viewReference.getId().equals(NavigationViewPart.ID)) {
return viewReference.getView(true);
}
}
return null;
}
}
private class MySubApplicationNodeListener extends SubApplicationNodeListener {
/**
* {@inheritDoc}
* <p>
* Shows the specified perspective (sub-application).
*/
@Override
public void activated(final ISubApplicationNode source) {
if (source != null) {
showPerspective(source);
if (titleComposite != null) {
// Redraw so that the active tab is displayed correct
titleComposite.setRedraw(false);
titleComposite.setRedraw(true);
}
prepare(source);
}
super.activated(source);
}
private void showPerspective(final ISubApplicationNode source) {
try {
PlatformUI.getWorkbench().showPerspective(SwtViewProvider.getInstance().getSwtViewId(source).getId(),
PlatformUI.getWorkbench().getActiveWorkbenchWindow());
} catch (final WorkbenchException e) {
throw new UIViewFailure(e.getMessage(), e);
}
}
@Override
public void disposed(final ISubApplicationNode source) {
final SwtViewProvider viewProvider = SwtViewProvider.getInstance();
final String id = viewProvider.getSwtViewId(source).getId();
final IWorkbench workbench = PlatformUI.getWorkbench();
final IPerspectiveRegistry registry = workbench.getPerspectiveRegistry();
final IPerspectiveDescriptor perspDesc = registry.findPerspectiveWithId(id);
workbench.getActiveWorkbenchWindow().getActivePage().closePerspective(perspDesc, false, false);
viewProvider.unregisterSwtViewId(source);
}
}
/**
* This listener of a module group ensures the preparation of nodes (if
* necessary).
*/
private class MyModuleGroupNodeListener extends ModuleGroupNodeListener {
/**
* {@inheritDoc}
* <p>
* After activation of a module group prepare - if necessary - every
* child (sub module) node.
*/
@Override
public void activated(final IModuleGroupNode source) {
prepare(source);
super.activated(source);
}
/**
* {@inheritDoc}
* <p>
* After the parent of a module group changed prepare - if necessary -
* every child node.
*/
@Override
public void parentChanged(final IModuleGroupNode source) {
super.parentChanged(source);
prepare(source);
}
}
/**
* This listener of a module ensures the preparation of nodes (if
* necessary).
*/
private class MyModuleNodeListener extends ModuleNodeListener {
/**
* {@inheritDoc}
* <p>
* After activation of a module prepare - if necessary - every child
* (sub module) node.
*/
@Override
public void activated(final IModuleNode source) {
prepare(source);
super.activated(source);
}
/**
* {@inheritDoc}
* <p>
* After the parent of a module changed prepare - if necessary - every
* child node.
*/
@Override
public void parentChanged(final IModuleNode source) {
super.parentChanged(source);
prepare(source);
}
}
/**
* This listener of a sub module ensures the preparation of nodes (if
* necessary).
*/
private class MySubModuleNodeListener extends SubModuleNodeListener {
/**
* {@inheritDoc}
* <p>
* After activation of a sub module prepare - if necessary - every child
* node.
*/
@Override
public void activated(final ISubModuleNode source) {
prepare(source);
super.activated(source);
}
/**
* {@inheritDoc}
* <p>
* After the parent of a sub module changed prepare - if necessary -
* every child node.
*/
@Override
public void parentChanged(final ISubModuleNode source) {
super.parentChanged(source);
prepare(source);
}
}
/**
* Prepares every sub-module whose definition requires preparation.
*
* @param node
* navigation node
*/
private void prepare(final INavigationNode<?> node) {
if ((node == null) || (node.getParent() == null)) {
return;
}
if (node instanceof ISubModuleNode) {
final ISubModuleNode subModuleNode = (ISubModuleNode) node;
final IWorkareaDefinition definition = WorkareaManager.getInstance().getDefinition(subModuleNode);
if ((definition != null) && definition.isRequiredPreparation() && subModuleNode.isCreated()) {
subModuleNode.prepare();
}
}
/*
* The number of children can change while iterating. Only observe the
* node children !before! the iteration begins. Any child added while
* iterating will be handled automatically if preparation is required.
* Just ensure that there will be no concurrent modification of the
* children list while iterating over it. Conclusion is a copy..
*/
final List<INavigationNode<?>> children = new ArrayList<INavigationNode<?>>(node.getChildren());
for (final INavigationNode<?> child : children) {
prepare(child);
}
}
/**
* This listener paints the shell (the border of the shell).
*/
private static class ShellPaintListener implements PaintListener {
public void paintControl(final PaintEvent e) {
onPaint(e);
}
/**
* Paints the border of the (titleless) shell.
*
* @param e
* event
*/
private void onPaint(final PaintEvent e) {
if (e.getSource() instanceof Control) {
final Control shell = (Control) e.getSource();
final Rectangle shellBounds = shell.getBounds();
final Rectangle bounds = new Rectangle(0, 0, shellBounds.width, shellBounds.height);
final ILnfRenderer borderRenderer = LnfManager.getLnf().getRenderer(
LnfKeyConstants.TITLELESS_SHELL_BORDER_RENDERER);
borderRenderer.setBounds(bounds);
borderRenderer.paint(e.gc, null);
}
}
}
public IStatusLineContentFactory getStatuslineContentFactory() {
return statuslineContentFactory;
}
}
|
diff --git a/editor-impl/src/main/java/org/cytoscape/editor/internal/CyActivator.java b/editor-impl/src/main/java/org/cytoscape/editor/internal/CyActivator.java
index 27e08e207..db0da61a8 100644
--- a/editor-impl/src/main/java/org/cytoscape/editor/internal/CyActivator.java
+++ b/editor-impl/src/main/java/org/cytoscape/editor/internal/CyActivator.java
@@ -1,120 +1,120 @@
package org.cytoscape.editor.internal;
import java.util.Properties;
import org.cytoscape.application.CyApplicationManager;
import org.cytoscape.event.CyEventHelper;
import org.cytoscape.group.CyGroupManager;
import org.cytoscape.model.CyNetworkManager;
import org.cytoscape.service.util.AbstractCyActivator;
import org.cytoscape.task.NetworkViewLocationTaskFactory;
import org.cytoscape.task.NetworkViewTaskFactory;
import org.cytoscape.task.NodeViewTaskFactory;
import org.cytoscape.task.create.CreateNetworkViewTaskFactory;
import org.cytoscape.view.model.CyNetworkViewManager;
import org.cytoscape.view.vizmap.VisualMappingManager;
import org.osgi.framework.BundleContext;
import static org.cytoscape.work.ServiceProperties.*;
public class CyActivator extends AbstractCyActivator {
public CyActivator() {
super();
}
public void start(BundleContext bc) {
CyApplicationManager cyApplicationManagerServiceRef = getService(bc, CyApplicationManager.class);
CyNetworkManager cyNetworkManagerServiceRef = getService(bc, CyNetworkManager.class);
CyNetworkViewManager cyNetworkViewManagerServiceRef = getService(bc, CyNetworkViewManager.class);
CyEventHelper cyEventHelperServiceRef = getService(bc, CyEventHelper.class);
VisualMappingManager visualMappingManagerServiceRef = getService(bc, VisualMappingManager.class);
CyGroupManager cyGroupManagerServiceRef = getService(bc, CyGroupManager.class);
CreateNetworkViewTaskFactory createNetworkViewTaskFactoryServiceRef = getService(bc, CreateNetworkViewTaskFactory.class);
SIFInterpreterTaskFactory sifInterpreterTaskFactory = new SIFInterpreterTaskFactory();
Properties sifInterpreterTaskFactoryProps = new Properties();
sifInterpreterTaskFactoryProps.setProperty(ENABLE_FOR, "networkAndView");
sifInterpreterTaskFactoryProps.setProperty(PREFERRED_ACTION, "NEW");
- sifInterpreterTaskFactoryProps.setProperty(PREFERRED_MENU, "Add");
- sifInterpreterTaskFactoryProps.setProperty(MENU_GRAVITY, "1.2");
- sifInterpreterTaskFactoryProps.setProperty(TITLE, "Add Edge (by SIF Syntax)");
+// sifInterpreterTaskFactoryProps.setProperty(PREFERRED_MENU, "Add");
+ sifInterpreterTaskFactoryProps.setProperty(MENU_GRAVITY, "2.5");
+ sifInterpreterTaskFactoryProps.setProperty(TITLE, "SIF Interpreter");
registerService(bc, sifInterpreterTaskFactory, NetworkViewTaskFactory.class, sifInterpreterTaskFactoryProps);
NetworkViewLocationTaskFactory networkViewLocationTaskFactory = new AddNodeTaskFactory(cyEventHelperServiceRef, visualMappingManagerServiceRef);
Properties networkViewLocationTaskFactoryProps = new Properties();
networkViewLocationTaskFactoryProps.setProperty(PREFERRED_ACTION, "NEW");
networkViewLocationTaskFactoryProps.setProperty(PREFERRED_MENU, "Add");
networkViewLocationTaskFactoryProps.setProperty(MENU_GRAVITY, "1.1");
networkViewLocationTaskFactoryProps.setProperty(TITLE, "Add Node");
registerService(bc, networkViewLocationTaskFactory, NetworkViewLocationTaskFactory.class, networkViewLocationTaskFactoryProps);
// We need a place to hold the objects themselves
ClipboardManagerImpl clipboardManager = new ClipboardManagerImpl();
// Copy node
NetworkViewTaskFactory copyTaskFactory =
new CopyTaskFactory(clipboardManager, cyNetworkManagerServiceRef);
Properties copyTaskFactoryProps = new Properties();
copyTaskFactoryProps.setProperty(ENABLE_FOR, "networkAndView");
copyTaskFactoryProps.setProperty(PREFERRED_ACTION, "NEW");
copyTaskFactoryProps.setProperty(PREFERRED_MENU, "Edit");
copyTaskFactoryProps.setProperty(ACCELERATOR, "cmd c");
copyTaskFactoryProps.setProperty(TITLE, "Copy");
copyTaskFactoryProps.setProperty(MENU_GRAVITY, "0.0f");
registerService(bc, copyTaskFactory, NetworkViewTaskFactory.class, copyTaskFactoryProps);
// Cut node
NetworkViewTaskFactory cutTaskFactory =
new CutTaskFactory(clipboardManager, cyNetworkManagerServiceRef);
Properties cutTaskFactoryProps = new Properties();
cutTaskFactoryProps.setProperty(ENABLE_FOR, "networkAndView");
cutTaskFactoryProps.setProperty(PREFERRED_ACTION, "NEW");
cutTaskFactoryProps.setProperty(PREFERRED_MENU, "Edit");
cutTaskFactoryProps.setProperty(ACCELERATOR, "cmd x");
cutTaskFactoryProps.setProperty(MENU_GRAVITY, "0.1f");
cutTaskFactoryProps.setProperty(TITLE, "Cut");
registerService(bc, cutTaskFactory, NetworkViewTaskFactory.class, cutTaskFactoryProps);
// Paste node
NetworkViewLocationTaskFactory pasteTaskFactory =
new PasteTaskFactory(clipboardManager, cyEventHelperServiceRef, visualMappingManagerServiceRef);
Properties pasteTaskFactoryProps = new Properties();
cutTaskFactoryProps.setProperty(ENABLE_FOR, "networkAndView");
pasteTaskFactoryProps.setProperty(PREFERRED_ACTION, "NEW");
pasteTaskFactoryProps.setProperty(PREFERRED_MENU, "Edit");
pasteTaskFactoryProps.setProperty(TITLE, "Paste");
pasteTaskFactoryProps.setProperty(MENU_GRAVITY, "0.2f");
pasteTaskFactoryProps.setProperty(ACCELERATOR, "cmd v");
pasteTaskFactoryProps.setProperty(IN_MENU_BAR, "true");
registerService(bc, pasteTaskFactory, NetworkViewLocationTaskFactory.class, pasteTaskFactoryProps);
// At some point, add Paste Special. Paste special would allow paste node only, paste copy, etc.
NodeViewTaskFactory addNestedNetworkTaskFactory =
new AddNestedNetworkTaskFactory(cyNetworkManagerServiceRef, visualMappingManagerServiceRef, cyGroupManagerServiceRef);
Properties addNestedNetworkProps = new Properties();
addNestedNetworkProps.setProperty(PREFERRED_ACTION, "NEW");
addNestedNetworkProps.setProperty(PREFERRED_MENU, "Nested Network");
addNestedNetworkProps.setProperty(TITLE, "Add Nested Network");
registerService(bc, addNestedNetworkTaskFactory, NodeViewTaskFactory.class, addNestedNetworkProps);
NodeViewTaskFactory deleteNestedNetworkTaskFactory =
new DeleteNestedNetworkTaskFactory(cyNetworkManagerServiceRef, visualMappingManagerServiceRef, cyGroupManagerServiceRef);
Properties deleteNestedNetworkProps = new Properties();
deleteNestedNetworkProps.setProperty(PREFERRED_ACTION, "NEW");
deleteNestedNetworkProps.setProperty(PREFERRED_MENU, "Nested Network");
deleteNestedNetworkProps.setProperty(TITLE, "Delete Nested Network");
registerService(bc, deleteNestedNetworkTaskFactory, NodeViewTaskFactory.class, deleteNestedNetworkProps);
NodeViewTaskFactory goToNestedNetworkTaskFactory = new GoToNestedNetworkTaskFactory(cyNetworkManagerServiceRef, cyNetworkViewManagerServiceRef, cyApplicationManagerServiceRef, createNetworkViewTaskFactoryServiceRef);
Properties goToNestedNetworkProps = new Properties();
goToNestedNetworkProps.setProperty(PREFERRED_ACTION, "NEW");
goToNestedNetworkProps.setProperty(PREFERRED_MENU, "Nested Network");
goToNestedNetworkProps.setProperty(TITLE, "Go to Nested Network");
registerService(bc, goToNestedNetworkTaskFactory, NodeViewTaskFactory.class, goToNestedNetworkProps);
}
}
| true | true | public void start(BundleContext bc) {
CyApplicationManager cyApplicationManagerServiceRef = getService(bc, CyApplicationManager.class);
CyNetworkManager cyNetworkManagerServiceRef = getService(bc, CyNetworkManager.class);
CyNetworkViewManager cyNetworkViewManagerServiceRef = getService(bc, CyNetworkViewManager.class);
CyEventHelper cyEventHelperServiceRef = getService(bc, CyEventHelper.class);
VisualMappingManager visualMappingManagerServiceRef = getService(bc, VisualMappingManager.class);
CyGroupManager cyGroupManagerServiceRef = getService(bc, CyGroupManager.class);
CreateNetworkViewTaskFactory createNetworkViewTaskFactoryServiceRef = getService(bc, CreateNetworkViewTaskFactory.class);
SIFInterpreterTaskFactory sifInterpreterTaskFactory = new SIFInterpreterTaskFactory();
Properties sifInterpreterTaskFactoryProps = new Properties();
sifInterpreterTaskFactoryProps.setProperty(ENABLE_FOR, "networkAndView");
sifInterpreterTaskFactoryProps.setProperty(PREFERRED_ACTION, "NEW");
sifInterpreterTaskFactoryProps.setProperty(PREFERRED_MENU, "Add");
sifInterpreterTaskFactoryProps.setProperty(MENU_GRAVITY, "1.2");
sifInterpreterTaskFactoryProps.setProperty(TITLE, "Add Edge (by SIF Syntax)");
registerService(bc, sifInterpreterTaskFactory, NetworkViewTaskFactory.class, sifInterpreterTaskFactoryProps);
NetworkViewLocationTaskFactory networkViewLocationTaskFactory = new AddNodeTaskFactory(cyEventHelperServiceRef, visualMappingManagerServiceRef);
Properties networkViewLocationTaskFactoryProps = new Properties();
networkViewLocationTaskFactoryProps.setProperty(PREFERRED_ACTION, "NEW");
networkViewLocationTaskFactoryProps.setProperty(PREFERRED_MENU, "Add");
networkViewLocationTaskFactoryProps.setProperty(MENU_GRAVITY, "1.1");
networkViewLocationTaskFactoryProps.setProperty(TITLE, "Add Node");
registerService(bc, networkViewLocationTaskFactory, NetworkViewLocationTaskFactory.class, networkViewLocationTaskFactoryProps);
// We need a place to hold the objects themselves
ClipboardManagerImpl clipboardManager = new ClipboardManagerImpl();
// Copy node
NetworkViewTaskFactory copyTaskFactory =
new CopyTaskFactory(clipboardManager, cyNetworkManagerServiceRef);
Properties copyTaskFactoryProps = new Properties();
copyTaskFactoryProps.setProperty(ENABLE_FOR, "networkAndView");
copyTaskFactoryProps.setProperty(PREFERRED_ACTION, "NEW");
copyTaskFactoryProps.setProperty(PREFERRED_MENU, "Edit");
copyTaskFactoryProps.setProperty(ACCELERATOR, "cmd c");
copyTaskFactoryProps.setProperty(TITLE, "Copy");
copyTaskFactoryProps.setProperty(MENU_GRAVITY, "0.0f");
registerService(bc, copyTaskFactory, NetworkViewTaskFactory.class, copyTaskFactoryProps);
// Cut node
NetworkViewTaskFactory cutTaskFactory =
new CutTaskFactory(clipboardManager, cyNetworkManagerServiceRef);
Properties cutTaskFactoryProps = new Properties();
cutTaskFactoryProps.setProperty(ENABLE_FOR, "networkAndView");
cutTaskFactoryProps.setProperty(PREFERRED_ACTION, "NEW");
cutTaskFactoryProps.setProperty(PREFERRED_MENU, "Edit");
cutTaskFactoryProps.setProperty(ACCELERATOR, "cmd x");
cutTaskFactoryProps.setProperty(MENU_GRAVITY, "0.1f");
cutTaskFactoryProps.setProperty(TITLE, "Cut");
registerService(bc, cutTaskFactory, NetworkViewTaskFactory.class, cutTaskFactoryProps);
// Paste node
NetworkViewLocationTaskFactory pasteTaskFactory =
new PasteTaskFactory(clipboardManager, cyEventHelperServiceRef, visualMappingManagerServiceRef);
Properties pasteTaskFactoryProps = new Properties();
cutTaskFactoryProps.setProperty(ENABLE_FOR, "networkAndView");
pasteTaskFactoryProps.setProperty(PREFERRED_ACTION, "NEW");
pasteTaskFactoryProps.setProperty(PREFERRED_MENU, "Edit");
pasteTaskFactoryProps.setProperty(TITLE, "Paste");
pasteTaskFactoryProps.setProperty(MENU_GRAVITY, "0.2f");
pasteTaskFactoryProps.setProperty(ACCELERATOR, "cmd v");
pasteTaskFactoryProps.setProperty(IN_MENU_BAR, "true");
registerService(bc, pasteTaskFactory, NetworkViewLocationTaskFactory.class, pasteTaskFactoryProps);
// At some point, add Paste Special. Paste special would allow paste node only, paste copy, etc.
NodeViewTaskFactory addNestedNetworkTaskFactory =
new AddNestedNetworkTaskFactory(cyNetworkManagerServiceRef, visualMappingManagerServiceRef, cyGroupManagerServiceRef);
Properties addNestedNetworkProps = new Properties();
addNestedNetworkProps.setProperty(PREFERRED_ACTION, "NEW");
addNestedNetworkProps.setProperty(PREFERRED_MENU, "Nested Network");
addNestedNetworkProps.setProperty(TITLE, "Add Nested Network");
registerService(bc, addNestedNetworkTaskFactory, NodeViewTaskFactory.class, addNestedNetworkProps);
NodeViewTaskFactory deleteNestedNetworkTaskFactory =
new DeleteNestedNetworkTaskFactory(cyNetworkManagerServiceRef, visualMappingManagerServiceRef, cyGroupManagerServiceRef);
Properties deleteNestedNetworkProps = new Properties();
deleteNestedNetworkProps.setProperty(PREFERRED_ACTION, "NEW");
deleteNestedNetworkProps.setProperty(PREFERRED_MENU, "Nested Network");
deleteNestedNetworkProps.setProperty(TITLE, "Delete Nested Network");
registerService(bc, deleteNestedNetworkTaskFactory, NodeViewTaskFactory.class, deleteNestedNetworkProps);
NodeViewTaskFactory goToNestedNetworkTaskFactory = new GoToNestedNetworkTaskFactory(cyNetworkManagerServiceRef, cyNetworkViewManagerServiceRef, cyApplicationManagerServiceRef, createNetworkViewTaskFactoryServiceRef);
Properties goToNestedNetworkProps = new Properties();
goToNestedNetworkProps.setProperty(PREFERRED_ACTION, "NEW");
goToNestedNetworkProps.setProperty(PREFERRED_MENU, "Nested Network");
goToNestedNetworkProps.setProperty(TITLE, "Go to Nested Network");
registerService(bc, goToNestedNetworkTaskFactory, NodeViewTaskFactory.class, goToNestedNetworkProps);
}
| public void start(BundleContext bc) {
CyApplicationManager cyApplicationManagerServiceRef = getService(bc, CyApplicationManager.class);
CyNetworkManager cyNetworkManagerServiceRef = getService(bc, CyNetworkManager.class);
CyNetworkViewManager cyNetworkViewManagerServiceRef = getService(bc, CyNetworkViewManager.class);
CyEventHelper cyEventHelperServiceRef = getService(bc, CyEventHelper.class);
VisualMappingManager visualMappingManagerServiceRef = getService(bc, VisualMappingManager.class);
CyGroupManager cyGroupManagerServiceRef = getService(bc, CyGroupManager.class);
CreateNetworkViewTaskFactory createNetworkViewTaskFactoryServiceRef = getService(bc, CreateNetworkViewTaskFactory.class);
SIFInterpreterTaskFactory sifInterpreterTaskFactory = new SIFInterpreterTaskFactory();
Properties sifInterpreterTaskFactoryProps = new Properties();
sifInterpreterTaskFactoryProps.setProperty(ENABLE_FOR, "networkAndView");
sifInterpreterTaskFactoryProps.setProperty(PREFERRED_ACTION, "NEW");
// sifInterpreterTaskFactoryProps.setProperty(PREFERRED_MENU, "Add");
sifInterpreterTaskFactoryProps.setProperty(MENU_GRAVITY, "2.5");
sifInterpreterTaskFactoryProps.setProperty(TITLE, "SIF Interpreter");
registerService(bc, sifInterpreterTaskFactory, NetworkViewTaskFactory.class, sifInterpreterTaskFactoryProps);
NetworkViewLocationTaskFactory networkViewLocationTaskFactory = new AddNodeTaskFactory(cyEventHelperServiceRef, visualMappingManagerServiceRef);
Properties networkViewLocationTaskFactoryProps = new Properties();
networkViewLocationTaskFactoryProps.setProperty(PREFERRED_ACTION, "NEW");
networkViewLocationTaskFactoryProps.setProperty(PREFERRED_MENU, "Add");
networkViewLocationTaskFactoryProps.setProperty(MENU_GRAVITY, "1.1");
networkViewLocationTaskFactoryProps.setProperty(TITLE, "Add Node");
registerService(bc, networkViewLocationTaskFactory, NetworkViewLocationTaskFactory.class, networkViewLocationTaskFactoryProps);
// We need a place to hold the objects themselves
ClipboardManagerImpl clipboardManager = new ClipboardManagerImpl();
// Copy node
NetworkViewTaskFactory copyTaskFactory =
new CopyTaskFactory(clipboardManager, cyNetworkManagerServiceRef);
Properties copyTaskFactoryProps = new Properties();
copyTaskFactoryProps.setProperty(ENABLE_FOR, "networkAndView");
copyTaskFactoryProps.setProperty(PREFERRED_ACTION, "NEW");
copyTaskFactoryProps.setProperty(PREFERRED_MENU, "Edit");
copyTaskFactoryProps.setProperty(ACCELERATOR, "cmd c");
copyTaskFactoryProps.setProperty(TITLE, "Copy");
copyTaskFactoryProps.setProperty(MENU_GRAVITY, "0.0f");
registerService(bc, copyTaskFactory, NetworkViewTaskFactory.class, copyTaskFactoryProps);
// Cut node
NetworkViewTaskFactory cutTaskFactory =
new CutTaskFactory(clipboardManager, cyNetworkManagerServiceRef);
Properties cutTaskFactoryProps = new Properties();
cutTaskFactoryProps.setProperty(ENABLE_FOR, "networkAndView");
cutTaskFactoryProps.setProperty(PREFERRED_ACTION, "NEW");
cutTaskFactoryProps.setProperty(PREFERRED_MENU, "Edit");
cutTaskFactoryProps.setProperty(ACCELERATOR, "cmd x");
cutTaskFactoryProps.setProperty(MENU_GRAVITY, "0.1f");
cutTaskFactoryProps.setProperty(TITLE, "Cut");
registerService(bc, cutTaskFactory, NetworkViewTaskFactory.class, cutTaskFactoryProps);
// Paste node
NetworkViewLocationTaskFactory pasteTaskFactory =
new PasteTaskFactory(clipboardManager, cyEventHelperServiceRef, visualMappingManagerServiceRef);
Properties pasteTaskFactoryProps = new Properties();
cutTaskFactoryProps.setProperty(ENABLE_FOR, "networkAndView");
pasteTaskFactoryProps.setProperty(PREFERRED_ACTION, "NEW");
pasteTaskFactoryProps.setProperty(PREFERRED_MENU, "Edit");
pasteTaskFactoryProps.setProperty(TITLE, "Paste");
pasteTaskFactoryProps.setProperty(MENU_GRAVITY, "0.2f");
pasteTaskFactoryProps.setProperty(ACCELERATOR, "cmd v");
pasteTaskFactoryProps.setProperty(IN_MENU_BAR, "true");
registerService(bc, pasteTaskFactory, NetworkViewLocationTaskFactory.class, pasteTaskFactoryProps);
// At some point, add Paste Special. Paste special would allow paste node only, paste copy, etc.
NodeViewTaskFactory addNestedNetworkTaskFactory =
new AddNestedNetworkTaskFactory(cyNetworkManagerServiceRef, visualMappingManagerServiceRef, cyGroupManagerServiceRef);
Properties addNestedNetworkProps = new Properties();
addNestedNetworkProps.setProperty(PREFERRED_ACTION, "NEW");
addNestedNetworkProps.setProperty(PREFERRED_MENU, "Nested Network");
addNestedNetworkProps.setProperty(TITLE, "Add Nested Network");
registerService(bc, addNestedNetworkTaskFactory, NodeViewTaskFactory.class, addNestedNetworkProps);
NodeViewTaskFactory deleteNestedNetworkTaskFactory =
new DeleteNestedNetworkTaskFactory(cyNetworkManagerServiceRef, visualMappingManagerServiceRef, cyGroupManagerServiceRef);
Properties deleteNestedNetworkProps = new Properties();
deleteNestedNetworkProps.setProperty(PREFERRED_ACTION, "NEW");
deleteNestedNetworkProps.setProperty(PREFERRED_MENU, "Nested Network");
deleteNestedNetworkProps.setProperty(TITLE, "Delete Nested Network");
registerService(bc, deleteNestedNetworkTaskFactory, NodeViewTaskFactory.class, deleteNestedNetworkProps);
NodeViewTaskFactory goToNestedNetworkTaskFactory = new GoToNestedNetworkTaskFactory(cyNetworkManagerServiceRef, cyNetworkViewManagerServiceRef, cyApplicationManagerServiceRef, createNetworkViewTaskFactoryServiceRef);
Properties goToNestedNetworkProps = new Properties();
goToNestedNetworkProps.setProperty(PREFERRED_ACTION, "NEW");
goToNestedNetworkProps.setProperty(PREFERRED_MENU, "Nested Network");
goToNestedNetworkProps.setProperty(TITLE, "Go to Nested Network");
registerService(bc, goToNestedNetworkTaskFactory, NodeViewTaskFactory.class, goToNestedNetworkProps);
}
|
diff --git a/src/com/modcrafting/ultrabans/commands/Mute.java b/src/com/modcrafting/ultrabans/commands/Mute.java
index 9e7adee..deccb9c 100644
--- a/src/com/modcrafting/ultrabans/commands/Mute.java
+++ b/src/com/modcrafting/ultrabans/commands/Mute.java
@@ -1,95 +1,95 @@
package com.modcrafting.ultrabans.commands;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import com.modcrafting.ultrabans.UltraBan;
public class Mute implements CommandExecutor {
public static final Logger log = Logger.getLogger("Minecraft");
UltraBan plugin;
String permission = "ultraban.mute";
public Mute(UltraBan ultraBan) {
this.plugin = ultraBan;
}
public boolean autoComplete;
public String expandName(String p) {
int m = 0;
String Result = "";
for (int n = 0; n < plugin.getServer().getOnlinePlayers().length; n++) {
String str = plugin.getServer().getOnlinePlayers()[n].getName();
if (str.matches("(?i).*" + p + ".*")) {
m++;
Result = str;
if(m==2) {
return null;
}
}
if (str.equalsIgnoreCase(p))
return str;
}
if (m == 1)
return Result;
if (m > 1) {
return null;
}
if (m < 1) {
return p;
}
return p;
}
public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) {
YamlConfiguration config = (YamlConfiguration) plugin.getConfig();
boolean auth = false;
Player player = null;
String admin = config.getString("defAdminName", "server");
if (sender instanceof Player){
player = (Player)sender;
if(player.hasPermission(permission) || player.isOp()) auth = true;
admin = player.getName();
}else{
auth = true; //if sender is not a player - Console
}
if (!auth){
sender.sendMessage(ChatColor.RED + "You do not have the required permissions.");
return true;
}
if (args.length < 1) return false;
String p = expandName(args[0]);
Player victim = plugin.getServer().getPlayer(p);
if(victim != null){
if (plugin.muted.contains(p.toLowerCase())){
- plugin.muted.remove(p);
+ plugin.muted.remove(p.toLowerCase());
String adminMsg = config.getString("messages.unmuteMsgVictim", "You have been unmuted.");
victim.sendMessage(ChatColor.GRAY + adminMsg);
String adminMsgs = config.getString("messages.unmuteMsg", "You have unmuted %victim%.");
adminMsgs = adminMsgs.replaceAll("%victim%", p);
sender.sendMessage(ChatColor.GRAY + adminMsgs);
return true;
}
plugin.muted.add(p.toLowerCase());
String adminMsg = config.getString("messages.muteChatMsg", "You have been muted.");
victim.sendMessage(ChatColor.GRAY + adminMsg);
String adminMsgs = config.getString("messages.muteMsg", "You have muted %victim%.");
adminMsgs = adminMsgs.replaceAll("%victim%", p);
sender.sendMessage(ChatColor.GRAY + adminMsgs);
log.log(Level.INFO, "[UltraBan] " + admin + " muted player " + p + ".");
plugin.db.addPlayer(p, "Muted", admin, 0, 7);
return true;
}else{
sender.sendMessage(ChatColor.GRAY + "Player must be online!");
return true;
}
}
}
| true | true | public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) {
YamlConfiguration config = (YamlConfiguration) plugin.getConfig();
boolean auth = false;
Player player = null;
String admin = config.getString("defAdminName", "server");
if (sender instanceof Player){
player = (Player)sender;
if(player.hasPermission(permission) || player.isOp()) auth = true;
admin = player.getName();
}else{
auth = true; //if sender is not a player - Console
}
if (!auth){
sender.sendMessage(ChatColor.RED + "You do not have the required permissions.");
return true;
}
if (args.length < 1) return false;
String p = expandName(args[0]);
Player victim = plugin.getServer().getPlayer(p);
if(victim != null){
if (plugin.muted.contains(p.toLowerCase())){
plugin.muted.remove(p);
String adminMsg = config.getString("messages.unmuteMsgVictim", "You have been unmuted.");
victim.sendMessage(ChatColor.GRAY + adminMsg);
String adminMsgs = config.getString("messages.unmuteMsg", "You have unmuted %victim%.");
adminMsgs = adminMsgs.replaceAll("%victim%", p);
sender.sendMessage(ChatColor.GRAY + adminMsgs);
return true;
}
plugin.muted.add(p.toLowerCase());
String adminMsg = config.getString("messages.muteChatMsg", "You have been muted.");
victim.sendMessage(ChatColor.GRAY + adminMsg);
String adminMsgs = config.getString("messages.muteMsg", "You have muted %victim%.");
adminMsgs = adminMsgs.replaceAll("%victim%", p);
sender.sendMessage(ChatColor.GRAY + adminMsgs);
log.log(Level.INFO, "[UltraBan] " + admin + " muted player " + p + ".");
plugin.db.addPlayer(p, "Muted", admin, 0, 7);
return true;
}else{
sender.sendMessage(ChatColor.GRAY + "Player must be online!");
return true;
}
}
| public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) {
YamlConfiguration config = (YamlConfiguration) plugin.getConfig();
boolean auth = false;
Player player = null;
String admin = config.getString("defAdminName", "server");
if (sender instanceof Player){
player = (Player)sender;
if(player.hasPermission(permission) || player.isOp()) auth = true;
admin = player.getName();
}else{
auth = true; //if sender is not a player - Console
}
if (!auth){
sender.sendMessage(ChatColor.RED + "You do not have the required permissions.");
return true;
}
if (args.length < 1) return false;
String p = expandName(args[0]);
Player victim = plugin.getServer().getPlayer(p);
if(victim != null){
if (plugin.muted.contains(p.toLowerCase())){
plugin.muted.remove(p.toLowerCase());
String adminMsg = config.getString("messages.unmuteMsgVictim", "You have been unmuted.");
victim.sendMessage(ChatColor.GRAY + adminMsg);
String adminMsgs = config.getString("messages.unmuteMsg", "You have unmuted %victim%.");
adminMsgs = adminMsgs.replaceAll("%victim%", p);
sender.sendMessage(ChatColor.GRAY + adminMsgs);
return true;
}
plugin.muted.add(p.toLowerCase());
String adminMsg = config.getString("messages.muteChatMsg", "You have been muted.");
victim.sendMessage(ChatColor.GRAY + adminMsg);
String adminMsgs = config.getString("messages.muteMsg", "You have muted %victim%.");
adminMsgs = adminMsgs.replaceAll("%victim%", p);
sender.sendMessage(ChatColor.GRAY + adminMsgs);
log.log(Level.INFO, "[UltraBan] " + admin + " muted player " + p + ".");
plugin.db.addPlayer(p, "Muted", admin, 0, 7);
return true;
}else{
sender.sendMessage(ChatColor.GRAY + "Player must be online!");
return true;
}
}
|
diff --git a/restful-gwt/gwt-persistence/src/main/java/de/saumya/gwt/persistence/client/AbstractResource.java b/restful-gwt/gwt-persistence/src/main/java/de/saumya/gwt/persistence/client/AbstractResource.java
index 33ad6ac..a1eabca 100644
--- a/restful-gwt/gwt-persistence/src/main/java/de/saumya/gwt/persistence/client/AbstractResource.java
+++ b/restful-gwt/gwt-persistence/src/main/java/de/saumya/gwt/persistence/client/AbstractResource.java
@@ -1,341 +1,340 @@
/**
*
*/
package de.saumya.gwt.persistence.client;
import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.HashSet;
import java.util.Set;
import com.google.gwt.xml.client.Document;
import com.google.gwt.xml.client.Element;
import com.google.gwt.xml.client.Node;
import com.google.gwt.xml.client.NodeList;
import com.google.gwt.xml.client.XMLParser;
public abstract class AbstractResource<E extends AbstractResource<E>> {
static final String INDENT = " ";
protected enum State {
NEW, TO_BE_CREATED, TO_BE_UPDATED, UP_TO_DATE, TO_BE_DELETED, DELETED, TO_BE_LOADED, STALE;
}
private final Set<ResourceChangeListener<E>> listeners = new HashSet<ResourceChangeListener<E>>();
final Repository repository;
final AbstractResourceFactory<E> factory;
protected State state = State.NEW;
protected AbstractResource(final Repository repository,
final AbstractResourceFactory<E> factory) {
this.repository = repository;
this.factory = factory;
}
public final boolean isImmutable() {
return this.factory.isImmutable();
}
public boolean isNew() {
return this.state == State.NEW; // || this.state == State.TO_BE_CREATED;
}
public boolean isUptodate() {
return this.state == State.UP_TO_DATE;
}
public boolean isDeleted() {
return this.state == State.DELETED;
}
public void save() {
switch (this.state) {
case NEW:
case TO_BE_CREATED:
this.state = State.TO_BE_CREATED;
post();
break;
case UP_TO_DATE:
case TO_BE_UPDATED:
case TO_BE_DELETED:
this.state = State.TO_BE_UPDATED;
put();
break;
default:
throw new IllegalStateException("can not save in state "
+ this.state);
}
}
public void save(final String verb) {
switch (this.state) {
case UP_TO_DATE:
case TO_BE_UPDATED:
this.state = State.TO_BE_UPDATED;
put(verb);
break;
default:
throw new IllegalStateException("can not save with verb " + verb
+ " in state " + this.state);
}
}
public void destroy() {
switch (this.state) {
case UP_TO_DATE:
case TO_BE_DELETED:
this.state = State.TO_BE_DELETED;
delete();
break;
default:
throw new IllegalStateException("can not delete with state "
+ this.state);
}
}
public void fromXml(final String xml) {
final Document doc = XMLParser.parse(xml);
fromRootElement(doc.getDocumentElement());
}
void fromRootElement(final Element root) {
fromElement(root);
}
public String toXml() {
final StringBuilder buf = new StringBuilder();
toXml(buf);
return buf.toString();
}
/**
* bit strange from object hierarchy point of view but convenient to share
* the same methods in all implementations !!!
*/
protected void appendXml(final StringBuilder buf, final String name,
final Resource<?> value) {
if (value != null) {
buf.append("<").append(name).append(">");
value.appendXml(buf, "id", value.id);
value.appendXml(buf);
buf.append("</").append(name).append(">");
}
}
/**
* bit strange from object hierarchy point of view but convenient to share
* the same methods in all implementations !!!
*/
protected void appendXml(final StringBuilder buf, final String name,
final SingletonResource<?> value) {
if (value != null) {
buf.append("<").append(name).append(">");
value.appendXml(buf);
buf.append("</").append(name).append(">");
}
}
/**
* bit strange from object hierarchy point of view but convenient to share
* the same methods in all implementations !!!
*/
protected void appendXml(final StringBuilder buf, final String name,
final AnonymousResource<?> value) {
if (value != null) {
buf.append("<").append(name).append(">");
value.appendXml(buf);
buf.append("</").append(name).append(">");
}
}
protected void appendXml(final StringBuilder buf, final String name,
final ResourceCollection<?> value) {
if (value != null) {
value.toXml(buf);
}
else {
buf.append("<").append(name).append(">");
buf.append("</").append(name).append(">");
}
}
protected void appendXml(final StringBuilder buf, final String name,
final String value) {
// follow what the browser does with empty strings: do not send them
if (value != null && !"".equals(value)) {
buf.append("<")
.append(name)
.append(">")
.append(value)
.append("</")
.append(name)
.append(">");
}
}
protected void appendXml(final StringBuilder buf, final String name,
final Object value) {
if (value != null) {
appendXml(buf, name, value.toString());
}
}
protected void toString(final String indent, final StringBuilder buf,
final String name, final AbstractResource<?> value) {
if (value != null) {
buf.append("\n")
.append(indent)
.append(":")
.append(name)
.append(" => ");
value.toStringRoot(indent, buf);
}
}
protected void toString(final String indent, final StringBuilder buf,
final String name, final ResourceCollection<?> value) {
if (value != null) {
buf.append("\n")
.append(indent)
.append(":")
.append(name)
.append(" => [\n");
boolean first = true;
final String nextIndent = indent + INDENT;
for (final AbstractResource<?> resource : value) {
if (first) {
- buf.append(indent).append(INDENT);
first = false;
}
else {
buf.append(",\n");
}
resource.toStringRoot(nextIndent, buf);
}
buf.append(first ? "" : "\n").append(indent).append("]");
}
}
protected void toString(final String indent, final StringBuilder buf,
final String name, final String value) {
if (value != null) {
buf.append("\n")
.append(indent)
.append(":")
.append(name)
.append(" => ")
.append(value);
}
}
protected void toString(final String indent, final StringBuilder buf,
final String name, final Object value) {
if (value != null) {
toString(indent, buf, name, value.toString());
}
}
protected Timestamp getTimestamp(final Element root, final String name) {
return getTimestamp(root, name, null);
}
protected Timestamp getTimestamp(final Element root, final String name,
final Timestamp defaultValue) {
final String value = getString(root, name);
return value == null ? defaultValue : (value.matches("[0-9]*")
? new Timestamp(Long.parseLong(value))
: new TimestampFactory(value).toTimestamp());
}
protected Date getDate(final Element root, final String name) {
final String value = getString(root, name);
return value == null ? null : Date.valueOf(value);
}
protected Time getTime(final Element root, final String name) {
final String value = getString(root, name);
return value == null ? null : Time.valueOf(value);
}
protected int getInt(final Element root, final String name) {
final String value = getString(root, name);
return value == null ? 0 : Integer.parseInt(value);
}
protected boolean getBoolean(final Element root, final String name) {
final String value = getString(root, name);
return "true".equals(value);
}
protected String getString(final Element root, final String name) {
if (root == null) {
return null;
}
final NodeList list = root.getElementsByTagName(name);
for (int i = 0; i < list.getLength(); i++) {
final Node node = list.item(i);
if (node.getParentNode().equals(root)) {
return node.getFirstChild() == null
? null
: node.getFirstChild().getNodeValue();
}
}
return null;
}
public void addResourceChangeListener(
final ResourceChangeListener<E> listener) {
if (listener != null) {
this.listeners.add(listener);
}
}
public void removeResourceChangeListener(
final ResourceChangeListener<E> listener) {
this.listeners.remove(listener);
}
@SuppressWarnings("unchecked")
void fireResourceChangeEvents() {
for (final ResourceChangeListener<E> listener : this.listeners) {
listener.onChange((E) this);
}
this.listeners.clear();
}
@SuppressWarnings("unchecked")
void fireResourceErrorEvents(final int status, final String statusText) {
for (final ResourceChangeListener<E> listener : this.listeners) {
listener.onError(status, statusText, (E) this);
}
this.listeners.clear();
}
protected abstract void fromElement(Element root);
protected abstract void appendXml(StringBuilder buf);
protected abstract void toString(String indent, StringBuilder buf);
abstract void toStringRoot(final String indent, final StringBuilder buf);
protected abstract void post();
protected abstract void put();
protected abstract void put(String verb);
protected abstract void delete();
public abstract void reload();
public abstract void toXml(final StringBuilder buf);
public abstract String display();
}
| true | true | protected void toString(final String indent, final StringBuilder buf,
final String name, final ResourceCollection<?> value) {
if (value != null) {
buf.append("\n")
.append(indent)
.append(":")
.append(name)
.append(" => [\n");
boolean first = true;
final String nextIndent = indent + INDENT;
for (final AbstractResource<?> resource : value) {
if (first) {
buf.append(indent).append(INDENT);
first = false;
}
else {
buf.append(",\n");
}
resource.toStringRoot(nextIndent, buf);
}
buf.append(first ? "" : "\n").append(indent).append("]");
}
}
| protected void toString(final String indent, final StringBuilder buf,
final String name, final ResourceCollection<?> value) {
if (value != null) {
buf.append("\n")
.append(indent)
.append(":")
.append(name)
.append(" => [\n");
boolean first = true;
final String nextIndent = indent + INDENT;
for (final AbstractResource<?> resource : value) {
if (first) {
first = false;
}
else {
buf.append(",\n");
}
resource.toStringRoot(nextIndent, buf);
}
buf.append(first ? "" : "\n").append(indent).append("]");
}
}
|
diff --git a/core/src/main/java/org/apache/mahout/classifier/sgd/CrossFoldLearner.java b/core/src/main/java/org/apache/mahout/classifier/sgd/CrossFoldLearner.java
index 099670709..0975ad386 100644
--- a/core/src/main/java/org/apache/mahout/classifier/sgd/CrossFoldLearner.java
+++ b/core/src/main/java/org/apache/mahout/classifier/sgd/CrossFoldLearner.java
@@ -1,235 +1,237 @@
package org.apache.mahout.classifier.sgd;
import com.google.common.collect.Lists;
import org.apache.mahout.classifier.AbstractVectorClassifier;
import org.apache.mahout.classifier.OnlineLearner;
import org.apache.mahout.math.DenseVector;
import org.apache.mahout.math.Vector;
import org.apache.mahout.math.function.Functions;
import org.apache.mahout.math.stats.OnlineAuc;
import java.util.List;
/**
* Does cross-fold validation of log-likelihood and AUC on several online logistic regression
* models. Each record is passed to all but one of the models for training and to the remaining
* model for evaluation. In order to maintain proper segregation between the different folds across
* training data iterations, data should either be passed to this learner in the same order each
* time the training data is traversed or a tracking key such as the file offset of the training
* record should be passed with each training example.
*/
public class CrossFoldLearner extends AbstractVectorClassifier implements OnlineLearner {
// minimum score to be used for computing log likelihood
private static final double MIN_SCORE = 1e-50;
private int record = 0;
private OnlineAuc auc = new OnlineAuc();
private double logLikelihood;
private final List<OnlineLogisticRegression> models = Lists.newArrayList();
// lambda, learningRate, perTermOffset, perTermExponent
private double[] parameters = new double[4];
private int numFeatures;
private PriorFunction prior;
// pretty much just for GSON
public CrossFoldLearner() {
}
public CrossFoldLearner(int folds, int numCategories, int numFeatures, PriorFunction prior) {
this.numFeatures = numFeatures;
this.prior = prior;
for (int i = 0; i < folds; i++) {
OnlineLogisticRegression model = new OnlineLogisticRegression(numCategories, numFeatures, prior);
model.alpha(1).stepOffset(0).decayExponent(0);
models.add(model);
}
}
// -------- builder-like configuration methods
public CrossFoldLearner lambda(double v) {
for (OnlineLogisticRegression model : models) {
model.lambda(v);
}
return this;
}
public CrossFoldLearner learningRate(double x) {
for (OnlineLogisticRegression model : models) {
model.learningRate(x);
}
return this;
}
public CrossFoldLearner stepOffset(int x) {
for (OnlineLogisticRegression model : models) {
model.stepOffset(x);
}
return this;
}
public CrossFoldLearner decayExponent(double x) {
for (OnlineLogisticRegression model : models) {
model.decayExponent(x);
}
return this;
}
public CrossFoldLearner alpha(double alpha) {
for (OnlineLogisticRegression model : models) {
model.alpha(alpha);
}
return this;
}
// -------- training methods
@Override
public void train(int actual, Vector instance) {
train(record, actual, instance);
}
@Override
public void train(long trackingKey, int actual, Vector instance) {
record++;
int k = 0;
for (OnlineLogisticRegression model : models) {
if (k == trackingKey % models.size()) {
Vector v = model.classifyFull(instance);
- double score = v.get(actual);
+ double score = Math.max(v.get(actual), MIN_SCORE);
logLikelihood += (Math.log(score) - logLikelihood) / record;
- auc.addSample(actual, v.get(1));
+ if (numCategories() == 2) {
+ auc.addSample(actual, v.get(1));
+ }
} else {
model.train(trackingKey, actual, instance);
}
k++;
}
}
@Override
public void close() {
for (OnlineLogisticRegression m : models) {
m.close();
}
}
public void resetLineCounter() {
record = 0;
}
public boolean validModel() {
boolean r = true;
for (OnlineLogisticRegression model : models) {
r &= model.validModel();
}
return r;
}
// -------- classification methods
@Override
public Vector classify(Vector instance) {
Vector r = new DenseVector(numCategories() - 1);
double scale = 1.0 / models.size();
for (OnlineLogisticRegression model : models) {
r.assign(model.classify(instance), Functions.plusMult(scale));
}
return r;
}
@Override
public double classifyScalar(Vector instance) {
double r = 0;
int n = 0;
for (OnlineLogisticRegression model : models) {
n++;
r += model.classifyScalar(instance);
}
return r / n;
}
// -------- status reporting methods
@Override
public int numCategories() {
return models.get(0).numCategories();
}
public double auc() {
return auc.auc();
}
public double logLikelihood() {
return logLikelihood;
}
// -------- evolutionary optimization
public CrossFoldLearner copy() {
CrossFoldLearner r = new CrossFoldLearner(models.size(), numCategories(), numFeatures, prior);
r.models.clear();
for (OnlineLogisticRegression model : models) {
model.close();
OnlineLogisticRegression newModel = new OnlineLogisticRegression(model.numCategories(), model.numFeatures(), model.prior);
newModel.copyFrom(model);
r.models.add(newModel);
}
return r;
}
public int getRecord() {
return record;
}
public void setRecord(int record) {
this.record = record;
}
public OnlineAuc getAuc() {
return auc;
}
public void setAuc(OnlineAuc auc) {
this.auc = auc;
}
public double getLogLikelihood() {
return logLikelihood;
}
public void setLogLikelihood(double logLikelihood) {
this.logLikelihood = logLikelihood;
}
public List<OnlineLogisticRegression> getModels() {
return models;
}
public void addModel(OnlineLogisticRegression model) {
models.add(model);
}
public double[] getParameters() {
return parameters;
}
public void setParameters(double[] parameters) {
this.parameters = parameters;
}
public int getNumFeatures() {
return numFeatures;
}
public void setNumFeatures(int numFeatures) {
this.numFeatures = numFeatures;
}
public PriorFunction getPrior() {
return prior;
}
public void setPrior(PriorFunction prior) {
this.prior = prior;
}
}
| false | true | public void train(long trackingKey, int actual, Vector instance) {
record++;
int k = 0;
for (OnlineLogisticRegression model : models) {
if (k == trackingKey % models.size()) {
Vector v = model.classifyFull(instance);
double score = v.get(actual);
logLikelihood += (Math.log(score) - logLikelihood) / record;
auc.addSample(actual, v.get(1));
} else {
model.train(trackingKey, actual, instance);
}
k++;
}
}
| public void train(long trackingKey, int actual, Vector instance) {
record++;
int k = 0;
for (OnlineLogisticRegression model : models) {
if (k == trackingKey % models.size()) {
Vector v = model.classifyFull(instance);
double score = Math.max(v.get(actual), MIN_SCORE);
logLikelihood += (Math.log(score) - logLikelihood) / record;
if (numCategories() == 2) {
auc.addSample(actual, v.get(1));
}
} else {
model.train(trackingKey, actual, instance);
}
k++;
}
}
|
diff --git a/src/net/sf/freecol/client/gui/menu/DebugMenu.java b/src/net/sf/freecol/client/gui/menu/DebugMenu.java
index 447a4446c..111c5268a 100644
--- a/src/net/sf/freecol/client/gui/menu/DebugMenu.java
+++ b/src/net/sf/freecol/client/gui/menu/DebugMenu.java
@@ -1,536 +1,545 @@
/**
* Copyright (C) 2002-2007 The FreeCol Team
*
* This file is part of FreeCol.
*
* FreeCol 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.
*
* FreeCol 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 FreeCol. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.freecol.client.gui.menu;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import javax.swing.ButtonGroup;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.KeyStroke;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import net.sf.freecol.FreeCol;
import net.sf.freecol.client.FreeColClient;
import net.sf.freecol.client.gui.Canvas;
import net.sf.freecol.client.gui.GUI;
import net.sf.freecol.client.gui.i18n.Messages;
import net.sf.freecol.client.gui.panel.ChoiceItem;
import net.sf.freecol.client.gui.panel.MonarchPanel;
import net.sf.freecol.client.gui.panel.StatisticsPanel;
import net.sf.freecol.client.gui.panel.VictoryPanel;
import net.sf.freecol.common.PseudoRandom;
import net.sf.freecol.common.model.Colony;
import net.sf.freecol.common.model.FoundingFather;
import net.sf.freecol.common.model.Map;
import net.sf.freecol.common.model.Monarch;
import net.sf.freecol.common.model.Player;
import net.sf.freecol.common.model.Tile;
import net.sf.freecol.common.model.Unit;
import net.sf.freecol.common.model.Map.Position;
import net.sf.freecol.common.model.Unit.UnitState;
import net.sf.freecol.server.ai.AIUnit;
public class DebugMenu extends JMenu {
private FreeColClient freeColClient;
private final Canvas canvas;
private final GUI gui;
private JMenuItem skipTurnsMenuItem;
public DebugMenu(FreeColClient fcc) {
super(Messages.message("menuBar.debug"));
this.freeColClient = fcc;
gui = freeColClient.getGUI();
canvas = freeColClient.getCanvas();
buildDebugMenu();
}
private void stepRNG() {
PseudoRandom clientRnd = freeColClient
.getGame().getModelController().getPseudoRandom();
PseudoRandom serverRnd = freeColClient.getFreeColServer()
.getGame().getModelController().getPseudoRandom();
boolean more = false;
do {
int cVal = clientRnd.nextInt(100);
int sVal = serverRnd.nextInt(100);
String value = Integer.toString(cVal) + ":" + Integer.toString(sVal);
more = canvas.showConfirmDialog("menuBar.debug.stepRandomNumberGenerator",
"more", "ok",
"%value%", value);
} while (more);
}
private void buildDebugMenu() {
this.setOpaque(false);
this.setMnemonic(KeyEvent.VK_D);
add(this);
JMenu debugFixMenu = new JMenu("Fixes");
debugFixMenu.setOpaque(false);
debugFixMenu.setMnemonic(KeyEvent.VK_F);
this.add(debugFixMenu);
final JMenuItem crossBug = new JCheckBoxMenuItem("Fix \"not enough crosses\"-bug");
crossBug.setOpaque(false);
crossBug.setMnemonic(KeyEvent.VK_B);
debugFixMenu.add(crossBug);
crossBug.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
freeColClient.getMyPlayer().updateImmigrationRequired();
if (freeColClient.getFreeColServer() != null) {
Iterator<Player> pi = freeColClient.getFreeColServer().getGame().getPlayerIterator();
while (pi.hasNext()) {
pi.next().updateImmigrationRequired();
}
}
}
});
this.addSeparator();
JCheckBoxMenuItem sc = new JCheckBoxMenuItem(Messages.message("menuBar.debug.showCoordinates"),
gui.displayCoordinates);
sc.setOpaque(false);
sc.setMnemonic(KeyEvent.VK_S);
this.add(sc);
sc.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
gui.displayCoordinates = ((JCheckBoxMenuItem) e.getSource()).isSelected();
canvas.refresh();
}
});
final JCheckBoxMenuItem dami = new JCheckBoxMenuItem("Additional AI-mission info", gui.debugShowMissionInfo);
dami.setOpaque(false);
dami.setMnemonic(KeyEvent.VK_I);
dami.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
gui.debugShowMissionInfo = ((JCheckBoxMenuItem) e.getSource()).isSelected();
canvas.refresh();
}
});
JCheckBoxMenuItem dam = new JCheckBoxMenuItem("Display AI-missions", gui.debugShowMission);
dam.setOpaque(false);
dam.setMnemonic(KeyEvent.VK_M);
this.add(dam);
dam.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
gui.debugShowMission = ((JCheckBoxMenuItem) e.getSource()).isSelected();
dami.setEnabled(gui.debugShowMission);
canvas.refresh();
}
});
this.add(dami);
dami.setEnabled(gui.debugShowMission);
final JMenuItem reveal = new JCheckBoxMenuItem(Messages.message("menuBar.debug.revealEntireMap"));
reveal.setOpaque(false);
reveal.setMnemonic(KeyEvent.VK_R);
this.add(reveal);
reveal.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (freeColClient.getFreeColServer() != null) {
freeColClient.getFreeColServer().revealMapForAllPlayers();
}
reveal.setEnabled(false);
}
});
JMenu cvpMenu = new JMenu(Messages.message("menuBar.debug.showColonyValue"));
cvpMenu.setOpaque(false);
ButtonGroup bg = new ButtonGroup();
JRadioButtonMenuItem cv1 = new JRadioButtonMenuItem("Do not display", !gui.displayColonyValue);
cv1.setOpaque(false);
cv1.setMnemonic(KeyEvent.VK_C);
cvpMenu.add(cv1);
bg.add(cv1);
cv1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
gui.displayColonyValue = false;
gui.displayColonyValuePlayer = null;
canvas.refresh();
}
});
add(cvpMenu);
JRadioButtonMenuItem cv3 = new JRadioButtonMenuItem("Common outpost value", gui.displayColonyValue
&& gui.displayColonyValuePlayer == null);
cv3.setOpaque(false);
cv3.setMnemonic(KeyEvent.VK_C);
cvpMenu.add(cv3);
bg.add(cv3);
cv3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
gui.displayColonyValue = true;
gui.displayColonyValuePlayer = null;
canvas.refresh();
}
});
this.add(cvpMenu);
cvpMenu.addSeparator();
Iterator<Player> it = freeColClient.getGame().getPlayerIterator();
while (it.hasNext()) {
final Player p = it.next();
if (p.isEuropean() && p.canBuildColonies()) {
JRadioButtonMenuItem cv2 = new JRadioButtonMenuItem(p.getNationAsString(),
gui.displayColonyValue && gui.displayColonyValuePlayer == p);
cv2.setOpaque(false);
cv2.setMnemonic(KeyEvent.VK_C);
cvpMenu.add(cv2);
bg.add(cv2);
cv2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
gui.displayColonyValue = true;
gui.displayColonyValuePlayer = p;
canvas.refresh();
}
});
}
}
this.addSeparator();
setupSkipTurnsMenuItem();
if (freeColClient.getFreeColServer() != null) {
final JMenuItem giveBells = new JMenuItem("Adds 100 bells to each Colony");
giveBells.setOpaque(false);
giveBells.setMnemonic(KeyEvent.VK_B);
this.add(giveBells);
giveBells.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for (Colony c : freeColClient.getMyPlayer().getColonies()) {
c.addLiberty(100);
Colony sc = (Colony) freeColClient.getFreeColServer().getGame().getFreeColGameObject(c.getId());
sc.addLiberty(100);
}
}
});
}
final JMenuItem addFather = new JMenuItem("Add Founding Father");
addFather.setOpaque(false);
addFather.setMnemonic(KeyEvent.VK_F);
this.add(addFather);
addFather.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Player player = freeColClient.getMyPlayer();
List<ChoiceItem<FoundingFather>> fathers = new ArrayList<ChoiceItem<FoundingFather>>();
for (FoundingFather father : FreeCol.getSpecification().getFoundingFathers()) {
if (!player.hasFather(father)) {
fathers.add(new ChoiceItem<FoundingFather>(father.getName(), father));
}
}
FoundingFather fatherToAdd = freeColClient.getCanvas()
.showChoiceDialog("Select Founding Father", "cancel", fathers);
player.addFather(fatherToAdd);
Player serverPlayer = (Player) freeColClient.getFreeColServer().getGame().
getFreeColGameObject(player.getId());
serverPlayer.addFather(fatherToAdd);
}
});
final JMenuItem addCrosses = new JMenuItem("Add Immigration");
addCrosses.setOpaque(false);
// addCrosses.setMnemonic(KeyEvent.VK_????);
this.add(addCrosses);
addCrosses.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String response = freeColClient.getCanvas()
.showInputDialog("menuBar.debug.addImmigration",
Integer.toString(100),
"ok", "cancel");
Player player = freeColClient.getMyPlayer();
int crosses = Integer.parseInt(response);
Player serverPlayer = (Player) freeColClient.getFreeColServer()
.getGame().getFreeColGameObject(player.getId());
player.incrementImmigration(crosses);
serverPlayer.incrementImmigration(crosses);
}
});
// random number generator
final JMenuItem rng = new JMenuItem("Step random number generator");
rng.setOpaque(false);
rng.setMnemonic(KeyEvent.VK_X);
this.add(rng);
rng.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
stepRNG();
}
});
this.addSeparator();
JMenu panelMenu = new JMenu("Display panels");
panelMenu.setOpaque(false);
final JMenuItem monarchPanel = new JMenuItem("Display Monarch panel");
monarchPanel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
canvas.showFreeColDialog(new MonarchPanel(canvas, Monarch.MonarchAction.RAISE_TAX));
}
});
panelMenu.add(monarchPanel);
final JMenuItem victoryPanel = new JMenuItem("Display Victory panel");
monarchPanel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
canvas.showPanel(new VictoryPanel(canvas));
}
});
panelMenu.add(victoryPanel);
add(panelMenu);
final JMenuItem europeStatus = new JMenuItem("Display Europe Status");
europeStatus.setOpaque(false);
europeStatus.setMnemonic(KeyEvent.VK_E);
this.add(europeStatus);
europeStatus.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (freeColClient.getFreeColServer() != null) {
net.sf.freecol.server.ai.AIMain aiMain = freeColClient.getFreeColServer().getAIMain();
StringBuilder sb = new StringBuilder();
for (Player tp : freeColClient.getGame().getPlayers()) {
final Player p = (Player) freeColClient.getFreeColServer().getGame().getFreeColGameObject(tp.getId());
if (p.getEurope() == null) {
continue;
}
List<Unit> inEurope = new ArrayList<Unit>();
List<Unit> toEurope = new ArrayList<Unit>();
List<Unit> toAmerica = new ArrayList<Unit>();
LinkedHashMap<String,List<Unit>> units = new LinkedHashMap<String, List<Unit>>();
units.put("To Europe", toEurope);
units.put("In Europe", inEurope);
units.put("To America", toAmerica);
sb.append("\n==");
sb.append(p.getNationAsString());
sb.append("==\n");
for(Unit u : p.getEurope().getUnitList()){
if(u.getState() == UnitState.TO_AMERICA){
toAmerica.add(u);
continue;
}
if(u.getState() == UnitState.TO_EUROPE){
toEurope.add(u);
continue;
}
inEurope.add(u);
}
for(String label : units.keySet()){
List<Unit> list = units.get(label);
if(list.size() > 0){
sb.append("\n->" + label + "\n");
for(Unit u : list){
sb.append('\n');
sb.append(u.getName());
if(u.isUnderRepair()){
sb.append(" (Repairing)");
}
- sb.append(" " + ((AIUnit) aiMain.getAIObject(u)).getMission().toString().replaceAll("\n", " \n"));
+ else{
+ sb.append(" ");
+ AIUnit aiu = (AIUnit) aiMain.getAIObject(u);
+ if(aiu.getMission() == null){
+ sb.append(" (None)");
+ }
+ else{
+ sb.append(aiu.getMission().toString().replaceAll("\n", " \n"));
+ }
+ }
}
sb.append('\n');
}
}
}
canvas.showInformationMessage(sb.toString());
}
}
});
final JMenuItem useAI = new JMenuItem("Use AI");
useAI.setOpaque(false);
useAI.setMnemonic(KeyEvent.VK_A);
useAI.setAccelerator(KeyStroke.getKeyStroke('A', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()
| InputEvent.ALT_MASK));
this.add(useAI);
useAI.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (freeColClient.getFreeColServer() != null) {
net.sf.freecol.server.ai.AIMain aiMain = freeColClient.getFreeColServer().getAIMain();
net.sf.freecol.server.ai.AIPlayer ap = (net.sf.freecol.server.ai.AIPlayer) aiMain
.getAIObject(freeColClient.getMyPlayer().getId());
ap.setDebuggingConnection(freeColClient.getClient().getConnection());
ap.startWorking();
freeColClient.getConnectController().reconnect();
}
}
});
this.addSeparator();
final JMenuItem compareMaps = new JMenuItem(Messages.message("menuBar.debug.compareMaps"));
compareMaps.setOpaque(false);
compareMaps.setMnemonic(KeyEvent.VK_C);
compareMaps.setAccelerator(KeyStroke.getKeyStroke('C', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()
| InputEvent.ALT_MASK));
this.add(compareMaps);
compareMaps.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
boolean problemDetected = false;
Map serverMap = freeColClient.getFreeColServer().getGame().getMap();
Player myServerPlayer = (Player) freeColClient.getFreeColServer().getGame().getFreeColGameObject(
freeColClient.getMyPlayer().getId());
Iterator<Position> it = serverMap.getWholeMapIterator();
while (it.hasNext()) {
Tile t = serverMap.getTile(it.next());
if (myServerPlayer.canSee(t)) {
Iterator<Unit> unitIterator = t.getUnitIterator();
while (unitIterator.hasNext()) {
Unit u = unitIterator.next();
if (u.isVisibleTo(myServerPlayer)) {
if (freeColClient.getGame().getFreeColGameObject(u.getId()) == null) {
System.out.println("Unsynchronization detected: Unit missing on client-side");
System.out.println(u.getName() + "(" + u.getId() + "). Position: "
+ u.getTile().getPosition());
try {
System.out.println("Possible unit on client-side: "
+ freeColClient.getGame().getMap().getTile(u.getTile().getPosition())
.getFirstUnit().getId());
} catch (NullPointerException npe) {
}
System.out.println();
problemDetected = true;
} else {
Unit clientSideUnit = (Unit) freeColClient.getGame()
.getFreeColGameObject(u.getId());
if (clientSideUnit.getTile() != null
&& !clientSideUnit.getTile().getId().equals(u.getTile().getId())) {
System.out
.println("Unsynchronization detected: Unit located on different tiles");
System.out.println("Server: " + u.getName() + "(" + u.getId() + "). Position: "
+ u.getTile().getPosition());
System.out.println("Client: " + clientSideUnit.getName() + "("
+ clientSideUnit.getId() + "). Position: "
+ clientSideUnit.getTile().getPosition());
System.out.println();
problemDetected = true;
}
}
}
}
}
}
if (problemDetected) {
canvas.showInformationMessage("menuBar.debug.compareMaps.problem");
} else {
canvas.showInformationMessage("menuBar.debug.compareMaps.checkComplete");
}
}
});
// statistics
final JMenuItem statistics = new JMenuItem("Statistics");
statistics.setOpaque(false);
statistics.setMnemonic(KeyEvent.VK_I);
this.add(statistics);
statistics.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
canvas.showPanel(new StatisticsPanel(canvas));
}
});
// garbage collector
final JMenuItem gc = new JMenuItem(Messages.message("menuBar.debug.memoryManager.gc"));
gc.setOpaque(false);
gc.setMnemonic(KeyEvent.VK_G);
this.add(gc);
gc.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.gc();
}
});
this.addSeparator();
final JMenuItem loadResource = new JMenuItem("Reload images");
loadResource.setOpaque(false);
this.add(loadResource);
loadResource.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
canvas.getImageLibrary().init();
} catch (Exception ex) {
System.out.println("Failed to reload images.");
}
}
});
}
private void setupSkipTurnsMenuItem() {
skipTurnsMenuItem = new JMenuItem("Skip turns");
skipTurnsMenuItem.setOpaque(false);
skipTurnsMenuItem.setMnemonic(KeyEvent.VK_S);
this.add(skipTurnsMenuItem);
if (freeColClient.getFreeColServer() == null){
skipTurnsMenuItem.setEnabled(false);
return;
}
skipTurnsMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
boolean isSkipping = freeColClient.getFreeColServer().getInGameController().debugOnlyAITurns != 0;
if(isSkipping){
freeColClient.getFreeColServer().getInGameController().debugOnlyAITurns = 0;
return;
}
int skipTurns = Integer.parseInt(freeColClient.getCanvas().showInputDialog(
"How many turns should be skipped:", Integer.toString(10), "ok", "cancel"));
freeColClient.getFreeColServer().getInGameController().debugOnlyAITurns = skipTurns;
freeColClient.getInGameController().endTurn();
}
});
this.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
boolean skippingTurns = freeColClient.getFreeColServer().getInGameController().debugOnlyAITurns != 0;
String skipMenuItemStr = (skippingTurns)? "Stop skipping" : "Skip turns";
skipTurnsMenuItem.setText(skipMenuItemStr);
}
});
}
}
| true | true | private void buildDebugMenu() {
this.setOpaque(false);
this.setMnemonic(KeyEvent.VK_D);
add(this);
JMenu debugFixMenu = new JMenu("Fixes");
debugFixMenu.setOpaque(false);
debugFixMenu.setMnemonic(KeyEvent.VK_F);
this.add(debugFixMenu);
final JMenuItem crossBug = new JCheckBoxMenuItem("Fix \"not enough crosses\"-bug");
crossBug.setOpaque(false);
crossBug.setMnemonic(KeyEvent.VK_B);
debugFixMenu.add(crossBug);
crossBug.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
freeColClient.getMyPlayer().updateImmigrationRequired();
if (freeColClient.getFreeColServer() != null) {
Iterator<Player> pi = freeColClient.getFreeColServer().getGame().getPlayerIterator();
while (pi.hasNext()) {
pi.next().updateImmigrationRequired();
}
}
}
});
this.addSeparator();
JCheckBoxMenuItem sc = new JCheckBoxMenuItem(Messages.message("menuBar.debug.showCoordinates"),
gui.displayCoordinates);
sc.setOpaque(false);
sc.setMnemonic(KeyEvent.VK_S);
this.add(sc);
sc.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
gui.displayCoordinates = ((JCheckBoxMenuItem) e.getSource()).isSelected();
canvas.refresh();
}
});
final JCheckBoxMenuItem dami = new JCheckBoxMenuItem("Additional AI-mission info", gui.debugShowMissionInfo);
dami.setOpaque(false);
dami.setMnemonic(KeyEvent.VK_I);
dami.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
gui.debugShowMissionInfo = ((JCheckBoxMenuItem) e.getSource()).isSelected();
canvas.refresh();
}
});
JCheckBoxMenuItem dam = new JCheckBoxMenuItem("Display AI-missions", gui.debugShowMission);
dam.setOpaque(false);
dam.setMnemonic(KeyEvent.VK_M);
this.add(dam);
dam.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
gui.debugShowMission = ((JCheckBoxMenuItem) e.getSource()).isSelected();
dami.setEnabled(gui.debugShowMission);
canvas.refresh();
}
});
this.add(dami);
dami.setEnabled(gui.debugShowMission);
final JMenuItem reveal = new JCheckBoxMenuItem(Messages.message("menuBar.debug.revealEntireMap"));
reveal.setOpaque(false);
reveal.setMnemonic(KeyEvent.VK_R);
this.add(reveal);
reveal.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (freeColClient.getFreeColServer() != null) {
freeColClient.getFreeColServer().revealMapForAllPlayers();
}
reveal.setEnabled(false);
}
});
JMenu cvpMenu = new JMenu(Messages.message("menuBar.debug.showColonyValue"));
cvpMenu.setOpaque(false);
ButtonGroup bg = new ButtonGroup();
JRadioButtonMenuItem cv1 = new JRadioButtonMenuItem("Do not display", !gui.displayColonyValue);
cv1.setOpaque(false);
cv1.setMnemonic(KeyEvent.VK_C);
cvpMenu.add(cv1);
bg.add(cv1);
cv1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
gui.displayColonyValue = false;
gui.displayColonyValuePlayer = null;
canvas.refresh();
}
});
add(cvpMenu);
JRadioButtonMenuItem cv3 = new JRadioButtonMenuItem("Common outpost value", gui.displayColonyValue
&& gui.displayColonyValuePlayer == null);
cv3.setOpaque(false);
cv3.setMnemonic(KeyEvent.VK_C);
cvpMenu.add(cv3);
bg.add(cv3);
cv3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
gui.displayColonyValue = true;
gui.displayColonyValuePlayer = null;
canvas.refresh();
}
});
this.add(cvpMenu);
cvpMenu.addSeparator();
Iterator<Player> it = freeColClient.getGame().getPlayerIterator();
while (it.hasNext()) {
final Player p = it.next();
if (p.isEuropean() && p.canBuildColonies()) {
JRadioButtonMenuItem cv2 = new JRadioButtonMenuItem(p.getNationAsString(),
gui.displayColonyValue && gui.displayColonyValuePlayer == p);
cv2.setOpaque(false);
cv2.setMnemonic(KeyEvent.VK_C);
cvpMenu.add(cv2);
bg.add(cv2);
cv2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
gui.displayColonyValue = true;
gui.displayColonyValuePlayer = p;
canvas.refresh();
}
});
}
}
this.addSeparator();
setupSkipTurnsMenuItem();
if (freeColClient.getFreeColServer() != null) {
final JMenuItem giveBells = new JMenuItem("Adds 100 bells to each Colony");
giveBells.setOpaque(false);
giveBells.setMnemonic(KeyEvent.VK_B);
this.add(giveBells);
giveBells.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for (Colony c : freeColClient.getMyPlayer().getColonies()) {
c.addLiberty(100);
Colony sc = (Colony) freeColClient.getFreeColServer().getGame().getFreeColGameObject(c.getId());
sc.addLiberty(100);
}
}
});
}
final JMenuItem addFather = new JMenuItem("Add Founding Father");
addFather.setOpaque(false);
addFather.setMnemonic(KeyEvent.VK_F);
this.add(addFather);
addFather.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Player player = freeColClient.getMyPlayer();
List<ChoiceItem<FoundingFather>> fathers = new ArrayList<ChoiceItem<FoundingFather>>();
for (FoundingFather father : FreeCol.getSpecification().getFoundingFathers()) {
if (!player.hasFather(father)) {
fathers.add(new ChoiceItem<FoundingFather>(father.getName(), father));
}
}
FoundingFather fatherToAdd = freeColClient.getCanvas()
.showChoiceDialog("Select Founding Father", "cancel", fathers);
player.addFather(fatherToAdd);
Player serverPlayer = (Player) freeColClient.getFreeColServer().getGame().
getFreeColGameObject(player.getId());
serverPlayer.addFather(fatherToAdd);
}
});
final JMenuItem addCrosses = new JMenuItem("Add Immigration");
addCrosses.setOpaque(false);
// addCrosses.setMnemonic(KeyEvent.VK_????);
this.add(addCrosses);
addCrosses.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String response = freeColClient.getCanvas()
.showInputDialog("menuBar.debug.addImmigration",
Integer.toString(100),
"ok", "cancel");
Player player = freeColClient.getMyPlayer();
int crosses = Integer.parseInt(response);
Player serverPlayer = (Player) freeColClient.getFreeColServer()
.getGame().getFreeColGameObject(player.getId());
player.incrementImmigration(crosses);
serverPlayer.incrementImmigration(crosses);
}
});
// random number generator
final JMenuItem rng = new JMenuItem("Step random number generator");
rng.setOpaque(false);
rng.setMnemonic(KeyEvent.VK_X);
this.add(rng);
rng.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
stepRNG();
}
});
this.addSeparator();
JMenu panelMenu = new JMenu("Display panels");
panelMenu.setOpaque(false);
final JMenuItem monarchPanel = new JMenuItem("Display Monarch panel");
monarchPanel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
canvas.showFreeColDialog(new MonarchPanel(canvas, Monarch.MonarchAction.RAISE_TAX));
}
});
panelMenu.add(monarchPanel);
final JMenuItem victoryPanel = new JMenuItem("Display Victory panel");
monarchPanel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
canvas.showPanel(new VictoryPanel(canvas));
}
});
panelMenu.add(victoryPanel);
add(panelMenu);
final JMenuItem europeStatus = new JMenuItem("Display Europe Status");
europeStatus.setOpaque(false);
europeStatus.setMnemonic(KeyEvent.VK_E);
this.add(europeStatus);
europeStatus.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (freeColClient.getFreeColServer() != null) {
net.sf.freecol.server.ai.AIMain aiMain = freeColClient.getFreeColServer().getAIMain();
StringBuilder sb = new StringBuilder();
for (Player tp : freeColClient.getGame().getPlayers()) {
final Player p = (Player) freeColClient.getFreeColServer().getGame().getFreeColGameObject(tp.getId());
if (p.getEurope() == null) {
continue;
}
List<Unit> inEurope = new ArrayList<Unit>();
List<Unit> toEurope = new ArrayList<Unit>();
List<Unit> toAmerica = new ArrayList<Unit>();
LinkedHashMap<String,List<Unit>> units = new LinkedHashMap<String, List<Unit>>();
units.put("To Europe", toEurope);
units.put("In Europe", inEurope);
units.put("To America", toAmerica);
sb.append("\n==");
sb.append(p.getNationAsString());
sb.append("==\n");
for(Unit u : p.getEurope().getUnitList()){
if(u.getState() == UnitState.TO_AMERICA){
toAmerica.add(u);
continue;
}
if(u.getState() == UnitState.TO_EUROPE){
toEurope.add(u);
continue;
}
inEurope.add(u);
}
for(String label : units.keySet()){
List<Unit> list = units.get(label);
if(list.size() > 0){
sb.append("\n->" + label + "\n");
for(Unit u : list){
sb.append('\n');
sb.append(u.getName());
if(u.isUnderRepair()){
sb.append(" (Repairing)");
}
sb.append(" " + ((AIUnit) aiMain.getAIObject(u)).getMission().toString().replaceAll("\n", " \n"));
}
sb.append('\n');
}
}
}
canvas.showInformationMessage(sb.toString());
}
}
});
final JMenuItem useAI = new JMenuItem("Use AI");
useAI.setOpaque(false);
useAI.setMnemonic(KeyEvent.VK_A);
useAI.setAccelerator(KeyStroke.getKeyStroke('A', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()
| InputEvent.ALT_MASK));
this.add(useAI);
useAI.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (freeColClient.getFreeColServer() != null) {
net.sf.freecol.server.ai.AIMain aiMain = freeColClient.getFreeColServer().getAIMain();
net.sf.freecol.server.ai.AIPlayer ap = (net.sf.freecol.server.ai.AIPlayer) aiMain
.getAIObject(freeColClient.getMyPlayer().getId());
ap.setDebuggingConnection(freeColClient.getClient().getConnection());
ap.startWorking();
freeColClient.getConnectController().reconnect();
}
}
});
this.addSeparator();
final JMenuItem compareMaps = new JMenuItem(Messages.message("menuBar.debug.compareMaps"));
compareMaps.setOpaque(false);
compareMaps.setMnemonic(KeyEvent.VK_C);
compareMaps.setAccelerator(KeyStroke.getKeyStroke('C', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()
| InputEvent.ALT_MASK));
this.add(compareMaps);
compareMaps.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
boolean problemDetected = false;
Map serverMap = freeColClient.getFreeColServer().getGame().getMap();
Player myServerPlayer = (Player) freeColClient.getFreeColServer().getGame().getFreeColGameObject(
freeColClient.getMyPlayer().getId());
Iterator<Position> it = serverMap.getWholeMapIterator();
while (it.hasNext()) {
Tile t = serverMap.getTile(it.next());
if (myServerPlayer.canSee(t)) {
Iterator<Unit> unitIterator = t.getUnitIterator();
while (unitIterator.hasNext()) {
Unit u = unitIterator.next();
if (u.isVisibleTo(myServerPlayer)) {
if (freeColClient.getGame().getFreeColGameObject(u.getId()) == null) {
System.out.println("Unsynchronization detected: Unit missing on client-side");
System.out.println(u.getName() + "(" + u.getId() + "). Position: "
+ u.getTile().getPosition());
try {
System.out.println("Possible unit on client-side: "
+ freeColClient.getGame().getMap().getTile(u.getTile().getPosition())
.getFirstUnit().getId());
} catch (NullPointerException npe) {
}
System.out.println();
problemDetected = true;
} else {
Unit clientSideUnit = (Unit) freeColClient.getGame()
.getFreeColGameObject(u.getId());
if (clientSideUnit.getTile() != null
&& !clientSideUnit.getTile().getId().equals(u.getTile().getId())) {
System.out
.println("Unsynchronization detected: Unit located on different tiles");
System.out.println("Server: " + u.getName() + "(" + u.getId() + "). Position: "
+ u.getTile().getPosition());
System.out.println("Client: " + clientSideUnit.getName() + "("
+ clientSideUnit.getId() + "). Position: "
+ clientSideUnit.getTile().getPosition());
System.out.println();
problemDetected = true;
}
}
}
}
}
}
if (problemDetected) {
canvas.showInformationMessage("menuBar.debug.compareMaps.problem");
} else {
canvas.showInformationMessage("menuBar.debug.compareMaps.checkComplete");
}
}
});
// statistics
final JMenuItem statistics = new JMenuItem("Statistics");
statistics.setOpaque(false);
statistics.setMnemonic(KeyEvent.VK_I);
this.add(statistics);
statistics.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
canvas.showPanel(new StatisticsPanel(canvas));
}
});
// garbage collector
final JMenuItem gc = new JMenuItem(Messages.message("menuBar.debug.memoryManager.gc"));
gc.setOpaque(false);
gc.setMnemonic(KeyEvent.VK_G);
this.add(gc);
gc.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.gc();
}
});
this.addSeparator();
final JMenuItem loadResource = new JMenuItem("Reload images");
loadResource.setOpaque(false);
this.add(loadResource);
loadResource.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
canvas.getImageLibrary().init();
} catch (Exception ex) {
System.out.println("Failed to reload images.");
}
}
});
}
| private void buildDebugMenu() {
this.setOpaque(false);
this.setMnemonic(KeyEvent.VK_D);
add(this);
JMenu debugFixMenu = new JMenu("Fixes");
debugFixMenu.setOpaque(false);
debugFixMenu.setMnemonic(KeyEvent.VK_F);
this.add(debugFixMenu);
final JMenuItem crossBug = new JCheckBoxMenuItem("Fix \"not enough crosses\"-bug");
crossBug.setOpaque(false);
crossBug.setMnemonic(KeyEvent.VK_B);
debugFixMenu.add(crossBug);
crossBug.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
freeColClient.getMyPlayer().updateImmigrationRequired();
if (freeColClient.getFreeColServer() != null) {
Iterator<Player> pi = freeColClient.getFreeColServer().getGame().getPlayerIterator();
while (pi.hasNext()) {
pi.next().updateImmigrationRequired();
}
}
}
});
this.addSeparator();
JCheckBoxMenuItem sc = new JCheckBoxMenuItem(Messages.message("menuBar.debug.showCoordinates"),
gui.displayCoordinates);
sc.setOpaque(false);
sc.setMnemonic(KeyEvent.VK_S);
this.add(sc);
sc.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
gui.displayCoordinates = ((JCheckBoxMenuItem) e.getSource()).isSelected();
canvas.refresh();
}
});
final JCheckBoxMenuItem dami = new JCheckBoxMenuItem("Additional AI-mission info", gui.debugShowMissionInfo);
dami.setOpaque(false);
dami.setMnemonic(KeyEvent.VK_I);
dami.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
gui.debugShowMissionInfo = ((JCheckBoxMenuItem) e.getSource()).isSelected();
canvas.refresh();
}
});
JCheckBoxMenuItem dam = new JCheckBoxMenuItem("Display AI-missions", gui.debugShowMission);
dam.setOpaque(false);
dam.setMnemonic(KeyEvent.VK_M);
this.add(dam);
dam.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
gui.debugShowMission = ((JCheckBoxMenuItem) e.getSource()).isSelected();
dami.setEnabled(gui.debugShowMission);
canvas.refresh();
}
});
this.add(dami);
dami.setEnabled(gui.debugShowMission);
final JMenuItem reveal = new JCheckBoxMenuItem(Messages.message("menuBar.debug.revealEntireMap"));
reveal.setOpaque(false);
reveal.setMnemonic(KeyEvent.VK_R);
this.add(reveal);
reveal.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (freeColClient.getFreeColServer() != null) {
freeColClient.getFreeColServer().revealMapForAllPlayers();
}
reveal.setEnabled(false);
}
});
JMenu cvpMenu = new JMenu(Messages.message("menuBar.debug.showColonyValue"));
cvpMenu.setOpaque(false);
ButtonGroup bg = new ButtonGroup();
JRadioButtonMenuItem cv1 = new JRadioButtonMenuItem("Do not display", !gui.displayColonyValue);
cv1.setOpaque(false);
cv1.setMnemonic(KeyEvent.VK_C);
cvpMenu.add(cv1);
bg.add(cv1);
cv1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
gui.displayColonyValue = false;
gui.displayColonyValuePlayer = null;
canvas.refresh();
}
});
add(cvpMenu);
JRadioButtonMenuItem cv3 = new JRadioButtonMenuItem("Common outpost value", gui.displayColonyValue
&& gui.displayColonyValuePlayer == null);
cv3.setOpaque(false);
cv3.setMnemonic(KeyEvent.VK_C);
cvpMenu.add(cv3);
bg.add(cv3);
cv3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
gui.displayColonyValue = true;
gui.displayColonyValuePlayer = null;
canvas.refresh();
}
});
this.add(cvpMenu);
cvpMenu.addSeparator();
Iterator<Player> it = freeColClient.getGame().getPlayerIterator();
while (it.hasNext()) {
final Player p = it.next();
if (p.isEuropean() && p.canBuildColonies()) {
JRadioButtonMenuItem cv2 = new JRadioButtonMenuItem(p.getNationAsString(),
gui.displayColonyValue && gui.displayColonyValuePlayer == p);
cv2.setOpaque(false);
cv2.setMnemonic(KeyEvent.VK_C);
cvpMenu.add(cv2);
bg.add(cv2);
cv2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
gui.displayColonyValue = true;
gui.displayColonyValuePlayer = p;
canvas.refresh();
}
});
}
}
this.addSeparator();
setupSkipTurnsMenuItem();
if (freeColClient.getFreeColServer() != null) {
final JMenuItem giveBells = new JMenuItem("Adds 100 bells to each Colony");
giveBells.setOpaque(false);
giveBells.setMnemonic(KeyEvent.VK_B);
this.add(giveBells);
giveBells.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for (Colony c : freeColClient.getMyPlayer().getColonies()) {
c.addLiberty(100);
Colony sc = (Colony) freeColClient.getFreeColServer().getGame().getFreeColGameObject(c.getId());
sc.addLiberty(100);
}
}
});
}
final JMenuItem addFather = new JMenuItem("Add Founding Father");
addFather.setOpaque(false);
addFather.setMnemonic(KeyEvent.VK_F);
this.add(addFather);
addFather.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Player player = freeColClient.getMyPlayer();
List<ChoiceItem<FoundingFather>> fathers = new ArrayList<ChoiceItem<FoundingFather>>();
for (FoundingFather father : FreeCol.getSpecification().getFoundingFathers()) {
if (!player.hasFather(father)) {
fathers.add(new ChoiceItem<FoundingFather>(father.getName(), father));
}
}
FoundingFather fatherToAdd = freeColClient.getCanvas()
.showChoiceDialog("Select Founding Father", "cancel", fathers);
player.addFather(fatherToAdd);
Player serverPlayer = (Player) freeColClient.getFreeColServer().getGame().
getFreeColGameObject(player.getId());
serverPlayer.addFather(fatherToAdd);
}
});
final JMenuItem addCrosses = new JMenuItem("Add Immigration");
addCrosses.setOpaque(false);
// addCrosses.setMnemonic(KeyEvent.VK_????);
this.add(addCrosses);
addCrosses.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String response = freeColClient.getCanvas()
.showInputDialog("menuBar.debug.addImmigration",
Integer.toString(100),
"ok", "cancel");
Player player = freeColClient.getMyPlayer();
int crosses = Integer.parseInt(response);
Player serverPlayer = (Player) freeColClient.getFreeColServer()
.getGame().getFreeColGameObject(player.getId());
player.incrementImmigration(crosses);
serverPlayer.incrementImmigration(crosses);
}
});
// random number generator
final JMenuItem rng = new JMenuItem("Step random number generator");
rng.setOpaque(false);
rng.setMnemonic(KeyEvent.VK_X);
this.add(rng);
rng.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
stepRNG();
}
});
this.addSeparator();
JMenu panelMenu = new JMenu("Display panels");
panelMenu.setOpaque(false);
final JMenuItem monarchPanel = new JMenuItem("Display Monarch panel");
monarchPanel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
canvas.showFreeColDialog(new MonarchPanel(canvas, Monarch.MonarchAction.RAISE_TAX));
}
});
panelMenu.add(monarchPanel);
final JMenuItem victoryPanel = new JMenuItem("Display Victory panel");
monarchPanel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
canvas.showPanel(new VictoryPanel(canvas));
}
});
panelMenu.add(victoryPanel);
add(panelMenu);
final JMenuItem europeStatus = new JMenuItem("Display Europe Status");
europeStatus.setOpaque(false);
europeStatus.setMnemonic(KeyEvent.VK_E);
this.add(europeStatus);
europeStatus.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (freeColClient.getFreeColServer() != null) {
net.sf.freecol.server.ai.AIMain aiMain = freeColClient.getFreeColServer().getAIMain();
StringBuilder sb = new StringBuilder();
for (Player tp : freeColClient.getGame().getPlayers()) {
final Player p = (Player) freeColClient.getFreeColServer().getGame().getFreeColGameObject(tp.getId());
if (p.getEurope() == null) {
continue;
}
List<Unit> inEurope = new ArrayList<Unit>();
List<Unit> toEurope = new ArrayList<Unit>();
List<Unit> toAmerica = new ArrayList<Unit>();
LinkedHashMap<String,List<Unit>> units = new LinkedHashMap<String, List<Unit>>();
units.put("To Europe", toEurope);
units.put("In Europe", inEurope);
units.put("To America", toAmerica);
sb.append("\n==");
sb.append(p.getNationAsString());
sb.append("==\n");
for(Unit u : p.getEurope().getUnitList()){
if(u.getState() == UnitState.TO_AMERICA){
toAmerica.add(u);
continue;
}
if(u.getState() == UnitState.TO_EUROPE){
toEurope.add(u);
continue;
}
inEurope.add(u);
}
for(String label : units.keySet()){
List<Unit> list = units.get(label);
if(list.size() > 0){
sb.append("\n->" + label + "\n");
for(Unit u : list){
sb.append('\n');
sb.append(u.getName());
if(u.isUnderRepair()){
sb.append(" (Repairing)");
}
else{
sb.append(" ");
AIUnit aiu = (AIUnit) aiMain.getAIObject(u);
if(aiu.getMission() == null){
sb.append(" (None)");
}
else{
sb.append(aiu.getMission().toString().replaceAll("\n", " \n"));
}
}
}
sb.append('\n');
}
}
}
canvas.showInformationMessage(sb.toString());
}
}
});
final JMenuItem useAI = new JMenuItem("Use AI");
useAI.setOpaque(false);
useAI.setMnemonic(KeyEvent.VK_A);
useAI.setAccelerator(KeyStroke.getKeyStroke('A', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()
| InputEvent.ALT_MASK));
this.add(useAI);
useAI.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (freeColClient.getFreeColServer() != null) {
net.sf.freecol.server.ai.AIMain aiMain = freeColClient.getFreeColServer().getAIMain();
net.sf.freecol.server.ai.AIPlayer ap = (net.sf.freecol.server.ai.AIPlayer) aiMain
.getAIObject(freeColClient.getMyPlayer().getId());
ap.setDebuggingConnection(freeColClient.getClient().getConnection());
ap.startWorking();
freeColClient.getConnectController().reconnect();
}
}
});
this.addSeparator();
final JMenuItem compareMaps = new JMenuItem(Messages.message("menuBar.debug.compareMaps"));
compareMaps.setOpaque(false);
compareMaps.setMnemonic(KeyEvent.VK_C);
compareMaps.setAccelerator(KeyStroke.getKeyStroke('C', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()
| InputEvent.ALT_MASK));
this.add(compareMaps);
compareMaps.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
boolean problemDetected = false;
Map serverMap = freeColClient.getFreeColServer().getGame().getMap();
Player myServerPlayer = (Player) freeColClient.getFreeColServer().getGame().getFreeColGameObject(
freeColClient.getMyPlayer().getId());
Iterator<Position> it = serverMap.getWholeMapIterator();
while (it.hasNext()) {
Tile t = serverMap.getTile(it.next());
if (myServerPlayer.canSee(t)) {
Iterator<Unit> unitIterator = t.getUnitIterator();
while (unitIterator.hasNext()) {
Unit u = unitIterator.next();
if (u.isVisibleTo(myServerPlayer)) {
if (freeColClient.getGame().getFreeColGameObject(u.getId()) == null) {
System.out.println("Unsynchronization detected: Unit missing on client-side");
System.out.println(u.getName() + "(" + u.getId() + "). Position: "
+ u.getTile().getPosition());
try {
System.out.println("Possible unit on client-side: "
+ freeColClient.getGame().getMap().getTile(u.getTile().getPosition())
.getFirstUnit().getId());
} catch (NullPointerException npe) {
}
System.out.println();
problemDetected = true;
} else {
Unit clientSideUnit = (Unit) freeColClient.getGame()
.getFreeColGameObject(u.getId());
if (clientSideUnit.getTile() != null
&& !clientSideUnit.getTile().getId().equals(u.getTile().getId())) {
System.out
.println("Unsynchronization detected: Unit located on different tiles");
System.out.println("Server: " + u.getName() + "(" + u.getId() + "). Position: "
+ u.getTile().getPosition());
System.out.println("Client: " + clientSideUnit.getName() + "("
+ clientSideUnit.getId() + "). Position: "
+ clientSideUnit.getTile().getPosition());
System.out.println();
problemDetected = true;
}
}
}
}
}
}
if (problemDetected) {
canvas.showInformationMessage("menuBar.debug.compareMaps.problem");
} else {
canvas.showInformationMessage("menuBar.debug.compareMaps.checkComplete");
}
}
});
// statistics
final JMenuItem statistics = new JMenuItem("Statistics");
statistics.setOpaque(false);
statistics.setMnemonic(KeyEvent.VK_I);
this.add(statistics);
statistics.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
canvas.showPanel(new StatisticsPanel(canvas));
}
});
// garbage collector
final JMenuItem gc = new JMenuItem(Messages.message("menuBar.debug.memoryManager.gc"));
gc.setOpaque(false);
gc.setMnemonic(KeyEvent.VK_G);
this.add(gc);
gc.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.gc();
}
});
this.addSeparator();
final JMenuItem loadResource = new JMenuItem("Reload images");
loadResource.setOpaque(false);
this.add(loadResource);
loadResource.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
canvas.getImageLibrary().init();
} catch (Exception ex) {
System.out.println("Failed to reload images.");
}
}
});
}
|
diff --git a/Examples/Java/ScanDirectory.java b/Examples/Java/ScanDirectory.java
index 57c74cc3d..c015b974c 100644
--- a/Examples/Java/ScanDirectory.java
+++ b/Examples/Java/ScanDirectory.java
@@ -1,220 +1,221 @@
/*=========================================================================
Program: GDCM (Grassroots DICOM). A DICOM library
Copyright (c) 2006-2011 Mathieu Malaterre
All rights reserved.
See Copyright.txt or http://gdcm.sourceforge.net/Copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
/**
* Simple example showing how to bind a custom Observer to the Scanner in response
* to ProgressEvent
* If found, icons will be extracted or else they will be generated and save as PNG
*
* Compilation:
* $ CLASSPATH=gdcm.jar javac ../../gdcm/Examples/Java/ScanDirectory.java -d .
*
* Usage:
* $ LD_LIBRARY_PATH=. CLASSPATH=gdcm.jar:. java ScanDirectory gdcmData
*/
import gdcm.*;
import gdcm.LookupTable;
import java.io.File;
import java.io.*;
import java.awt.image.*;
import javax.imageio.ImageIO;
public class ScanDirectory
{
public static class MyWatcher extends SimpleSubjectWatcher
{
public MyWatcher(Subject s) { super(s,"Override String"); }
protected void ShowProgress(Subject caller, Event evt)
{
ProgressEvent pe = ProgressEvent.Cast(evt);
System.out.println( "This is my progress: " + pe.GetProgress() );
}
}
public static boolean WritePNG(Bitmap input, String outfilename )
{
long len = input.GetBufferLength();
byte[] buffer = new byte[ (int)len ];
input.GetBuffer( buffer );
/*
try {
FileOutputStream fos = new FileOutputStream("debug.raw");
fos.write(buffer);
fos.close();
} catch(FileNotFoundException ex) {
} catch(IOException ex) {
}
*/
int imageType = BufferedImage.TYPE_CUSTOM;
PixelFormat pf = input.GetPixelFormat();
PhotometricInterpretation pi = input.GetPhotometricInterpretation();
// We need to handle both public and private icon
// It could well be that we are getting an RGB Icon or 16 bits Icon:
ColorModel colorModel = null;
if( pf.GetSamplesPerPixel() == 1 )
{
if( pi.GetType() == PhotometricInterpretation.PIType.MONOCHROME1
|| pi.GetType() == PhotometricInterpretation.PIType.MONOCHROME2 )
{
if( pf.GetScalarType() == PixelFormat.ScalarType.UINT8 )
{
imageType = BufferedImage.TYPE_BYTE_GRAY;
}
else if( pf.GetScalarType() == PixelFormat.ScalarType.UINT16 )
{
imageType = BufferedImage.TYPE_USHORT_GRAY;
}
}
else if( pi.GetType() == PhotometricInterpretation.PIType.PALETTE_COLOR )
{
LookupTable lut = input.GetLUT();
long rl = lut.GetLUTLength( LookupTable.LookupTableType.RED );
byte[] rbuf = new byte[ (int)rl ];
long rl2 = lut.GetLUT( LookupTable.LookupTableType.RED, rbuf );
assert rl == rl2;
long gl = lut.GetLUTLength( LookupTable.LookupTableType.GREEN );
byte[] gbuf = new byte[ (int)gl ];
long gl2 = lut.GetLUT( LookupTable.LookupTableType.GREEN, gbuf );
assert gl == gl2;
long bl = lut.GetLUTLength( LookupTable.LookupTableType.BLUE );
byte[] bbuf = new byte[ (int)bl ];
long bl2 = lut.GetLUT( LookupTable.LookupTableType.BLUE, bbuf );
assert bl == bl2;
colorModel = new IndexColorModel(8, (int)rl, rbuf, gbuf, bbuf);
}
}
else if( pf.GetSamplesPerPixel() == 3 )
{
if( pf.GetScalarType() == PixelFormat.ScalarType.UINT8 )
{
// FIXME should be TYPE_3BYTE_RGB
imageType = BufferedImage.TYPE_3BYTE_BGR;
}
}
long width = input.GetDimension(0);
long height = input.GetDimension(0);
BufferedImage bi;
if( pi.GetType() == PhotometricInterpretation.PIType.PALETTE_COLOR )
{
bi = new BufferedImage(colorModel,
colorModel.createCompatibleWritableRaster((int)width, (int)height),
false, null);
}
else
{
bi = new BufferedImage((int)width,(int)height,imageType);
}
WritableRaster wr = bi.getRaster();
wr.setDataElements (0, 0, (int)width, (int)height, buffer);
File outputfile = new File( outfilename );
try {
ImageIO.write(bi, "png", outputfile);
} catch (IOException e) {
return false;
}
return true;
}
public static void main(String[] args) throws Exception
{
String directory = args[0];
Directory d = new Directory();
long nfiles = d.Load( directory );
if(nfiles == 0)
{
throw new Exception("No files found");
}
// System.out.println( "Files:\n" + d.toString() );
FilenamesType fns = d.GetFilenames();
//Scanner s = new Scanner();
SmartPtrScan sscan = Scanner.New();
Scanner s = sscan.__ref__();
//SimpleSubjectWatcher watcher = new SimpleSubjectWatcher(s, "MySimple");
MyWatcher watcher = new MyWatcher(s);
Tag[] tagarray = {
new Tag(0x0010, 0x0010), // PatientName
new Tag(0x0010, 0x0020), // PatientID
new Tag(0x0010, 0x0030), // PatientBirthDate
new Tag(0x0010, 0x0040), // PatientSex
new Tag(0x0010, 0x1010), // PatientAge
new Tag(0x0020, 0x000d), // StudyInstanceUID
new Tag(0x0020, 0x0010), // StudyID
new Tag(0x0008, 0x0020), // StudyDate
new Tag(0x0008, 0x1030), // StudyDescription
new Tag(0x0020, 0x000e), // SeriesInstanceUID
new Tag(0x0020, 0x0011), // SeriesNumber
new Tag(0x0008, 0x0021), // SeriesDate
new Tag(0x0008, 0x103e), // SeriesDescription
new Tag(0x0008, 0x0090), // ReferringPhysicianName
new Tag(0x0008, 0x0060), // Modality
new Tag(0x0054, 0x0400), // ImageID ?? Should be Instance number ??
new Tag(0x0008, 0x0018), // SOPInstanceUID
new Tag(0x0008, 0x0032), // AcquisitionTime
new Tag(0x0008, 0x0033), // ContentTime
new Tag(0x0020, 0x0013), // InstanceNumber
new Tag(0x0020, 0x1041), // SliceLocation
new Tag(0x0018, 0x0050), // SliceThickness ?? Eg. Enhanced MR Image Storage
new Tag(0x0008, 0x0080), // InstitutionName
};
for( Tag t : tagarray ) {
+ //System.out.println( "Tag: " + t.toString() );
s.AddTag( t );
}
boolean b = s.Scan( fns );
if(!b)
{
throw new Exception("Could not scan");
}
for( long idx = 0; idx < fns.size(); ++idx )
{
ImageReader r = new ImageReader();
String fn = fns.get( (int)idx );
String outfn = fn + ".png";
r.SetFileName( fn );
b = r.Read();
if( b )
{
IconImageFilter iif = new IconImageFilter();
System.out.println( "Processing: " + fn );
iif.SetFile( r.GetFile() );
b = iif.Extract();
if( b )
{
Bitmap icon = iif.GetIconImage(0);
WritePNG(icon, outfn);
}
else
{
Image img = r.GetImage();
IconImageGenerator iig = new IconImageGenerator();
iig.SetPixmap( img );
long idims[] = { 64, 64 };
iig.SetOutputDimensions( idims );
iig.Generate();
Bitmap icon = iig.GetIconImage();
WritePNG(icon, outfn);
}
}
}
System.out.println( "Scan:\n" + s.toString() );
System.out.println( "success" );
}
}
| true | true | public static void main(String[] args) throws Exception
{
String directory = args[0];
Directory d = new Directory();
long nfiles = d.Load( directory );
if(nfiles == 0)
{
throw new Exception("No files found");
}
// System.out.println( "Files:\n" + d.toString() );
FilenamesType fns = d.GetFilenames();
//Scanner s = new Scanner();
SmartPtrScan sscan = Scanner.New();
Scanner s = sscan.__ref__();
//SimpleSubjectWatcher watcher = new SimpleSubjectWatcher(s, "MySimple");
MyWatcher watcher = new MyWatcher(s);
Tag[] tagarray = {
new Tag(0x0010, 0x0010), // PatientName
new Tag(0x0010, 0x0020), // PatientID
new Tag(0x0010, 0x0030), // PatientBirthDate
new Tag(0x0010, 0x0040), // PatientSex
new Tag(0x0010, 0x1010), // PatientAge
new Tag(0x0020, 0x000d), // StudyInstanceUID
new Tag(0x0020, 0x0010), // StudyID
new Tag(0x0008, 0x0020), // StudyDate
new Tag(0x0008, 0x1030), // StudyDescription
new Tag(0x0020, 0x000e), // SeriesInstanceUID
new Tag(0x0020, 0x0011), // SeriesNumber
new Tag(0x0008, 0x0021), // SeriesDate
new Tag(0x0008, 0x103e), // SeriesDescription
new Tag(0x0008, 0x0090), // ReferringPhysicianName
new Tag(0x0008, 0x0060), // Modality
new Tag(0x0054, 0x0400), // ImageID ?? Should be Instance number ??
new Tag(0x0008, 0x0018), // SOPInstanceUID
new Tag(0x0008, 0x0032), // AcquisitionTime
new Tag(0x0008, 0x0033), // ContentTime
new Tag(0x0020, 0x0013), // InstanceNumber
new Tag(0x0020, 0x1041), // SliceLocation
new Tag(0x0018, 0x0050), // SliceThickness ?? Eg. Enhanced MR Image Storage
new Tag(0x0008, 0x0080), // InstitutionName
};
for( Tag t : tagarray ) {
s.AddTag( t );
}
boolean b = s.Scan( fns );
if(!b)
{
throw new Exception("Could not scan");
}
for( long idx = 0; idx < fns.size(); ++idx )
{
ImageReader r = new ImageReader();
String fn = fns.get( (int)idx );
String outfn = fn + ".png";
r.SetFileName( fn );
b = r.Read();
if( b )
{
IconImageFilter iif = new IconImageFilter();
System.out.println( "Processing: " + fn );
iif.SetFile( r.GetFile() );
b = iif.Extract();
if( b )
{
Bitmap icon = iif.GetIconImage(0);
WritePNG(icon, outfn);
}
else
{
Image img = r.GetImage();
IconImageGenerator iig = new IconImageGenerator();
iig.SetPixmap( img );
long idims[] = { 64, 64 };
iig.SetOutputDimensions( idims );
iig.Generate();
Bitmap icon = iig.GetIconImage();
WritePNG(icon, outfn);
}
}
}
System.out.println( "Scan:\n" + s.toString() );
System.out.println( "success" );
}
| public static void main(String[] args) throws Exception
{
String directory = args[0];
Directory d = new Directory();
long nfiles = d.Load( directory );
if(nfiles == 0)
{
throw new Exception("No files found");
}
// System.out.println( "Files:\n" + d.toString() );
FilenamesType fns = d.GetFilenames();
//Scanner s = new Scanner();
SmartPtrScan sscan = Scanner.New();
Scanner s = sscan.__ref__();
//SimpleSubjectWatcher watcher = new SimpleSubjectWatcher(s, "MySimple");
MyWatcher watcher = new MyWatcher(s);
Tag[] tagarray = {
new Tag(0x0010, 0x0010), // PatientName
new Tag(0x0010, 0x0020), // PatientID
new Tag(0x0010, 0x0030), // PatientBirthDate
new Tag(0x0010, 0x0040), // PatientSex
new Tag(0x0010, 0x1010), // PatientAge
new Tag(0x0020, 0x000d), // StudyInstanceUID
new Tag(0x0020, 0x0010), // StudyID
new Tag(0x0008, 0x0020), // StudyDate
new Tag(0x0008, 0x1030), // StudyDescription
new Tag(0x0020, 0x000e), // SeriesInstanceUID
new Tag(0x0020, 0x0011), // SeriesNumber
new Tag(0x0008, 0x0021), // SeriesDate
new Tag(0x0008, 0x103e), // SeriesDescription
new Tag(0x0008, 0x0090), // ReferringPhysicianName
new Tag(0x0008, 0x0060), // Modality
new Tag(0x0054, 0x0400), // ImageID ?? Should be Instance number ??
new Tag(0x0008, 0x0018), // SOPInstanceUID
new Tag(0x0008, 0x0032), // AcquisitionTime
new Tag(0x0008, 0x0033), // ContentTime
new Tag(0x0020, 0x0013), // InstanceNumber
new Tag(0x0020, 0x1041), // SliceLocation
new Tag(0x0018, 0x0050), // SliceThickness ?? Eg. Enhanced MR Image Storage
new Tag(0x0008, 0x0080), // InstitutionName
};
for( Tag t : tagarray ) {
//System.out.println( "Tag: " + t.toString() );
s.AddTag( t );
}
boolean b = s.Scan( fns );
if(!b)
{
throw new Exception("Could not scan");
}
for( long idx = 0; idx < fns.size(); ++idx )
{
ImageReader r = new ImageReader();
String fn = fns.get( (int)idx );
String outfn = fn + ".png";
r.SetFileName( fn );
b = r.Read();
if( b )
{
IconImageFilter iif = new IconImageFilter();
System.out.println( "Processing: " + fn );
iif.SetFile( r.GetFile() );
b = iif.Extract();
if( b )
{
Bitmap icon = iif.GetIconImage(0);
WritePNG(icon, outfn);
}
else
{
Image img = r.GetImage();
IconImageGenerator iig = new IconImageGenerator();
iig.SetPixmap( img );
long idims[] = { 64, 64 };
iig.SetOutputDimensions( idims );
iig.Generate();
Bitmap icon = iig.GetIconImage();
WritePNG(icon, outfn);
}
}
}
System.out.println( "Scan:\n" + s.toString() );
System.out.println( "success" );
}
|
diff --git a/core/src/org/icepdf/core/pobjects/fonts/FontFactory.java b/core/src/org/icepdf/core/pobjects/fonts/FontFactory.java
index d7607bc8..a47058a3 100644
--- a/core/src/org/icepdf/core/pobjects/fonts/FontFactory.java
+++ b/core/src/org/icepdf/core/pobjects/fonts/FontFactory.java
@@ -1,287 +1,287 @@
/*
* Copyright 2006-2013 ICEsoft Technologies 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 org.icepdf.core.pobjects.fonts;
import org.icepdf.core.pobjects.Stream;
import org.icepdf.core.pobjects.fonts.ofont.OFont;
import org.icepdf.core.util.Defs;
import org.icepdf.core.util.Library;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.net.URL;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Simple Factory for loading of font library if present.
*/
public class FontFactory {
private static final Logger logger =
Logger.getLogger(FontFactory.class.toString());
// allow scaling of large images to improve clarity on screen
private static boolean awtFontLoading;
// dynamic property to switch between font engine and awt font substitution.
private static boolean awtFontSubstitution;
static {
// turn on font file loading using awt, can cause the jvm to crash
// if the font file is corrupt.
awtFontLoading =
Defs.sysPropertyBoolean("org.icepdf.core.awtFontLoading",
false);
}
public static final int FONT_OPEN_TYPE = 5;
public static final int FONT_TRUE_TYPE = java.awt.Font.TRUETYPE_FONT;
public static final int FONT_TYPE_0 = 6;
public static final int FONT_TYPE_1 = java.awt.Font.TYPE1_FONT;
public static final int FONT_TYPE_3 = 7;
// Singleton instance of class
private static FontFactory fontFactory;
// NFont class path
private static final String FONT_CLASS =
"org.icepdf.core.pobjects.fonts.nfont.Font";
private static final String NFONT_CLASS =
"org.icepdf.core.pobjects.fonts.nfont.NFont";
private static final String NFONT_OPEN_TYPE =
"org.icepdf.core.pobjects.fonts.nfont.NFontOpenType";
private static final String NFONT_TRUE_TYPE =
"org.icepdf.core.pobjects.fonts.nfont.NFontTrueType";
private static final String NFONT_TRUE_TYPE_0 =
"org.icepdf.core.pobjects.fonts.nfont.NFontType0";
private static final String NFONT_TRUE_TYPE_1 =
"org.icepdf.core.pobjects.fonts.nfont.NFontType1";
private static final String NFONT_TRUE_TYPE_3 =
"org.icepdf.core.pobjects.fonts.nfont.NFontType3";
static {
// check class bath for NFont library, and declare results.
try {
Class.forName(NFONT_CLASS);
} catch (ClassNotFoundException e) {
logger.log(Level.FINE, "NFont font library was not found on the class path");
}
}
private static boolean foundNFont;
/**
* <p>Returns a static instance of the FontManager class.</p>
*
* @return instance of the FontManager.
*/
public static FontFactory getInstance() {
// make sure we have initialized the manager
if (fontFactory == null) {
fontFactory = new FontFactory();
}
return fontFactory;
}
private FontFactory() {
}
public Font getFont(Library library, HashMap entries) {
Font fontDictionary = null;
if (foundFontEngine()) {
// load each know file type reflectively.
try {
Class fontClass = Class.forName(FONT_CLASS);
Class[] fontArgs = {Library.class, HashMap.class};
Constructor fontClassConstructor =
fontClass.getDeclaredConstructor(fontArgs);
Object[] fontUrl = {library, entries};
fontDictionary = (Font) fontClassConstructor.newInstance(fontUrl);
} catch (Throwable e) {
logger.log(Level.FINE, "Could not load font dictionary class", e);
}
} else {
// create OFont implementation.
fontDictionary =
new org.icepdf.core.pobjects.fonts.ofont.Font(library, entries);
}
return fontDictionary;
}
public FontFile createFontFile(Stream fontStream, int fontType) {
FontFile fontFile = null;
if (foundFontEngine()) {
try {
Class fontClass = getNFontClass(fontType);
if (fontClass != null) {
// convert the stream to byte[]
Class[] bytArrayArg = {byte[].class};
Constructor fontClassConstructor =
fontClass.getDeclaredConstructor(bytArrayArg);
byte[] data = fontStream.getDecodedStreamBytes(0);
Object[] fontStreamBytes = {data};
if (data.length > 0) {
fontFile = (FontFile) fontClassConstructor
.newInstance(fontStreamBytes);
}
}
} catch (Throwable e) {
- logger.log(Level.FINE, "Could not create instance oof font file " + fontType, e);
+ logger.log(Level.FINE, "Could not create instance of font file " + fontType, e);
}
} else if (awtFontLoading) {
// see if the font file can be loaded with Java Fonts
InputStream in = null;
try {
in = fontStream.getDecodedByteArrayInputStream();
// disabling create font as it brings the JVM down a little too often.
java.awt.Font javaFont = java.awt.Font.createFont(fontType, in);
if (javaFont != null) {
// create instance of OFont.
fontFile = new OFont(javaFont);
if (logger.isLoggable(Level.FINE)) {
logger.fine("Successfully created embedded OFont: " + fontTypeToString(fontType));
}
try {
in.close();
} catch (IOException e) {
logger.log(Level.FINE, "Error closing font stream.", e);
}
}
} catch (Throwable e) {
logger.log(Level.FINE, "Error reading font file with ", e);
try {
if (in != null) in.close();
} catch (Throwable e1) {
logger.log(Level.FINE, "Error closing font stream.", e);
}
}
}
return fontFile;
}
public FontFile createFontFile(File file, int fontType) {
FontFile fontFile = null;
if (foundFontEngine()) {
try {
Class fontClass = getNFontClass(fontType);
if (fontClass != null) {
// convert the stream to byte[]
Class[] urlArg = {URL.class};
Constructor fontClassConstructor =
fontClass.getDeclaredConstructor(urlArg);
Object[] fontUrl = {file.toURI().toURL()};
fontFile = (FontFile) fontClassConstructor.newInstance(fontUrl);
}
} catch (Throwable e) {
logger.log(Level.FINE, "Could not create instance oof font file " + fontType, e);
}
} else {
// see if the font file can be loaded with Java Fonts
try {
java.awt.Font javaFont = java.awt.Font.createFont(fontType, file);
if (javaFont != null) {
// create instance of OFont.
fontFile = new OFont(javaFont);
if (logger.isLoggable(Level.FINE)) {
logger.fine("Successfully loaded OFont: " + file.toURI().toURL());
}
}
} catch (Throwable e) {
logger.log(Level.FINE, "Error ready font file with ", e);
}
}
return fontFile;
}
public boolean isAwtFontSubstitution() {
return awtFontSubstitution;
}
public void setAwtFontSubstitution(boolean awtFontSubstitution) {
this.awtFontSubstitution = awtFontSubstitution;
}
public void toggleAwtFontSubstitution() {
awtFontSubstitution = !awtFontSubstitution;
}
private Class getNFontClass(int fontType) throws ClassNotFoundException {
Class fontClass = null;
if (FONT_OPEN_TYPE == fontType) {
fontClass = Class.forName(NFONT_OPEN_TYPE);
} else if (FONT_TRUE_TYPE == fontType) {
fontClass = Class.forName(NFONT_TRUE_TYPE);
} else if (FONT_TYPE_0 == fontType) {
fontClass = Class.forName(NFONT_TRUE_TYPE_0);
} else if (FONT_TYPE_1 == fontType) {
fontClass = Class.forName(NFONT_TRUE_TYPE_1);
} else if (FONT_TYPE_3 == fontType) {
fontClass = Class.forName(NFONT_TRUE_TYPE_3);
}
return fontClass;
}
private String fontTypeToString(int fontType) {
if (fontType == FONT_OPEN_TYPE) {
return "Open Type Font";
} else if (fontType == FONT_TRUE_TYPE) {
return "True Type Font";
} else if (fontType == FONT_TYPE_0) {
return "Type 0 Font";
} else if (fontType == FONT_TYPE_1) {
return "Type 1 Font";
} else if (fontType == FONT_TYPE_3) {
return "Type 3 Font";
} else {
return "unkown font type: " + fontType;
}
}
/**
* Test if font engine is available on the class path and it has been
* disabled with the proeprty awtFontSubstitution.
*
* @return true if font engine was found, false otherwise.
*/
public boolean foundFontEngine() {
// check class bath for NFont library
try {
Class.forName(NFONT_CLASS);
foundNFont = true;
} catch (ClassNotFoundException e) {
}
return foundNFont && !awtFontSubstitution;
}
}
| true | true | public FontFile createFontFile(Stream fontStream, int fontType) {
FontFile fontFile = null;
if (foundFontEngine()) {
try {
Class fontClass = getNFontClass(fontType);
if (fontClass != null) {
// convert the stream to byte[]
Class[] bytArrayArg = {byte[].class};
Constructor fontClassConstructor =
fontClass.getDeclaredConstructor(bytArrayArg);
byte[] data = fontStream.getDecodedStreamBytes(0);
Object[] fontStreamBytes = {data};
if (data.length > 0) {
fontFile = (FontFile) fontClassConstructor
.newInstance(fontStreamBytes);
}
}
} catch (Throwable e) {
logger.log(Level.FINE, "Could not create instance oof font file " + fontType, e);
}
} else if (awtFontLoading) {
// see if the font file can be loaded with Java Fonts
InputStream in = null;
try {
in = fontStream.getDecodedByteArrayInputStream();
// disabling create font as it brings the JVM down a little too often.
java.awt.Font javaFont = java.awt.Font.createFont(fontType, in);
if (javaFont != null) {
// create instance of OFont.
fontFile = new OFont(javaFont);
if (logger.isLoggable(Level.FINE)) {
logger.fine("Successfully created embedded OFont: " + fontTypeToString(fontType));
}
try {
in.close();
} catch (IOException e) {
logger.log(Level.FINE, "Error closing font stream.", e);
}
}
} catch (Throwable e) {
logger.log(Level.FINE, "Error reading font file with ", e);
try {
if (in != null) in.close();
} catch (Throwable e1) {
logger.log(Level.FINE, "Error closing font stream.", e);
}
}
}
return fontFile;
}
| public FontFile createFontFile(Stream fontStream, int fontType) {
FontFile fontFile = null;
if (foundFontEngine()) {
try {
Class fontClass = getNFontClass(fontType);
if (fontClass != null) {
// convert the stream to byte[]
Class[] bytArrayArg = {byte[].class};
Constructor fontClassConstructor =
fontClass.getDeclaredConstructor(bytArrayArg);
byte[] data = fontStream.getDecodedStreamBytes(0);
Object[] fontStreamBytes = {data};
if (data.length > 0) {
fontFile = (FontFile) fontClassConstructor
.newInstance(fontStreamBytes);
}
}
} catch (Throwable e) {
logger.log(Level.FINE, "Could not create instance of font file " + fontType, e);
}
} else if (awtFontLoading) {
// see if the font file can be loaded with Java Fonts
InputStream in = null;
try {
in = fontStream.getDecodedByteArrayInputStream();
// disabling create font as it brings the JVM down a little too often.
java.awt.Font javaFont = java.awt.Font.createFont(fontType, in);
if (javaFont != null) {
// create instance of OFont.
fontFile = new OFont(javaFont);
if (logger.isLoggable(Level.FINE)) {
logger.fine("Successfully created embedded OFont: " + fontTypeToString(fontType));
}
try {
in.close();
} catch (IOException e) {
logger.log(Level.FINE, "Error closing font stream.", e);
}
}
} catch (Throwable e) {
logger.log(Level.FINE, "Error reading font file with ", e);
try {
if (in != null) in.close();
} catch (Throwable e1) {
logger.log(Level.FINE, "Error closing font stream.", e);
}
}
}
return fontFile;
}
|
diff --git a/src/main/java/com/metaweb/gridworks/clustering/binning/BinningClusterer.java b/src/main/java/com/metaweb/gridworks/clustering/binning/BinningClusterer.java
index b83ca76..adb3600 100644
--- a/src/main/java/com/metaweb/gridworks/clustering/binning/BinningClusterer.java
+++ b/src/main/java/com/metaweb/gridworks/clustering/binning/BinningClusterer.java
@@ -1,151 +1,151 @@
package com.metaweb.gridworks.clustering.binning;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.TreeMap;
import java.util.Map.Entry;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONWriter;
import com.metaweb.gridworks.browsing.Engine;
import com.metaweb.gridworks.browsing.FilteredRows;
import com.metaweb.gridworks.browsing.RowVisitor;
import com.metaweb.gridworks.clustering.Clusterer;
import com.metaweb.gridworks.model.Cell;
import com.metaweb.gridworks.model.Project;
import com.metaweb.gridworks.model.Row;
public class BinningClusterer extends Clusterer {
private Keyer _keyer;
static protected Map<String, Keyer> _keyers = new HashMap<String, Keyer>();
List<Map<String,Integer>> _clusters;
static {
_keyers.put("fingerprint", new FingerprintKeyer());
_keyers.put("ngram-fingerprint", new NGramFingerprintKeyer());
_keyers.put("metaphone", new MetaphoneKeyer());
_keyers.put("double-metaphone", new DoubleMetaphoneKeyer());
_keyers.put("soundex", new SoundexKeyer());
}
class BinningRowVisitor implements RowVisitor {
Keyer _keyer;
Object[] _params;
JSONObject _config;
Map<String,Map<String,Integer>> _map = new HashMap<String,Map<String,Integer>>();
public BinningRowVisitor(Keyer k, JSONObject o) {
_keyer = k;
_config = o;
if (k instanceof NGramFingerprintKeyer) {
try {
int size = _config.getJSONObject("params").getInt("ngram-size");
_params = new Object[1];
_params[0] = size;
} catch (JSONException e) {
//Gridworks.warn("No params specified, using default");
}
}
}
public boolean visit(Project project, int rowIndex, Row row, boolean contextual) {
- Cell cell = row.cells.get(_colindex);
+ Cell cell = row.getCell(_colindex);
if (cell != null && cell.value != null) {
String v = cell.value.toString();
String s = (v instanceof String) ? ((String) v) : v.toString();
String key = _keyer.key(s,_params);
if (_map.containsKey(key)) {
Map<String,Integer> m = _map.get(key);
if (m.containsKey(v)) {
m.put(v, m.get(v) + 1);
} else {
m.put(v,1);
}
} else {
Map<String,Integer> m = new TreeMap<String,Integer>();
m.put(v,0);
_map.put(key, m);
}
}
return false;
}
public Map<String,Map<String,Integer>> getMap() {
return _map;
}
}
public class SizeComparator implements Comparator<Map<String,Integer>> {
public int compare(Map<String,Integer> o1, Map<String,Integer> o2) {
int s1 = o1.size();
int s2 = o2.size();
if (o1 == o2) {
int total1 = 0;
for (int i : o1.values()) {
total1 += i;
}
int total2 = 0;
for (int i : o2.values()) {
total2 += i;
}
return total2 - total1;
} else {
return s2 - s1;
}
}
}
public class EntriesComparator implements Comparator<Entry<String,Integer>> {
public int compare(Entry<String,Integer> o1, Entry<String,Integer> o2) {
return o2.getValue() - o1.getValue();
}
}
public void initializeFromJSON(Project project, JSONObject o) throws Exception {
super.initializeFromJSON(project, o);
_keyer = _keyers.get(o.getString("function").toLowerCase());
}
public void computeClusters(Engine engine) {
BinningRowVisitor visitor = new BinningRowVisitor(_keyer,_config);
FilteredRows filteredRows = engine.getAllFilteredRows(true);
filteredRows.accept(_project, visitor);
Map<String,Map<String,Integer>> map = visitor.getMap();
_clusters = new ArrayList<Map<String,Integer>>(map.values());
Collections.sort(_clusters, new SizeComparator());
}
public void write(JSONWriter writer, Properties options) throws JSONException {
EntriesComparator c = new EntriesComparator();
writer.array();
for (Map<String,Integer> m : _clusters) {
if (m.size() > 1) {
writer.array();
List<Entry<String,Integer>> entries = new ArrayList<Entry<String,Integer>>(m.entrySet());
Collections.sort(entries,c);
for (Entry<String,Integer> e : entries) {
writer.object();
writer.key("v"); writer.value(e.getKey());
writer.key("c"); writer.value(e.getValue());
writer.endObject();
}
writer.endArray();
}
}
writer.endArray();
}
}
| true | true | public boolean visit(Project project, int rowIndex, Row row, boolean contextual) {
Cell cell = row.cells.get(_colindex);
if (cell != null && cell.value != null) {
String v = cell.value.toString();
String s = (v instanceof String) ? ((String) v) : v.toString();
String key = _keyer.key(s,_params);
if (_map.containsKey(key)) {
Map<String,Integer> m = _map.get(key);
if (m.containsKey(v)) {
m.put(v, m.get(v) + 1);
} else {
m.put(v,1);
}
} else {
Map<String,Integer> m = new TreeMap<String,Integer>();
m.put(v,0);
_map.put(key, m);
}
}
return false;
}
| public boolean visit(Project project, int rowIndex, Row row, boolean contextual) {
Cell cell = row.getCell(_colindex);
if (cell != null && cell.value != null) {
String v = cell.value.toString();
String s = (v instanceof String) ? ((String) v) : v.toString();
String key = _keyer.key(s,_params);
if (_map.containsKey(key)) {
Map<String,Integer> m = _map.get(key);
if (m.containsKey(v)) {
m.put(v, m.get(v) + 1);
} else {
m.put(v,1);
}
} else {
Map<String,Integer> m = new TreeMap<String,Integer>();
m.put(v,0);
_map.put(key, m);
}
}
return false;
}
|
diff --git a/org.eclipse.egit.core/src/org/eclipse/egit/core/internal/util/ProjectUtil.java b/org.eclipse.egit.core/src/org/eclipse/egit/core/internal/util/ProjectUtil.java
index b65d2808..0e839fea 100644
--- a/org.eclipse.egit.core/src/org/eclipse/egit/core/internal/util/ProjectUtil.java
+++ b/org.eclipse.egit.core/src/org/eclipse/egit/core/internal/util/ProjectUtil.java
@@ -1,241 +1,241 @@
/*******************************************************************************
* Copyright (c) 2004, 2008 IBM Corporation and others.
* Copyright (C) 2007, Martin Oberhuber ([email protected])
* Copyright (C) 2008, Robin Rosenberg <[email protected]>
* Copyright (C) 2010, Jens Baumgart <[email protected]>
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package org.eclipse.egit.core.internal.util;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.egit.core.Activator;
import org.eclipse.egit.core.CoreText;
import org.eclipse.egit.core.project.RepositoryMapping;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.osgi.util.NLS;
/**
* This class contains utility methods related to projects
* TODO: rename to RefreshUtil or ResourceUtil?
*/
public class ProjectUtil {
/**
* The name of the folder containing metadata information for the workspace.
*/
public static final String METADATA_FOLDER = ".metadata"; //$NON-NLS-1$
/**
* The method returns all valid open projects contained in the given Git
* repository. A project is considered as valid if the .project file exists.
* @see ProjectUtil#refreshValidProjects(IProject[], IProgressMonitor)
* @param repository
* @return valid open projects
* @throws CoreException
*/
public static IProject[] getValidOpenProjects(Repository repository)
throws CoreException {
final IProject[] projects = ResourcesPlugin.getWorkspace().getRoot()
.getProjects();
List<IProject> result = new ArrayList<IProject>();
final File parentFile = repository.getWorkTree();
for (IProject p : projects) {
IPath projectLocation = p.getLocation();
if (!p.isOpen() || projectLocation == null)
continue;
String projectFilePath = projectLocation
.append(".project").toOSString(); //$NON-NLS-1$
File projectFile = new File(projectFilePath);
if (projectFile.exists()) {
final File file = p.getLocation().toFile();
if (file.getAbsolutePath().startsWith(
parentFile.getAbsolutePath())) {
result.add(p);
}
}
}
return result.toArray(new IProject[result.size()]);
}
/**
* The method refreshes the given projects. Projects with missing .project
* file are deleted. The method should be called in the following flow:<br>
* <ol>
* <li>Call {@link ProjectUtil#getValidOpenProjects(Repository)}
* <li>Perform a workdir checkout (e.g. branch, reset)
* <li>Call
* {@link ProjectUtil#refreshValidProjects(IProject[], IProgressMonitor)}
* </ol>
*
* @param projects
* list of valid projects before workdir checkout.
* @param monitor
* @throws CoreException
*/
public static void refreshValidProjects(IProject[] projects,
IProgressMonitor monitor) throws CoreException {
try {
monitor.beginTask(CoreText.ProjectUtil_refreshingProjects,
projects.length);
for (IProject p : projects) {
if (monitor.isCanceled())
break;
String projectFilePath = p.getLocation().append(".project").toOSString(); //$NON-NLS-1$
File projectFile = new File(projectFilePath);
if (projectFile.exists())
p.refreshLocal(IResource.DEPTH_INFINITE,
new SubProgressMonitor(monitor, 1));
else
p.delete(false, true, new SubProgressMonitor(monitor, 1));
monitor.worked(1);
}
} finally {
monitor.done();
}
}
/**
* The method refreshes resources
*
* @param resources
* resources to refresh
* @param monitor
* @throws CoreException
*/
public static void refreshResources(IResource[] resources,
IProgressMonitor monitor) throws CoreException {
try {
monitor.beginTask(CoreText.ProjectUtil_refreshing,
resources.length);
for (IResource resource : resources) {
if (monitor.isCanceled())
break;
resource.refreshLocal(IResource.DEPTH_INFINITE,
new SubProgressMonitor(monitor, 1));
monitor.worked(1);
}
} finally {
monitor.done();
}
}
/**
* The method retrieves all accessible projects related to the given
* repository
*
* @param repository
* @return list of projects
*/
public static IProject[] getProjects(Repository repository) {
List<IProject> result = new ArrayList<IProject>();
final IProject[] projects = ResourcesPlugin.getWorkspace().getRoot()
.getProjects();
for (IProject project : projects) {
if (project.isAccessible()) {
RepositoryMapping mapping = RepositoryMapping
.getMapping(project);
if (mapping != null && mapping.getRepository() == repository)
result.add(project);
}
}
return result.toArray(new IProject[result.size()]);
}
/**
* Find directories containing .project files recursively starting at given
* directory
*
* @param files
* @param directory
* @param visistedDirs
* @param monitor
* @return true if projects files found, false otherwise
*/
public static boolean findProjectFiles(final Collection<File> files,
final File directory, final Set<String> visistedDirs,
final IProgressMonitor monitor) {
if (directory == null)
return false;
IProgressMonitor pm = monitor;
if (pm == null)
pm = new NullProgressMonitor();
else if (pm.isCanceled())
return false;
- monitor.subTask(NLS.bind(CoreText.ProjectUtil_taskCheckingDirectory,
+ pm.subTask(NLS.bind(CoreText.ProjectUtil_taskCheckingDirectory,
directory.getPath()));
final File[] contents = directory.listFiles();
if (contents == null || contents.length == 0)
return false;
Set<String> directoriesVisited;
// Initialize recursion guard for recursive symbolic links
if (visistedDirs == null) {
directoriesVisited = new HashSet<String>();
try {
directoriesVisited.add(directory.getCanonicalPath());
} catch (IOException exception) {
Activator.logError(exception.getLocalizedMessage(), exception);
}
} else
directoriesVisited = visistedDirs;
// first look for project description files
final String dotProject = IProjectDescription.DESCRIPTION_FILE_NAME;
for (int i = 0; i < contents.length; i++) {
File file = contents[i];
if (file.isFile() && file.getName().equals(dotProject)) {
files.add(file);
// don't search sub-directories since we can't have nested
// projects
return true;
}
}
// no project description found, so recurse into sub-directories
for (int i = 0; i < contents.length; i++) {
// Skip non-directories
if (!contents[i].isDirectory())
continue;
// Skip .metadata folders
if (contents[i].getName().equals(METADATA_FOLDER))
continue;
try {
String canonicalPath = contents[i].getCanonicalPath();
if (!directoriesVisited.add(canonicalPath)) {
// already been here --> do not recurse
continue;
}
} catch (IOException exception) {
Activator.logError(exception.getLocalizedMessage(), exception);
}
findProjectFiles(files, contents[i], directoriesVisited, pm);
}
return true;
}
}
| true | true | public static boolean findProjectFiles(final Collection<File> files,
final File directory, final Set<String> visistedDirs,
final IProgressMonitor monitor) {
if (directory == null)
return false;
IProgressMonitor pm = monitor;
if (pm == null)
pm = new NullProgressMonitor();
else if (pm.isCanceled())
return false;
monitor.subTask(NLS.bind(CoreText.ProjectUtil_taskCheckingDirectory,
directory.getPath()));
final File[] contents = directory.listFiles();
if (contents == null || contents.length == 0)
return false;
Set<String> directoriesVisited;
// Initialize recursion guard for recursive symbolic links
if (visistedDirs == null) {
directoriesVisited = new HashSet<String>();
try {
directoriesVisited.add(directory.getCanonicalPath());
} catch (IOException exception) {
Activator.logError(exception.getLocalizedMessage(), exception);
}
} else
directoriesVisited = visistedDirs;
// first look for project description files
final String dotProject = IProjectDescription.DESCRIPTION_FILE_NAME;
for (int i = 0; i < contents.length; i++) {
File file = contents[i];
if (file.isFile() && file.getName().equals(dotProject)) {
files.add(file);
// don't search sub-directories since we can't have nested
// projects
return true;
}
}
// no project description found, so recurse into sub-directories
for (int i = 0; i < contents.length; i++) {
// Skip non-directories
if (!contents[i].isDirectory())
continue;
// Skip .metadata folders
if (contents[i].getName().equals(METADATA_FOLDER))
continue;
try {
String canonicalPath = contents[i].getCanonicalPath();
if (!directoriesVisited.add(canonicalPath)) {
// already been here --> do not recurse
continue;
}
} catch (IOException exception) {
Activator.logError(exception.getLocalizedMessage(), exception);
}
findProjectFiles(files, contents[i], directoriesVisited, pm);
}
return true;
}
| public static boolean findProjectFiles(final Collection<File> files,
final File directory, final Set<String> visistedDirs,
final IProgressMonitor monitor) {
if (directory == null)
return false;
IProgressMonitor pm = monitor;
if (pm == null)
pm = new NullProgressMonitor();
else if (pm.isCanceled())
return false;
pm.subTask(NLS.bind(CoreText.ProjectUtil_taskCheckingDirectory,
directory.getPath()));
final File[] contents = directory.listFiles();
if (contents == null || contents.length == 0)
return false;
Set<String> directoriesVisited;
// Initialize recursion guard for recursive symbolic links
if (visistedDirs == null) {
directoriesVisited = new HashSet<String>();
try {
directoriesVisited.add(directory.getCanonicalPath());
} catch (IOException exception) {
Activator.logError(exception.getLocalizedMessage(), exception);
}
} else
directoriesVisited = visistedDirs;
// first look for project description files
final String dotProject = IProjectDescription.DESCRIPTION_FILE_NAME;
for (int i = 0; i < contents.length; i++) {
File file = contents[i];
if (file.isFile() && file.getName().equals(dotProject)) {
files.add(file);
// don't search sub-directories since we can't have nested
// projects
return true;
}
}
// no project description found, so recurse into sub-directories
for (int i = 0; i < contents.length; i++) {
// Skip non-directories
if (!contents[i].isDirectory())
continue;
// Skip .metadata folders
if (contents[i].getName().equals(METADATA_FOLDER))
continue;
try {
String canonicalPath = contents[i].getCanonicalPath();
if (!directoriesVisited.add(canonicalPath)) {
// already been here --> do not recurse
continue;
}
} catch (IOException exception) {
Activator.logError(exception.getLocalizedMessage(), exception);
}
findProjectFiles(files, contents[i], directoriesVisited, pm);
}
return true;
}
|
diff --git a/src/main/java/com/onarandombox/MultiverseNetherPortals/listeners/MVNPPlayerListener.java b/src/main/java/com/onarandombox/MultiverseNetherPortals/listeners/MVNPPlayerListener.java
index 7fe46fc..43dc863 100644
--- a/src/main/java/com/onarandombox/MultiverseNetherPortals/listeners/MVNPPlayerListener.java
+++ b/src/main/java/com/onarandombox/MultiverseNetherPortals/listeners/MVNPPlayerListener.java
@@ -1,102 +1,103 @@
package com.onarandombox.MultiverseNetherPortals.listeners;
import com.onarandombox.MultiverseCore.api.MVWorldManager;
import com.onarandombox.MultiverseCore.api.MultiverseWorld;
import com.onarandombox.MultiverseCore.utils.PermissionTools;
import com.onarandombox.MultiverseNetherPortals.MultiverseNetherPortals;
import com.onarandombox.MultiverseNetherPortals.enums.PortalType;
import com.onarandombox.MultiverseNetherPortals.utils.MVLinkChecker;
import com.onarandombox.MultiverseNetherPortals.utils.MVNameChecker;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerPortalEvent;
import java.util.logging.Level;
public class MVNPPlayerListener implements Listener {
private MultiverseNetherPortals plugin;
private MVNameChecker nameChecker;
private MVLinkChecker linkChecker;
private MVWorldManager worldManager;
private PermissionTools pt;
public MVNPPlayerListener(MultiverseNetherPortals plugin) {
this.plugin = plugin;
this.nameChecker = new MVNameChecker(plugin);
this.worldManager = this.plugin.getCore().getMVWorldManager();
this.pt = new PermissionTools(this.plugin.getCore());
this.linkChecker = new MVLinkChecker(this.plugin);
}
@EventHandler(priority = EventPriority.NORMAL)
public void onPlayerPortal(PlayerPortalEvent event) {
if (event.isCancelled()) {
this.plugin.log(Level.FINEST, "PlayerPortalEvent was cancelled! NOT teleporting!");
return;
}
Location originalTo = event.getTo();
if (originalTo != null) {
originalTo = originalTo.clone();
}
Location currentLocation = event.getFrom().clone();
String currentWorld = currentLocation.getWorld().getName();
PortalType type = PortalType.END;
if (event.getFrom().getBlock().getType() == Material.PORTAL) {
type = PortalType.NETHER;
+ event.useTravelAgent(true);
}
String linkedWorld = this.plugin.getWorldLink(currentWorld, type);
if (linkedWorld != null) {
this.linkChecker.getNewTeleportLocation(event, currentLocation, linkedWorld);
} else if (this.nameChecker.isValidNetherName(currentWorld)) {
if (type == PortalType.NETHER) {
this.plugin.log(Level.FINER, "");
this.linkChecker.getNewTeleportLocation(event, currentLocation, this.nameChecker.getNormalName(currentWorld, PortalType.NETHER));
} else {
this.linkChecker.getNewTeleportLocation(event, currentLocation, this.nameChecker.getEndName(this.nameChecker.getNormalName(currentWorld, PortalType.NETHER)));
}
} else if (this.nameChecker.isValidEndName(currentWorld)) {
if (type == PortalType.NETHER) {
this.linkChecker.getNewTeleportLocation(event, currentLocation, this.nameChecker.getNetherName(this.nameChecker.getNormalName(currentWorld, PortalType.END)));
} else {
this.linkChecker.getNewTeleportLocation(event, currentLocation, this.nameChecker.getNormalName(currentWorld, PortalType.END));
}
} else {
if(type == PortalType.END) {
this.linkChecker.getNewTeleportLocation(event, currentLocation, this.nameChecker.getEndName(currentWorld));
} else {
this.linkChecker.getNewTeleportLocation(event, currentLocation, this.nameChecker.getNetherName(currentWorld));
}
}
if (event.getTo() == null || event.getFrom() == null) {
return;
}
if (event.getFrom().getWorld().equals(event.getTo().getWorld())) {
// The player is Portaling to the same world.
this.plugin.log(Level.FINER, "Player '" + event.getPlayer().getName() + "' is portaling to the same world. Ignoring.");
event.setTo(originalTo);
return;
}
MultiverseWorld fromWorld = this.worldManager.getMVWorld(event.getFrom().getWorld().getName());
MultiverseWorld toWorld = this.worldManager.getMVWorld(event.getTo().getWorld().getName());
if (!event.isCancelled() && fromWorld.getEnvironment() == World.Environment.THE_END && type == PortalType.END) {
this.plugin.log(Level.FINE, "Player '" + event.getPlayer().getName() + "' will be teleported to the spawn of '" + toWorld.getName() + "' since they used an end exit portal.");
event.getPortalTravelAgent().setCanCreatePortal(false);
if (toWorld.getBedRespawn()
&& event.getPlayer().getBedSpawnLocation() != null
&& event.getPlayer().getBedSpawnLocation().getWorld().getUID() == toWorld.getCBWorld().getUID()) {
event.setTo(event.getPlayer().getBedSpawnLocation());
} else {
event.setTo(toWorld.getSpawnLocation());
}
}
}
}
| true | true | public void onPlayerPortal(PlayerPortalEvent event) {
if (event.isCancelled()) {
this.plugin.log(Level.FINEST, "PlayerPortalEvent was cancelled! NOT teleporting!");
return;
}
Location originalTo = event.getTo();
if (originalTo != null) {
originalTo = originalTo.clone();
}
Location currentLocation = event.getFrom().clone();
String currentWorld = currentLocation.getWorld().getName();
PortalType type = PortalType.END;
if (event.getFrom().getBlock().getType() == Material.PORTAL) {
type = PortalType.NETHER;
}
String linkedWorld = this.plugin.getWorldLink(currentWorld, type);
if (linkedWorld != null) {
this.linkChecker.getNewTeleportLocation(event, currentLocation, linkedWorld);
} else if (this.nameChecker.isValidNetherName(currentWorld)) {
if (type == PortalType.NETHER) {
this.plugin.log(Level.FINER, "");
this.linkChecker.getNewTeleportLocation(event, currentLocation, this.nameChecker.getNormalName(currentWorld, PortalType.NETHER));
} else {
this.linkChecker.getNewTeleportLocation(event, currentLocation, this.nameChecker.getEndName(this.nameChecker.getNormalName(currentWorld, PortalType.NETHER)));
}
} else if (this.nameChecker.isValidEndName(currentWorld)) {
if (type == PortalType.NETHER) {
this.linkChecker.getNewTeleportLocation(event, currentLocation, this.nameChecker.getNetherName(this.nameChecker.getNormalName(currentWorld, PortalType.END)));
} else {
this.linkChecker.getNewTeleportLocation(event, currentLocation, this.nameChecker.getNormalName(currentWorld, PortalType.END));
}
} else {
if(type == PortalType.END) {
this.linkChecker.getNewTeleportLocation(event, currentLocation, this.nameChecker.getEndName(currentWorld));
} else {
this.linkChecker.getNewTeleportLocation(event, currentLocation, this.nameChecker.getNetherName(currentWorld));
}
}
if (event.getTo() == null || event.getFrom() == null) {
return;
}
if (event.getFrom().getWorld().equals(event.getTo().getWorld())) {
// The player is Portaling to the same world.
this.plugin.log(Level.FINER, "Player '" + event.getPlayer().getName() + "' is portaling to the same world. Ignoring.");
event.setTo(originalTo);
return;
}
MultiverseWorld fromWorld = this.worldManager.getMVWorld(event.getFrom().getWorld().getName());
MultiverseWorld toWorld = this.worldManager.getMVWorld(event.getTo().getWorld().getName());
if (!event.isCancelled() && fromWorld.getEnvironment() == World.Environment.THE_END && type == PortalType.END) {
this.plugin.log(Level.FINE, "Player '" + event.getPlayer().getName() + "' will be teleported to the spawn of '" + toWorld.getName() + "' since they used an end exit portal.");
event.getPortalTravelAgent().setCanCreatePortal(false);
if (toWorld.getBedRespawn()
&& event.getPlayer().getBedSpawnLocation() != null
&& event.getPlayer().getBedSpawnLocation().getWorld().getUID() == toWorld.getCBWorld().getUID()) {
event.setTo(event.getPlayer().getBedSpawnLocation());
} else {
event.setTo(toWorld.getSpawnLocation());
}
}
}
| public void onPlayerPortal(PlayerPortalEvent event) {
if (event.isCancelled()) {
this.plugin.log(Level.FINEST, "PlayerPortalEvent was cancelled! NOT teleporting!");
return;
}
Location originalTo = event.getTo();
if (originalTo != null) {
originalTo = originalTo.clone();
}
Location currentLocation = event.getFrom().clone();
String currentWorld = currentLocation.getWorld().getName();
PortalType type = PortalType.END;
if (event.getFrom().getBlock().getType() == Material.PORTAL) {
type = PortalType.NETHER;
event.useTravelAgent(true);
}
String linkedWorld = this.plugin.getWorldLink(currentWorld, type);
if (linkedWorld != null) {
this.linkChecker.getNewTeleportLocation(event, currentLocation, linkedWorld);
} else if (this.nameChecker.isValidNetherName(currentWorld)) {
if (type == PortalType.NETHER) {
this.plugin.log(Level.FINER, "");
this.linkChecker.getNewTeleportLocation(event, currentLocation, this.nameChecker.getNormalName(currentWorld, PortalType.NETHER));
} else {
this.linkChecker.getNewTeleportLocation(event, currentLocation, this.nameChecker.getEndName(this.nameChecker.getNormalName(currentWorld, PortalType.NETHER)));
}
} else if (this.nameChecker.isValidEndName(currentWorld)) {
if (type == PortalType.NETHER) {
this.linkChecker.getNewTeleportLocation(event, currentLocation, this.nameChecker.getNetherName(this.nameChecker.getNormalName(currentWorld, PortalType.END)));
} else {
this.linkChecker.getNewTeleportLocation(event, currentLocation, this.nameChecker.getNormalName(currentWorld, PortalType.END));
}
} else {
if(type == PortalType.END) {
this.linkChecker.getNewTeleportLocation(event, currentLocation, this.nameChecker.getEndName(currentWorld));
} else {
this.linkChecker.getNewTeleportLocation(event, currentLocation, this.nameChecker.getNetherName(currentWorld));
}
}
if (event.getTo() == null || event.getFrom() == null) {
return;
}
if (event.getFrom().getWorld().equals(event.getTo().getWorld())) {
// The player is Portaling to the same world.
this.plugin.log(Level.FINER, "Player '" + event.getPlayer().getName() + "' is portaling to the same world. Ignoring.");
event.setTo(originalTo);
return;
}
MultiverseWorld fromWorld = this.worldManager.getMVWorld(event.getFrom().getWorld().getName());
MultiverseWorld toWorld = this.worldManager.getMVWorld(event.getTo().getWorld().getName());
if (!event.isCancelled() && fromWorld.getEnvironment() == World.Environment.THE_END && type == PortalType.END) {
this.plugin.log(Level.FINE, "Player '" + event.getPlayer().getName() + "' will be teleported to the spawn of '" + toWorld.getName() + "' since they used an end exit portal.");
event.getPortalTravelAgent().setCanCreatePortal(false);
if (toWorld.getBedRespawn()
&& event.getPlayer().getBedSpawnLocation() != null
&& event.getPlayer().getBedSpawnLocation().getWorld().getUID() == toWorld.getCBWorld().getUID()) {
event.setTo(event.getPlayer().getBedSpawnLocation());
} else {
event.setTo(toWorld.getSpawnLocation());
}
}
}
|
diff --git a/distributed1/serversrc/resImpl/Middleware.java b/distributed1/serversrc/resImpl/Middleware.java
index b08b1d9..0ae9ed6 100644
--- a/distributed1/serversrc/resImpl/Middleware.java
+++ b/distributed1/serversrc/resImpl/Middleware.java
@@ -1,367 +1,372 @@
package serversrc.resImpl;
import java.rmi.RMISecurityManager;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.Enumeration;
import java.util.Vector;
import serversrc.resInterface.*;
public class Middleware implements ResourceManager {
RMCar rmCar;
RMFlight rmFlight;
RMHotel rmHotel;
RMCustomer rmCustomer;
public static void main(String args[]) {
// Figure out where server is running
String server = "localhost";
int port = 1099;
Registry registry;
if (args.length == 5) {
server = server + ":" + args[4];
port = Integer.parseInt(args[4]);
} else {
System.err.println ("Wrong usage");
System.out.println("Usage: java ResImpl.Middleware rmCar rmFlight rmHotel rmCustomer [port]");
System.exit(1);
}
try {
// create a new Server object
// dynamically generate the stub (client proxy)
Middleware obj = new Middleware();
ResourceManager rm = (ResourceManager) UnicastRemoteObject.exportObject(obj, 0);
// get a reference to the rmiregistry
registry = LocateRegistry.getRegistry(args[0], port);
// get the proxy and the remote reference by rmiregistry lookup
obj.rmCar = (RMCar) registry.lookup("Group2RMCar");
registry = LocateRegistry.getRegistry(args[1], port);
obj.rmFlight = (RMFlight) registry.lookup("Group2RMFlight");
registry = LocateRegistry.getRegistry(args[2], port);
obj.rmHotel = (RMHotel) registry.lookup("Group2RMHotel");
registry = LocateRegistry.getRegistry(args[3], port);
obj.rmCustomer = (RMCustomer) registry.lookup("Group2RMCustomer");
if(obj.rmCar!=null && obj.rmFlight != null && obj.rmHotel!=null)
{
System.out.println("Successful");
System.out.println("Connected to RMs");
}
else
{
System.out.println("Unsuccessful");
}
// Bind the remote object's stub in the registry
registry = LocateRegistry.getRegistry(port);
registry = LocateRegistry.getRegistry(port);
registry.rebind("Group2Middleware", rm);
System.err.println("Server ready");
} catch (Exception e) {
System.err.println("Server exception: " + e.toString());
e.printStackTrace();
}
// Create and install a security manager
if (System.getSecurityManager() == null) {
System.setSecurityManager(new RMISecurityManager());
}
}
@Override
public boolean addFlight(int id, int flightNum, int flightSeats,
int flightPrice) throws RemoteException {
return rmFlight.addFlight(id, flightNum, flightSeats, flightPrice);
}
@Override
public boolean addCars(int id, String location, int numCars, int price)
throws RemoteException {
return rmCar.addCars(id, location, numCars, price);
}
@Override
public boolean addRooms(int id, String location, int numRooms, int price)
throws RemoteException {
return rmHotel.addRooms(id, location, numRooms, price);
}
@Override
public int newCustomer(int id) throws RemoteException {
return rmCustomer.newCustomer(id);
}
@Override
public boolean newCustomer(int id, int cid) throws RemoteException {
return rmCustomer.newCustomer(id, cid);
}
@Override
public boolean deleteFlight(int id, int flightNum) throws RemoteException {
return rmFlight.deleteFlight(id, flightNum);
}
@Override
public boolean deleteCars(int id, String location) throws RemoteException {
return rmCar.deleteCars(id, location);
}
@Override
public boolean deleteRooms(int id, String location) throws RemoteException {
return rmHotel.deleteRooms(id, location);
}
@Override
public boolean deleteCustomer(int id, int customer) throws RemoteException {
RMHashtable reservationHT = rmCustomer.deleteCustomer(id, customer);
for (Enumeration e = reservationHT.keys(); e.hasMoreElements();) {
String reservedkey = (String) (e.nextElement());
ReservedItem reserveditem = (ReservedItem) reservationHT.get( reservedkey );
Trace.info("RM::deleteCustomer(" + id + ", " + customer + ") has reserved " + reserveditem.getKey() + " " + reserveditem.getCount() + " times" );
if (reserveditem.getrType() == ReservedItem.rType.FLIGHT)
rmFlight.unreserveItem(id, reserveditem);
else if (reserveditem.getrType() == ReservedItem.rType.CAR)
rmCar.unreserveItem(id, reserveditem);
else if (reserveditem.getrType() == ReservedItem.rType.ROOM)
rmHotel.unreserveItem(id, reserveditem);
}
return true;
}
@Override
public int queryFlight(int id, int flightNumber) throws RemoteException {
return rmFlight.queryFlight(id, flightNumber);
}
@Override
public int queryCars(int id, String location) throws RemoteException {
return rmCar.queryCars(id, location);
}
@Override
public int queryRooms(int id, String location) throws RemoteException {
return rmHotel.queryRooms(id, location);
}
@Override
public String queryCustomerInfo(int id, int customer)
throws RemoteException {
return rmCustomer.queryCustomerInfo(id, customer);
}
@Override
public int queryFlightPrice(int id, int flightNumber)
throws RemoteException {
return rmFlight.queryFlightPrice(id, flightNumber);
}
@Override
public int queryCarsPrice(int id, String location) throws RemoteException {
return rmCar.queryCarsPrice(id, location);
}
@Override
public int queryRoomsPrice(int id, String location) throws RemoteException {
return rmHotel.queryRoomsPrice(id, location);
}
@Override
public boolean reserveFlight(int id, int customer, int flightNum)
throws RemoteException {
ReservedItem item = reserveItem(id, customer, Flight.getKey(flightNum), String.valueOf(flightNum), ReservedItem.rType.FLIGHT);
return (item != null);
}
@Override
public boolean reserveCar(int id, int customer, String location)
throws RemoteException {
ReservedItem item = reserveItem(id, customer, Car.getKey(location), location, ReservedItem.rType.CAR);
return (item != null);
}
@Override
public boolean reserveRoom(int id, int customer, String location)
throws RemoteException {
ReservedItem item = reserveItem(id, customer, Hotel.getKey(location), location, ReservedItem.rType.ROOM);
return (item != null);
}
@Override
public boolean itinerary(int id, int customer, Vector flightNumbers,
String location, boolean car, boolean room) throws RemoteException {
Trace.info("RM::itinerary( " + id + ", customer=" + customer + ", " +flightNumbers+ ", "+location+
", " + car + ", " + room + " ) called" );
// Read customer object if it exists (and read lock it)
Customer cust = rmCustomer.getCustomer(id, customer);
if ( cust == null ) {
Trace.info("RM::itinerary( " + id + ", customer=" + customer + ", " +flightNumbers+ ", "+location+
", " + car + ", " + room + " ) -- Customer non existent, adding it." );
return false;
}
ReservedItem reservedCar = null;
ReservedItem reservedRoom = null;
if (car){
reservedCar = reserveItem(id, customer, Car.getKey(location) ,location, ReservedItem.rType.CAR);
if (reservedCar == null) {
Trace.info("RM::itinerary( " + id + ", customer=" + customer + ", " +flightNumbers+ ", "+location+
", " + car + ", " + room + " ) -- Car could not have been reserved." );
return false;
}
}
if (room){
reservedRoom = reserveItem(id, customer, Hotel.getKey(location) ,location, ReservedItem.rType.ROOM);
if (reservedRoom == null) {
Trace.info("RM::itinerary( " + id + ", customer=" + customer + ", " +flightNumbers+ ", "+location+
", " + car + ", " + room + " ) -- Room could not have been reserved." );
- unreserveItem(id, customer, reservedCar, ReservedItem.rType.CAR);
+ if(reservedCar != null)
+ unreserveItem(id, customer, reservedCar, ReservedItem.rType.CAR);
return false;
}
}
Vector flightsDone = new Vector();
for (Enumeration e = flightNumbers.elements(); e.hasMoreElements();) {
int flightnum = 0;
try {
flightnum = getInt(e.nextElement());
} catch(Exception ex) {
Trace.info("RM::itinerary( " + id + ", customer=" + customer + ", " +flightNumbers+ ", "+location+
", " + car + ", " + room + " ) -- Expected FlightNumber was not a valid integer. Exception "
+ ex + " cached");
- unreserveItem(id, customer, reservedCar, ReservedItem.rType.CAR);
- unreserveItem(id, customer, reservedRoom, ReservedItem.rType.ROOM);
+ if(reservedCar != null)
+ unreserveItem(id, customer, reservedCar, ReservedItem.rType.CAR);
+ if(reservedRoom != null)
+ unreserveItem(id, customer, reservedRoom, ReservedItem.rType.ROOM);
for (Enumeration f = flightsDone.elements(); f.hasMoreElements();) {
unreserveItem(id, customer, (ReservedItem) f.nextElement(), ReservedItem.rType.ROOM);
}
return false;
}
ReservedItem reservedFlight = reserveItem(id, customer, Flight.getKey(flightnum), String.valueOf(flightnum), ReservedItem.rType.FLIGHT);
if (reservedFlight == null){
Trace.info("RM::itinerary( " + id + ", customer=" + customer + ", " +flightnum+ ", "+location+
", " + car + ", " + room + " ) -- flight could not have been reserved." );
- unreserveItem(id, customer, reservedCar, ReservedItem.rType.CAR);
- unreserveItem(id, customer, reservedRoom, ReservedItem.rType.ROOM);
+ if(reservedCar != null)
+ unreserveItem(id, customer, reservedCar, ReservedItem.rType.CAR);
+ if(reservedRoom != null)
+ unreserveItem(id, customer, reservedRoom, ReservedItem.rType.ROOM);
for (Enumeration f = flightsDone.elements(); f.hasMoreElements();) {
unreserveItem(id, customer, (ReservedItem) f.nextElement(), ReservedItem.rType.ROOM);
}
return false;
}
flightsDone.add(reservedFlight);
}
return true;
}
/*Since the client sends a Vector of objects, we need this
* unsafe function that retrieves the int from the vector.
*
*/
public int getInt(Object temp) throws Exception {
try {
return (new Integer((String)temp)).intValue();
}
catch(Exception e) {
throw e;
}
}
/*
* Call RMCust to obtain customer, if it exists.
* Verify if item exists and is available. (Call RM*obj*)
* Reserve with RMCustomer
* Tell RM*obj* to reduce the number of available
*/
protected ReservedItem reserveItem(int id, int customerID, String key, String location, ReservedItem.rType rtype)
throws RemoteException {
Trace.info("RM::reserveItem( " + id + ", customer=" + customerID + ", " +key+ ", "+location+" ) called" );
// Verifies if customer exists
Customer cust = rmCustomer.getCustomer(id, customerID);
if ( cust == null ) {
Trace.warn("RM::reserveCar( " + id + ", " + customerID + ", " + key + ", "+location+") failed--customer doesn't exist" );
return null;
}
RMInteger price = null;
// check if the item is available
if (rtype == ReservedItem.rType.CAR)
price = rmCar.reserveItem(id, customerID, key, location);
else if (rtype == ReservedItem.rType.FLIGHT)
price = rmFlight.reserveItem(id, customerID, key, location);
else if (rtype == ReservedItem.rType.ROOM)
price = rmHotel.reserveItem(id, customerID, key, location);
if ( price == null ) {
Trace.warn("RM::reserveItem( " + id + ", " + customerID + ", " + key+", " +location+") failed-- Object RM returned false." );
return null;
} else {
// We do the following check in case the customer has been
// deleted between the first verification and now.
ReservedItem item = rmCustomer.reserve(id, customerID, key, location, price.getValue(), rtype);
if(item != null){
Trace.info("RM::reserveItem( " + id + ", " + customerID + ", " + key + ", " +location+") succeeded" );
return item;
} else {
Trace.info("RM::reserveItem( " + id + ", " + customerID + ", " + key + ", " +location+") failed -- Customer has been deleted!" );
if (rtype == ReservedItem.rType.CAR)
rmCar.unreserveItem(id, key);
else if (rtype == ReservedItem.rType.FLIGHT)
rmFlight.unreserveItem(id, key);
else if (rtype == ReservedItem.rType.ROOM)
rmHotel.unreserveItem(id, key);
}
return null;
}
}
/*
* unreserveItem is used by the itinerary class to cancel a reserved item when the whole reservation failed.
*/
protected boolean unreserveItem(int id, int customerID, ReservedItem item, ReservedItem.rType rtype)
throws RemoteException {
Trace.info("RM::unreserveItem( " + id + ", customer=" + customerID + ", " +item+ " ) called" );
// Verifies if customer exists
if(!rmCustomer.unreserve(id, customerID, item)){
Trace.warn("RM::unreserveItem( " + id + ", " + customerID + ", " +item +" ) failed -- Customer has been deleted." );
return false;
}
boolean done = false;
// check if the item is available
if (rtype == ReservedItem.rType.CAR)
done = rmCar.unreserveItem(id, item);
else if (rtype == ReservedItem.rType.FLIGHT)
done = rmFlight.unreserveItem(id, item);
else if (rtype == ReservedItem.rType.ROOM)
done = rmHotel.unreserveItem(id, item);
if (!done) {
Trace.warn("RM::unreserveItem( " + id + ", " + customerID + ", " +item +" ) failed-- Object RM returned false." );
return false;
}
return true;
}
}
| false | true | public boolean itinerary(int id, int customer, Vector flightNumbers,
String location, boolean car, boolean room) throws RemoteException {
Trace.info("RM::itinerary( " + id + ", customer=" + customer + ", " +flightNumbers+ ", "+location+
", " + car + ", " + room + " ) called" );
// Read customer object if it exists (and read lock it)
Customer cust = rmCustomer.getCustomer(id, customer);
if ( cust == null ) {
Trace.info("RM::itinerary( " + id + ", customer=" + customer + ", " +flightNumbers+ ", "+location+
", " + car + ", " + room + " ) -- Customer non existent, adding it." );
return false;
}
ReservedItem reservedCar = null;
ReservedItem reservedRoom = null;
if (car){
reservedCar = reserveItem(id, customer, Car.getKey(location) ,location, ReservedItem.rType.CAR);
if (reservedCar == null) {
Trace.info("RM::itinerary( " + id + ", customer=" + customer + ", " +flightNumbers+ ", "+location+
", " + car + ", " + room + " ) -- Car could not have been reserved." );
return false;
}
}
if (room){
reservedRoom = reserveItem(id, customer, Hotel.getKey(location) ,location, ReservedItem.rType.ROOM);
if (reservedRoom == null) {
Trace.info("RM::itinerary( " + id + ", customer=" + customer + ", " +flightNumbers+ ", "+location+
", " + car + ", " + room + " ) -- Room could not have been reserved." );
unreserveItem(id, customer, reservedCar, ReservedItem.rType.CAR);
return false;
}
}
Vector flightsDone = new Vector();
for (Enumeration e = flightNumbers.elements(); e.hasMoreElements();) {
int flightnum = 0;
try {
flightnum = getInt(e.nextElement());
} catch(Exception ex) {
Trace.info("RM::itinerary( " + id + ", customer=" + customer + ", " +flightNumbers+ ", "+location+
", " + car + ", " + room + " ) -- Expected FlightNumber was not a valid integer. Exception "
+ ex + " cached");
unreserveItem(id, customer, reservedCar, ReservedItem.rType.CAR);
unreserveItem(id, customer, reservedRoom, ReservedItem.rType.ROOM);
for (Enumeration f = flightsDone.elements(); f.hasMoreElements();) {
unreserveItem(id, customer, (ReservedItem) f.nextElement(), ReservedItem.rType.ROOM);
}
return false;
}
ReservedItem reservedFlight = reserveItem(id, customer, Flight.getKey(flightnum), String.valueOf(flightnum), ReservedItem.rType.FLIGHT);
if (reservedFlight == null){
Trace.info("RM::itinerary( " + id + ", customer=" + customer + ", " +flightnum+ ", "+location+
", " + car + ", " + room + " ) -- flight could not have been reserved." );
unreserveItem(id, customer, reservedCar, ReservedItem.rType.CAR);
unreserveItem(id, customer, reservedRoom, ReservedItem.rType.ROOM);
for (Enumeration f = flightsDone.elements(); f.hasMoreElements();) {
unreserveItem(id, customer, (ReservedItem) f.nextElement(), ReservedItem.rType.ROOM);
}
return false;
}
flightsDone.add(reservedFlight);
}
return true;
}
| public boolean itinerary(int id, int customer, Vector flightNumbers,
String location, boolean car, boolean room) throws RemoteException {
Trace.info("RM::itinerary( " + id + ", customer=" + customer + ", " +flightNumbers+ ", "+location+
", " + car + ", " + room + " ) called" );
// Read customer object if it exists (and read lock it)
Customer cust = rmCustomer.getCustomer(id, customer);
if ( cust == null ) {
Trace.info("RM::itinerary( " + id + ", customer=" + customer + ", " +flightNumbers+ ", "+location+
", " + car + ", " + room + " ) -- Customer non existent, adding it." );
return false;
}
ReservedItem reservedCar = null;
ReservedItem reservedRoom = null;
if (car){
reservedCar = reserveItem(id, customer, Car.getKey(location) ,location, ReservedItem.rType.CAR);
if (reservedCar == null) {
Trace.info("RM::itinerary( " + id + ", customer=" + customer + ", " +flightNumbers+ ", "+location+
", " + car + ", " + room + " ) -- Car could not have been reserved." );
return false;
}
}
if (room){
reservedRoom = reserveItem(id, customer, Hotel.getKey(location) ,location, ReservedItem.rType.ROOM);
if (reservedRoom == null) {
Trace.info("RM::itinerary( " + id + ", customer=" + customer + ", " +flightNumbers+ ", "+location+
", " + car + ", " + room + " ) -- Room could not have been reserved." );
if(reservedCar != null)
unreserveItem(id, customer, reservedCar, ReservedItem.rType.CAR);
return false;
}
}
Vector flightsDone = new Vector();
for (Enumeration e = flightNumbers.elements(); e.hasMoreElements();) {
int flightnum = 0;
try {
flightnum = getInt(e.nextElement());
} catch(Exception ex) {
Trace.info("RM::itinerary( " + id + ", customer=" + customer + ", " +flightNumbers+ ", "+location+
", " + car + ", " + room + " ) -- Expected FlightNumber was not a valid integer. Exception "
+ ex + " cached");
if(reservedCar != null)
unreserveItem(id, customer, reservedCar, ReservedItem.rType.CAR);
if(reservedRoom != null)
unreserveItem(id, customer, reservedRoom, ReservedItem.rType.ROOM);
for (Enumeration f = flightsDone.elements(); f.hasMoreElements();) {
unreserveItem(id, customer, (ReservedItem) f.nextElement(), ReservedItem.rType.ROOM);
}
return false;
}
ReservedItem reservedFlight = reserveItem(id, customer, Flight.getKey(flightnum), String.valueOf(flightnum), ReservedItem.rType.FLIGHT);
if (reservedFlight == null){
Trace.info("RM::itinerary( " + id + ", customer=" + customer + ", " +flightnum+ ", "+location+
", " + car + ", " + room + " ) -- flight could not have been reserved." );
if(reservedCar != null)
unreserveItem(id, customer, reservedCar, ReservedItem.rType.CAR);
if(reservedRoom != null)
unreserveItem(id, customer, reservedRoom, ReservedItem.rType.ROOM);
for (Enumeration f = flightsDone.elements(); f.hasMoreElements();) {
unreserveItem(id, customer, (ReservedItem) f.nextElement(), ReservedItem.rType.ROOM);
}
return false;
}
flightsDone.add(reservedFlight);
}
return true;
}
|
diff --git a/opentripplanner-api-webapp/src/main/java/org/opentripplanner/api/ws/PlanGenerator.java b/opentripplanner-api-webapp/src/main/java/org/opentripplanner/api/ws/PlanGenerator.java
index e991cb4db..43a242c68 100644
--- a/opentripplanner-api-webapp/src/main/java/org/opentripplanner/api/ws/PlanGenerator.java
+++ b/opentripplanner-api-webapp/src/main/java/org/opentripplanner/api/ws/PlanGenerator.java
@@ -1,819 +1,821 @@
/* 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 (props, 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.opentripplanner.api.ws;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.TimeZone;
import org.onebusaway.gtfs.model.Agency;
import org.onebusaway.gtfs.model.Trip;
import org.onebusaway.gtfs.model.calendar.CalendarServiceData;
import org.onebusaway.gtfs.services.calendar.CalendarService;
import org.opentripplanner.api.model.Itinerary;
import org.opentripplanner.api.model.Leg;
import org.opentripplanner.api.model.Place;
import org.opentripplanner.api.model.RelativeDirection;
import org.opentripplanner.api.model.TripPlan;
import org.opentripplanner.api.model.WalkStep;
import org.opentripplanner.common.geometry.DirectionUtils;
import org.opentripplanner.common.geometry.GeometryUtils;
import org.opentripplanner.common.geometry.PackedCoordinateSequence;
import org.opentripplanner.routing.core.EdgeNarrative;
import org.opentripplanner.routing.core.RoutingRequest;
import org.opentripplanner.routing.core.State;
import org.opentripplanner.routing.core.TraverseMode;
import org.opentripplanner.routing.edgetype.DwellEdge;
import org.opentripplanner.routing.edgetype.EdgeWithElevation;
import org.opentripplanner.routing.edgetype.ElevatorAlightEdge;
import org.opentripplanner.routing.edgetype.FreeEdge;
import org.opentripplanner.routing.edgetype.HopEdge;
import org.opentripplanner.routing.edgetype.LegSwitchingEdge;
import org.opentripplanner.routing.edgetype.PlainStreetEdge;
import org.opentripplanner.routing.edgetype.PreAlightEdge;
import org.opentripplanner.routing.edgetype.PreBoardEdge;
import org.opentripplanner.routing.edgetype.RentABikeOnEdge;
import org.opentripplanner.routing.edgetype.TinyTurnEdge;
import org.opentripplanner.routing.error.PathNotFoundException;
import org.opentripplanner.routing.error.TrivialPathException;
import org.opentripplanner.routing.error.VertexNotFoundException;
import org.opentripplanner.routing.graph.Edge;
import org.opentripplanner.routing.graph.Graph;
import org.opentripplanner.routing.graph.Vertex;
import org.opentripplanner.routing.patch.Alert;
import org.opentripplanner.routing.services.FareService;
import org.opentripplanner.routing.services.PathService;
import org.opentripplanner.routing.services.TransitIndexService;
import org.opentripplanner.routing.spt.GraphPath;
import org.opentripplanner.routing.vertextype.TransitVertex;
import org.opentripplanner.util.PolylineEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Geometry;
@Service @Scope("singleton")
public class PlanGenerator {
private static final Logger LOG = LoggerFactory.getLogger(PlanGenerator.class);
@Autowired public PathService pathService;
/** Generates a TripPlan from a Request */
public TripPlan generate(RoutingRequest options) {
// TODO: this seems to only check the endpoints, which are usually auto-generated
//if ( ! options.isAccessible())
// throw new LocationNotAccessible();
/* try to plan the trip */
List<GraphPath> paths = null;
boolean tooSloped = false;
try {
paths = pathService.getPaths(options);
if (paths == null && options.getWheelchairAccessible()) {
// There are no paths that meet the user's slope restrictions.
// Try again without slope restrictions (and warn user).
options.maxSlope = Double.MAX_VALUE;
paths = pathService.getPaths(options);
tooSloped = true;
}
} catch (VertexNotFoundException e) {
LOG.info("Vertex not found: " + options.getFrom() + " : " + options.getTo(), e);
throw e;
}
if (paths == null || paths.size() == 0) {
LOG.info("Path not found: " + options.getFrom() + " : " + options.getTo());
throw new PathNotFoundException();
}
TripPlan plan = generatePlan(paths, options);
if (plan != null) {
for (Itinerary i : plan.itinerary) {
i.tooSloped = tooSloped;
/* fix up from/to on first/last legs */
if (i.legs.size() == 0) {
LOG.warn("itinerary has no legs");
continue;
}
Leg firstLeg = i.legs.get(0);
firstLeg.from.orig = options.getFromName();
Leg lastLeg = i.legs.get(i.legs.size() - 1);
lastLeg.to.orig = options.getToName();
}
}
return plan;
}
/**
* Generates a TripPlan from a set of paths
*/
public TripPlan generatePlan(List<GraphPath> paths, RoutingRequest request) {
GraphPath exemplar = paths.get(0);
Vertex tripStartVertex = exemplar.getStartVertex();
Vertex tripEndVertex = exemplar.getEndVertex();
String startName = tripStartVertex.getName();
String endName = tripEndVertex.getName();
// Use vertex labels if they don't have names
if (startName == null) {
startName = tripStartVertex.getLabel();
}
if (endName == null) {
endName = tripEndVertex.getLabel();
}
Place from = new Place(tripStartVertex.getX(), tripStartVertex.getY(), startName);
Place to = new Place(tripEndVertex.getX(), tripEndVertex.getY(), endName);
TripPlan plan = new TripPlan(from, to, request.getDateTime());
for (GraphPath path : paths) {
Itinerary itinerary = generateItinerary(path, request.getShowIntermediateStops());
plan.addItinerary(itinerary);
}
return plan;
}
/**
* Generate an itinerary from a @{link GraphPath}. The algorithm here is to walk over each state
* in the graph path, accumulating geometry, time, and length data from the incoming edge. When
* the incoming edge and outgoing edge have different modes (or when a vehicle changes names due
* to interlining) a new leg is generated. Street legs undergo an additional processing step to
* generate turn-by-turn directions.
*
* @param path
* @param showIntermediateStops whether intermediate stops are included in the generated
* itinerary
* @return itinerary
*/
private Itinerary generateItinerary(GraphPath path, boolean showIntermediateStops) {
Graph graph = path.getRoutingContext().graph;
TransitIndexService transitIndex = graph.getService(TransitIndexService.class);
Itinerary itinerary = makeEmptyItinerary(path);
EdgeNarrative postponedAlerts = null;
Leg leg = null;
CoordinateArrayListSequence coordinates = new CoordinateArrayListSequence();
double previousElevation = Double.MAX_VALUE;
int startWalk = -1;
int i = -1;
PlanGenState pgstate = PlanGenState.START;
String nextName = null;
for (State state : path.states) {
i += 1;
Edge backEdge = state.getBackEdge();
EdgeNarrative backEdgeNarrative = state.getBackEdgeNarrative();
if (backEdge == null) {
continue;
}
TraverseMode mode = backEdgeNarrative.getMode();
if (mode != null) {
long dt = state.getAbsTimeDeltaSec();
if (mode == TraverseMode.BOARDING || mode == TraverseMode.ALIGHTING
|| mode == TraverseMode.STL) {
itinerary.waitingTime += dt;
} else if (mode.isOnStreetNonTransit()) {
itinerary.walkDistance += backEdgeNarrative.getDistance();
itinerary.walkTime += dt;
} else if (mode.isTransit()) {
itinerary.transitTime += dt;
}
}
if (backEdge instanceof FreeEdge) {
if (backEdge instanceof PreBoardEdge) {
// Add boarding alerts to the next leg
postponedAlerts = backEdgeNarrative;
} else if (backEdge instanceof PreAlightEdge) {
// Add alighting alerts to the previous leg
addNotesToLeg(itinerary.legs.get(itinerary.legs.size() - 1), backEdgeNarrative);
}
continue;
}
if (backEdge instanceof EdgeWithElevation) {
PackedCoordinateSequence profile = ((EdgeWithElevation) backEdge)
.getElevationProfile();
previousElevation = applyElevation(profile, itinerary, previousElevation);
}
switch (pgstate) {
case START:
if (mode == TraverseMode.WALK) {
pgstate = PlanGenState.WALK;
leg = makeLeg(itinerary, state);
leg.from.orig = nextName;
startWalk = i;
} else if (mode == TraverseMode.BICYCLE) {
pgstate = PlanGenState.BICYCLE;
leg = makeLeg(itinerary, state);
leg.from.orig = nextName;
startWalk = i;
} else if (mode == TraverseMode.CAR) {
pgstate = PlanGenState.CAR;
leg = makeLeg(itinerary, state);
leg.from.orig = nextName;
startWalk = i;
} else if (mode == TraverseMode.BOARDING) {
// this itinerary starts with transit
pgstate = PlanGenState.PRETRANSIT;
leg = makeLeg(itinerary, state);
leg.from.orig = nextName;
startWalk = -1;
} else if (mode == TraverseMode.STL) {
// this comes after an alight; do nothing
} else if (mode == TraverseMode.TRANSFER) {
// handle the whole thing in one step
leg = makeLeg(itinerary, state);
coordinates = new CoordinateArrayListSequence();
coordinates.add(state.getBackState().getVertex().getCoordinate());
coordinates.add(state.getVertex().getCoordinate());
finalizeLeg(leg, state, path.states, i, i, coordinates);
coordinates.clear();
} else {
LOG.error("Unexpected state (in START): " + mode);
}
break;
case WALK:
if (leg == null) {
leg = makeLeg(itinerary, state);
}
if (mode == TraverseMode.WALK) {
// do nothing
} else if (mode == TraverseMode.BICYCLE) {
finalizeLeg(leg, state, path.states, startWalk, i, coordinates);
startWalk = i;
leg = makeLeg(itinerary, state);
if (backEdge instanceof RentABikeOnEdge) {
leg.rentedBike = true;
}
pgstate = PlanGenState.BICYCLE;
} else if (mode == TraverseMode.STL) {
finalizeLeg(leg, state, path.states, startWalk, i, coordinates);
leg = null;
pgstate = PlanGenState.PRETRANSIT;
} else if (mode == TraverseMode.BOARDING) {
// this only happens in case of a timed transfer.
pgstate = PlanGenState.PRETRANSIT;
finalizeLeg(leg, state, path.states, startWalk, i, coordinates);
leg = makeLeg(itinerary, state);
itinerary.transfers++;
} else if (backEdgeNarrative instanceof LegSwitchingEdge) {
nextName = state.getBackState().getBackState().getBackState().getVertex()
.getName();
finalizeLeg(leg, state, path.states, startWalk, i - 1, coordinates);
leg = null;
pgstate = PlanGenState.START;
} else {
LOG.error("Unexpected state (in WALK): " + mode);
}
break;
case BICYCLE:
if (leg == null) {
leg = makeLeg(itinerary, state);
}
if (mode == TraverseMode.BICYCLE) {
// do nothing
} else if (mode == TraverseMode.WALK) {
finalizeLeg(leg, state, path.states, startWalk, i, coordinates);
leg = makeLeg(itinerary, state);
startWalk = i;
pgstate = PlanGenState.WALK;
} else if (mode == TraverseMode.STL) {
finalizeLeg(leg, state, path.states, startWalk, i, coordinates);
leg = null;
pgstate = PlanGenState.PRETRANSIT;
} else if (backEdgeNarrative instanceof LegSwitchingEdge) {
finalizeLeg(leg, state, path.states, startWalk, i - 1, coordinates);
leg = null;
pgstate = PlanGenState.START;
} else {
LOG.error("Unexpected state (in BICYCLE): " + mode);
}
break;
case CAR:
if (leg == null) {
leg = makeLeg(itinerary, state);
}
if (mode == TraverseMode.CAR) {
// do nothing
} else if (mode == TraverseMode.STL) {
finalizeLeg(leg, state, path.states, startWalk, i, coordinates);
leg = null;
pgstate = PlanGenState.PRETRANSIT;
} else if (backEdgeNarrative instanceof LegSwitchingEdge) {
finalizeLeg(leg, state, path.states, startWalk, i - 1, coordinates);
leg = null;
pgstate = PlanGenState.START;
} else {
LOG.error("Unexpected state (in CAR): " + mode);
}
break;
case PRETRANSIT:
if (mode == TraverseMode.BOARDING) {
if (leg != null) {
LOG.error("leg unexpectedly not null (boarding loop)");
} else {
leg = makeLeg(itinerary, state);
+ leg.stop = new ArrayList<Place>();
itinerary.transfers++;
leg.boardRule = (String) state.getExtension("boardAlightRule");
}
} else if (backEdge instanceof HopEdge) {
pgstate = PlanGenState.TRANSIT;
fixupTransitLeg(leg, state, transitIndex);
leg.stop = new ArrayList<Place>();
} else {
LOG.error("Unexpected state (in PRETRANSIT): " + mode);
}
break;
case TRANSIT:
String route = backEdgeNarrative.getName();
if (mode == TraverseMode.ALIGHTING) {
if (showIntermediateStops && leg.stop != null && leg.stop.size() > 0) {
if (leg.stop.isEmpty()) {
leg.stop = null;
}
}
leg.alightRule = (String) state.getExtension("boardAlightRule");
finalizeLeg(leg, state, null, -1, -1, coordinates);
leg = null;
pgstate = PlanGenState.START;
} else if (mode.toString().equals(leg.mode)) {
// no mode change, handle intermediate stops
if (showIntermediateStops) {
/*
* any further transit edge, add "from" vertex to intermediate stops
*/
if (!(backEdge instanceof DwellEdge)) {
Place stop = makePlace(state.getBackState(), true);
leg.stop.add(stop);
} else if (leg.stop.size() > 0) {
leg.stop.get(leg.stop.size() - 1).departure = makeCalendar(state);
}
}
if (!route.equals(leg.route)) {
// interline dwell
finalizeLeg(leg, state, null, -1, -1, coordinates);
leg = makeLeg(itinerary, state);
+ leg.stop = new ArrayList<Place>();
fixupTransitLeg(leg, state, transitIndex);
leg.startTime = makeCalendar(state);
leg.interlineWithPreviousLeg = true;
}
} else {
LOG.error("Unexpected state (in TRANSIT): " + mode);
}
break;
}
if (leg != null) {
leg.distance += backEdgeNarrative.getDistance();
Geometry edgeGeometry = backEdgeNarrative.getGeometry();
if (edgeGeometry != null) {
Coordinate[] edgeCoordinates = edgeGeometry.getCoordinates();
if (coordinates.size() > 0
&& coordinates.getCoordinate(coordinates.size() - 1).equals(
edgeCoordinates[0])) {
coordinates.extend(edgeCoordinates, 1);
} else {
coordinates.extend(edgeCoordinates);
}
}
if (postponedAlerts != null) {
addNotesToLeg(leg, postponedAlerts);
postponedAlerts = null;
}
addNotesToLeg(leg, backEdgeNarrative);
}
} /* end loop over graphPath edge list */
if (leg != null) {
finalizeLeg(leg, path.states.getLast(), path.states, startWalk, i, coordinates);
}
itinerary.removeBogusLegs();
itinerary.fixupDates(graph.getService(CalendarServiceData.class));
if (itinerary.legs.size() == 0)
throw new TrivialPathException();
return itinerary;
}
private Calendar makeCalendar(State state) {
CalendarService service = state.getContext().calendarService;
Collection<String> agencyIds = state.getContext().graph.getAgencyIds();
TimeZone timeZone;
if (agencyIds.size() == 0) {
timeZone = TimeZone.getTimeZone("GMT");
} else {
timeZone = service.getTimeZoneForAgencyId(agencyIds.iterator().next());
}
Calendar calendar = Calendar.getInstance(timeZone);
calendar.setTimeInMillis(state.getTimeInMillis());
return calendar;
}
private void fixupTransitLeg(Leg leg, State state, TransitIndexService transitIndex) {
EdgeNarrative en = state.getBackEdgeNarrative();
leg.route = en.getName();
Trip trip = en.getTrip();
if (trip != null) {
leg.headsign = trip.getTripHeadsign();
leg.tripId = trip.getId().getId();
leg.agencyId = trip.getId().getAgencyId();
leg.tripShortName = trip.getTripShortName();
leg.routeShortName = trip.getRoute().getShortName();
leg.routeLongName = trip.getRoute().getLongName();
leg.routeColor = trip.getRoute().getColor();
leg.routeTextColor = trip.getRoute().getTextColor();
if (transitIndex != null) {
Agency agency = transitIndex.getAgency(leg.agencyId);
leg.agencyName = agency.getName();
leg.agencyUrl = agency.getUrl();
}
}
leg.mode = en.getMode().toString();
leg.startTime = makeCalendar(state.getBackState());
}
private void finalizeLeg(Leg leg, State state, List<State> states, int start, int end,
CoordinateArrayListSequence coordinates) {
if (start != -1) {
leg.walkSteps = getWalkSteps(states.subList(start, end + 1));
}
leg.endTime = makeCalendar(state.getBackState());
Geometry geometry = GeometryUtils.getGeometryFactory().createLineString(coordinates);
leg.legGeometry = PolylineEncoder.createEncodings(geometry);
leg.to = makePlace(state, true);
coordinates.clear();
}
private Set<Alert> addNotesToLeg(Leg leg, EdgeNarrative edgeNarrative) {
Set<Alert> notes = edgeNarrative.getNotes();
if (notes != null) {
for (Alert note : notes) {
leg.addAlert(note);
}
}
return notes;
}
/**
* Adjusts an Itinerary's elevation fields from an elevation profile
*
* @return the elevation at the end of the profile
*/
private double applyElevation(PackedCoordinateSequence profile, Itinerary itinerary,
double previousElevation) {
if (profile != null) {
for (Coordinate coordinate : profile.toCoordinateArray()) {
if (previousElevation == Double.MAX_VALUE) {
previousElevation = coordinate.y;
continue;
}
double elevationChange = previousElevation - coordinate.y;
if (elevationChange > 0) {
itinerary.elevationGained += elevationChange;
} else {
itinerary.elevationLost -= elevationChange;
}
previousElevation = coordinate.y;
}
}
return previousElevation;
}
/**
* Makes a new empty leg from a starting edge
*
* @param itinerary
*/
private Leg makeLeg(Itinerary itinerary, State s) {
Leg leg = new Leg();
itinerary.addLeg(leg);
leg.startTime = makeCalendar(s.getBackState());
EdgeNarrative en = s.getBackEdgeNarrative();
leg.distance = 0.0;
leg.from = makePlace(s.getBackState(), false);
leg.mode = en.getMode().toString();
return leg;
}
/**
* Makes a new empty Itinerary for a given path.
*
* @return
*/
private Itinerary makeEmptyItinerary(GraphPath path) {
Itinerary itinerary = new Itinerary();
State startState = path.states.getFirst();
State endState = path.states.getLast();
itinerary.startTime = makeCalendar(startState);
itinerary.endTime = makeCalendar(endState);
itinerary.duration = endState.getTimeInMillis() - startState.getTimeInMillis();
Graph graph = path.getRoutingContext().graph;
FareService fareService = graph.getService(FareService.class);
if (fareService != null) {
itinerary.fare = fareService.getCost(path);
}
itinerary.transfers = -1;
return itinerary;
}
/**
* Makes a new Place from a state. Contains information about time.
*
* @return
*/
private Place makePlace(State state, boolean time) {
Vertex v = state.getVertex();
Coordinate endCoord = v.getCoordinate();
String name = v.getName();
Place place;
if (time) {
Calendar timeAtState = makeCalendar(state);
place = new Place(endCoord.x, endCoord.y, name, timeAtState);
} else {
place = new Place(endCoord.x, endCoord.y, name);
}
if (v instanceof TransitVertex) {
TransitVertex transitVertex = (TransitVertex) v;
place.stopId = transitVertex.getStopId();
place.stopCode = transitVertex.getStopCode();
place.zoneId = state.getZone();
}
return place;
}
/**
* Converts a list of street edges to a list of turn-by-turn directions.
*
* @param edges : A list of street edges
* @return
*/
private List<WalkStep> getWalkSteps(List<State> states) {
List<WalkStep> steps = new ArrayList<WalkStep>();
WalkStep step = null;
double lastAngle = 0, distance = 0; // distance used for appending elevation profiles
int roundaboutExit = 0; // track whether we are in a roundabout, and if so the exit number
String roundaboutPreviousStreet = null;
for (State currState : states) {
State backState = currState.getBackState();
Edge edge = currState.getBackEdge();
EdgeNarrative edgeNarrative = currState.getBackEdgeNarrative();
boolean createdNewStep = false;
if (edge instanceof FreeEdge) {
continue;
}
if (!edgeNarrative.getMode().isOnStreetNonTransit()) {
continue; // ignore STLs and the like
}
Geometry geom = edgeNarrative.getGeometry();
if (geom == null) {
continue;
}
// generate a step for getting off an elevator (all
// elevator narrative generation occurs when alighting). We don't need to know what came
// before or will come after
if (edge instanceof ElevatorAlightEdge) {
// don't care what came before or comes after
step = createWalkStep(currState);
// tell the user where to get off the elevator using the exit notation, so the
// i18n interface will say 'Elevator to <exit>'
// what happens is that the webapp sees name == null and ignores that, and it sees
// exit != null and uses to <exit>
// the floor name is the AlightEdge name
// reset to avoid confusion with 'Elevator on floor 1 to floor 1'
step.streetName = ((ElevatorAlightEdge) edge).getName();
step.relativeDirection = RelativeDirection.ELEVATOR;
steps.add(step);
continue;
}
String streetName = edgeNarrative.getName();
if (step == null) {
// first step
step = createWalkStep(currState);
createdNewStep = true;
steps.add(step);
double thisAngle = DirectionUtils.getFirstAngle(geom);
step.setAbsoluteDirection(thisAngle);
// new step, set distance to length of first edge
distance = edgeNarrative.getDistance();
} else if ((step.streetName != null && !step.streetName.equals(streetName))
&& (!step.bogusName || !edgeNarrative.hasBogusName())) {
/* street name has changed */
if (roundaboutExit > 0) {
// if we were just on a roundabout,
// make note of which exit was taken in the existing step
step.exit = Integer.toString(roundaboutExit); // ordinal numbers from
if (streetName.equals(roundaboutPreviousStreet)) {
step.stayOn = true;
}
// localization
roundaboutExit = 0;
}
/* start a new step */
step = createWalkStep(currState);
createdNewStep = true;
steps.add(step);
if (edgeNarrative.isRoundabout()) {
// indicate that we are now on a roundabout
// and use one-based exit numbering
roundaboutExit = 1;
roundaboutPreviousStreet = backState.getBackEdgeNarrative().getName();
}
double thisAngle = DirectionUtils.getFirstAngle(geom);
step.setDirections(lastAngle, thisAngle, edgeNarrative.isRoundabout());
// new step, set distance to length of first edge
distance = edgeNarrative.getDistance();
} else {
/* street name has not changed */
double thisAngle = DirectionUtils.getFirstAngle(geom);
RelativeDirection direction = WalkStep.getRelativeDirection(lastAngle, thisAngle,
edgeNarrative.isRoundabout());
boolean optionsBefore = backState.multipleOptionsBefore();
if (edgeNarrative.isRoundabout()) {
// we are on a roundabout, and have already traversed at least one edge of it.
if (optionsBefore) {
// increment exit count if we passed one.
roundaboutExit += 1;
}
}
if (edgeNarrative.isRoundabout() || direction == RelativeDirection.CONTINUE) {
// we are continuing almost straight, or continuing along a roundabout.
// just append elevation info onto the existing step.
} else {
// we are not on a roundabout, and not continuing straight through.
// figure out if there were other plausible turn options at the last
// intersection
// to see if we should generate a "left to continue" instruction.
boolean shouldGenerateContinue = false;
if (edge instanceof PlainStreetEdge) {
// the next edges will be TinyTurnEdges or PlainStreetEdges, we hope
double angleDiff = getAbsoluteAngleDiff(thisAngle, lastAngle);
for (Edge alternative : backState.getVertex().getOutgoingStreetEdges()) {
if (alternative instanceof TinyTurnEdge) {
// a tiny turn edge has no geometry, but the next
// edge will be a TurnEdge or PSE and will have direction
alternative = alternative.getToVertex().getOutgoingStreetEdges()
.get(0);
}
if (alternative.getName().equals(streetName)) {
// alternatives that have the same name
// are usually caused by street splits
continue;
}
double altAngle = DirectionUtils.getFirstAngle(alternative
.getGeometry());
double altAngleDiff = getAbsoluteAngleDiff(altAngle, lastAngle);
if (angleDiff > Math.PI / 4 || altAngleDiff - angleDiff < Math.PI / 16) {
shouldGenerateContinue = true;
break;
}
}
} else if (edge instanceof TinyTurnEdge) {
// do nothing as this will be handled in other cases
} else {
double angleDiff = getAbsoluteAngleDiff(lastAngle, thisAngle);
// in the case of a turn edge, we actually have to go back two steps to see
// where
// else we might be, as once we are on the streetvertex leading into this
// edge,
// we are stuck
State twoStatesBack = backState.getBackState();
Vertex backVertex = twoStatesBack.getVertex();
for (Edge alternative : backVertex.getOutgoingStreetEdges()) {
List<Edge> alternatives = alternative.getToVertex()
.getOutgoingStreetEdges();
if (alternatives.size() == 0) {
continue; // this is not an alternative
}
alternative = alternatives.get(0);
if (alternative.getName().equals(streetName)) {
// alternatives that have the same name
// are usually caused by street splits
continue;
}
double altAngle = DirectionUtils.getFirstAngle(alternative
.getGeometry());
double altAngleDiff = getAbsoluteAngleDiff(altAngle, lastAngle);
if (angleDiff > Math.PI / 4 || altAngleDiff - angleDiff < Math.PI / 16) {
shouldGenerateContinue = true;
break;
}
}
}
if (shouldGenerateContinue) {
// turn to stay on same-named street
step = createWalkStep(currState);
createdNewStep = true;
steps.add(step);
step.setDirections(lastAngle, thisAngle, false);
step.stayOn = true;
// new step, set distance to length of first edge
distance = edgeNarrative.getDistance();
}
}
}
if (!createdNewStep) {
if (step.elevation != null) {
String s = encodeElevationProfile(edge, distance);
if (step.elevation.length() > 0 && s != null && s.length() > 0)
step.elevation += ",";
step.elevation += s;
}
distance += edgeNarrative.getDistance();
}
// increment the total length for this step
step.distance += edgeNarrative.getDistance();
step.addAlerts(edgeNarrative.getNotes());
lastAngle = DirectionUtils.getLastAngle(geom);
}
return steps;
}
private double getAbsoluteAngleDiff(double thisAngle, double lastAngle) {
double angleDiff = thisAngle - lastAngle;
if (angleDiff < 0) {
angleDiff += Math.PI * 2;
}
double ccwAngleDiff = Math.PI * 2 - angleDiff;
if (ccwAngleDiff < angleDiff) {
angleDiff = ccwAngleDiff;
}
return angleDiff;
}
private WalkStep createWalkStep(State s) {
EdgeNarrative en = s.getBackEdgeNarrative();
WalkStep step;
step = new WalkStep();
step.streetName = en.getName();
step.lon = en.getFromVertex().getX();
step.lat = en.getFromVertex().getY();
step.elevation = encodeElevationProfile(s.getBackEdge(), 0);
step.bogusName = en.hasBogusName();
step.addAlerts(en.getNotes());
return step;
}
private String encodeElevationProfile(Edge edge, double offset) {
if (!(edge instanceof EdgeWithElevation)) {
return "";
}
EdgeWithElevation elevEdge = (EdgeWithElevation) edge;
if (elevEdge.getElevationProfile() == null) {
return "";
}
StringBuilder str = new StringBuilder();
Coordinate[] coordArr = elevEdge.getElevationProfile().toCoordinateArray();
for (int i = 0; i < coordArr.length; i++) {
str.append(Math.round(coordArr[i].x + offset));
str.append(",");
str.append(Math.round(coordArr[i].y * 10.0) / 10.0);
str.append(i < coordArr.length - 1 ? "," : "");
}
return str.toString();
}
}
| false | true | private Itinerary generateItinerary(GraphPath path, boolean showIntermediateStops) {
Graph graph = path.getRoutingContext().graph;
TransitIndexService transitIndex = graph.getService(TransitIndexService.class);
Itinerary itinerary = makeEmptyItinerary(path);
EdgeNarrative postponedAlerts = null;
Leg leg = null;
CoordinateArrayListSequence coordinates = new CoordinateArrayListSequence();
double previousElevation = Double.MAX_VALUE;
int startWalk = -1;
int i = -1;
PlanGenState pgstate = PlanGenState.START;
String nextName = null;
for (State state : path.states) {
i += 1;
Edge backEdge = state.getBackEdge();
EdgeNarrative backEdgeNarrative = state.getBackEdgeNarrative();
if (backEdge == null) {
continue;
}
TraverseMode mode = backEdgeNarrative.getMode();
if (mode != null) {
long dt = state.getAbsTimeDeltaSec();
if (mode == TraverseMode.BOARDING || mode == TraverseMode.ALIGHTING
|| mode == TraverseMode.STL) {
itinerary.waitingTime += dt;
} else if (mode.isOnStreetNonTransit()) {
itinerary.walkDistance += backEdgeNarrative.getDistance();
itinerary.walkTime += dt;
} else if (mode.isTransit()) {
itinerary.transitTime += dt;
}
}
if (backEdge instanceof FreeEdge) {
if (backEdge instanceof PreBoardEdge) {
// Add boarding alerts to the next leg
postponedAlerts = backEdgeNarrative;
} else if (backEdge instanceof PreAlightEdge) {
// Add alighting alerts to the previous leg
addNotesToLeg(itinerary.legs.get(itinerary.legs.size() - 1), backEdgeNarrative);
}
continue;
}
if (backEdge instanceof EdgeWithElevation) {
PackedCoordinateSequence profile = ((EdgeWithElevation) backEdge)
.getElevationProfile();
previousElevation = applyElevation(profile, itinerary, previousElevation);
}
switch (pgstate) {
case START:
if (mode == TraverseMode.WALK) {
pgstate = PlanGenState.WALK;
leg = makeLeg(itinerary, state);
leg.from.orig = nextName;
startWalk = i;
} else if (mode == TraverseMode.BICYCLE) {
pgstate = PlanGenState.BICYCLE;
leg = makeLeg(itinerary, state);
leg.from.orig = nextName;
startWalk = i;
} else if (mode == TraverseMode.CAR) {
pgstate = PlanGenState.CAR;
leg = makeLeg(itinerary, state);
leg.from.orig = nextName;
startWalk = i;
} else if (mode == TraverseMode.BOARDING) {
// this itinerary starts with transit
pgstate = PlanGenState.PRETRANSIT;
leg = makeLeg(itinerary, state);
leg.from.orig = nextName;
startWalk = -1;
} else if (mode == TraverseMode.STL) {
// this comes after an alight; do nothing
} else if (mode == TraverseMode.TRANSFER) {
// handle the whole thing in one step
leg = makeLeg(itinerary, state);
coordinates = new CoordinateArrayListSequence();
coordinates.add(state.getBackState().getVertex().getCoordinate());
coordinates.add(state.getVertex().getCoordinate());
finalizeLeg(leg, state, path.states, i, i, coordinates);
coordinates.clear();
} else {
LOG.error("Unexpected state (in START): " + mode);
}
break;
case WALK:
if (leg == null) {
leg = makeLeg(itinerary, state);
}
if (mode == TraverseMode.WALK) {
// do nothing
} else if (mode == TraverseMode.BICYCLE) {
finalizeLeg(leg, state, path.states, startWalk, i, coordinates);
startWalk = i;
leg = makeLeg(itinerary, state);
if (backEdge instanceof RentABikeOnEdge) {
leg.rentedBike = true;
}
pgstate = PlanGenState.BICYCLE;
} else if (mode == TraverseMode.STL) {
finalizeLeg(leg, state, path.states, startWalk, i, coordinates);
leg = null;
pgstate = PlanGenState.PRETRANSIT;
} else if (mode == TraverseMode.BOARDING) {
// this only happens in case of a timed transfer.
pgstate = PlanGenState.PRETRANSIT;
finalizeLeg(leg, state, path.states, startWalk, i, coordinates);
leg = makeLeg(itinerary, state);
itinerary.transfers++;
} else if (backEdgeNarrative instanceof LegSwitchingEdge) {
nextName = state.getBackState().getBackState().getBackState().getVertex()
.getName();
finalizeLeg(leg, state, path.states, startWalk, i - 1, coordinates);
leg = null;
pgstate = PlanGenState.START;
} else {
LOG.error("Unexpected state (in WALK): " + mode);
}
break;
case BICYCLE:
if (leg == null) {
leg = makeLeg(itinerary, state);
}
if (mode == TraverseMode.BICYCLE) {
// do nothing
} else if (mode == TraverseMode.WALK) {
finalizeLeg(leg, state, path.states, startWalk, i, coordinates);
leg = makeLeg(itinerary, state);
startWalk = i;
pgstate = PlanGenState.WALK;
} else if (mode == TraverseMode.STL) {
finalizeLeg(leg, state, path.states, startWalk, i, coordinates);
leg = null;
pgstate = PlanGenState.PRETRANSIT;
} else if (backEdgeNarrative instanceof LegSwitchingEdge) {
finalizeLeg(leg, state, path.states, startWalk, i - 1, coordinates);
leg = null;
pgstate = PlanGenState.START;
} else {
LOG.error("Unexpected state (in BICYCLE): " + mode);
}
break;
case CAR:
if (leg == null) {
leg = makeLeg(itinerary, state);
}
if (mode == TraverseMode.CAR) {
// do nothing
} else if (mode == TraverseMode.STL) {
finalizeLeg(leg, state, path.states, startWalk, i, coordinates);
leg = null;
pgstate = PlanGenState.PRETRANSIT;
} else if (backEdgeNarrative instanceof LegSwitchingEdge) {
finalizeLeg(leg, state, path.states, startWalk, i - 1, coordinates);
leg = null;
pgstate = PlanGenState.START;
} else {
LOG.error("Unexpected state (in CAR): " + mode);
}
break;
case PRETRANSIT:
if (mode == TraverseMode.BOARDING) {
if (leg != null) {
LOG.error("leg unexpectedly not null (boarding loop)");
} else {
leg = makeLeg(itinerary, state);
itinerary.transfers++;
leg.boardRule = (String) state.getExtension("boardAlightRule");
}
} else if (backEdge instanceof HopEdge) {
pgstate = PlanGenState.TRANSIT;
fixupTransitLeg(leg, state, transitIndex);
leg.stop = new ArrayList<Place>();
} else {
LOG.error("Unexpected state (in PRETRANSIT): " + mode);
}
break;
case TRANSIT:
String route = backEdgeNarrative.getName();
if (mode == TraverseMode.ALIGHTING) {
if (showIntermediateStops && leg.stop != null && leg.stop.size() > 0) {
if (leg.stop.isEmpty()) {
leg.stop = null;
}
}
leg.alightRule = (String) state.getExtension("boardAlightRule");
finalizeLeg(leg, state, null, -1, -1, coordinates);
leg = null;
pgstate = PlanGenState.START;
} else if (mode.toString().equals(leg.mode)) {
// no mode change, handle intermediate stops
if (showIntermediateStops) {
/*
* any further transit edge, add "from" vertex to intermediate stops
*/
if (!(backEdge instanceof DwellEdge)) {
Place stop = makePlace(state.getBackState(), true);
leg.stop.add(stop);
} else if (leg.stop.size() > 0) {
leg.stop.get(leg.stop.size() - 1).departure = makeCalendar(state);
}
}
if (!route.equals(leg.route)) {
// interline dwell
finalizeLeg(leg, state, null, -1, -1, coordinates);
leg = makeLeg(itinerary, state);
fixupTransitLeg(leg, state, transitIndex);
leg.startTime = makeCalendar(state);
leg.interlineWithPreviousLeg = true;
}
} else {
LOG.error("Unexpected state (in TRANSIT): " + mode);
}
break;
}
if (leg != null) {
leg.distance += backEdgeNarrative.getDistance();
Geometry edgeGeometry = backEdgeNarrative.getGeometry();
if (edgeGeometry != null) {
Coordinate[] edgeCoordinates = edgeGeometry.getCoordinates();
if (coordinates.size() > 0
&& coordinates.getCoordinate(coordinates.size() - 1).equals(
edgeCoordinates[0])) {
coordinates.extend(edgeCoordinates, 1);
} else {
coordinates.extend(edgeCoordinates);
}
}
if (postponedAlerts != null) {
addNotesToLeg(leg, postponedAlerts);
postponedAlerts = null;
}
addNotesToLeg(leg, backEdgeNarrative);
}
} /* end loop over graphPath edge list */
if (leg != null) {
finalizeLeg(leg, path.states.getLast(), path.states, startWalk, i, coordinates);
}
itinerary.removeBogusLegs();
itinerary.fixupDates(graph.getService(CalendarServiceData.class));
if (itinerary.legs.size() == 0)
throw new TrivialPathException();
return itinerary;
}
| private Itinerary generateItinerary(GraphPath path, boolean showIntermediateStops) {
Graph graph = path.getRoutingContext().graph;
TransitIndexService transitIndex = graph.getService(TransitIndexService.class);
Itinerary itinerary = makeEmptyItinerary(path);
EdgeNarrative postponedAlerts = null;
Leg leg = null;
CoordinateArrayListSequence coordinates = new CoordinateArrayListSequence();
double previousElevation = Double.MAX_VALUE;
int startWalk = -1;
int i = -1;
PlanGenState pgstate = PlanGenState.START;
String nextName = null;
for (State state : path.states) {
i += 1;
Edge backEdge = state.getBackEdge();
EdgeNarrative backEdgeNarrative = state.getBackEdgeNarrative();
if (backEdge == null) {
continue;
}
TraverseMode mode = backEdgeNarrative.getMode();
if (mode != null) {
long dt = state.getAbsTimeDeltaSec();
if (mode == TraverseMode.BOARDING || mode == TraverseMode.ALIGHTING
|| mode == TraverseMode.STL) {
itinerary.waitingTime += dt;
} else if (mode.isOnStreetNonTransit()) {
itinerary.walkDistance += backEdgeNarrative.getDistance();
itinerary.walkTime += dt;
} else if (mode.isTransit()) {
itinerary.transitTime += dt;
}
}
if (backEdge instanceof FreeEdge) {
if (backEdge instanceof PreBoardEdge) {
// Add boarding alerts to the next leg
postponedAlerts = backEdgeNarrative;
} else if (backEdge instanceof PreAlightEdge) {
// Add alighting alerts to the previous leg
addNotesToLeg(itinerary.legs.get(itinerary.legs.size() - 1), backEdgeNarrative);
}
continue;
}
if (backEdge instanceof EdgeWithElevation) {
PackedCoordinateSequence profile = ((EdgeWithElevation) backEdge)
.getElevationProfile();
previousElevation = applyElevation(profile, itinerary, previousElevation);
}
switch (pgstate) {
case START:
if (mode == TraverseMode.WALK) {
pgstate = PlanGenState.WALK;
leg = makeLeg(itinerary, state);
leg.from.orig = nextName;
startWalk = i;
} else if (mode == TraverseMode.BICYCLE) {
pgstate = PlanGenState.BICYCLE;
leg = makeLeg(itinerary, state);
leg.from.orig = nextName;
startWalk = i;
} else if (mode == TraverseMode.CAR) {
pgstate = PlanGenState.CAR;
leg = makeLeg(itinerary, state);
leg.from.orig = nextName;
startWalk = i;
} else if (mode == TraverseMode.BOARDING) {
// this itinerary starts with transit
pgstate = PlanGenState.PRETRANSIT;
leg = makeLeg(itinerary, state);
leg.from.orig = nextName;
startWalk = -1;
} else if (mode == TraverseMode.STL) {
// this comes after an alight; do nothing
} else if (mode == TraverseMode.TRANSFER) {
// handle the whole thing in one step
leg = makeLeg(itinerary, state);
coordinates = new CoordinateArrayListSequence();
coordinates.add(state.getBackState().getVertex().getCoordinate());
coordinates.add(state.getVertex().getCoordinate());
finalizeLeg(leg, state, path.states, i, i, coordinates);
coordinates.clear();
} else {
LOG.error("Unexpected state (in START): " + mode);
}
break;
case WALK:
if (leg == null) {
leg = makeLeg(itinerary, state);
}
if (mode == TraverseMode.WALK) {
// do nothing
} else if (mode == TraverseMode.BICYCLE) {
finalizeLeg(leg, state, path.states, startWalk, i, coordinates);
startWalk = i;
leg = makeLeg(itinerary, state);
if (backEdge instanceof RentABikeOnEdge) {
leg.rentedBike = true;
}
pgstate = PlanGenState.BICYCLE;
} else if (mode == TraverseMode.STL) {
finalizeLeg(leg, state, path.states, startWalk, i, coordinates);
leg = null;
pgstate = PlanGenState.PRETRANSIT;
} else if (mode == TraverseMode.BOARDING) {
// this only happens in case of a timed transfer.
pgstate = PlanGenState.PRETRANSIT;
finalizeLeg(leg, state, path.states, startWalk, i, coordinates);
leg = makeLeg(itinerary, state);
itinerary.transfers++;
} else if (backEdgeNarrative instanceof LegSwitchingEdge) {
nextName = state.getBackState().getBackState().getBackState().getVertex()
.getName();
finalizeLeg(leg, state, path.states, startWalk, i - 1, coordinates);
leg = null;
pgstate = PlanGenState.START;
} else {
LOG.error("Unexpected state (in WALK): " + mode);
}
break;
case BICYCLE:
if (leg == null) {
leg = makeLeg(itinerary, state);
}
if (mode == TraverseMode.BICYCLE) {
// do nothing
} else if (mode == TraverseMode.WALK) {
finalizeLeg(leg, state, path.states, startWalk, i, coordinates);
leg = makeLeg(itinerary, state);
startWalk = i;
pgstate = PlanGenState.WALK;
} else if (mode == TraverseMode.STL) {
finalizeLeg(leg, state, path.states, startWalk, i, coordinates);
leg = null;
pgstate = PlanGenState.PRETRANSIT;
} else if (backEdgeNarrative instanceof LegSwitchingEdge) {
finalizeLeg(leg, state, path.states, startWalk, i - 1, coordinates);
leg = null;
pgstate = PlanGenState.START;
} else {
LOG.error("Unexpected state (in BICYCLE): " + mode);
}
break;
case CAR:
if (leg == null) {
leg = makeLeg(itinerary, state);
}
if (mode == TraverseMode.CAR) {
// do nothing
} else if (mode == TraverseMode.STL) {
finalizeLeg(leg, state, path.states, startWalk, i, coordinates);
leg = null;
pgstate = PlanGenState.PRETRANSIT;
} else if (backEdgeNarrative instanceof LegSwitchingEdge) {
finalizeLeg(leg, state, path.states, startWalk, i - 1, coordinates);
leg = null;
pgstate = PlanGenState.START;
} else {
LOG.error("Unexpected state (in CAR): " + mode);
}
break;
case PRETRANSIT:
if (mode == TraverseMode.BOARDING) {
if (leg != null) {
LOG.error("leg unexpectedly not null (boarding loop)");
} else {
leg = makeLeg(itinerary, state);
leg.stop = new ArrayList<Place>();
itinerary.transfers++;
leg.boardRule = (String) state.getExtension("boardAlightRule");
}
} else if (backEdge instanceof HopEdge) {
pgstate = PlanGenState.TRANSIT;
fixupTransitLeg(leg, state, transitIndex);
leg.stop = new ArrayList<Place>();
} else {
LOG.error("Unexpected state (in PRETRANSIT): " + mode);
}
break;
case TRANSIT:
String route = backEdgeNarrative.getName();
if (mode == TraverseMode.ALIGHTING) {
if (showIntermediateStops && leg.stop != null && leg.stop.size() > 0) {
if (leg.stop.isEmpty()) {
leg.stop = null;
}
}
leg.alightRule = (String) state.getExtension("boardAlightRule");
finalizeLeg(leg, state, null, -1, -1, coordinates);
leg = null;
pgstate = PlanGenState.START;
} else if (mode.toString().equals(leg.mode)) {
// no mode change, handle intermediate stops
if (showIntermediateStops) {
/*
* any further transit edge, add "from" vertex to intermediate stops
*/
if (!(backEdge instanceof DwellEdge)) {
Place stop = makePlace(state.getBackState(), true);
leg.stop.add(stop);
} else if (leg.stop.size() > 0) {
leg.stop.get(leg.stop.size() - 1).departure = makeCalendar(state);
}
}
if (!route.equals(leg.route)) {
// interline dwell
finalizeLeg(leg, state, null, -1, -1, coordinates);
leg = makeLeg(itinerary, state);
leg.stop = new ArrayList<Place>();
fixupTransitLeg(leg, state, transitIndex);
leg.startTime = makeCalendar(state);
leg.interlineWithPreviousLeg = true;
}
} else {
LOG.error("Unexpected state (in TRANSIT): " + mode);
}
break;
}
if (leg != null) {
leg.distance += backEdgeNarrative.getDistance();
Geometry edgeGeometry = backEdgeNarrative.getGeometry();
if (edgeGeometry != null) {
Coordinate[] edgeCoordinates = edgeGeometry.getCoordinates();
if (coordinates.size() > 0
&& coordinates.getCoordinate(coordinates.size() - 1).equals(
edgeCoordinates[0])) {
coordinates.extend(edgeCoordinates, 1);
} else {
coordinates.extend(edgeCoordinates);
}
}
if (postponedAlerts != null) {
addNotesToLeg(leg, postponedAlerts);
postponedAlerts = null;
}
addNotesToLeg(leg, backEdgeNarrative);
}
} /* end loop over graphPath edge list */
if (leg != null) {
finalizeLeg(leg, path.states.getLast(), path.states, startWalk, i, coordinates);
}
itinerary.removeBogusLegs();
itinerary.fixupDates(graph.getService(CalendarServiceData.class));
if (itinerary.legs.size() == 0)
throw new TrivialPathException();
return itinerary;
}
|
diff --git a/src/main/java/org/instructionexecutor/InstructionAnalyzer.java b/src/main/java/org/instructionexecutor/InstructionAnalyzer.java
index a37440a5f..2b4bba659 100644
--- a/src/main/java/org/instructionexecutor/InstructionAnalyzer.java
+++ b/src/main/java/org/instructionexecutor/InstructionAnalyzer.java
@@ -1,138 +1,139 @@
package org.instructionexecutor;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.instructionexecutor.InstructionUtil.Closure;
import org.instructionexecutor.InstructionUtil.Insn;
import org.instructionexecutor.InstructionUtil.Instruction;
import org.suite.node.Node;
import org.suite.node.Tree;
public class InstructionAnalyzer {
private List<Integer> frames = new ArrayList<>();
private Map<Integer, Integer> parentFramesByFrame = new HashMap<>();
private Map<Integer, Class<?>[]> registerTypesByFrame = new HashMap<>();
public void analyze(List<Instruction> instructions) {
// Identify frame regions
findFrameInformation(instructions);
// Find out register types in each frame
findRegisterInformation(instructions);
}
private void findFrameInformation(List<Instruction> instructions) {
Deque<Integer> lastEnterIps = new ArrayDeque<>();
// Find out the parent of closures.
// Assumes every ENTER has a ASSIGN-CLOSURE referencing it.
for (int ip = 0; ip < instructions.size(); ip++) {
Instruction insn = instructions.get(ip);
if (insn.insn == Insn.ENTER_________)
lastEnterIps.push(ip);
Integer frame = !lastEnterIps.isEmpty() ? lastEnterIps.peek() : null;
frames.add(frame);
// Recognize frames and their parents.
// Assumes ENTER instruction should be after LABEL.
if (insn.insn == Insn.ASSIGNCLOSURE_)
parentFramesByFrame.put(insn.op1 + 1, frame);
if (insn.insn == Insn.LEAVE_________)
lastEnterIps.pop();
}
}
private void findRegisterInformation(List<Instruction> instructions) {
Class<?> registerTypes[] = null;
int ip = 0;
while (ip < instructions.size()) {
int currentIp = ip;
Instruction insn = instructions.get(ip++);
int op0 = insn.op0, op1 = insn.op1, op2 = insn.op2;
switch (insn.insn) {
case EVALEQ________:
case EVALGE________:
case EVALGT________:
case EVALLE________:
case EVALLT________:
case EVALNE________:
case ISTREE________:
registerTypes[op0] = boolean.class;
break;
case ASSIGNCLOSURE_:
registerTypes[op0] = Closure.class;
break;
case ASSIGNINT_____:
case BINDMARK______:
case COMPARE_______:
case CUTBEGIN______:
case EVALADD_______:
case EVALDIV_______:
case EVALMOD_______:
case EVALMUL_______:
case EVALSUB_______:
registerTypes[op0] = int.class;
break;
case ASSIGNCONST___:
case CONS__________:
case FGETC_________:
case HEAD__________:
case LOG1__________:
case LOG2__________:
case NEWNODE_______:
case POP___________:
case POPEN_________:
case PROVE_________:
case SETRESULT_____:
case SETCLOSURERES_:
case SUBST_________:
case TAIL__________:
case TOP___________:
registerTypes[op0] = Node.class;
break;
case FORMTREE1_____:
registerTypes[insn.op1] = Tree.class;
break;
case ASSIGNFRAMEREG:
int f = frames.get(currentIp);
for (int i = op1; i < 0; i++)
f = parentFramesByFrame.get(f);
Class<?> clazz1 = registerTypesByFrame.get(f)[op2];
if (registerTypes[op0] != clazz1) // Merge into Node if clashed
registerTypes[op0] = registerTypes[op0] != null ? Node.class : clazz1;
break;
case DECOMPOSETREE1:
registerTypes[op1] = registerTypes[op2] = Node.class;
+ break;
case ENTER_________:
registerTypesByFrame.put(frames.get(currentIp), registerTypes = new Class<?>[op0]);
break;
default:
}
}
}
public List<Integer> getFrames() {
return frames;
}
public Map<Integer, Integer> getParentFramesByFrame() {
return parentFramesByFrame;
}
public Map<Integer, Class<?>[]> getRegisterTypesByFrame() {
return registerTypesByFrame;
}
}
| true | true | private void findRegisterInformation(List<Instruction> instructions) {
Class<?> registerTypes[] = null;
int ip = 0;
while (ip < instructions.size()) {
int currentIp = ip;
Instruction insn = instructions.get(ip++);
int op0 = insn.op0, op1 = insn.op1, op2 = insn.op2;
switch (insn.insn) {
case EVALEQ________:
case EVALGE________:
case EVALGT________:
case EVALLE________:
case EVALLT________:
case EVALNE________:
case ISTREE________:
registerTypes[op0] = boolean.class;
break;
case ASSIGNCLOSURE_:
registerTypes[op0] = Closure.class;
break;
case ASSIGNINT_____:
case BINDMARK______:
case COMPARE_______:
case CUTBEGIN______:
case EVALADD_______:
case EVALDIV_______:
case EVALMOD_______:
case EVALMUL_______:
case EVALSUB_______:
registerTypes[op0] = int.class;
break;
case ASSIGNCONST___:
case CONS__________:
case FGETC_________:
case HEAD__________:
case LOG1__________:
case LOG2__________:
case NEWNODE_______:
case POP___________:
case POPEN_________:
case PROVE_________:
case SETRESULT_____:
case SETCLOSURERES_:
case SUBST_________:
case TAIL__________:
case TOP___________:
registerTypes[op0] = Node.class;
break;
case FORMTREE1_____:
registerTypes[insn.op1] = Tree.class;
break;
case ASSIGNFRAMEREG:
int f = frames.get(currentIp);
for (int i = op1; i < 0; i++)
f = parentFramesByFrame.get(f);
Class<?> clazz1 = registerTypesByFrame.get(f)[op2];
if (registerTypes[op0] != clazz1) // Merge into Node if clashed
registerTypes[op0] = registerTypes[op0] != null ? Node.class : clazz1;
break;
case DECOMPOSETREE1:
registerTypes[op1] = registerTypes[op2] = Node.class;
case ENTER_________:
registerTypesByFrame.put(frames.get(currentIp), registerTypes = new Class<?>[op0]);
break;
default:
}
}
}
| private void findRegisterInformation(List<Instruction> instructions) {
Class<?> registerTypes[] = null;
int ip = 0;
while (ip < instructions.size()) {
int currentIp = ip;
Instruction insn = instructions.get(ip++);
int op0 = insn.op0, op1 = insn.op1, op2 = insn.op2;
switch (insn.insn) {
case EVALEQ________:
case EVALGE________:
case EVALGT________:
case EVALLE________:
case EVALLT________:
case EVALNE________:
case ISTREE________:
registerTypes[op0] = boolean.class;
break;
case ASSIGNCLOSURE_:
registerTypes[op0] = Closure.class;
break;
case ASSIGNINT_____:
case BINDMARK______:
case COMPARE_______:
case CUTBEGIN______:
case EVALADD_______:
case EVALDIV_______:
case EVALMOD_______:
case EVALMUL_______:
case EVALSUB_______:
registerTypes[op0] = int.class;
break;
case ASSIGNCONST___:
case CONS__________:
case FGETC_________:
case HEAD__________:
case LOG1__________:
case LOG2__________:
case NEWNODE_______:
case POP___________:
case POPEN_________:
case PROVE_________:
case SETRESULT_____:
case SETCLOSURERES_:
case SUBST_________:
case TAIL__________:
case TOP___________:
registerTypes[op0] = Node.class;
break;
case FORMTREE1_____:
registerTypes[insn.op1] = Tree.class;
break;
case ASSIGNFRAMEREG:
int f = frames.get(currentIp);
for (int i = op1; i < 0; i++)
f = parentFramesByFrame.get(f);
Class<?> clazz1 = registerTypesByFrame.get(f)[op2];
if (registerTypes[op0] != clazz1) // Merge into Node if clashed
registerTypes[op0] = registerTypes[op0] != null ? Node.class : clazz1;
break;
case DECOMPOSETREE1:
registerTypes[op1] = registerTypes[op2] = Node.class;
break;
case ENTER_________:
registerTypesByFrame.put(frames.get(currentIp), registerTypes = new Class<?>[op0]);
break;
default:
}
}
}
|
diff --git a/src/main/java/pl/psnc/dl/wf4ever/portal/pages/my/MyRosPage.java b/src/main/java/pl/psnc/dl/wf4ever/portal/pages/my/MyRosPage.java
index 36ccfcf..05f348c 100644
--- a/src/main/java/pl/psnc/dl/wf4ever/portal/pages/my/MyRosPage.java
+++ b/src/main/java/pl/psnc/dl/wf4ever/portal/pages/my/MyRosPage.java
@@ -1,312 +1,312 @@
package pl.psnc.dl.wf4ever.portal.pages.my;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.http.HttpStatus;
import org.apache.log4j.Logger;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Check;
import org.apache.wicket.markup.html.form.CheckGroup;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.RequiredTextField;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.markup.repeater.RefreshingView;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.validation.IValidatable;
import org.apache.wicket.validation.IValidator;
import org.apache.wicket.validation.ValidationError;
import org.purl.wf4ever.rosrs.client.common.ROSRSException;
import org.purl.wf4ever.rosrs.client.common.ROSRService;
import org.scribe.model.Token;
import pl.psnc.dl.wf4ever.portal.MySession;
import pl.psnc.dl.wf4ever.portal.PortalApplication;
import pl.psnc.dl.wf4ever.portal.model.AggregatedResource;
import pl.psnc.dl.wf4ever.portal.model.ResearchObject;
import pl.psnc.dl.wf4ever.portal.pages.MyExpImportPage;
import pl.psnc.dl.wf4ever.portal.pages.TemplatePage;
import pl.psnc.dl.wf4ever.portal.pages.ro.RoPage;
import pl.psnc.dl.wf4ever.portal.pages.util.ModelIteratorAdapter;
import pl.psnc.dl.wf4ever.portal.pages.util.MyAjaxButton;
import pl.psnc.dl.wf4ever.portal.pages.util.MyFeedbackPanel;
import pl.psnc.dl.wf4ever.portal.services.RoFactory;
import com.sun.jersey.api.client.ClientResponse;
/**
* A page with user's own Research Objects.
*
* @author piotrekhol
*
*/
@AuthorizeInstantiation("USER")
public class MyRosPage extends TemplatePage {
/** id. */
private static final long serialVersionUID = 1L;
/** Logger. */
private static final Logger LOG = Logger.getLogger(MyRosPage.class);
/** ROs selected by the user. */
final List<ResearchObject> selectedResearchObjects = new ArrayList<ResearchObject>();
/** New RO id. */
private String roId;
/** Feedback panel for adding ROs. */
private MyFeedbackPanel addFeedbackPanel;
/** Default feedback panel. */
private MyFeedbackPanel deleteFeedbackPanel;
/**
* Constructor.
*
* @param parameters
* page params
* @throws URISyntaxException
* can't connect to RODL
* @throws ROSRSException
* getting the RO list ends with an unexpected response code
*/
@SuppressWarnings("serial")
public MyRosPage(final PageParameters parameters)
throws URISyntaxException, ROSRSException {
super(parameters);
List<URI> uris = ROSRService.getROList(rodlURI, MySession.get().getdLibraAccessToken());
final List<ResearchObject> researchObjects = new ArrayList<ResearchObject>();
for (URI uri : uris) {
try {
researchObjects
.add(RoFactory.createResearchObject(rodlURI, uri, false, MySession.get().getUsernames()));
} catch (Exception e) {
error("Could not get manifest for: " + uri + " (" + e.getMessage() + ")");
}
}
final Form<?> form = new Form<Void>("form");
form.setOutputMarkupId(true);
add(form);
form.add(new MyFeedbackPanel("feedbackPanel"));
CheckGroup<ResearchObject> group = new CheckGroup<ResearchObject>("group", selectedResearchObjects);
form.add(group);
RefreshingView<ResearchObject> list = new MyROsRefreshingView("rosListView", researchObjects);
group.add(list);
final Label deleteCntLabel = new Label("deleteCnt", new PropertyModel<String>(this, "deleteCnt"));
deleteCntLabel.setOutputMarkupId(true);
add(deleteCntLabel);
final Form<?> addForm = new Form<Void>("addForm");
RequiredTextField<String> name = new RequiredTextField<String>("roId", new PropertyModel<String>(this, "roId"));
name.add(new IValidator<String>() {
@Override
public void validate(IValidatable<String> validatable) {
try {
if (!ROSRService.isRoIdFree(((PortalApplication) getApplication()).getRodlURI(),
validatable.getValue())) {
validatable.error(new ValidationError().setMessage("This ID is already in use"));
}
} catch (Exception e) {
LOG.error(e);
// assume it's ok
}
}
});
addForm.add(name);
add(addForm);
addFeedbackPanel = new MyFeedbackPanel("addFeedbackPanel");
addFeedbackPanel.setOutputMarkupId(true);
addForm.add(addFeedbackPanel);
form.add(new MyAjaxButton("delete", form) {
@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
super.onSubmit(target, form);
form.process(null);
if (!selectedResearchObjects.isEmpty()) {
target.add(deleteCntLabel);
target.appendJavaScript("$('#confirm-delete-modal').modal('show')");
}
}
});
deleteFeedbackPanel = new MyFeedbackPanel("deleteFeedbackPanel");
deleteFeedbackPanel.setOutputMarkupId(true);
add(deleteFeedbackPanel);
add(new MyAjaxButton("confirmDelete", form) {
@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
super.onSubmit(target, form);
Token dLibraToken = MySession.get().getdLibraAccessToken();
for (AggregatedResource ro : selectedResearchObjects) {
try {
ROSRService.deleteResearchObject(ro.getURI(), dLibraToken);
researchObjects.remove(ro);
} catch (Exception e) {
error("Could not delete Research Object: " + ro.getURI() + " (" + e.getMessage() + ")");
}
}
target.add(form);
target.add(deleteFeedbackPanel);
target.appendJavaScript("$('#confirm-delete-modal').modal('hide')");
}
});
add(new MyAjaxButton("cancelDelete", form) {
@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
super.onSubmit(target, form);
target.appendJavaScript("$('#confirm-delete-modal').modal('hide')");
}
});
form.add(new MyAjaxButton("add", form) {
@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
super.onSubmit(target, form);
target.appendJavaScript("$('#confirm-add-modal').modal('show')");
}
});
addForm.add(new MyAjaxButton("confirmAdd", addForm) {
@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> addForm) {
super.onSubmit(target, addForm);
Token dLibraToken = MySession.get().getdLibraAccessToken();
try {
ClientResponse response = ROSRService.createResearchObject(
((PortalApplication) getApplication()).getRodlURI(), roId, dLibraToken);
if (response.getStatus() == HttpStatus.SC_CREATED) {
URI researchObjectURI = response.getLocation();
researchObjects.add(RoFactory.createResearchObject(rodlURI, researchObjectURI, false, MySession
.get().getUsernames()));
+ target.appendJavaScript("$('#confirm-add-modal').modal('hide')");
} else if (response.getStatus() == HttpStatus.SC_CONFLICT) {
error("This ID is already used.");
}
} catch (ROSRSException e) {
error("Could not add Research Object: " + roId + " (" + e.getMessage() + ")");
}
target.add(form);
target.add(addFeedbackPanel);
- target.appendJavaScript("$('#confirm-add-modal').modal('hide')");
}
@Override
protected void onError(AjaxRequestTarget target, Form<?> form) {
super.onError(target, form);
target.add(addFeedbackPanel);
}
});
addForm.add(new MyAjaxButton("cancelAdd", addForm) {
@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
super.onSubmit(target, form);
target.appendJavaScript("$('#confirm-add-modal').modal('hide')");
}
}.setDefaultFormProcessing(false));
form.add(new BookmarkablePageLink<Void>("myExpImport", MyExpImportPage.class));
}
/**
* The message to display when deleting ROs.
*
* @return the message
*/
public String getDeleteCnt() {
if (selectedResearchObjects.size() == 1) {
return "1 Research Object";
}
return selectedResearchObjects.size() + " Research Objects";
}
public String getRoId() {
return roId;
}
public void setRoId(String roId) {
this.roId = roId;
}
/**
* The ROs refreshing view.
*
* @author piotrekhol
*
*/
private final class MyROsRefreshingView extends RefreshingView<ResearchObject> {
/** id. */
private static final long serialVersionUID = -6310254217773728128L;
/** ROs. */
private final List<ResearchObject> researchObjects;
/**
* Constructor.
*
* @param id
* wicket id
* @param researchObjects
* list of ROs
*/
private MyROsRefreshingView(String id, List<ResearchObject> researchObjects) {
super(id);
this.researchObjects = researchObjects;
}
@Override
protected void populateItem(Item<ResearchObject> item) {
AggregatedResource researchObject = (AggregatedResource) item.getDefaultModelObject();
item.add(new Check<ResearchObject>("checkbox", item.getModel()));
BookmarkablePageLink<Void> link = new BookmarkablePageLink<>("link", RoPage.class);
link.getPageParameters().add("ro", researchObject.getURI().toString());
link.add(new Label("URI"));
item.add(link);
item.add(new Label("createdFormatted"));
}
@Override
protected Iterator<IModel<ResearchObject>> getItemModels() {
return new ModelIteratorAdapter<ResearchObject>(researchObjects.iterator()) {
@Override
protected IModel<ResearchObject> model(ResearchObject ro) {
return new CompoundPropertyModel<ResearchObject>(ro);
}
};
}
}
}
| false | true | public MyRosPage(final PageParameters parameters)
throws URISyntaxException, ROSRSException {
super(parameters);
List<URI> uris = ROSRService.getROList(rodlURI, MySession.get().getdLibraAccessToken());
final List<ResearchObject> researchObjects = new ArrayList<ResearchObject>();
for (URI uri : uris) {
try {
researchObjects
.add(RoFactory.createResearchObject(rodlURI, uri, false, MySession.get().getUsernames()));
} catch (Exception e) {
error("Could not get manifest for: " + uri + " (" + e.getMessage() + ")");
}
}
final Form<?> form = new Form<Void>("form");
form.setOutputMarkupId(true);
add(form);
form.add(new MyFeedbackPanel("feedbackPanel"));
CheckGroup<ResearchObject> group = new CheckGroup<ResearchObject>("group", selectedResearchObjects);
form.add(group);
RefreshingView<ResearchObject> list = new MyROsRefreshingView("rosListView", researchObjects);
group.add(list);
final Label deleteCntLabel = new Label("deleteCnt", new PropertyModel<String>(this, "deleteCnt"));
deleteCntLabel.setOutputMarkupId(true);
add(deleteCntLabel);
final Form<?> addForm = new Form<Void>("addForm");
RequiredTextField<String> name = new RequiredTextField<String>("roId", new PropertyModel<String>(this, "roId"));
name.add(new IValidator<String>() {
@Override
public void validate(IValidatable<String> validatable) {
try {
if (!ROSRService.isRoIdFree(((PortalApplication) getApplication()).getRodlURI(),
validatable.getValue())) {
validatable.error(new ValidationError().setMessage("This ID is already in use"));
}
} catch (Exception e) {
LOG.error(e);
// assume it's ok
}
}
});
addForm.add(name);
add(addForm);
addFeedbackPanel = new MyFeedbackPanel("addFeedbackPanel");
addFeedbackPanel.setOutputMarkupId(true);
addForm.add(addFeedbackPanel);
form.add(new MyAjaxButton("delete", form) {
@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
super.onSubmit(target, form);
form.process(null);
if (!selectedResearchObjects.isEmpty()) {
target.add(deleteCntLabel);
target.appendJavaScript("$('#confirm-delete-modal').modal('show')");
}
}
});
deleteFeedbackPanel = new MyFeedbackPanel("deleteFeedbackPanel");
deleteFeedbackPanel.setOutputMarkupId(true);
add(deleteFeedbackPanel);
add(new MyAjaxButton("confirmDelete", form) {
@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
super.onSubmit(target, form);
Token dLibraToken = MySession.get().getdLibraAccessToken();
for (AggregatedResource ro : selectedResearchObjects) {
try {
ROSRService.deleteResearchObject(ro.getURI(), dLibraToken);
researchObjects.remove(ro);
} catch (Exception e) {
error("Could not delete Research Object: " + ro.getURI() + " (" + e.getMessage() + ")");
}
}
target.add(form);
target.add(deleteFeedbackPanel);
target.appendJavaScript("$('#confirm-delete-modal').modal('hide')");
}
});
add(new MyAjaxButton("cancelDelete", form) {
@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
super.onSubmit(target, form);
target.appendJavaScript("$('#confirm-delete-modal').modal('hide')");
}
});
form.add(new MyAjaxButton("add", form) {
@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
super.onSubmit(target, form);
target.appendJavaScript("$('#confirm-add-modal').modal('show')");
}
});
addForm.add(new MyAjaxButton("confirmAdd", addForm) {
@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> addForm) {
super.onSubmit(target, addForm);
Token dLibraToken = MySession.get().getdLibraAccessToken();
try {
ClientResponse response = ROSRService.createResearchObject(
((PortalApplication) getApplication()).getRodlURI(), roId, dLibraToken);
if (response.getStatus() == HttpStatus.SC_CREATED) {
URI researchObjectURI = response.getLocation();
researchObjects.add(RoFactory.createResearchObject(rodlURI, researchObjectURI, false, MySession
.get().getUsernames()));
} else if (response.getStatus() == HttpStatus.SC_CONFLICT) {
error("This ID is already used.");
}
} catch (ROSRSException e) {
error("Could not add Research Object: " + roId + " (" + e.getMessage() + ")");
}
target.add(form);
target.add(addFeedbackPanel);
target.appendJavaScript("$('#confirm-add-modal').modal('hide')");
}
@Override
protected void onError(AjaxRequestTarget target, Form<?> form) {
super.onError(target, form);
target.add(addFeedbackPanel);
}
});
addForm.add(new MyAjaxButton("cancelAdd", addForm) {
@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
super.onSubmit(target, form);
target.appendJavaScript("$('#confirm-add-modal').modal('hide')");
}
}.setDefaultFormProcessing(false));
form.add(new BookmarkablePageLink<Void>("myExpImport", MyExpImportPage.class));
}
| public MyRosPage(final PageParameters parameters)
throws URISyntaxException, ROSRSException {
super(parameters);
List<URI> uris = ROSRService.getROList(rodlURI, MySession.get().getdLibraAccessToken());
final List<ResearchObject> researchObjects = new ArrayList<ResearchObject>();
for (URI uri : uris) {
try {
researchObjects
.add(RoFactory.createResearchObject(rodlURI, uri, false, MySession.get().getUsernames()));
} catch (Exception e) {
error("Could not get manifest for: " + uri + " (" + e.getMessage() + ")");
}
}
final Form<?> form = new Form<Void>("form");
form.setOutputMarkupId(true);
add(form);
form.add(new MyFeedbackPanel("feedbackPanel"));
CheckGroup<ResearchObject> group = new CheckGroup<ResearchObject>("group", selectedResearchObjects);
form.add(group);
RefreshingView<ResearchObject> list = new MyROsRefreshingView("rosListView", researchObjects);
group.add(list);
final Label deleteCntLabel = new Label("deleteCnt", new PropertyModel<String>(this, "deleteCnt"));
deleteCntLabel.setOutputMarkupId(true);
add(deleteCntLabel);
final Form<?> addForm = new Form<Void>("addForm");
RequiredTextField<String> name = new RequiredTextField<String>("roId", new PropertyModel<String>(this, "roId"));
name.add(new IValidator<String>() {
@Override
public void validate(IValidatable<String> validatable) {
try {
if (!ROSRService.isRoIdFree(((PortalApplication) getApplication()).getRodlURI(),
validatable.getValue())) {
validatable.error(new ValidationError().setMessage("This ID is already in use"));
}
} catch (Exception e) {
LOG.error(e);
// assume it's ok
}
}
});
addForm.add(name);
add(addForm);
addFeedbackPanel = new MyFeedbackPanel("addFeedbackPanel");
addFeedbackPanel.setOutputMarkupId(true);
addForm.add(addFeedbackPanel);
form.add(new MyAjaxButton("delete", form) {
@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
super.onSubmit(target, form);
form.process(null);
if (!selectedResearchObjects.isEmpty()) {
target.add(deleteCntLabel);
target.appendJavaScript("$('#confirm-delete-modal').modal('show')");
}
}
});
deleteFeedbackPanel = new MyFeedbackPanel("deleteFeedbackPanel");
deleteFeedbackPanel.setOutputMarkupId(true);
add(deleteFeedbackPanel);
add(new MyAjaxButton("confirmDelete", form) {
@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
super.onSubmit(target, form);
Token dLibraToken = MySession.get().getdLibraAccessToken();
for (AggregatedResource ro : selectedResearchObjects) {
try {
ROSRService.deleteResearchObject(ro.getURI(), dLibraToken);
researchObjects.remove(ro);
} catch (Exception e) {
error("Could not delete Research Object: " + ro.getURI() + " (" + e.getMessage() + ")");
}
}
target.add(form);
target.add(deleteFeedbackPanel);
target.appendJavaScript("$('#confirm-delete-modal').modal('hide')");
}
});
add(new MyAjaxButton("cancelDelete", form) {
@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
super.onSubmit(target, form);
target.appendJavaScript("$('#confirm-delete-modal').modal('hide')");
}
});
form.add(new MyAjaxButton("add", form) {
@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
super.onSubmit(target, form);
target.appendJavaScript("$('#confirm-add-modal').modal('show')");
}
});
addForm.add(new MyAjaxButton("confirmAdd", addForm) {
@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> addForm) {
super.onSubmit(target, addForm);
Token dLibraToken = MySession.get().getdLibraAccessToken();
try {
ClientResponse response = ROSRService.createResearchObject(
((PortalApplication) getApplication()).getRodlURI(), roId, dLibraToken);
if (response.getStatus() == HttpStatus.SC_CREATED) {
URI researchObjectURI = response.getLocation();
researchObjects.add(RoFactory.createResearchObject(rodlURI, researchObjectURI, false, MySession
.get().getUsernames()));
target.appendJavaScript("$('#confirm-add-modal').modal('hide')");
} else if (response.getStatus() == HttpStatus.SC_CONFLICT) {
error("This ID is already used.");
}
} catch (ROSRSException e) {
error("Could not add Research Object: " + roId + " (" + e.getMessage() + ")");
}
target.add(form);
target.add(addFeedbackPanel);
}
@Override
protected void onError(AjaxRequestTarget target, Form<?> form) {
super.onError(target, form);
target.add(addFeedbackPanel);
}
});
addForm.add(new MyAjaxButton("cancelAdd", addForm) {
@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
super.onSubmit(target, form);
target.appendJavaScript("$('#confirm-add-modal').modal('hide')");
}
}.setDefaultFormProcessing(false));
form.add(new BookmarkablePageLink<Void>("myExpImport", MyExpImportPage.class));
}
|
diff --git a/src/main/java/de/weltraumschaf/caythe/frontend/pascal/parsers/DeclarationsParser.java b/src/main/java/de/weltraumschaf/caythe/frontend/pascal/parsers/DeclarationsParser.java
index 79fc5850..0bbcf3cd 100644
--- a/src/main/java/de/weltraumschaf/caythe/frontend/pascal/parsers/DeclarationsParser.java
+++ b/src/main/java/de/weltraumschaf/caythe/frontend/pascal/parsers/DeclarationsParser.java
@@ -1,98 +1,99 @@
package de.weltraumschaf.caythe.frontend.pascal.parsers;
import de.weltraumschaf.caythe.frontend.Token;
import de.weltraumschaf.caythe.frontend.TokenType;
import de.weltraumschaf.caythe.frontend.pascal.PascalTokenType;
import de.weltraumschaf.caythe.frontend.pascal.PascalTopDownParser;
import de.weltraumschaf.caythe.intermediate.SymbolTableEntry;
import de.weltraumschaf.caythe.intermediate.symboltableimpl.DefinitionImpl;
import java.util.EnumSet;
import static de.weltraumschaf.caythe.frontend.pascal.PascalTokenType.*;
/**
*
* @author Sven Strittmatter <[email protected]>
* @license http://www.weltraumschaf.de/the-beer-ware-license.txt THE BEER-WARE LICENSE
*/
public class DeclarationsParser extends PascalTopDownParser {
public DeclarationsParser(PascalTopDownParser parent) {
super(parent);
}
static final EnumSet<PascalTokenType> DECLARATION_START_SET =
EnumSet.of(CONST, TYPE, VAR, PROCEDURE, FUNCTION, BEGIN);
static final EnumSet<PascalTokenType> TYPE_START_SET =
DECLARATION_START_SET.clone();
static {
TYPE_START_SET.remove(CONST);
}
static final EnumSet<PascalTokenType> VAR_START_SET =
TYPE_START_SET.clone();
static {
VAR_START_SET.remove(TYPE);
}
static final EnumSet<PascalTokenType> ROUTINE_START_SET =
VAR_START_SET.clone();
static {
ROUTINE_START_SET.remove(VAR);
}
public SymbolTableEntry parse(Token token, SymbolTableEntry parentId) throws Exception {
token = synchronize(DECLARATION_START_SET);
if (token.getType() == CONST) {
token = nextToken(); // consume CONST
ConstantDefinitionsParser constantDefinitionsParser =
new ConstantDefinitionsParser(this);
constantDefinitionsParser.parse(token, null);
}
token = synchronize(TYPE_START_SET);
if (token.getType() == TYPE) {
token = nextToken(); // consume TYPE
TypeDefinitionsParser typeDefinitionsParser =
new TypeDefinitionsParser(this);
typeDefinitionsParser.parse(token, null);
}
token = synchronize(VAR_START_SET);
if (token.getType() == VAR) {
token = nextToken(); // consume VAR
VariableDeclarationsParser variableDeclarationsParser =
new VariableDeclarationsParser(this);
variableDeclarationsParser.setDefinition(DefinitionImpl.VARIABLE);
variableDeclarationsParser.parse(token, null);
}
token = synchronize(ROUTINE_START_SET);
TokenType tokenType = token.getType();
while ((tokenType == PROCEDURE) || (tokenType == FUNCTION)) {
DeclaredRoutineParser routineParser = new DeclaredRoutineParser(this);
routineParser.parse(token, parentId);
// Look for one or more semicolons after a definition.
+ token = currentToken();
if (token.getType() == SEMICOLON) {
while (token.getType() == SEMICOLON) {
token = nextToken(); // consume the ;
}
}
token = synchronize(ROUTINE_START_SET);
tokenType = token.getType();
}
return null;
}
}
| true | true | public SymbolTableEntry parse(Token token, SymbolTableEntry parentId) throws Exception {
token = synchronize(DECLARATION_START_SET);
if (token.getType() == CONST) {
token = nextToken(); // consume CONST
ConstantDefinitionsParser constantDefinitionsParser =
new ConstantDefinitionsParser(this);
constantDefinitionsParser.parse(token, null);
}
token = synchronize(TYPE_START_SET);
if (token.getType() == TYPE) {
token = nextToken(); // consume TYPE
TypeDefinitionsParser typeDefinitionsParser =
new TypeDefinitionsParser(this);
typeDefinitionsParser.parse(token, null);
}
token = synchronize(VAR_START_SET);
if (token.getType() == VAR) {
token = nextToken(); // consume VAR
VariableDeclarationsParser variableDeclarationsParser =
new VariableDeclarationsParser(this);
variableDeclarationsParser.setDefinition(DefinitionImpl.VARIABLE);
variableDeclarationsParser.parse(token, null);
}
token = synchronize(ROUTINE_START_SET);
TokenType tokenType = token.getType();
while ((tokenType == PROCEDURE) || (tokenType == FUNCTION)) {
DeclaredRoutineParser routineParser = new DeclaredRoutineParser(this);
routineParser.parse(token, parentId);
// Look for one or more semicolons after a definition.
if (token.getType() == SEMICOLON) {
while (token.getType() == SEMICOLON) {
token = nextToken(); // consume the ;
}
}
token = synchronize(ROUTINE_START_SET);
tokenType = token.getType();
}
return null;
}
| public SymbolTableEntry parse(Token token, SymbolTableEntry parentId) throws Exception {
token = synchronize(DECLARATION_START_SET);
if (token.getType() == CONST) {
token = nextToken(); // consume CONST
ConstantDefinitionsParser constantDefinitionsParser =
new ConstantDefinitionsParser(this);
constantDefinitionsParser.parse(token, null);
}
token = synchronize(TYPE_START_SET);
if (token.getType() == TYPE) {
token = nextToken(); // consume TYPE
TypeDefinitionsParser typeDefinitionsParser =
new TypeDefinitionsParser(this);
typeDefinitionsParser.parse(token, null);
}
token = synchronize(VAR_START_SET);
if (token.getType() == VAR) {
token = nextToken(); // consume VAR
VariableDeclarationsParser variableDeclarationsParser =
new VariableDeclarationsParser(this);
variableDeclarationsParser.setDefinition(DefinitionImpl.VARIABLE);
variableDeclarationsParser.parse(token, null);
}
token = synchronize(ROUTINE_START_SET);
TokenType tokenType = token.getType();
while ((tokenType == PROCEDURE) || (tokenType == FUNCTION)) {
DeclaredRoutineParser routineParser = new DeclaredRoutineParser(this);
routineParser.parse(token, parentId);
// Look for one or more semicolons after a definition.
token = currentToken();
if (token.getType() == SEMICOLON) {
while (token.getType() == SEMICOLON) {
token = nextToken(); // consume the ;
}
}
token = synchronize(ROUTINE_START_SET);
tokenType = token.getType();
}
return null;
}
|
diff --git a/src/main/java/de/minestar/AdminStuff/commands/cmdGod.java b/src/main/java/de/minestar/AdminStuff/commands/cmdGod.java
index 86ff194..174c83d 100644
--- a/src/main/java/de/minestar/AdminStuff/commands/cmdGod.java
+++ b/src/main/java/de/minestar/AdminStuff/commands/cmdGod.java
@@ -1,98 +1,98 @@
/*
* Copyright (C) 2011 MineStar.de
*
* This file is part of 'AdminStuff'.
*
* 'AdminStuff' is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3 of the License.
*
* 'AdminStuff' 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 'AdminStuff'. If not, see <http://www.gnu.org/licenses/>.
*
* AUTHOR: GeMoschen
*
*/
package de.minestar.AdminStuff.commands;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.entity.Player;
import de.minestar.AdminStuff.Core;
import de.minestar.core.MinestarCore;
import de.minestar.core.units.MinestarPlayer;
import de.minestar.minestarlibrary.commands.AbstractExtendedCommand;
import de.minestar.minestarlibrary.utils.ChatUtils;
import de.minestar.minestarlibrary.utils.ConsoleUtils;
import de.minestar.minestarlibrary.utils.PlayerUtils;
public class cmdGod extends AbstractExtendedCommand {
public cmdGod(String syntax, String arguments, String node) {
super(Core.NAME, syntax, arguments, node);
}
@Override
/**
* Representing the command <br>
* /god <br>
* Toggle God-status
*
* @param player
* Called the command
* @param split
*/
public void execute(String[] args, Player player) {
// make himself a god
if (args.length == 0)
changeGodMode(player, player);
else
changeGodMode(player, args);
}
@Override
public void execute(String[] args, ConsoleCommandSender console) {
if (args.length == 0)
ConsoleUtils.printError(pluginName, "You are God, why do you want to activate god mode?");
else
changeGodMode(console, args);
}
// function to search the players
private void changeGodMode(CommandSender sender, String... targetNames) {
Player target = null;
for (String targetName : targetNames) {
target = PlayerUtils.getOnlinePlayer(targetName);
if (target == null)
ChatUtils.writeError(sender, pluginName, "Spieler '" + targetName + "' wurde nicht gefunden!");
else if (target.isDead() || !target.isOnline())
ChatUtils.writeError(sender, pluginName, "Spieler '" + targetName + "' ist tot oder nicht online!");
else
changeGodMode(sender, target);
}
}
// function to make them god
private void changeGodMode(CommandSender sender, Player target) {
MinestarPlayer mPlayer = MinestarCore.getPlayer(target);
Boolean godMode = mPlayer.getBoolean("adminstuff.god");
- if (godMode == null || false)
+ if (godMode == null || !godMode)
godMode = true;
else
godMode = false;
mPlayer.setBoolean("adminstuff.god", godMode);
if (godMode) {
ChatUtils.writeSuccess(sender, pluginName, "Spieler '" + target.getName() + "' ist jetzt unsterblich!");
PlayerUtils.sendInfo(target, pluginName, "Unsterblichkeit aktiviert!");
} else {
ChatUtils.writeSuccess(sender, pluginName, "Spieler '" + target.getName() + "' ist wieder sterblich!");
PlayerUtils.sendInfo(target, pluginName, "Unsterblichkeit deaktiviert!");
}
}
}
| true | true | private void changeGodMode(CommandSender sender, Player target) {
MinestarPlayer mPlayer = MinestarCore.getPlayer(target);
Boolean godMode = mPlayer.getBoolean("adminstuff.god");
if (godMode == null || false)
godMode = true;
else
godMode = false;
mPlayer.setBoolean("adminstuff.god", godMode);
if (godMode) {
ChatUtils.writeSuccess(sender, pluginName, "Spieler '" + target.getName() + "' ist jetzt unsterblich!");
PlayerUtils.sendInfo(target, pluginName, "Unsterblichkeit aktiviert!");
} else {
ChatUtils.writeSuccess(sender, pluginName, "Spieler '" + target.getName() + "' ist wieder sterblich!");
PlayerUtils.sendInfo(target, pluginName, "Unsterblichkeit deaktiviert!");
}
}
| private void changeGodMode(CommandSender sender, Player target) {
MinestarPlayer mPlayer = MinestarCore.getPlayer(target);
Boolean godMode = mPlayer.getBoolean("adminstuff.god");
if (godMode == null || !godMode)
godMode = true;
else
godMode = false;
mPlayer.setBoolean("adminstuff.god", godMode);
if (godMode) {
ChatUtils.writeSuccess(sender, pluginName, "Spieler '" + target.getName() + "' ist jetzt unsterblich!");
PlayerUtils.sendInfo(target, pluginName, "Unsterblichkeit aktiviert!");
} else {
ChatUtils.writeSuccess(sender, pluginName, "Spieler '" + target.getName() + "' ist wieder sterblich!");
PlayerUtils.sendInfo(target, pluginName, "Unsterblichkeit deaktiviert!");
}
}
|
diff --git a/gui/src/main/java/org/jboss/as/console/client/core/BootstrapContext.java b/gui/src/main/java/org/jboss/as/console/client/core/BootstrapContext.java
index 292db090..e92a8ad7 100644
--- a/gui/src/main/java/org/jboss/as/console/client/core/BootstrapContext.java
+++ b/gui/src/main/java/org/jboss/as/console/client/core/BootstrapContext.java
@@ -1,188 +1,192 @@
/*
* JBoss, Home of Professional Open Source
* Copyright 2011 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @author tags. All rights reserved.
* See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* 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 Lesser General Public License, v. 2.1.
* 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 Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License,
* v.2.1 along with this distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.jboss.as.console.client.core;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Window;
import com.gwtplatform.mvp.client.proxy.PlaceRequest;
import org.jboss.as.console.client.shared.Preferences;
import javax.inject.Inject;
import java.util.HashMap;
import java.util.Map;
/**
* @author Heiko Braun
* @date 2/11/11
*/
public class BootstrapContext implements ApplicationProperties {
private Map<String,String> ctx = new HashMap<String,String>();
private static final String[] persistentProperties = new String[] {
//STANDALONE
};
private String initialPlace = null;
@Inject
public BootstrapContext() {
/*String token = History.getToken();
if(token!=null && !token.equals("") && !token.equals(NameTokens.signInPage))
setProperty(INITIAL_TOKEN, token);
*/
loadPersistedProperties();
String devHost = org.jboss.as.console.client.Build.DEV_HOST;
String domainApi = GWT.isScript() ? getBaseUrl()+"management" : "http://"+devHost+":8888/app/proxy";
setProperty(DOMAIN_API, domainApi);
String deploymentApi = GWT.isScript() ? getBaseUrl()+"management/add-content" : "http://"+devHost+":8888/app/upload";
setProperty(DEPLOYMENT_API, deploymentApi);
String logoutApi = GWT.isScript() ? getBaseUrl()+"logout" : "http://"+devHost+":8888/app/logout";
setProperty(LOGOUT_API, logoutApi);
//Log.info("Domain API Endpoint: " + domainApi);
}
private String getBaseUrl() {
// extract host
String base = GWT.getHostPageBaseURL();
return extractHttpEndpointUrl(base);
}
public static String extractHttpEndpointUrl(String base) {
String protocol = base.substring(0, base.indexOf("//")+2);
String remainder = base.substring(base.indexOf(protocol)+protocol.length(), base.length());
String host = null;
String port = null;
int portDelim = remainder.indexOf(":");
if(portDelim !=-1 )
{
host = remainder.substring(0, portDelim);
String portRemainder = remainder.substring(portDelim+1, remainder.length());
if(portRemainder.indexOf("/")!=-1)
{
port = portRemainder.substring(0, portRemainder.indexOf("/"));
}
else
{
port = portRemainder;
}
}
else
{
host = remainder.substring(0, remainder.indexOf("/"));
- port = "80";
+ if ("https://".equalsIgnoreCase(protocol)) {
+ port = "443";
+ } else {
+ port = "80";
+ }
}
// default url
return protocol + host + ":" + port + "/";
}
private void loadPersistedProperties() {
for(String key : persistentProperties)
{
String pref = Preferences.get(key);
if(pref!=null)
setProperty(key, pref);
}
}
@Override
public void setProperty(String key, String value)
{
if(isPersistent(key))
Preferences.set(key, value);
ctx.put(key, value);
}
@Override
public String getProperty(String key)
{
return ctx.get(key);
}
@Override
public boolean hasProperty(String key)
{
return getProperty(key)!=null;
}
public PlaceRequest getDefaultPlace() {
PlaceRequest defaultPlace = getProperty(STANDALONE).equals("true") ?
new PlaceRequest(NameTokens.StandaloneServerPresenter) : new PlaceRequest(NameTokens.DomainRuntimePresenter);
return defaultPlace;
}
@Override
public void removeProperty(String key) {
if(isPersistent(key))
Preferences.clear(key);
ctx.remove(key);
}
boolean isPersistent(String key)
{
boolean b = false;
for(String s : persistentProperties)
{
if(s.equals(key))
{
b=true;
break;
}
}
return b;
}
@Override
public boolean isStandalone() {
return getProperty(BootstrapContext.STANDALONE).equals("true");
}
public void setInitialPlace(String nameToken) {
this.initialPlace = nameToken;
}
public String getInitialPlace() {
return initialPlace;
}
public String getLogoutUrl() {
String url = getProperty(LOGOUT_API);
if(!GWT.isScript())
url += "?gwt.codesvr=" + Window.Location.getParameter("gwt.codesvr");
return url;
}
}
| true | true | public static String extractHttpEndpointUrl(String base) {
String protocol = base.substring(0, base.indexOf("//")+2);
String remainder = base.substring(base.indexOf(protocol)+protocol.length(), base.length());
String host = null;
String port = null;
int portDelim = remainder.indexOf(":");
if(portDelim !=-1 )
{
host = remainder.substring(0, portDelim);
String portRemainder = remainder.substring(portDelim+1, remainder.length());
if(portRemainder.indexOf("/")!=-1)
{
port = portRemainder.substring(0, portRemainder.indexOf("/"));
}
else
{
port = portRemainder;
}
}
else
{
host = remainder.substring(0, remainder.indexOf("/"));
port = "80";
}
// default url
return protocol + host + ":" + port + "/";
}
| public static String extractHttpEndpointUrl(String base) {
String protocol = base.substring(0, base.indexOf("//")+2);
String remainder = base.substring(base.indexOf(protocol)+protocol.length(), base.length());
String host = null;
String port = null;
int portDelim = remainder.indexOf(":");
if(portDelim !=-1 )
{
host = remainder.substring(0, portDelim);
String portRemainder = remainder.substring(portDelim+1, remainder.length());
if(portRemainder.indexOf("/")!=-1)
{
port = portRemainder.substring(0, portRemainder.indexOf("/"));
}
else
{
port = portRemainder;
}
}
else
{
host = remainder.substring(0, remainder.indexOf("/"));
if ("https://".equalsIgnoreCase(protocol)) {
port = "443";
} else {
port = "80";
}
}
// default url
return protocol + host + ":" + port + "/";
}
|
diff --git a/src/main/java/tconstruct/armor/items/TravelWings.java b/src/main/java/tconstruct/armor/items/TravelWings.java
index ab5cb66ae..53bfa0014 100644
--- a/src/main/java/tconstruct/armor/items/TravelWings.java
+++ b/src/main/java/tconstruct/armor/items/TravelWings.java
@@ -1,72 +1,73 @@
package tconstruct.armor.items;
import cpw.mods.fml.relauncher.*;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.IIcon;
import net.minecraft.world.World;
import tconstruct.library.armor.ArmorPart;
import tconstruct.tools.TinkerTools;
public class TravelWings extends TravelGear
{
public TravelWings()
{
super(ArmorPart.Legs);
}
@Override
@SideOnly(Side.CLIENT)
protected void registerModifiers (IIconRegister IIconRegister)
{
String base = "tinker:armor/travel_wings_";
modifiers = new IIcon[5];
modifiers[0] = IIconRegister.registerIcon("tinker:" + textureFolder + "/" + "wings" + "_" + "doublejump");
modifiers[1] = IIconRegister.registerIcon("tinker:" + textureFolder + "/" + "wings" + "_" + "featherfall");
modifiers[4] = IIconRegister.registerIcon("tinker:" + textureFolder + "/" + "wings" + "_" + "moss");
/*modifiers = new IIcon[3];
modifiers[0] = IIconRegister.registerIcon(base + "slimewings");
modifiers[1] = IIconRegister.registerIcon(base + "piston");
modifiers[2] = IIconRegister.registerIcon(base + "pearl");*/
}
@Override
public void onArmorTick (World world, EntityPlayer player, ItemStack itemStack)
{
+ super.onArmorTick(world, player, itemStack);
NBTTagCompound tag = itemStack.getTagCompound().getCompoundTag(getBaseTagName());
int feather = tag.getInteger("Feather Fall");
if (feather > 0)
{
if (player.fallDistance > 2.5)
player.fallDistance = 2.5f;
float terminalVelocity = -0.4f + (feather * 0.08f);
if (terminalVelocity > -0.05f)
terminalVelocity = -0.05f;
if (player.isSneaking() && terminalVelocity > -0.8f)
terminalVelocity = -0.8F;
boolean flying = false;
flying = player.capabilities.isFlying;
if (!flying && player.motionY < terminalVelocity)
{
player.motionY = terminalVelocity;
}
}
}
@Override
@SideOnly(Side.CLIENT)
public String getArmorTexture (ItemStack stack, Entity entity, int slot, String layer)
{
return "tinker:textures/armor/travel_wings.png";
}
@Override
public ItemStack getRepairMaterial (ItemStack input)
{
return new ItemStack(TinkerTools.materials, 1, 13);
}
}
| true | true | public void onArmorTick (World world, EntityPlayer player, ItemStack itemStack)
{
NBTTagCompound tag = itemStack.getTagCompound().getCompoundTag(getBaseTagName());
int feather = tag.getInteger("Feather Fall");
if (feather > 0)
{
if (player.fallDistance > 2.5)
player.fallDistance = 2.5f;
float terminalVelocity = -0.4f + (feather * 0.08f);
if (terminalVelocity > -0.05f)
terminalVelocity = -0.05f;
if (player.isSneaking() && terminalVelocity > -0.8f)
terminalVelocity = -0.8F;
boolean flying = false;
flying = player.capabilities.isFlying;
if (!flying && player.motionY < terminalVelocity)
{
player.motionY = terminalVelocity;
}
}
}
| public void onArmorTick (World world, EntityPlayer player, ItemStack itemStack)
{
super.onArmorTick(world, player, itemStack);
NBTTagCompound tag = itemStack.getTagCompound().getCompoundTag(getBaseTagName());
int feather = tag.getInteger("Feather Fall");
if (feather > 0)
{
if (player.fallDistance > 2.5)
player.fallDistance = 2.5f;
float terminalVelocity = -0.4f + (feather * 0.08f);
if (terminalVelocity > -0.05f)
terminalVelocity = -0.05f;
if (player.isSneaking() && terminalVelocity > -0.8f)
terminalVelocity = -0.8F;
boolean flying = false;
flying = player.capabilities.isFlying;
if (!flying && player.motionY < terminalVelocity)
{
player.motionY = terminalVelocity;
}
}
}
|
diff --git a/src/org/pentaho/agilebi/modeler/util/MultiTableModelerSource.java b/src/org/pentaho/agilebi/modeler/util/MultiTableModelerSource.java
index 53dd152..c600646 100644
--- a/src/org/pentaho/agilebi/modeler/util/MultiTableModelerSource.java
+++ b/src/org/pentaho/agilebi/modeler/util/MultiTableModelerSource.java
@@ -1,193 +1,195 @@
/*
* This program is free software; you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software
* Foundation.
*
* You should have received a copy of the GNU Lesser General Public License along with this
* program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
* or from the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* 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.
*
* Copyright (c) 2011 Pentaho Corporation.. All rights reserved.
*
* @author Ezequiel Cuellar
*/
package org.pentaho.agilebi.modeler.util;
import org.pentaho.agilebi.modeler.ModelerException;
import org.pentaho.agilebi.modeler.ModelerWorkspace;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.metadata.automodel.SchemaTable;
import org.pentaho.metadata.model.*;
import org.pentaho.metadata.model.concept.types.LocalizedString;
import org.pentaho.metadata.model.concept.types.RelationshipType;
import org.pentaho.pms.core.exception.PentahoMetadataException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
public class MultiTableModelerSource implements ISpoonModelerSource {
private ModelGenerator generator;
private DatabaseMeta databaseMeta;
private List<LogicalRelationship> joinTemplates;
private String datasourceName;
public static final String SOURCE_TYPE = MultiTableModelerSource.class.getSimpleName();
private static Logger logger = LoggerFactory.getLogger(MultiTableModelerSource.class);
public MultiTableModelerSource(DatabaseMeta databaseMeta, List<LogicalRelationship> joinTemplates, String datasourceName) {
this.datasourceName = datasourceName;
this.databaseMeta = databaseMeta;
this.joinTemplates = joinTemplates;
this.generator = new ModelGenerator();
}
@Override
public Domain generateDomain() throws ModelerException {
return this.generateDomain(this.databaseMeta, this.joinTemplates);
}
@Override
public Domain generateDomain(boolean dualModelingMode) throws ModelerException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public String getDatabaseName() {
String name = null;
if (this.databaseMeta != null) {
name = this.databaseMeta.getDatabaseName();
}
return name;
}
@Override
public void initialize(Domain domain) throws ModelerException {
}
@Override
public void serializeIntoDomain(Domain d) {
LogicalModel lm = d.getLogicalModels().get(0);
lm.setProperty("source_type", SOURCE_TYPE);
}
@Override
public String getSchemaName() {
return null;
}
@Override
public String getTableName() {
return null;
}
@Override
public DatabaseMeta getDatabaseMeta() {
return this.databaseMeta;
}
public Domain generateDomain(DatabaseMeta databaseMeta, List<LogicalRelationship> joinTemplates) {
Domain domain = null;
try {
// Generate domain based on the table names.
String locale = LocalizedString.DEFAULT_LOCALE;
this.generator.setLocale(locale);
this.generator.setDatabaseMeta(databaseMeta);
this.generator.setModelName(datasourceName);
List<SchemaTable> schemas = new ArrayList<SchemaTable>();
for (LogicalRelationship joinTemplate : joinTemplates) {
schemas.add(new SchemaTable("", joinTemplate.getFromTable().getName(locale)));
schemas.add(new SchemaTable("", joinTemplate.getToTable().getName(locale)));
}
SchemaTable tableNames[] = new SchemaTable[schemas.size()];
tableNames = schemas.toArray(tableNames);
this.generator.setTableNames(tableNames);
domain = this.generator.generateDomain();
domain.setId(datasourceName);
// Automodel to create categories
ModelerWorkspaceHelper helper = new ModelerWorkspaceHelper(locale);
ModelerWorkspace workspace = new ModelerWorkspace(helper);
+ workspace.setModelName(datasourceName);
workspace.setDomain(domain);
// Create and add LogicalRelationships to the LogicalModel from the
// domain.
LogicalModel logicalModel = domain.getLogicalModels().get(0);
// TODO do this with messages
logicalModel.setName(new LocalizedString(locale, datasourceName));
logicalModel.setDescription(new LocalizedString(locale, "This is the data model for "
+ datasourceName));
LogicalTable businessTable = logicalModel.getLogicalTables().get(0);
businessTable.setName(new LocalizedString(locale, datasourceName));
for (LogicalRelationship joinTemplate : joinTemplates) {
String lTable = joinTemplate.getFromTable().getName(locale);
String rTable = joinTemplate.getToTable().getName(locale);
LogicalTable fromTable = null;
LogicalColumn fromColumn = null;
LogicalTable toTable = null;
LogicalColumn toColumn = null;
for (LogicalTable logicalTable : logicalModel.getLogicalTables()) {
if (logicalTable.getName(locale).equals(lTable)) {
fromTable = logicalTable;
for (LogicalColumn logicalColumn : fromTable.getLogicalColumns()) {
if (logicalColumn.getName(locale).equals(joinTemplate.getFromColumn().getName(locale))) {
fromColumn = logicalColumn;
}
}
}
if (logicalTable.getName(locale).equals(rTable)) {
toTable = logicalTable;
for (LogicalColumn logicalColumn : toTable.getLogicalColumns()) {
if (logicalColumn.getName(locale).equals(joinTemplate.getToColumn().getName(locale))) {
toColumn = logicalColumn;
}
}
}
}
LogicalRelationship logicalRelationship = new LogicalRelationship();
// TODO is this INNER JOIN?
logicalRelationship.setRelationshipType(RelationshipType._1_1);
logicalRelationship.setFromTable(fromTable);
logicalRelationship.setFromColumn(fromColumn);
logicalRelationship.setToTable(toTable);
logicalRelationship.setToColumn(toColumn);
logicalModel.addLogicalRelationship(logicalRelationship);
}
helper.autoModelMultiTableRelational(workspace);
+ helper.populateDomain(workspace);
} catch (PentahoMetadataException e) {
e.printStackTrace();
logger.info(e.getLocalizedMessage());
} catch (ModelerException e) {
e.printStackTrace();
logger.info(e.getLocalizedMessage());
} catch (Exception e) {
e.printStackTrace();
logger.info(e.getLocalizedMessage());
}
return domain;
}
}
| false | true | public Domain generateDomain(DatabaseMeta databaseMeta, List<LogicalRelationship> joinTemplates) {
Domain domain = null;
try {
// Generate domain based on the table names.
String locale = LocalizedString.DEFAULT_LOCALE;
this.generator.setLocale(locale);
this.generator.setDatabaseMeta(databaseMeta);
this.generator.setModelName(datasourceName);
List<SchemaTable> schemas = new ArrayList<SchemaTable>();
for (LogicalRelationship joinTemplate : joinTemplates) {
schemas.add(new SchemaTable("", joinTemplate.getFromTable().getName(locale)));
schemas.add(new SchemaTable("", joinTemplate.getToTable().getName(locale)));
}
SchemaTable tableNames[] = new SchemaTable[schemas.size()];
tableNames = schemas.toArray(tableNames);
this.generator.setTableNames(tableNames);
domain = this.generator.generateDomain();
domain.setId(datasourceName);
// Automodel to create categories
ModelerWorkspaceHelper helper = new ModelerWorkspaceHelper(locale);
ModelerWorkspace workspace = new ModelerWorkspace(helper);
workspace.setDomain(domain);
// Create and add LogicalRelationships to the LogicalModel from the
// domain.
LogicalModel logicalModel = domain.getLogicalModels().get(0);
// TODO do this with messages
logicalModel.setName(new LocalizedString(locale, datasourceName));
logicalModel.setDescription(new LocalizedString(locale, "This is the data model for "
+ datasourceName));
LogicalTable businessTable = logicalModel.getLogicalTables().get(0);
businessTable.setName(new LocalizedString(locale, datasourceName));
for (LogicalRelationship joinTemplate : joinTemplates) {
String lTable = joinTemplate.getFromTable().getName(locale);
String rTable = joinTemplate.getToTable().getName(locale);
LogicalTable fromTable = null;
LogicalColumn fromColumn = null;
LogicalTable toTable = null;
LogicalColumn toColumn = null;
for (LogicalTable logicalTable : logicalModel.getLogicalTables()) {
if (logicalTable.getName(locale).equals(lTable)) {
fromTable = logicalTable;
for (LogicalColumn logicalColumn : fromTable.getLogicalColumns()) {
if (logicalColumn.getName(locale).equals(joinTemplate.getFromColumn().getName(locale))) {
fromColumn = logicalColumn;
}
}
}
if (logicalTable.getName(locale).equals(rTable)) {
toTable = logicalTable;
for (LogicalColumn logicalColumn : toTable.getLogicalColumns()) {
if (logicalColumn.getName(locale).equals(joinTemplate.getToColumn().getName(locale))) {
toColumn = logicalColumn;
}
}
}
}
LogicalRelationship logicalRelationship = new LogicalRelationship();
// TODO is this INNER JOIN?
logicalRelationship.setRelationshipType(RelationshipType._1_1);
logicalRelationship.setFromTable(fromTable);
logicalRelationship.setFromColumn(fromColumn);
logicalRelationship.setToTable(toTable);
logicalRelationship.setToColumn(toColumn);
logicalModel.addLogicalRelationship(logicalRelationship);
}
helper.autoModelMultiTableRelational(workspace);
} catch (PentahoMetadataException e) {
e.printStackTrace();
logger.info(e.getLocalizedMessage());
} catch (ModelerException e) {
e.printStackTrace();
logger.info(e.getLocalizedMessage());
} catch (Exception e) {
e.printStackTrace();
logger.info(e.getLocalizedMessage());
}
return domain;
}
| public Domain generateDomain(DatabaseMeta databaseMeta, List<LogicalRelationship> joinTemplates) {
Domain domain = null;
try {
// Generate domain based on the table names.
String locale = LocalizedString.DEFAULT_LOCALE;
this.generator.setLocale(locale);
this.generator.setDatabaseMeta(databaseMeta);
this.generator.setModelName(datasourceName);
List<SchemaTable> schemas = new ArrayList<SchemaTable>();
for (LogicalRelationship joinTemplate : joinTemplates) {
schemas.add(new SchemaTable("", joinTemplate.getFromTable().getName(locale)));
schemas.add(new SchemaTable("", joinTemplate.getToTable().getName(locale)));
}
SchemaTable tableNames[] = new SchemaTable[schemas.size()];
tableNames = schemas.toArray(tableNames);
this.generator.setTableNames(tableNames);
domain = this.generator.generateDomain();
domain.setId(datasourceName);
// Automodel to create categories
ModelerWorkspaceHelper helper = new ModelerWorkspaceHelper(locale);
ModelerWorkspace workspace = new ModelerWorkspace(helper);
workspace.setModelName(datasourceName);
workspace.setDomain(domain);
// Create and add LogicalRelationships to the LogicalModel from the
// domain.
LogicalModel logicalModel = domain.getLogicalModels().get(0);
// TODO do this with messages
logicalModel.setName(new LocalizedString(locale, datasourceName));
logicalModel.setDescription(new LocalizedString(locale, "This is the data model for "
+ datasourceName));
LogicalTable businessTable = logicalModel.getLogicalTables().get(0);
businessTable.setName(new LocalizedString(locale, datasourceName));
for (LogicalRelationship joinTemplate : joinTemplates) {
String lTable = joinTemplate.getFromTable().getName(locale);
String rTable = joinTemplate.getToTable().getName(locale);
LogicalTable fromTable = null;
LogicalColumn fromColumn = null;
LogicalTable toTable = null;
LogicalColumn toColumn = null;
for (LogicalTable logicalTable : logicalModel.getLogicalTables()) {
if (logicalTable.getName(locale).equals(lTable)) {
fromTable = logicalTable;
for (LogicalColumn logicalColumn : fromTable.getLogicalColumns()) {
if (logicalColumn.getName(locale).equals(joinTemplate.getFromColumn().getName(locale))) {
fromColumn = logicalColumn;
}
}
}
if (logicalTable.getName(locale).equals(rTable)) {
toTable = logicalTable;
for (LogicalColumn logicalColumn : toTable.getLogicalColumns()) {
if (logicalColumn.getName(locale).equals(joinTemplate.getToColumn().getName(locale))) {
toColumn = logicalColumn;
}
}
}
}
LogicalRelationship logicalRelationship = new LogicalRelationship();
// TODO is this INNER JOIN?
logicalRelationship.setRelationshipType(RelationshipType._1_1);
logicalRelationship.setFromTable(fromTable);
logicalRelationship.setFromColumn(fromColumn);
logicalRelationship.setToTable(toTable);
logicalRelationship.setToColumn(toColumn);
logicalModel.addLogicalRelationship(logicalRelationship);
}
helper.autoModelMultiTableRelational(workspace);
helper.populateDomain(workspace);
} catch (PentahoMetadataException e) {
e.printStackTrace();
logger.info(e.getLocalizedMessage());
} catch (ModelerException e) {
e.printStackTrace();
logger.info(e.getLocalizedMessage());
} catch (Exception e) {
e.printStackTrace();
logger.info(e.getLocalizedMessage());
}
return domain;
}
|
diff --git a/cejug-classifieds-server/src/net/java/dev/cejug/classifieds/service/endpoint/impl/LoadAtomOperation.java b/cejug-classifieds-server/src/net/java/dev/cejug/classifieds/service/endpoint/impl/LoadAtomOperation.java
index c3924415..3a0d7597 100644
--- a/cejug-classifieds-server/src/net/java/dev/cejug/classifieds/service/endpoint/impl/LoadAtomOperation.java
+++ b/cejug-classifieds-server/src/net/java/dev/cejug/classifieds/service/endpoint/impl/LoadAtomOperation.java
@@ -1,215 +1,215 @@
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Copyright (C) 2008 CEJUG - Ceará Java Users Group
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 (at your option) 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. 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
This file is part of the CEJUG-CLASSIFIEDS Project - an open source classifieds system
originally used by CEJUG - Ceará Java Users Group.
The project is hosted https://cejug-classifieds.dev.java.net/
You can contact us through the mail [email protected]
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
package net.java.dev.cejug.classifieds.service.endpoint.impl;
import java.util.Calendar;
import java.util.List;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.xml.ws.WebServiceException;
import net.java.dev.cejug.classifieds.business.interfaces.LoadAtomOperationLocal;
import net.java.dev.cejug.classifieds.entity.AdvertisementEntity;
import net.java.dev.cejug.classifieds.entity.CategoryEntity;
import net.java.dev.cejug.classifieds.entity.facade.AdvertisementFacadeLocal;
import net.java.dev.cejug.classifieds.entity.facade.CategoryFacadeLocal;
import net.java.dev.cejug_classifieds.metadata.business.SyndicationFilter;
import org.w3._2005.atom.DateTimeType;
import org.w3._2005.atom.EntryType;
import org.w3._2005.atom.Feed;
import org.w3._2005.atom.GeneratorType;
import org.w3._2005.atom.IdType;
import org.w3._2005.atom.LinkType;
import org.w3._2005.atom.LogoType;
import org.w3._2005.atom.ObjectFactory;
import org.w3._2005.atom.PersonType;
import org.w3._2005.atom.TextType;
import org.w3._2005.atom.UriType;
/**
* TODO: to comment.
*
* @author $Author$
* @version $Rev$ ($Date$)
*/
@Stateless
public class LoadAtomOperation implements LoadAtomOperationLocal {
/**
* Persistence façade of Advertisement entities.
*/
@EJB
private transient AdvertisementFacadeLocal advFacade;
@EJB
private transient CategoryFacadeLocal catFacade;
/**
* the global log manager, used to allow third party services to override
* the default logger.
*/
private static final Logger logger = Logger.getLogger(
LoadAtomOperation.class.getName(), "i18n/log");
public Feed loadAtomOperation(SyndicationFilter filter) {
try {
ObjectFactory factory = new ObjectFactory();
Feed atomFeed = factory.createFeed();
List<Object> feedAttributes = atomFeed
.getAuthorOrCategoryOrContributor();
// author.
PersonType author = factory.createPersonType();
List<Object> authorAttributes = author.getNameOrUriOrEmail();
authorAttributes.add(factory
.createPersonTypeName("Cejug-Classifieds"));
authorAttributes
.add(factory
.createPersonTypeEmail("[email protected]"));
UriType uri = factory.createUriType();
uri.setValue("https://cejug-classifieds.dev.java.net/");
authorAttributes.add(factory.createPersonTypeUri(uri));
feedAttributes.add(factory.createFeedAuthor(author));
// Title
TextType title = factory.createTextType();
title.setType("text");
// Generator
GeneratorType generator = factory.createGeneratorType();
generator.setUri("https://cejug-classifieds.dev.java.net/");
generator.setValue("Cejug-Classifieds");
generator.setVersion("$Revision$");
feedAttributes.add(factory.createFeedGenerator(generator));
feedAttributes.add(factory.createFeedContributor(author));
LogoType logo = factory.createLogoType();
logo
.setValue("https://cejug-classifieds.dev.java.net/images/logo.jpg");
feedAttributes.add(factory.createFeedLogo(logo));
CategoryEntity category = catFacade.read(filter.getCategoryId());
IdType id = factory.createIdType();
id.setValue("cejug-classifieds hard code test. TODO: real data...");
feedAttributes.add(factory.createEntryTypeId(id));
if (category == null) {
long categoryId = filter.getCategoryId();
if (categoryId < 1) {
title.getContent().add("Missed category identifier.");
} else {
title.getContent().add(
"Category #" + categoryId + " does not exist.");
}
feedAttributes.add(factory.createFeedTitle(title));
TextType subtitle = factory.createTextType();
subtitle.setType("text");
subtitle
.getContent()
.add(
"Please check the category id or read our documentation.");
feedAttributes.add(factory.createFeedSubtitle(subtitle));
atomFeed.getAuthorOrCategoryOrContributor().add(
factory.createFeedEntry(factory.createEntryType()));
} else {
title.getContent().add(category.getName());
feedAttributes.add(factory.createFeedTitle(title));
TextType subtitle = factory.createTextType();
subtitle.setType("text");
subtitle.getContent().add(category.getDescription());
feedAttributes.add(factory.createFeedSubtitle(subtitle));
// TODO: converter filter in a map of parameters...
List<AdvertisementEntity> result = advFacade
.readByCategory(filter.getCategoryId());
for (AdvertisementEntity adv : result) {
/*
* AttachmentEntity avatar = adv.getAvatar();
*
*
* if (avatar != null) { byte[] img = avatar.getContent();
* if (img != null && img.length > 0) { } }
*/
EntryType entry = factory.createEntryType();
List<Object> entryAttributes = entry
.getAuthorOrCategoryOrContent();
IdType entryId = factory.createIdType();
entryId.setValue("ADV" + adv.getId());
entryAttributes.add(factory.createEntryTypeId(entryId));
DateTimeType dt = factory.createDateTimeType();
dt.setValue(Calendar.getInstance());
entryAttributes.add(factory.createEntryTypeUpdated(dt));
entryAttributes.add(factory.createEntryTypePublished(dt));
TextType entryTitle = factory.createTextType();
entryTitle.setType("html");
entryTitle.getContent().add(adv.getTitle());
entryAttributes.add(factory
.createEntryTypeTitle(entryTitle));
TextType entrySummary = factory.createTextType();
entrySummary.setType("html");
entrySummary
.getContent()
.add(
- "<p><a href='http://ap.google.com/article/ALeqM5iidrMKZwVNDDlEtkssY6t1xxhg9QD94169T80'><img src='"
+ "<p><a href='http://devoxx.com/display/JV08/Home'><img src='"
+ adv.getAvatar().getReference()
- + "' alt='racebaitfail' style='float:left;'></a>"
+ + "' alt='devoxx.com' style='float:left;'></a>"
+ adv.getSummary() + "</p>");
entryAttributes.add(factory
.createEntryTypeSummary(entrySummary));
/*
* byte[] avatar = adv.getAvatar().getContent(); if (avatar
* != null && avatar.length > 0) { IconType icon =
* factory.createIconType(); icon.setValue(new
* String(adv.getAvatar().getContent()));
* entryAttributes.add(factory.createFeedIcon(icon)); }
*/
LinkType link = factory.createLinkType();
link
- .setHref("http://www.freeke.org/ffg/currentevents/national/racebaitfail.html");
+ .setHref("http://devoxx.com/display/JV08/Home");
link.setRel("alternate");
// TODO: get from advertisement or domain or category
link.setHreflang("en");
link.setTitle(adv.getTitle());
link.setType("text");
entryAttributes.add(factory.createEntryTypeLink(link));
atomFeed.getAuthorOrCategoryOrContributor().add(
factory.createFeedEntry(entry));
}
}
return atomFeed;
} catch (Exception e) {
// TODO: log
logger.severe(e.getMessage());
throw new WebServiceException(e);
}
}
}
| false | true | public Feed loadAtomOperation(SyndicationFilter filter) {
try {
ObjectFactory factory = new ObjectFactory();
Feed atomFeed = factory.createFeed();
List<Object> feedAttributes = atomFeed
.getAuthorOrCategoryOrContributor();
// author.
PersonType author = factory.createPersonType();
List<Object> authorAttributes = author.getNameOrUriOrEmail();
authorAttributes.add(factory
.createPersonTypeName("Cejug-Classifieds"));
authorAttributes
.add(factory
.createPersonTypeEmail("[email protected]"));
UriType uri = factory.createUriType();
uri.setValue("https://cejug-classifieds.dev.java.net/");
authorAttributes.add(factory.createPersonTypeUri(uri));
feedAttributes.add(factory.createFeedAuthor(author));
// Title
TextType title = factory.createTextType();
title.setType("text");
// Generator
GeneratorType generator = factory.createGeneratorType();
generator.setUri("https://cejug-classifieds.dev.java.net/");
generator.setValue("Cejug-Classifieds");
generator.setVersion("$Revision$");
feedAttributes.add(factory.createFeedGenerator(generator));
feedAttributes.add(factory.createFeedContributor(author));
LogoType logo = factory.createLogoType();
logo
.setValue("https://cejug-classifieds.dev.java.net/images/logo.jpg");
feedAttributes.add(factory.createFeedLogo(logo));
CategoryEntity category = catFacade.read(filter.getCategoryId());
IdType id = factory.createIdType();
id.setValue("cejug-classifieds hard code test. TODO: real data...");
feedAttributes.add(factory.createEntryTypeId(id));
if (category == null) {
long categoryId = filter.getCategoryId();
if (categoryId < 1) {
title.getContent().add("Missed category identifier.");
} else {
title.getContent().add(
"Category #" + categoryId + " does not exist.");
}
feedAttributes.add(factory.createFeedTitle(title));
TextType subtitle = factory.createTextType();
subtitle.setType("text");
subtitle
.getContent()
.add(
"Please check the category id or read our documentation.");
feedAttributes.add(factory.createFeedSubtitle(subtitle));
atomFeed.getAuthorOrCategoryOrContributor().add(
factory.createFeedEntry(factory.createEntryType()));
} else {
title.getContent().add(category.getName());
feedAttributes.add(factory.createFeedTitle(title));
TextType subtitle = factory.createTextType();
subtitle.setType("text");
subtitle.getContent().add(category.getDescription());
feedAttributes.add(factory.createFeedSubtitle(subtitle));
// TODO: converter filter in a map of parameters...
List<AdvertisementEntity> result = advFacade
.readByCategory(filter.getCategoryId());
for (AdvertisementEntity adv : result) {
/*
* AttachmentEntity avatar = adv.getAvatar();
*
*
* if (avatar != null) { byte[] img = avatar.getContent();
* if (img != null && img.length > 0) { } }
*/
EntryType entry = factory.createEntryType();
List<Object> entryAttributes = entry
.getAuthorOrCategoryOrContent();
IdType entryId = factory.createIdType();
entryId.setValue("ADV" + adv.getId());
entryAttributes.add(factory.createEntryTypeId(entryId));
DateTimeType dt = factory.createDateTimeType();
dt.setValue(Calendar.getInstance());
entryAttributes.add(factory.createEntryTypeUpdated(dt));
entryAttributes.add(factory.createEntryTypePublished(dt));
TextType entryTitle = factory.createTextType();
entryTitle.setType("html");
entryTitle.getContent().add(adv.getTitle());
entryAttributes.add(factory
.createEntryTypeTitle(entryTitle));
TextType entrySummary = factory.createTextType();
entrySummary.setType("html");
entrySummary
.getContent()
.add(
"<p><a href='http://ap.google.com/article/ALeqM5iidrMKZwVNDDlEtkssY6t1xxhg9QD94169T80'><img src='"
+ adv.getAvatar().getReference()
+ "' alt='racebaitfail' style='float:left;'></a>"
+ adv.getSummary() + "</p>");
entryAttributes.add(factory
.createEntryTypeSummary(entrySummary));
/*
* byte[] avatar = adv.getAvatar().getContent(); if (avatar
* != null && avatar.length > 0) { IconType icon =
* factory.createIconType(); icon.setValue(new
* String(adv.getAvatar().getContent()));
* entryAttributes.add(factory.createFeedIcon(icon)); }
*/
LinkType link = factory.createLinkType();
link
.setHref("http://www.freeke.org/ffg/currentevents/national/racebaitfail.html");
link.setRel("alternate");
// TODO: get from advertisement or domain or category
link.setHreflang("en");
link.setTitle(adv.getTitle());
link.setType("text");
entryAttributes.add(factory.createEntryTypeLink(link));
atomFeed.getAuthorOrCategoryOrContributor().add(
factory.createFeedEntry(entry));
}
}
return atomFeed;
} catch (Exception e) {
// TODO: log
logger.severe(e.getMessage());
throw new WebServiceException(e);
}
}
| public Feed loadAtomOperation(SyndicationFilter filter) {
try {
ObjectFactory factory = new ObjectFactory();
Feed atomFeed = factory.createFeed();
List<Object> feedAttributes = atomFeed
.getAuthorOrCategoryOrContributor();
// author.
PersonType author = factory.createPersonType();
List<Object> authorAttributes = author.getNameOrUriOrEmail();
authorAttributes.add(factory
.createPersonTypeName("Cejug-Classifieds"));
authorAttributes
.add(factory
.createPersonTypeEmail("[email protected]"));
UriType uri = factory.createUriType();
uri.setValue("https://cejug-classifieds.dev.java.net/");
authorAttributes.add(factory.createPersonTypeUri(uri));
feedAttributes.add(factory.createFeedAuthor(author));
// Title
TextType title = factory.createTextType();
title.setType("text");
// Generator
GeneratorType generator = factory.createGeneratorType();
generator.setUri("https://cejug-classifieds.dev.java.net/");
generator.setValue("Cejug-Classifieds");
generator.setVersion("$Revision$");
feedAttributes.add(factory.createFeedGenerator(generator));
feedAttributes.add(factory.createFeedContributor(author));
LogoType logo = factory.createLogoType();
logo
.setValue("https://cejug-classifieds.dev.java.net/images/logo.jpg");
feedAttributes.add(factory.createFeedLogo(logo));
CategoryEntity category = catFacade.read(filter.getCategoryId());
IdType id = factory.createIdType();
id.setValue("cejug-classifieds hard code test. TODO: real data...");
feedAttributes.add(factory.createEntryTypeId(id));
if (category == null) {
long categoryId = filter.getCategoryId();
if (categoryId < 1) {
title.getContent().add("Missed category identifier.");
} else {
title.getContent().add(
"Category #" + categoryId + " does not exist.");
}
feedAttributes.add(factory.createFeedTitle(title));
TextType subtitle = factory.createTextType();
subtitle.setType("text");
subtitle
.getContent()
.add(
"Please check the category id or read our documentation.");
feedAttributes.add(factory.createFeedSubtitle(subtitle));
atomFeed.getAuthorOrCategoryOrContributor().add(
factory.createFeedEntry(factory.createEntryType()));
} else {
title.getContent().add(category.getName());
feedAttributes.add(factory.createFeedTitle(title));
TextType subtitle = factory.createTextType();
subtitle.setType("text");
subtitle.getContent().add(category.getDescription());
feedAttributes.add(factory.createFeedSubtitle(subtitle));
// TODO: converter filter in a map of parameters...
List<AdvertisementEntity> result = advFacade
.readByCategory(filter.getCategoryId());
for (AdvertisementEntity adv : result) {
/*
* AttachmentEntity avatar = adv.getAvatar();
*
*
* if (avatar != null) { byte[] img = avatar.getContent();
* if (img != null && img.length > 0) { } }
*/
EntryType entry = factory.createEntryType();
List<Object> entryAttributes = entry
.getAuthorOrCategoryOrContent();
IdType entryId = factory.createIdType();
entryId.setValue("ADV" + adv.getId());
entryAttributes.add(factory.createEntryTypeId(entryId));
DateTimeType dt = factory.createDateTimeType();
dt.setValue(Calendar.getInstance());
entryAttributes.add(factory.createEntryTypeUpdated(dt));
entryAttributes.add(factory.createEntryTypePublished(dt));
TextType entryTitle = factory.createTextType();
entryTitle.setType("html");
entryTitle.getContent().add(adv.getTitle());
entryAttributes.add(factory
.createEntryTypeTitle(entryTitle));
TextType entrySummary = factory.createTextType();
entrySummary.setType("html");
entrySummary
.getContent()
.add(
"<p><a href='http://devoxx.com/display/JV08/Home'><img src='"
+ adv.getAvatar().getReference()
+ "' alt='devoxx.com' style='float:left;'></a>"
+ adv.getSummary() + "</p>");
entryAttributes.add(factory
.createEntryTypeSummary(entrySummary));
/*
* byte[] avatar = adv.getAvatar().getContent(); if (avatar
* != null && avatar.length > 0) { IconType icon =
* factory.createIconType(); icon.setValue(new
* String(adv.getAvatar().getContent()));
* entryAttributes.add(factory.createFeedIcon(icon)); }
*/
LinkType link = factory.createLinkType();
link
.setHref("http://devoxx.com/display/JV08/Home");
link.setRel("alternate");
// TODO: get from advertisement or domain or category
link.setHreflang("en");
link.setTitle(adv.getTitle());
link.setType("text");
entryAttributes.add(factory.createEntryTypeLink(link));
atomFeed.getAuthorOrCategoryOrContributor().add(
factory.createFeedEntry(entry));
}
}
return atomFeed;
} catch (Exception e) {
// TODO: log
logger.severe(e.getMessage());
throw new WebServiceException(e);
}
}
|
diff --git a/nexus/nexus-test-harness/nexus-test-harness-launcher/src/test/java/org/sonatype/nexus/integrationtests/nexus641/Nexus641ReindexTaskTest.java b/nexus/nexus-test-harness/nexus-test-harness-launcher/src/test/java/org/sonatype/nexus/integrationtests/nexus641/Nexus641ReindexTaskTest.java
index d7179a595..1870ed8fb 100644
--- a/nexus/nexus-test-harness/nexus-test-harness-launcher/src/test/java/org/sonatype/nexus/integrationtests/nexus641/Nexus641ReindexTaskTest.java
+++ b/nexus/nexus-test-harness/nexus-test-harness-launcher/src/test/java/org/sonatype/nexus/integrationtests/nexus641/Nexus641ReindexTaskTest.java
@@ -1,59 +1,60 @@
package org.sonatype.nexus.integrationtests.nexus641;
import java.io.File;
import java.util.List;
import junit.framework.Assert;
import org.apache.commons.io.FileUtils;
import org.junit.Test;
import org.sonatype.nexus.integrationtests.AbstractNexusIntegrationTest;
import org.sonatype.nexus.integrationtests.nexus533.TaskScheduleUtil;
import org.sonatype.nexus.rest.model.NexusArtifact;
import org.sonatype.nexus.rest.model.ScheduledServicePropertyResource;
import org.sonatype.nexus.test.utils.SearchMessageUtil;
/**
* @author marvin
* @description Test task Reindex Repositories
*/
public class Nexus641ReindexTaskTest
extends AbstractNexusIntegrationTest
{
private SearchMessageUtil messageUtil = new SearchMessageUtil();
@Test
public void testReindex()
throws Exception
{
// NEXUS-664
if ( true )
{
printKnownErrorButDoNotFail( getClass(), "testReindex" );
+ return;
}
File repositoryPath = new File( nexusBaseDir, "runtime/work/storage/nexus-test-harness-repo" );
File oldSnapshot = getTestFile( "repo" );
// Copy artifact to avoid indexing
FileUtils.copyDirectory( oldSnapshot, repositoryPath );
// try to seach and fail
List<NexusArtifact> search = messageUtil.searchFor( "nexus641" );
Assert.assertEquals( "The artifact was already indexed", 1, search.size() );
ScheduledServicePropertyResource prop = new ScheduledServicePropertyResource();
prop.setId( "repositoryOrGroupId" );
prop.setValue( "nexus-test-harness-repo" );
// reindex
TaskScheduleUtil.runTask( "org.sonatype.nexus.tasks.ReindexTask", prop );
// RepositoryMessageUtil.updateIndexes( "nexus-test-harness-repo" );
// try to download again and success
search = messageUtil.searchFor( "nexus641" );
Assert.assertEquals( "The artifact should be indexed", 2, search.size() );
}
}
| true | true | public void testReindex()
throws Exception
{
// NEXUS-664
if ( true )
{
printKnownErrorButDoNotFail( getClass(), "testReindex" );
}
File repositoryPath = new File( nexusBaseDir, "runtime/work/storage/nexus-test-harness-repo" );
File oldSnapshot = getTestFile( "repo" );
// Copy artifact to avoid indexing
FileUtils.copyDirectory( oldSnapshot, repositoryPath );
// try to seach and fail
List<NexusArtifact> search = messageUtil.searchFor( "nexus641" );
Assert.assertEquals( "The artifact was already indexed", 1, search.size() );
ScheduledServicePropertyResource prop = new ScheduledServicePropertyResource();
prop.setId( "repositoryOrGroupId" );
prop.setValue( "nexus-test-harness-repo" );
// reindex
TaskScheduleUtil.runTask( "org.sonatype.nexus.tasks.ReindexTask", prop );
// RepositoryMessageUtil.updateIndexes( "nexus-test-harness-repo" );
// try to download again and success
search = messageUtil.searchFor( "nexus641" );
Assert.assertEquals( "The artifact should be indexed", 2, search.size() );
}
| public void testReindex()
throws Exception
{
// NEXUS-664
if ( true )
{
printKnownErrorButDoNotFail( getClass(), "testReindex" );
return;
}
File repositoryPath = new File( nexusBaseDir, "runtime/work/storage/nexus-test-harness-repo" );
File oldSnapshot = getTestFile( "repo" );
// Copy artifact to avoid indexing
FileUtils.copyDirectory( oldSnapshot, repositoryPath );
// try to seach and fail
List<NexusArtifact> search = messageUtil.searchFor( "nexus641" );
Assert.assertEquals( "The artifact was already indexed", 1, search.size() );
ScheduledServicePropertyResource prop = new ScheduledServicePropertyResource();
prop.setId( "repositoryOrGroupId" );
prop.setValue( "nexus-test-harness-repo" );
// reindex
TaskScheduleUtil.runTask( "org.sonatype.nexus.tasks.ReindexTask", prop );
// RepositoryMessageUtil.updateIndexes( "nexus-test-harness-repo" );
// try to download again and success
search = messageUtil.searchFor( "nexus641" );
Assert.assertEquals( "The artifact should be indexed", 2, search.size() );
}
|
diff --git a/common/net/minecraftforge/common/ForgeDirection.java b/common/net/minecraftforge/common/ForgeDirection.java
index 3a2219a90..16516bbe2 100644
--- a/common/net/minecraftforge/common/ForgeDirection.java
+++ b/common/net/minecraftforge/common/ForgeDirection.java
@@ -1,56 +1,56 @@
package net.minecraftforge.common;
public enum ForgeDirection
{
/** -Y */
DOWN(0, -1, 0),
/** +Y */
UP(0, 1, 0),
/** -Z */
NORTH(0, 0, -1),
/** +Z */
SOUTH(0, 0, 1),
/** -X */
WEST(-1, 0, 0),
/** +X */
EAST(1, 0, 0),
/**
* Used only by getOrientation, for invalid inputs
*/
UNKNOWN(0, 0, 0);
public final int offsetX;
public final int offsetY;
public final int offsetZ;
public final int flag;
private ForgeDirection(int x, int y, int z)
{
offsetX = x;
offsetY = y;
offsetZ = z;
flag = 1 << ordinal();
}
public static ForgeDirection getOrientation(int id)
{
- if (id < ForgeDirection.values().length)
+ if (id > 0 && id < ForgeDirection.values().length)
{
return ForgeDirection.values()[id];
}
return UNKNOWN;
}
public static final int[] opposite = new int[] { 1, 0, 3, 2, 5, 4, 6};
public ForgeDirection getOpposite()
{
return getOrientation(opposite[ordinal()]);
}
}
| true | true | public static ForgeDirection getOrientation(int id)
{
if (id < ForgeDirection.values().length)
{
return ForgeDirection.values()[id];
}
return UNKNOWN;
}
| public static ForgeDirection getOrientation(int id)
{
if (id > 0 && id < ForgeDirection.values().length)
{
return ForgeDirection.values()[id];
}
return UNKNOWN;
}
|
diff --git a/src/edu/ucla/cens/mobility/ClassifierService.java b/src/edu/ucla/cens/mobility/ClassifierService.java
index cf5ee04..b7c5e50 100644
--- a/src/edu/ucla/cens/mobility/ClassifierService.java
+++ b/src/edu/ucla/cens/mobility/ClassifierService.java
@@ -1,1107 +1,1108 @@
package edu.ucla.cens.mobility;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.TimeZone;
import java.util.Vector;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import edu.ucla.cens.systemlog.ISystemLog;
import edu.ucla.cens.accelservice.IAccelService;
import edu.ucla.cens.systemlog.Log;
import edu.ucla.cens.wifigpslocation.IWiFiGPSLocationService;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.hardware.SensorManager;
import android.location.Location;
import android.os.IBinder;
import android.os.PowerManager;
import android.os.RemoteException;
import java.text.DateFormat;
import java.text.ParseException;
//import android.util.Log;
public class ClassifierService extends WakefulIntentService
{
public ClassifierService()
{
super("ClassifierService");
// TODO Auto-generated constructor stub
}
// private IWiFiGPSLocationService mWiFiGPS;
private static final String TAG = "ClassifierService";
private static MobilityDbAdapter tmdb;
@Override
public void onCreate()
{
// TODO Auto-generated method stub
super.onCreate();
// if (!Mobility.initialized)
// Mobility.initialize(this.getApplicationContext());
bindService(new Intent(ISystemLog.class.getName()),
Log.SystemLogConnection, Context.BIND_AUTO_CREATE);
Log.register(TAG);
}
@Override
public void onDestroy()
{
// TODO Auto-generated method stub
super.onDestroy();
unbindService(Log.SystemLogConnection);
// unbindService(AccelServiceConnection);
// unbindService(mConnection);
}
// private IWiFiGPSLocationService mWiFiGPS;
// private ServiceConnection mConnection = new ServiceConnection()
// {
// public void onServiceConnected(ComponentName className, IBinder service)
// {
// // This is called when the connection with the service has been
// // established, giving us the service object we can use to
// // interact with the service. We are communicating with our
// // service through an IDL interface, so get a client-side
// // representation of that from the raw service object.
// mWiFiGPS = IWiFiGPSLocationService.Stub.asInterface(service);
// Log.i(TAG, "Connected to WiFiGPSLocation Service");
//
// Log.i(TAG, "Connected");
// ready(gpsCode);
// }
//
// public void onServiceDisconnected(ComponentName className)
// {
// // This is called when the connection with the service has been
// // unexpectedly disconnected -- that is, its process crashed.
// mWiFiGPS = null;
//
// Log.i(TAG, "Disconnected from WiFiGPSLocation Service");
//
// }
// };
// public ServiceConnection AccelServiceConnection = new ServiceConnection()
// {
// public void onServiceConnected(ComponentName className, IBinder service)
// {
// mAccel = IAccelService.Stub.asInterface(service);
// ClassifierService.this.ready(ClassifierService.this.accelCode);
// Log.i(TAG, "Connected to accel service");
// }
//
// public void onServiceDisconnected(ComponentName className)
// {
// Log.d(TAG,
// "onServiceDisconnected was called!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
// mAccel = null;
// }
// };
// private IAccelService mAccel;
private int accelCode = 0;
private int gpsCode = 1;
boolean[] readySvc = { false, false };
private boolean wifiChecking = true;
private synchronized void ready(int serviceCode)
{
readySvc[serviceCode] = true;
if (readySvc[gpsCode] && readySvc[accelCode])
{
getTransportMode();
stopSelf();
}
}
@SuppressWarnings("unchecked")
private Vector<ArrayList<Double>> getAccSamples()
{
try
{
if (Mobility.getmAccel() == null
|| System.currentTimeMillis()
- Mobility.getmAccel().getLastTimeStamp() > 10000 + Mobility.sampleRate)
{
Log.e(TAG, "mAccel fails to not be null or old.");
if (Mobility.failCount++ > 2)
{
if (Mobility.getmAccel() == null)
Mobility.setNotification(this, Mobility.STATUS_ERROR,
"Please verify that AccelService is installed");
else
{
Log.e(TAG,
"Last accelerometer sample is "
+ (System.currentTimeMillis() - Mobility
.getmAccel().getLastTimeStamp())
/ 1000 + " seconds old");
Mobility.setNotification(this, Mobility.STATUS_ERROR,
"Mobility is waiting for new accelerometer data");
// A workaround for when AccelService failed to start
// all the way. The bug was fixed so the workaround is
// gone.
// Mobility.getWithTheProgram(this.getApplicationContext());
// // workaround for when fast restart on MyTouch 4G
// breaks AccelService
}
}
else
Mobility.setNotification(this, Mobility.STATUS_PENDING,
"Waiting for the first sensor sample");
return null;
}
Mobility.failCount = 0;
// ArrayList<Double[]> forceWithTimes =
// (ArrayList<Double[]>)mAccel.getLastForce();
ArrayList<Double> force = new ArrayList<Double>();
// if (forceWithTimes != null)
// for (int i = 0; i < forceWithTimes.size(); i++)
// {
// System.err.println(forceWithTimes.get(i) +"");
// force.add((Double)(forceWithTimes.get(i))[0]);
// Log.d(TAG, (forceWithTimes.get(i))[1] + " " + i);
// }
Log.d(TAG, (System.currentTimeMillis() - Mobility.getmAccel()
.getLastTimeStamp())
/ 1000
+ " is how old this sample is!!!!!!");
Vector<ArrayList<Double>> curList = new Vector<ArrayList<Double>>();
curList.add((ArrayList<Double>) Mobility.getmAccel()
.getLastXValues());
curList.add((ArrayList<Double>) Mobility.getmAccel()
.getLastYValues());
curList.add((ArrayList<Double>) Mobility.getmAccel()
.getLastZValues());
curList.add((ArrayList<Double>) Mobility.getmAccel().getLastForce());
if (curList.get(0) != null)
{
// Log.i(TAG, "Here is the force vector: \n" + curList.toString());
return curList;
}
else
Log.i(TAG, "List was null, try later.");
}
catch (RemoteException re)
{
Log.e(TAG, "Remote Ex", re);
}
return null;
}
private String printTriaxialData(Vector<ArrayList<Double>> triax)
{
StringBuffer sb = new StringBuffer();
for (int i = 0; i < triax.get(0).size(); i++)
{
sb.append("x:" + triax.get(0).get(i) + ",");
sb.append("y:" + triax.get(1).get(i) + ",");
sb.append("z:" + triax.get(2).get(i) + ";");
}
return sb.toString();
}
/** Provider strings */
private static final String WIFIGPS_PROVIDER = "WiFiGPSLocation:GPS";
private static final String WIFIGPSCACHED_PROVIDER = "WiFiGPSLocation:Cached";
private static final String FAKE_PROVIDER = "WiFiGPSLocation:Fake";
private static final String APPROX_PROVIDER = "WiFiGPSLocation:Approx";
private static final String NET_PROVIDER = "WiFiGPSLocation:Network";
private static final String UNAVAILABLE = "unavailable";
private static final String VALID = "valid";
private static final String INACCURATE = "inaccurate";
private static final String STALE = "stale";
private static final String NETWORK = "network";
private static final int INACCURACY_THRESHOLD = 30;
private static final int STALENESS_THRESHOLD = 3 * 60 * 1000;
private static final String WALK = "walk";
private static final String RUN = "run";
private static final String STILL = "still";
private static final String DRIVE = "drive";
private static final String BIKE = "bike";
private static final String ERROR = "error";
private static final String UNKNOWN = "unknown";
private static final String WIFI_HISTORY = "wifi_history";
private void getTransportMode()
{
Vector<ArrayList<Double>> samples = getAccSamples();
boolean gpsFail = false;
// Log.i(TAG, samples.size() + " is the sample size"); // Always 4 now
double lat = Double.NaN;
double lon = Double.NaN;
float speed = 0;
int cachedCount = 0;
boolean driveCheat = true;
double acc = Double.NaN;
long timestamp = 0;
String provider = "None";
// boolean setInterval = false;
String status = UNAVAILABLE;
// double acc = 99999;
Location loc;
String wifiData = "";
String wifiActivity = UNKNOWN;
try
{
// while (mWiFiGPS == null) Log.e(TAG,
// "wifigps is null even though android returned from onbind. Fantastic.");
// // make this better
if (Mobility.getmWiFiGPS() != null)
{
loc = Mobility.getmWiFiGPS().getLocation();
wifiData = Mobility.getmWiFiGPS().getWiFiScan();
// Log.d(TAG, wifiData);
try
{
wifiActivity = checkWifi(new JSONObject(wifiData));
}
catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
+// Log.d(TAG, "Error running checkWifi :" + wifiData);
}
// globalLoc = mWiFiGPS.getLocation();
// if (!setInterval)
// {
// Mobility.getmWiFiGPS().suggestInterval(Mobility.SERVICE_TAG,
// (int) Mobility.sampleRate);
// setInterval = true;
// }
Log.d(TAG, "mWiFiGPS is not null!");
if (loc != null)
{
lat = loc.getLatitude();
lon = loc.getLongitude();
speed = loc.getSpeed();
acc = loc.getAccuracy();
provider = loc.getProvider();
timestamp = loc.getTime();
if (provider.equals(FAKE_PROVIDER))
{
Log.d(TAG, "Fake provider");
status = UNAVAILABLE;
speed = Float.NaN;
cachedCount = 0;
}
else if (provider.equals(WIFIGPSCACHED_PROVIDER))
{
cachedCount++;
Log.d(TAG, "Cached provider");
if (acc > INACCURACY_THRESHOLD)
{
Log.d(TAG, "Inaccurate");
status = INACCURATE;
if (!driveCheat)
speed = Float.NaN;
}
else
{
Log.d(TAG, "Valid");
status = VALID;
}
}
else if (provider.equals(WIFIGPS_PROVIDER))
{
Log.d(TAG, "GPS provider");
cachedCount = 0;
if (timestamp > System.currentTimeMillis()
- STALENESS_THRESHOLD)
{
if (acc > INACCURACY_THRESHOLD)
{
Log.d(TAG, "Inaccurate");
status = INACCURATE;
if (!driveCheat)
speed = Float.NaN;
}
else
{
Log.d(TAG, "Valid");
status = VALID;
}
}
else
{
Log.d(TAG, "Stale");
status = STALE;
speed = Float.NaN;
}
}
else if (provider.equals(APPROX_PROVIDER))
{
cachedCount = 0;
Log.d(TAG, "Stale");
status = STALE;
speed = 0;
}
else if (provider.equals(NET_PROVIDER))
{
cachedCount = 0;
Log.d(TAG, "Network");
status = NETWORK;
speed = 0;
}
else
{
cachedCount = 0;
Log.e(TAG, "Invalid provider code received: "
+ provider);
Mobility.setDebugNotification(this,
"Invalid WiFiGPS code: " + provider);
}
}
else
{
Log.d(TAG, "mWiFiGPS.getLocation() is null, losing sample");
}
// Mobility.gpsFailCount = 0;
}
else
{
loc = null;
// Mobility.gpsFailCount++;
gpsFail = true;
Log.d(TAG, "mWiFiGPS is null, no GPS data");
status = UNAVAILABLE;
speed = Float.NaN;
}
}
catch (RemoteException e)
{
// TODO Auto-generated catch block
loc = null;
status = UNAVAILABLE;
speed = Float.NaN;
Log.e(TAG, "Exception happened with connection to WiFiGPS service");
e.printStackTrace();
}
String activity = UNKNOWN;
if (samples == null)
{
Log.i(TAG, "Null object from AccelService");
activity = ERROR;
addTransportMode(activity, samples, speed, acc, provider, status,
timestamp, wifiData, lat, lon);
return;
}
ArrayList<Double> accData = samples.get(3);
if (samples.get(0).size() < 10)
{
Log.i(TAG, "Too few samples to do accelerometer feature analysis");
addTransportMode(STILL, samples, speed, acc, provider, status,
timestamp, wifiData, lat, lon);
return;
}
// sample *= 310;
// Thread thread = new Thread(new Classify(samples));
// Log.d(TAG, "Starting thread");
// thread.start();
// int newVal = 0;
double dataSize = accData.size();
double sum = 0.0, s = 0.0;
double avg = 0.0, a = 0.0;
double var = 0.0, v = 0.0;
double accFft1, accFft2, accFft3, accFft4, accFft5, a1, a2, a3, a4, a5, a6, a7, a8, a9, a0;
// float speed = 0.0f;
a1 = goertzel(accData, 1., dataSize);
a2 = goertzel(accData, 2., dataSize);
a3 = goertzel(accData, 3., dataSize);
a4 = goertzel(accData, 4., dataSize);
a5 = goertzel(accData, 5., dataSize);
a6 = goertzel(accData, 6., dataSize);
a7 = goertzel(accData, 7., dataSize);
a8 = goertzel(accData, 8., dataSize);
a9 = goertzel(accData, 9., dataSize);
a0 = goertzel(accData, 10., dataSize);
for (int i = 0; i < dataSize; i++)
{
s += accData.get(i);
}
a = s / dataSize;
// Log.d(TAG, "s is " + s);
s = 0.0;
for (int i = 0; i < dataSize; i++)
{
s += Math.pow((accData.get(i) - a), 2.0);
}
v = s / dataSize;
for (int i = 0; i < dataSize; i++)
{
accData.set(i, accData.get(i) * 310.); // restore to android
// measurement
}
for (int i = 0; i < dataSize; i++)
{
sum += accData.get(i);
}
avg = sum / dataSize;
sum = 0.0;
for (int i = 0; i < dataSize; i++)
{
sum += Math.pow((accData.get(i) - avg), 2.0);
}
var = sum / dataSize;
accFft1 = goertzel(accData, 1., dataSize);
accFft2 = goertzel(accData, 2., dataSize);
accFft3 = goertzel(accData, 3., dataSize);
accFft4 = goertzel(accData, 4., dataSize);
accFft5 = goertzel(accData, 5., dataSize);
// Log.d(TAG, String.format("Samples = %4.0f", dataSize));
// if (loc != null)
// {
// speed = loc.getSpeed();
// //acc = loc.getAccuracy();
// }
Log.d(TAG, speed + " is the speed");
String features = String
.format("%2.4f,%2.4f,%2.4f,%2.4f,%2.4f,%2.4f,%2.4f,%2.4f,%2.4f,%2.4f,%2.4f,%2.4f,%2.4f,%2.4f,%2.4f,%2.4f,%2.4f,%2.4f,%2.4f,%2.4f",
var, accFft1, accFft2, accFft3, speed, v, a, a1, a2,
a3, a4, a5, a6, a7, a8, a9, a0, 0., 0., 0.);
// Log.d(TAG, speed +
// " is the speed and the features are " + features);
activity = activity(speed, a, v, a1, a2, a3, a4, a5, a6, a7, a8, a9, a0);
if (wifiChecking && !wifiActivity.equals(UNKNOWN))
{
if (activity.equals(DRIVE) || activity.equals(STILL))
activity = wifiActivity; // The other classifier is rubbish for
// still/drive, just use WiFi result
}
if (gpsFail && Mobility.debugMode)
Mobility.setNotification(this, Mobility.STATUS_OK, activity
+ " (Warning: No GPS)");
else
Mobility.setNotification(this, Mobility.STATUS_OK, activity);
// var, accFft1, accFft2, accFft3, speed, v, a, a1, a2, a3, a4, a5, a6,
// a7, a8, a9, a0);
// double [] fft = {a1, a2, a3, a4, a5, a6, a7, a8, a9, a0}; // real
// features
double[] fft = { a1, a2, a3, a5, a8, accFft1, accFft2, accFft3, var,
acc }; // wrong
// order
// hack
// to
// get
// all
// used
// features
addTransportMode(activity, samples, speed, acc, provider, status,
timestamp, wifiData, lat, lon);
}
// private static String indoorActivity(double var, double avg, double a1,
// double a2, double a3, double a4, double a5, double a6, double a7, double
// a8, double a9, double a0)
// {
// Log.d(TAG, "Features: var=" + var + " avg=" + avg + " a=" + a1 + "," + a2
// + "," + a3 + "," + a4 + "," + a5 + "," + a6 + "," + a7 + "," + a8 + "," +
// a9 + "," + a0);
// if (var <= 0.0047)
// {
// if (var <= 0.0016)
// return "still";
// else
// {
// if (a5 <= 0.1532)
// {
// if (a1 <= 0.5045)
// return "still";
// else
// return "walk";
// }
// else
// return "still";
// }
// }
// else
// {
// if (a3 <= 60.3539)
// {
// if (var <= 0.0085)
// {
// if (a8 <= 0.0506)
// return "walk";
// else
// {
// if (a2 <= 2.8607)
// return "still";
// else
// return "walk";
// }
// }
// else
// {
// if (a2 <= 2.7725)
// {
// if (a1 <= 13.0396)
// return "walk";
// else
// return "still";
// }
// else
// return "walk";
// }
// }
// else
// return "run";
// }
//
// }
// private static String activity(double acc_var, double accgz1, double
// accgz2, double accgz3, float gps_speed, double var, double avg, double
// a1, double a2, double a3, double a4, double a5,
// double a6, double a7, double a8, double a9, double a0)
// {
// String output = "still";
// Log.d(TAG, "Features: speed=" + gps_speed + " var=" + acc_var + " gz1=" +
// accgz1 + " gz2=" + accgz2 + " gz3=" + accgz3);
// if (gps_speed <= 0.29)
// output = indoorActivity(var, avg, a1, a2, a3, a4, a5, a6, a7, a8, a9,
// a0);// "still";
// else if (accgz3 <= 2663606.69633)
// if (gps_speed <= 6.37)
// if (accgz2 <= 463400.011249)
// if (acc_var <= 205.972492)
// if (acc_var <= 13.084102)
// if (gps_speed <= 0.8)
// output = "still";
// else
// output = "drive";// "bike";
// else if (gps_speed <= 1.33)
// output = "still";// "bike";
// else
// output = "drive";
// else if (gps_speed <= 1.84)
// if (accgz1 <= 125502.942136)
// output = "walk";// "bike";
// else
// output = "walk";
// else
// output = "bike";// "bike";
//
// else if (acc_var <= 41153.783729)
// if (gps_speed <= 2.12)
// output = "walk";
// else
// output = "bike";
// else
// output = "run";
// else
// output = "drive";
//
// else if (accgz3 <= 5132319.94693)
// if (gps_speed <= 1.86)
// output = "walk";// bike
// else
// output = "run";
// else
// output = "run";
// Log.d(TAG, output);
// return output;
// }
// private double historySize = 5.;
private double checkLength = 11 * 60 * 1000; // 11 minutes
private String checkWifi(JSONObject jsonObject) throws JSONException
{
// load previous
SharedPreferences settings = getSharedPreferences(Mobility.MOBILITY,
Context.MODE_PRIVATE);
String APsFromLastTimeStr = settings.getString(WIFI_HISTORY, null); // compare
// with
// previous
// sample
long time = jsonObject.getLong("time");
if (APsFromLastTimeStr != null)
{
HashMap<Long, Vector<String>> lastAPs = new HashMap<Long, Vector<String>>();
String[] lines = APsFromLastTimeStr.split("\n");
long lastTime = Long.parseLong(lines[0]);
String lastMode = lines[1];
Vector<String> APsFromLastTimes = new Vector<String>();
// Log.d(TAG, "aps from last time object: " + APsFromLastTimeStr);
// Log.d(TAG, APsFromLastTimes.size() + " previous scans");
int count = 0;
for (int l = 2; l < lines.length; l++)
{
try
{
Vector<String> prev = new Vector<String>();
String[] APStrs = lines[l].split(",");
long prevTimestamp = Long.parseLong(APStrs[0]);
for (int m = 1; m < APStrs.length; m++)
{
String str = APStrs[m];
APsFromLastTimes.add(str);
prev.add(str);
}
lastAPs.put(prevTimestamp, prev);
Log.d(TAG, count++ + " history lines!");
}
catch (NumberFormatException e)
{
Log.e(TAG, "Malformed timestamp in line " + l
+ " of previous strings: \"" + lines[1] + "\"");
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// Log.d(TAG, "AP from last time exists and is well-formed:\n"
// + APsFromLastTimeStr);
Vector<String> APs = JSONToList(jsonObject);
// compare to APsFromLastTime
int same = 0;
int total = 0;
if (lastTime == time) // no new wifi data
{
Log.d(TAG,
"Returning previous value since there has been no new WiFi data");
return lastMode;
}
Log.d(TAG, "Current wifi is " + (System.currentTimeMillis() - time)
/ 60000 + " minutes old.");
if (lastTime < System.currentTimeMillis() - 1000 * 60 * 8) // if no
// recent
// wifi
// for
// comparison
{
Log.d(TAG,
"Last stored wifi was ages ("
+ (System.currentTimeMillis() - lastTime)
/ 60000 + " minutes) ago .");
writeWifi(settings, time, UNKNOWN, APs, null);
return UNKNOWN;
}
else
Log.d(TAG, "Last stored wifi is "
+ (System.currentTimeMillis() - lastTime) / 60000
+ " minutes old.");
// Now we can do the comparison
for (String AP : APs)
{
if (APsFromLastTimes.contains(AP))
same++;
total++;
}
// for (String AP : APsFromLastTime)
// {
// if (APs.contains(AP)) // only count others that don't match. We
// don't count the same ones again.
// same++;
// total++;
// }
Log.d(TAG, "There were " + same + " matches out of "
+ total + " APs were in this sample. " + APsFromLastTimes);
if (total > 0)
{
int threshold = 2;
if (total <= 3)
threshold = 1;
if (total == 1)
threshold = 0;
if (same <= threshold)
{
Log.d(TAG, "Wifi chooses drive!");
writeWifi(settings, time, DRIVE, APs, lastAPs);
return DRIVE;// + " " + same / total;
}
else
{
Log.d(TAG, "Wifi chooses still!");
writeWifi(settings, time, STILL, APs, lastAPs);
return STILL;// + " " + same / total;
}
}
else
{
Log.d(TAG,
"No wifi detected in new sample; it's up to the GPS.");
writeWifi(settings, time, UNKNOWN, APs, lastAPs);
return UNKNOWN;
}
}
else
{
Log.d(TAG, "No previous AP!");
// no history
Vector<String> APs = JSONToList(jsonObject);
writeWifi(settings, time, UNKNOWN, APs, null);
return UNKNOWN;
}
}
private void writeWifi(SharedPreferences settings, long time, String mode,
Vector<String> APs, HashMap<Long, Vector<String>> lastAPs)
{
// APs = new Vector<String>(); // remove!
String store = time + "\n" + mode + "\n" + time + ",";
for (String s : APs)
store += s + ",";
if (APs.size() > 0)
{
if (!store.endsWith(","))
Log.e(TAG, "This is wrong: " + store + " " + APs.size());
store = store.substring(0, store.length() - 1); // cut off last
// comma
}
long now = System.currentTimeMillis();
if (lastAPs != null)
{
for (Long ts : lastAPs.keySet())
{
if (ts > now - checkLength)
{
store += "\n" + ts + ",";
for (String ap : lastAPs.get(ts))
store += ap + ",";
}
if (!store.endsWith(","))
Log.e(TAG, "This is wrong: " + store + " " + APs.size());
store = store.substring(0, store.length() - 1); // cut off last
// comma
}
}
// else if (store.endsWith("\n"))
// Log.d(TAG, "Ends with newline, so that's fine. Splits into " +
// store.split("\n").length + " lines.");
// Log.d(TAG, store);
Editor editor = settings.edit();
// Log.d(TAG, "Storing " + store);
editor.putString(WIFI_HISTORY, store);
editor.commit();
}
private Vector<String> JSONToList(JSONObject jsonObject)
throws JSONException
{
Vector<String> list = new Vector<String>();
int strsum = 0, strcount = 0;
JSONObject ap;
JSONArray array = jsonObject.getJSONArray("scan");
for (int i = 0; i < array.length(); i++)
{
ap = array.getJSONObject(i);
strsum += ap.getInt("strength");
strcount++;
// if (ap.getInt("strength") > -50)
// {
// list.add(ap.getString("ssid"));
//// Log.d(TAG, "Adding \"" + ap.getString("ssid") + "\" to APs");
// }
}
if (list.size() == 0 && strcount > 0)
{
double avg = strsum / strcount;
for (int i = 0; i < array.length(); i++)
{
ap = array.getJSONObject(i);
//strsum += ap.getInt("strength");
//strcount++;
if (ap.getInt("strength") >= avg)
{
list.add(ap.getString("ssid"));
}
}
}
return list;
}
/**
* This is the main classification method. Updated code after retraining
*
* @param acc_var
* @param accgz1
* @param accgz2
* @param accgz3
* @param gps_speed
* @param avg
* @param var
* @param a1
* @param a2
* @param a3
* @param a4
* @param a5
* @param a6
* @param a7
* @param a8
* @param a9
* @param a0
* @return Classification object with the mode
*/
private String activity(Float gps_speed, double avg, double var, double a1,
double a2, double a3, double a4, double a5, double a6, double a7,
double a8, double a9, double a0)
{
String output = STILL;
if (var <= 0.016791)
{
if (a6 <= 0.002427)
{
/*
* if(a7 <= 0.001608) {
*/
if (gps_speed <= 0.791462 || gps_speed.isNaN())// || gps_speed
// !=
// Double.NaN)
{
// if(avg <= 0.963016)
// {
// output = STILL;
// }
// else if(avg <= 0.98282)
// {
// output = DRIVE;Log.d(TAG, "Drive 0 because gps speed is "
// + gps_speed + " and avg is " + avg);
// }
// else if(avg <= 1.042821)
// {
// if(avg <= 1.040987)
// {
// if(avg <= 1.037199)
// {
// if(avg <= 1.03592)
// {
// output = STILL;
// }
// else
// {
// output = DRIVE;Log.d(TAG, "Drive 1");
// }
// }
// else
// {
// output = STILL;
// }
// }
// else
// {
// output = DRIVE;Log.d(TAG, "Drive 2");
// }
// }
// else
{
output = STILL;
}
}
else
{
output = DRIVE;
Log.d(TAG, "Drive 3");
}
/*
* } else { output = DRIVE;Log.d(TAG, "Drive 4"); }
*/
}
else if (gps_speed <= 0.791462 || gps_speed.isNaN())// && gps_speed
// !=
// Double.NaN)
{
output = STILL;
}
else
{
output = DRIVE;
Log.d(TAG, "Drive 5");
}
}
else
{
if (a3 <= 16.840921)
{
output = WALK;
}
else
{
output = RUN;
}
}
return output;
}
public String activity1(double gps_speed, double avg, double var,
double a1, double a2, double a3, double a4, double a5, double a6,
double a7, double a8, double a9, double a0)
{
if (a3 <= 0.096835)
{
if (a6 <= 0.002421)
{
if (a5 <= 0.002208)
{
return STILL;// (15611.0/4731.0)
}
else
{
return DRIVE;// a5 > 0.002208: drive (2238.0/841.0)
}
}
else
// if (a6 > 0.002421)
{
if (avg <= 1.066716)
{
if (gps_speed <= 5)
{
return BIKE;// (2723.27/1784.81)
}
else
{
return DRIVE;// speed > 5: drive (5528.73/350.99)
}
}
else
{
return BIKE;// average > 1.066716: bike (2358.0/423.0)
}
}
}
else
{// a3 > 0.096835
if (a3 <= 21.993029)
{
if (a2 <= 6.32047)
{
return BIKE;// : bike (8924.0/3077.0)
}
else
// a2 > 6.32047
{
if (var <= 0.139588)
{
return WALK;// : walk (7759.0/323.0)
}
else
// (var > 0.139588)
{
return BIKE;// : bike (2251.0/1265.0)
}
}
}
else
{
return RUN;// a3 > 21.993029: run (9217.0/90.0)
}
}
}
private static double goertzel(ArrayList<Double> accData, double freq,
double sr)
{
double s_prev = 0;
double s_prev2 = 0;
double coeff = 2 * Math.cos((2 * Math.PI * freq) / sr);
double s;
for (int i = 0; i < accData.size(); i++)
{
double sample = accData.get(i);
s = sample + coeff * s_prev - s_prev2;
s_prev2 = s_prev;
s_prev = s;
}
double power = s_prev2 * s_prev2 + s_prev * s_prev - coeff * s_prev2
* s_prev;
return power;
}
// public static void addTransportMode(String mode, String features, double
// speed, double variance, double average, double [] fft, double lat, double
// lon)
// {
// uploadMode(mode, speed, variance, average, fft, lat, lon);
// }
public void addTransportMode(String mode,
Vector<ArrayList<Double>> samples, double speed, double accuracy,
String provider, String status, long timestamp, String wifiData,
double lat, double lon)
{
Log.d(TAG, "GPS is " + lat + " and " + lon + "");
long time = System.currentTimeMillis();// resJson.setAndReturnTime();
// Open the database, and store the response
tmdb.open();
tmdb.createRow(mode, time, status, String.valueOf(speed), timestamp,
String.valueOf(accuracy), provider, wifiData, samples,
String.valueOf(lat), String.valueOf(lon));
tmdb.close();
}
@Override
public IBinder onBind(Intent arg0)
{
// TODO Auto-generated method stub
return null;
}
@Override
protected void doWakefulWork(Intent intent)
{
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
tmdb = new MobilityDbAdapter(this, "mobility", "mobility", "mobility");
if (!Mobility.gpsConnected)
this.getApplicationContext()
.bindService(
new Intent(
edu.ucla.cens.wifigpslocation.IWiFiGPSLocationService.class
.getName()), Mobility.mConnection,
Context.BIND_AUTO_CREATE);
if (!Mobility.accelConnected)
this.getApplicationContext().bindService(
new Intent(IAccelService.class.getName()),
Mobility.accelServiceConnection, Context.BIND_AUTO_CREATE);
getTransportMode();
stopSelf();
}
}
| true | true | private void getTransportMode()
{
Vector<ArrayList<Double>> samples = getAccSamples();
boolean gpsFail = false;
// Log.i(TAG, samples.size() + " is the sample size"); // Always 4 now
double lat = Double.NaN;
double lon = Double.NaN;
float speed = 0;
int cachedCount = 0;
boolean driveCheat = true;
double acc = Double.NaN;
long timestamp = 0;
String provider = "None";
// boolean setInterval = false;
String status = UNAVAILABLE;
// double acc = 99999;
Location loc;
String wifiData = "";
String wifiActivity = UNKNOWN;
try
{
// while (mWiFiGPS == null) Log.e(TAG,
// "wifigps is null even though android returned from onbind. Fantastic.");
// // make this better
if (Mobility.getmWiFiGPS() != null)
{
loc = Mobility.getmWiFiGPS().getLocation();
wifiData = Mobility.getmWiFiGPS().getWiFiScan();
// Log.d(TAG, wifiData);
try
{
wifiActivity = checkWifi(new JSONObject(wifiData));
}
catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
// globalLoc = mWiFiGPS.getLocation();
// if (!setInterval)
// {
// Mobility.getmWiFiGPS().suggestInterval(Mobility.SERVICE_TAG,
// (int) Mobility.sampleRate);
// setInterval = true;
// }
Log.d(TAG, "mWiFiGPS is not null!");
if (loc != null)
{
lat = loc.getLatitude();
lon = loc.getLongitude();
speed = loc.getSpeed();
acc = loc.getAccuracy();
provider = loc.getProvider();
timestamp = loc.getTime();
if (provider.equals(FAKE_PROVIDER))
{
Log.d(TAG, "Fake provider");
status = UNAVAILABLE;
speed = Float.NaN;
cachedCount = 0;
}
else if (provider.equals(WIFIGPSCACHED_PROVIDER))
{
cachedCount++;
Log.d(TAG, "Cached provider");
if (acc > INACCURACY_THRESHOLD)
{
Log.d(TAG, "Inaccurate");
status = INACCURATE;
if (!driveCheat)
speed = Float.NaN;
}
else
{
Log.d(TAG, "Valid");
status = VALID;
}
}
else if (provider.equals(WIFIGPS_PROVIDER))
{
Log.d(TAG, "GPS provider");
cachedCount = 0;
if (timestamp > System.currentTimeMillis()
- STALENESS_THRESHOLD)
{
if (acc > INACCURACY_THRESHOLD)
{
Log.d(TAG, "Inaccurate");
status = INACCURATE;
if (!driveCheat)
speed = Float.NaN;
}
else
{
Log.d(TAG, "Valid");
status = VALID;
}
}
else
{
Log.d(TAG, "Stale");
status = STALE;
speed = Float.NaN;
}
}
else if (provider.equals(APPROX_PROVIDER))
{
cachedCount = 0;
Log.d(TAG, "Stale");
status = STALE;
speed = 0;
}
else if (provider.equals(NET_PROVIDER))
{
cachedCount = 0;
Log.d(TAG, "Network");
status = NETWORK;
speed = 0;
}
else
{
cachedCount = 0;
Log.e(TAG, "Invalid provider code received: "
+ provider);
Mobility.setDebugNotification(this,
"Invalid WiFiGPS code: " + provider);
}
}
else
{
Log.d(TAG, "mWiFiGPS.getLocation() is null, losing sample");
}
// Mobility.gpsFailCount = 0;
}
else
{
loc = null;
// Mobility.gpsFailCount++;
gpsFail = true;
Log.d(TAG, "mWiFiGPS is null, no GPS data");
status = UNAVAILABLE;
speed = Float.NaN;
}
}
catch (RemoteException e)
{
// TODO Auto-generated catch block
loc = null;
status = UNAVAILABLE;
speed = Float.NaN;
Log.e(TAG, "Exception happened with connection to WiFiGPS service");
e.printStackTrace();
}
String activity = UNKNOWN;
if (samples == null)
{
Log.i(TAG, "Null object from AccelService");
activity = ERROR;
addTransportMode(activity, samples, speed, acc, provider, status,
timestamp, wifiData, lat, lon);
return;
}
ArrayList<Double> accData = samples.get(3);
if (samples.get(0).size() < 10)
{
Log.i(TAG, "Too few samples to do accelerometer feature analysis");
addTransportMode(STILL, samples, speed, acc, provider, status,
timestamp, wifiData, lat, lon);
return;
}
// sample *= 310;
// Thread thread = new Thread(new Classify(samples));
// Log.d(TAG, "Starting thread");
// thread.start();
// int newVal = 0;
double dataSize = accData.size();
double sum = 0.0, s = 0.0;
double avg = 0.0, a = 0.0;
double var = 0.0, v = 0.0;
double accFft1, accFft2, accFft3, accFft4, accFft5, a1, a2, a3, a4, a5, a6, a7, a8, a9, a0;
// float speed = 0.0f;
a1 = goertzel(accData, 1., dataSize);
a2 = goertzel(accData, 2., dataSize);
a3 = goertzel(accData, 3., dataSize);
a4 = goertzel(accData, 4., dataSize);
a5 = goertzel(accData, 5., dataSize);
a6 = goertzel(accData, 6., dataSize);
a7 = goertzel(accData, 7., dataSize);
a8 = goertzel(accData, 8., dataSize);
a9 = goertzel(accData, 9., dataSize);
a0 = goertzel(accData, 10., dataSize);
for (int i = 0; i < dataSize; i++)
{
s += accData.get(i);
}
a = s / dataSize;
// Log.d(TAG, "s is " + s);
s = 0.0;
for (int i = 0; i < dataSize; i++)
{
s += Math.pow((accData.get(i) - a), 2.0);
}
v = s / dataSize;
for (int i = 0; i < dataSize; i++)
{
accData.set(i, accData.get(i) * 310.); // restore to android
// measurement
}
for (int i = 0; i < dataSize; i++)
{
sum += accData.get(i);
}
avg = sum / dataSize;
sum = 0.0;
for (int i = 0; i < dataSize; i++)
{
sum += Math.pow((accData.get(i) - avg), 2.0);
}
var = sum / dataSize;
accFft1 = goertzel(accData, 1., dataSize);
accFft2 = goertzel(accData, 2., dataSize);
accFft3 = goertzel(accData, 3., dataSize);
accFft4 = goertzel(accData, 4., dataSize);
accFft5 = goertzel(accData, 5., dataSize);
// Log.d(TAG, String.format("Samples = %4.0f", dataSize));
// if (loc != null)
// {
// speed = loc.getSpeed();
// //acc = loc.getAccuracy();
// }
Log.d(TAG, speed + " is the speed");
String features = String
.format("%2.4f,%2.4f,%2.4f,%2.4f,%2.4f,%2.4f,%2.4f,%2.4f,%2.4f,%2.4f,%2.4f,%2.4f,%2.4f,%2.4f,%2.4f,%2.4f,%2.4f,%2.4f,%2.4f,%2.4f",
var, accFft1, accFft2, accFft3, speed, v, a, a1, a2,
a3, a4, a5, a6, a7, a8, a9, a0, 0., 0., 0.);
// Log.d(TAG, speed +
// " is the speed and the features are " + features);
activity = activity(speed, a, v, a1, a2, a3, a4, a5, a6, a7, a8, a9, a0);
if (wifiChecking && !wifiActivity.equals(UNKNOWN))
{
if (activity.equals(DRIVE) || activity.equals(STILL))
activity = wifiActivity; // The other classifier is rubbish for
// still/drive, just use WiFi result
}
if (gpsFail && Mobility.debugMode)
Mobility.setNotification(this, Mobility.STATUS_OK, activity
+ " (Warning: No GPS)");
else
Mobility.setNotification(this, Mobility.STATUS_OK, activity);
// var, accFft1, accFft2, accFft3, speed, v, a, a1, a2, a3, a4, a5, a6,
// a7, a8, a9, a0);
// double [] fft = {a1, a2, a3, a4, a5, a6, a7, a8, a9, a0}; // real
// features
double[] fft = { a1, a2, a3, a5, a8, accFft1, accFft2, accFft3, var,
acc }; // wrong
// order
// hack
// to
// get
// all
// used
// features
addTransportMode(activity, samples, speed, acc, provider, status,
timestamp, wifiData, lat, lon);
}
| private void getTransportMode()
{
Vector<ArrayList<Double>> samples = getAccSamples();
boolean gpsFail = false;
// Log.i(TAG, samples.size() + " is the sample size"); // Always 4 now
double lat = Double.NaN;
double lon = Double.NaN;
float speed = 0;
int cachedCount = 0;
boolean driveCheat = true;
double acc = Double.NaN;
long timestamp = 0;
String provider = "None";
// boolean setInterval = false;
String status = UNAVAILABLE;
// double acc = 99999;
Location loc;
String wifiData = "";
String wifiActivity = UNKNOWN;
try
{
// while (mWiFiGPS == null) Log.e(TAG,
// "wifigps is null even though android returned from onbind. Fantastic.");
// // make this better
if (Mobility.getmWiFiGPS() != null)
{
loc = Mobility.getmWiFiGPS().getLocation();
wifiData = Mobility.getmWiFiGPS().getWiFiScan();
// Log.d(TAG, wifiData);
try
{
wifiActivity = checkWifi(new JSONObject(wifiData));
}
catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
// Log.d(TAG, "Error running checkWifi :" + wifiData);
}
// globalLoc = mWiFiGPS.getLocation();
// if (!setInterval)
// {
// Mobility.getmWiFiGPS().suggestInterval(Mobility.SERVICE_TAG,
// (int) Mobility.sampleRate);
// setInterval = true;
// }
Log.d(TAG, "mWiFiGPS is not null!");
if (loc != null)
{
lat = loc.getLatitude();
lon = loc.getLongitude();
speed = loc.getSpeed();
acc = loc.getAccuracy();
provider = loc.getProvider();
timestamp = loc.getTime();
if (provider.equals(FAKE_PROVIDER))
{
Log.d(TAG, "Fake provider");
status = UNAVAILABLE;
speed = Float.NaN;
cachedCount = 0;
}
else if (provider.equals(WIFIGPSCACHED_PROVIDER))
{
cachedCount++;
Log.d(TAG, "Cached provider");
if (acc > INACCURACY_THRESHOLD)
{
Log.d(TAG, "Inaccurate");
status = INACCURATE;
if (!driveCheat)
speed = Float.NaN;
}
else
{
Log.d(TAG, "Valid");
status = VALID;
}
}
else if (provider.equals(WIFIGPS_PROVIDER))
{
Log.d(TAG, "GPS provider");
cachedCount = 0;
if (timestamp > System.currentTimeMillis()
- STALENESS_THRESHOLD)
{
if (acc > INACCURACY_THRESHOLD)
{
Log.d(TAG, "Inaccurate");
status = INACCURATE;
if (!driveCheat)
speed = Float.NaN;
}
else
{
Log.d(TAG, "Valid");
status = VALID;
}
}
else
{
Log.d(TAG, "Stale");
status = STALE;
speed = Float.NaN;
}
}
else if (provider.equals(APPROX_PROVIDER))
{
cachedCount = 0;
Log.d(TAG, "Stale");
status = STALE;
speed = 0;
}
else if (provider.equals(NET_PROVIDER))
{
cachedCount = 0;
Log.d(TAG, "Network");
status = NETWORK;
speed = 0;
}
else
{
cachedCount = 0;
Log.e(TAG, "Invalid provider code received: "
+ provider);
Mobility.setDebugNotification(this,
"Invalid WiFiGPS code: " + provider);
}
}
else
{
Log.d(TAG, "mWiFiGPS.getLocation() is null, losing sample");
}
// Mobility.gpsFailCount = 0;
}
else
{
loc = null;
// Mobility.gpsFailCount++;
gpsFail = true;
Log.d(TAG, "mWiFiGPS is null, no GPS data");
status = UNAVAILABLE;
speed = Float.NaN;
}
}
catch (RemoteException e)
{
// TODO Auto-generated catch block
loc = null;
status = UNAVAILABLE;
speed = Float.NaN;
Log.e(TAG, "Exception happened with connection to WiFiGPS service");
e.printStackTrace();
}
String activity = UNKNOWN;
if (samples == null)
{
Log.i(TAG, "Null object from AccelService");
activity = ERROR;
addTransportMode(activity, samples, speed, acc, provider, status,
timestamp, wifiData, lat, lon);
return;
}
ArrayList<Double> accData = samples.get(3);
if (samples.get(0).size() < 10)
{
Log.i(TAG, "Too few samples to do accelerometer feature analysis");
addTransportMode(STILL, samples, speed, acc, provider, status,
timestamp, wifiData, lat, lon);
return;
}
// sample *= 310;
// Thread thread = new Thread(new Classify(samples));
// Log.d(TAG, "Starting thread");
// thread.start();
// int newVal = 0;
double dataSize = accData.size();
double sum = 0.0, s = 0.0;
double avg = 0.0, a = 0.0;
double var = 0.0, v = 0.0;
double accFft1, accFft2, accFft3, accFft4, accFft5, a1, a2, a3, a4, a5, a6, a7, a8, a9, a0;
// float speed = 0.0f;
a1 = goertzel(accData, 1., dataSize);
a2 = goertzel(accData, 2., dataSize);
a3 = goertzel(accData, 3., dataSize);
a4 = goertzel(accData, 4., dataSize);
a5 = goertzel(accData, 5., dataSize);
a6 = goertzel(accData, 6., dataSize);
a7 = goertzel(accData, 7., dataSize);
a8 = goertzel(accData, 8., dataSize);
a9 = goertzel(accData, 9., dataSize);
a0 = goertzel(accData, 10., dataSize);
for (int i = 0; i < dataSize; i++)
{
s += accData.get(i);
}
a = s / dataSize;
// Log.d(TAG, "s is " + s);
s = 0.0;
for (int i = 0; i < dataSize; i++)
{
s += Math.pow((accData.get(i) - a), 2.0);
}
v = s / dataSize;
for (int i = 0; i < dataSize; i++)
{
accData.set(i, accData.get(i) * 310.); // restore to android
// measurement
}
for (int i = 0; i < dataSize; i++)
{
sum += accData.get(i);
}
avg = sum / dataSize;
sum = 0.0;
for (int i = 0; i < dataSize; i++)
{
sum += Math.pow((accData.get(i) - avg), 2.0);
}
var = sum / dataSize;
accFft1 = goertzel(accData, 1., dataSize);
accFft2 = goertzel(accData, 2., dataSize);
accFft3 = goertzel(accData, 3., dataSize);
accFft4 = goertzel(accData, 4., dataSize);
accFft5 = goertzel(accData, 5., dataSize);
// Log.d(TAG, String.format("Samples = %4.0f", dataSize));
// if (loc != null)
// {
// speed = loc.getSpeed();
// //acc = loc.getAccuracy();
// }
Log.d(TAG, speed + " is the speed");
String features = String
.format("%2.4f,%2.4f,%2.4f,%2.4f,%2.4f,%2.4f,%2.4f,%2.4f,%2.4f,%2.4f,%2.4f,%2.4f,%2.4f,%2.4f,%2.4f,%2.4f,%2.4f,%2.4f,%2.4f,%2.4f",
var, accFft1, accFft2, accFft3, speed, v, a, a1, a2,
a3, a4, a5, a6, a7, a8, a9, a0, 0., 0., 0.);
// Log.d(TAG, speed +
// " is the speed and the features are " + features);
activity = activity(speed, a, v, a1, a2, a3, a4, a5, a6, a7, a8, a9, a0);
if (wifiChecking && !wifiActivity.equals(UNKNOWN))
{
if (activity.equals(DRIVE) || activity.equals(STILL))
activity = wifiActivity; // The other classifier is rubbish for
// still/drive, just use WiFi result
}
if (gpsFail && Mobility.debugMode)
Mobility.setNotification(this, Mobility.STATUS_OK, activity
+ " (Warning: No GPS)");
else
Mobility.setNotification(this, Mobility.STATUS_OK, activity);
// var, accFft1, accFft2, accFft3, speed, v, a, a1, a2, a3, a4, a5, a6,
// a7, a8, a9, a0);
// double [] fft = {a1, a2, a3, a4, a5, a6, a7, a8, a9, a0}; // real
// features
double[] fft = { a1, a2, a3, a5, a8, accFft1, accFft2, accFft3, var,
acc }; // wrong
// order
// hack
// to
// get
// all
// used
// features
addTransportMode(activity, samples, speed, acc, provider, status,
timestamp, wifiData, lat, lon);
}
|
diff --git a/org.eclipse.jdt.launching.macosx/macosx/org/eclipse/jdt/internal/ui/macbundler/BundleWizardPage2.java b/org.eclipse.jdt.launching.macosx/macosx/org/eclipse/jdt/internal/ui/macbundler/BundleWizardPage2.java
index c5e8786e5..c9d3f3681 100644
--- a/org.eclipse.jdt.launching.macosx/macosx/org/eclipse/jdt/internal/ui/macbundler/BundleWizardPage2.java
+++ b/org.eclipse.jdt.launching.macosx/macosx/org/eclipse/jdt/internal/ui/macbundler/BundleWizardPage2.java
@@ -1,130 +1,130 @@
/*******************************************************************************
* Copyright (c) 2000, 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.macbundler;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
import org.eclipse.jface.util.PropertyChangeEvent;
public class BundleWizardPage2 extends BundleWizardBasePage {
Text fWorkingDir;
Table fClassPath;
Table fResources;
protected BundleWizardPage2(BundleDescription bd) {
super("page2", bd); //$NON-NLS-1$
}
public void createContents(Composite parent) {
Composite c= createComposite(parent, 2);
createLabel(c, Util.getString("page2.workingDirectory.label"), GridData.VERTICAL_ALIGN_CENTER); //$NON-NLS-1$
fWorkingDir= createText(c, WORKINGDIR, 1);
fClassPath= createTableGroup(parent, Util.getString("page2.addToClasspath.group.label"), true); //$NON-NLS-1$
fResources= createTableGroup(parent, Util.getString("page2.addToBundle.group.label"), false); //$NON-NLS-1$
}
Table createTableGroup(Composite parent, String groupName, final boolean onClasspath) {
Group g1= createGroup(parent, groupName, 1);
final Table table= new Table(g1, SWT.H_SCROLL | SWT.V_SCROLL | SWT.MULTI | SWT.FULL_SELECTION);
setHeightHint(table, 80);
Composite c1= createComposite(g1, 3);
final Button addButton1= createButton(c1, SWT.NONE, Util.getString("page2.addFile.button.label")); //$NON-NLS-1$
addButton1.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
FileDialog fd= new FileDialog(addButton1.getShell(), SWT.OPEN);
fd.setText(Util.getString("page2.chooseFileDialog.title")); //$NON-NLS-1$
String path= fd.open();
if (path != null) {
ResourceInfo ri= new ResourceInfo(path);
fBundleDescription.addResource(ri, onClasspath);
add(table, ri);
}
}
});
final Button addButton2= createButton(c1, SWT.NONE, Util.getString("page2.addFolder.button.label")); //$NON-NLS-1$
- addButton1.addSelectionListener(new SelectionAdapter() {
+ addButton2.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
DirectoryDialog fd= new DirectoryDialog(addButton2.getShell(), SWT.OPEN);
fd.setText(Util.getString("page2.chooseFolder.dialog.title")); //$NON-NLS-1$
String path= fd.open();
if (path != null) {
ResourceInfo ri= new ResourceInfo(path);
fBundleDescription.addResource(ri, onClasspath);
add(table, ri);
}
}
});
final Button removeButton= createButton(c1, SWT.NONE, Util.getString("page2.remove.button.label")); //$NON-NLS-1$
removeButton.setEnabled(false);
removeButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
remove(table, onClasspath, removeButton);
}
});
table.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
removeButton.setEnabled(table.getSelectionCount() > 0);
}
});
return table;
}
private void add(Table t, ResourceInfo ri) {
TableItem ti= new TableItem(t, SWT.NONE);
ti.setData(ri);
ti.setText(ri.fPath);
}
private void remove(Table table, boolean b, Button removeButton) {
TableItem[] selection= table.getSelection();
for (int i= 0; i < selection.length; i++) {
TableItem ti= selection[i];
ResourceInfo ri= (ResourceInfo) ti.getData();
if (fBundleDescription.removeResource(ri, b)) {
int ix= table.indexOf(ti);
if (ix >= 0)
table.remove(ix);
}
}
removeButton.setEnabled(table.getSelectionCount() > 0);
}
public void propertyChange(PropertyChangeEvent event) {
if (fWorkingDir != null)
fWorkingDir.setText(fBundleDescription.get(WORKINGDIR, "")); //$NON-NLS-1$
if (fClassPath != null) {
fClassPath.removeAll();
ResourceInfo[] ris= fBundleDescription.getResources(true);
for (int i= 0; i < ris.length; i++)
add(fClassPath, ris[i]);
}
if (fResources != null) {
fResources.removeAll();
ResourceInfo[] ris= fBundleDescription.getResources(false);
for (int i= 0; i < ris.length; i++)
add(fResources, ris[i]);
}
}
public boolean isPageComplete() {
return true;
}
}
| true | true | Table createTableGroup(Composite parent, String groupName, final boolean onClasspath) {
Group g1= createGroup(parent, groupName, 1);
final Table table= new Table(g1, SWT.H_SCROLL | SWT.V_SCROLL | SWT.MULTI | SWT.FULL_SELECTION);
setHeightHint(table, 80);
Composite c1= createComposite(g1, 3);
final Button addButton1= createButton(c1, SWT.NONE, Util.getString("page2.addFile.button.label")); //$NON-NLS-1$
addButton1.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
FileDialog fd= new FileDialog(addButton1.getShell(), SWT.OPEN);
fd.setText(Util.getString("page2.chooseFileDialog.title")); //$NON-NLS-1$
String path= fd.open();
if (path != null) {
ResourceInfo ri= new ResourceInfo(path);
fBundleDescription.addResource(ri, onClasspath);
add(table, ri);
}
}
});
final Button addButton2= createButton(c1, SWT.NONE, Util.getString("page2.addFolder.button.label")); //$NON-NLS-1$
addButton1.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
DirectoryDialog fd= new DirectoryDialog(addButton2.getShell(), SWT.OPEN);
fd.setText(Util.getString("page2.chooseFolder.dialog.title")); //$NON-NLS-1$
String path= fd.open();
if (path != null) {
ResourceInfo ri= new ResourceInfo(path);
fBundleDescription.addResource(ri, onClasspath);
add(table, ri);
}
}
});
final Button removeButton= createButton(c1, SWT.NONE, Util.getString("page2.remove.button.label")); //$NON-NLS-1$
removeButton.setEnabled(false);
removeButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
remove(table, onClasspath, removeButton);
}
});
table.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
removeButton.setEnabled(table.getSelectionCount() > 0);
}
});
return table;
}
| Table createTableGroup(Composite parent, String groupName, final boolean onClasspath) {
Group g1= createGroup(parent, groupName, 1);
final Table table= new Table(g1, SWT.H_SCROLL | SWT.V_SCROLL | SWT.MULTI | SWT.FULL_SELECTION);
setHeightHint(table, 80);
Composite c1= createComposite(g1, 3);
final Button addButton1= createButton(c1, SWT.NONE, Util.getString("page2.addFile.button.label")); //$NON-NLS-1$
addButton1.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
FileDialog fd= new FileDialog(addButton1.getShell(), SWT.OPEN);
fd.setText(Util.getString("page2.chooseFileDialog.title")); //$NON-NLS-1$
String path= fd.open();
if (path != null) {
ResourceInfo ri= new ResourceInfo(path);
fBundleDescription.addResource(ri, onClasspath);
add(table, ri);
}
}
});
final Button addButton2= createButton(c1, SWT.NONE, Util.getString("page2.addFolder.button.label")); //$NON-NLS-1$
addButton2.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
DirectoryDialog fd= new DirectoryDialog(addButton2.getShell(), SWT.OPEN);
fd.setText(Util.getString("page2.chooseFolder.dialog.title")); //$NON-NLS-1$
String path= fd.open();
if (path != null) {
ResourceInfo ri= new ResourceInfo(path);
fBundleDescription.addResource(ri, onClasspath);
add(table, ri);
}
}
});
final Button removeButton= createButton(c1, SWT.NONE, Util.getString("page2.remove.button.label")); //$NON-NLS-1$
removeButton.setEnabled(false);
removeButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
remove(table, onClasspath, removeButton);
}
});
table.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
removeButton.setEnabled(table.getSelectionCount() > 0);
}
});
return table;
}
|
diff --git a/g6/DangerAvoidance.java b/g6/DangerAvoidance.java
index a3004e6..17be0ad 100644
--- a/g6/DangerAvoidance.java
+++ b/g6/DangerAvoidance.java
@@ -1,88 +1,88 @@
package isnork.g6;
import isnork.sim.GameObject.Direction;
import isnork.sim.Observation;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Random;
import java.util.Set;
public class DangerAvoidance {
public boolean isLocationDangerous(Set<Observation> whatISee, Point2D pos) {
Iterator<Observation> itr = whatISee.iterator();
while (itr.hasNext()) {
Observation o = itr.next();
if (o.isDangerous()) {
if (tilesAway(pos, o.getLocation()) <= 2) {
return true;
}
}
}
return false;
}
public LinkedList<Direction> bestDirections(Set<Observation> whatISee, Direction d, Point2D currentPosition) {
LinkedList<Direction> newL = new LinkedList<Direction>();
ArrayList<Direction> directionOptions = Direction.allBut(d);
Direction bestDirection = null;
Point2D bestPoint = null;
for (Direction nextD : directionOptions) {
double newPosX = currentPosition.getX() + nextD.getDx();
double newPosY = currentPosition.getY() + nextD.getDy();
Point2D newPoint = new Point2D.Double(newPosX, newPosY);
if (!atTheWall(newPoint) && !isLocationDangerous(whatISee, newPoint)){
if (bestPoint == null){
bestPoint = newPoint;
bestDirection = nextD;
}
else{
if (tilesAway(currentPosition, newPoint) < tilesAway(currentPosition, bestPoint)){
bestPoint = newPoint;
bestDirection = nextD;
}
}
}
}
if (bestDirection == null){
Random r = new Random();
- Direction randomDirection = directionOptions.get(r.nextInt(Direction.values().length));
+ Direction randomDirection = directionOptions.get(r.nextInt(Direction.values().length-1));
newL.add(randomDirection);
double newPosX = currentPosition.getX() + randomDirection.getDx();
double newPosY = currentPosition.getY() + randomDirection.getDy();
Point2D randomPoint = new Point2D.Double(newPosX, newPosY);
LinkedList<Direction> temp = bestDirections(whatISee, randomDirection, randomPoint);
for (Direction tmpD: temp){
newL.add(tmpD);
}
return newL;
}
else{
newL.add(bestDirection);
return newL;
}
}
public int tilesAway(Point2D me, Point2D them) {
return ((int)PathManager.computeTotalSpaces(me, them));
}
public static boolean atBoat(Point2D p) {
if (p.getX() == 0 && p.getY() == 0) {
return true;
} else {
return false;
}
}
public static boolean atTheWall(Point2D p) {
if (Math.abs(p.getX()) == NewPlayer.d || Math.abs(p.getY()) == NewPlayer.d) {
return true;
} else {
return false;
}
}
}
| true | true | public LinkedList<Direction> bestDirections(Set<Observation> whatISee, Direction d, Point2D currentPosition) {
LinkedList<Direction> newL = new LinkedList<Direction>();
ArrayList<Direction> directionOptions = Direction.allBut(d);
Direction bestDirection = null;
Point2D bestPoint = null;
for (Direction nextD : directionOptions) {
double newPosX = currentPosition.getX() + nextD.getDx();
double newPosY = currentPosition.getY() + nextD.getDy();
Point2D newPoint = new Point2D.Double(newPosX, newPosY);
if (!atTheWall(newPoint) && !isLocationDangerous(whatISee, newPoint)){
if (bestPoint == null){
bestPoint = newPoint;
bestDirection = nextD;
}
else{
if (tilesAway(currentPosition, newPoint) < tilesAway(currentPosition, bestPoint)){
bestPoint = newPoint;
bestDirection = nextD;
}
}
}
}
if (bestDirection == null){
Random r = new Random();
Direction randomDirection = directionOptions.get(r.nextInt(Direction.values().length));
newL.add(randomDirection);
double newPosX = currentPosition.getX() + randomDirection.getDx();
double newPosY = currentPosition.getY() + randomDirection.getDy();
Point2D randomPoint = new Point2D.Double(newPosX, newPosY);
LinkedList<Direction> temp = bestDirections(whatISee, randomDirection, randomPoint);
for (Direction tmpD: temp){
newL.add(tmpD);
}
return newL;
}
else{
newL.add(bestDirection);
return newL;
}
}
| public LinkedList<Direction> bestDirections(Set<Observation> whatISee, Direction d, Point2D currentPosition) {
LinkedList<Direction> newL = new LinkedList<Direction>();
ArrayList<Direction> directionOptions = Direction.allBut(d);
Direction bestDirection = null;
Point2D bestPoint = null;
for (Direction nextD : directionOptions) {
double newPosX = currentPosition.getX() + nextD.getDx();
double newPosY = currentPosition.getY() + nextD.getDy();
Point2D newPoint = new Point2D.Double(newPosX, newPosY);
if (!atTheWall(newPoint) && !isLocationDangerous(whatISee, newPoint)){
if (bestPoint == null){
bestPoint = newPoint;
bestDirection = nextD;
}
else{
if (tilesAway(currentPosition, newPoint) < tilesAway(currentPosition, bestPoint)){
bestPoint = newPoint;
bestDirection = nextD;
}
}
}
}
if (bestDirection == null){
Random r = new Random();
Direction randomDirection = directionOptions.get(r.nextInt(Direction.values().length-1));
newL.add(randomDirection);
double newPosX = currentPosition.getX() + randomDirection.getDx();
double newPosY = currentPosition.getY() + randomDirection.getDy();
Point2D randomPoint = new Point2D.Double(newPosX, newPosY);
LinkedList<Direction> temp = bestDirections(whatISee, randomDirection, randomPoint);
for (Direction tmpD: temp){
newL.add(tmpD);
}
return newL;
}
else{
newL.add(bestDirection);
return newL;
}
}
|
diff --git a/src/main/java/com/orange/groupbuy/web/client/presenter/MainPresenter.java b/src/main/java/com/orange/groupbuy/web/client/presenter/MainPresenter.java
index 9beec75..08b4431 100644
--- a/src/main/java/com/orange/groupbuy/web/client/presenter/MainPresenter.java
+++ b/src/main/java/com/orange/groupbuy/web/client/presenter/MainPresenter.java
@@ -1,369 +1,370 @@
package com.orange.groupbuy.web.client.presenter;
import net.customware.gwt.dispatch.client.DefaultExceptionHandler;
import net.customware.gwt.dispatch.client.DispatchAsync;
import net.customware.gwt.dispatch.client.secure.CookieSecureSessionAccessor;
import net.customware.gwt.dispatch.client.secure.SecureDispatchAsync;
import net.customware.gwt.dispatch.client.standard.StandardDispatchAsync;
import net.customware.gwt.presenter.client.EventBus;
import net.customware.gwt.presenter.client.widget.WidgetDisplay;
import net.customware.gwt.presenter.client.widget.WidgetPresenter;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.AttachEvent;
import com.google.gwt.event.logical.shared.AttachEvent.Handler;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.TabLayoutPanel;
import com.orange.groupbuy.web.client.SimpleCallback;
import com.orange.groupbuy.web.client.component.CityWidget;
import com.orange.groupbuy.web.client.component.GroupBuyFootPanel;
import com.orange.groupbuy.web.client.component.GroupBuyHeaderPanel;
import com.orange.groupbuy.web.client.component.LoginDialog;
import com.orange.groupbuy.web.client.component.RegisterDialog;
import com.orange.groupbuy.web.client.component.RegisterDialog.RegisterOKEvent;
import com.orange.groupbuy.web.client.dispatch.GetUser;
import com.orange.groupbuy.web.client.dispatch.RegisterEmail;
import com.orange.groupbuy.web.client.event.CityChangedEvent;
import com.orange.groupbuy.web.client.event.CityChangedHandler;
import com.orange.groupbuy.web.client.event.LoginSuccessEvent;
import com.orange.groupbuy.web.client.event.LoginSuccessHandler;
import com.orange.groupbuy.web.client.event.TabHeaderTabChangedEvent;
import com.orange.groupbuy.web.client.model.UserInfo;
import com.orange.groupbuy.web.client.presenter.MainPresenter.MainView;
import com.orange.groupbuy.web.client.secure.CookiesUtil;
import com.orange.groupbuy.web.shared.ErrorCode;
import com.orange.groupbuy.web.shared.UIConstatns;
public class MainPresenter extends WidgetPresenter<MainView> {
private final DispatchAsync dispatch = new StandardDispatchAsync(
new DefaultExceptionHandler());
private final DispatchAsync secureDispatch = new SecureDispatchAsync(
new DefaultExceptionHandler(), new CookieSecureSessionAccessor(
UIConstatns.SESSION_COOKIE_NAME));
public static interface MainView extends WidgetDisplay {
TabLayoutPanel getTabHeader();
GroupBuyHeaderPanel getHeaderPanel();
GroupBuyFootPanel getFootPanel();
// ListBox getCitySelect();
Anchor getLoginLink();
Anchor getLogoutLink();
Anchor getProfileLink();
Anchor getCityLink();
Anchor getRegisterLink();
LoginDialog getLoginDialog();
RegisterDialog getRegisterDialog();
CityWidget getCityWidget();
}
public MainPresenter(MainView display, EventBus eventBus) {
super(display, eventBus);
}
public MainPresenter(MainView display, EventBus eventBus,
DispatchAsync dispatchAsync) {
super(display, eventBus);
}
private void loadCookies() {
String userName = CookiesUtil.get(UIConstatns.USER_NAME);
if(userName != null && userName.length() > 0) {
getDisplay().getProfileLink().setText(userName);
getDisplay().getLoginLink().setVisible(false);
getDisplay().getRegisterLink().setVisible(false);
getDisplay().getLogoutLink().setVisible(true);
getDisplay().getProfileLink().setVisible(true);
}
}
@Override
protected void onBind() {
loadCookies();
registerHandler(eventBus.addHandler(CityChangedEvent.getType(),
new CityChangedHandler() {
@Override
public void onChanged(CityChangedEvent event) {
getDisplay().getCityWidget().hide();
+ getDisplay().getCityWidget().setVisible(false);
getDisplay().getCityLink().setText(event.getCityName());
}
}));
registerHandler(eventBus.addHandler(LoginSuccessEvent.getType(),
new LoginSuccessHandler() {
@Override
public void onEvent(LoginSuccessEvent event) {
final String userName = event.getUserName();
dispatch.execute(new GetUser(event.getUserName(), event.getPassword()),
new SimpleCallback<UserInfo>() {
@Override
public void onSuccess(UserInfo result) {
if (result == null) {
Window.alert("userInfo null");
return;
}
Window.alert(result.toString());
String userId = result.getUserId();
if(userId != null && userId.length() > 0) {
CookiesUtil.set(UIConstatns.USER_ID,userId);
CookiesUtil.set(UIConstatns.USER_NAME,userName);
getDisplay().getLoginDialog().hide();
getDisplay().getProfileLink().setText(userName);
getDisplay().getProfileLink().setVisible(true);
getDisplay().getLogoutLink().setVisible(true);
getDisplay().getLoginLink().setVisible(false);
getDisplay().getRegisterLink().setVisible(false);
}
}
});
}
}));
registerHandler(eventBus.addHandler(RegisterOKEvent.getType(),
new RegisterDialog.RegisterOKEventHandler() {
@Override
public void onEvent(final RegisterOKEvent event) {
dispatch.execute(new RegisterEmail(event.getUserName(), event.getPassword()),
new SimpleCallback<UserInfo>() {
@Override
public void onSuccess(UserInfo result) {
if (result == null) {
Window.alert("userInfo null");
return;
}
String userId = result.getUserId();
String errcode = result.getRtCode();
String errstr = null;
if(userId != null){
getDisplay()
.getRegisterDialog()
.setTips(
"<label style=\"color:green\">注册成功,正在登陆....</label>");
getDisplay().getRegisterDialog().setVisible(false);
LoginSuccessEvent loginEvent = new LoginSuccessEvent();
loginEvent.setUserName(event.getUserName());
loginEvent.setPassword(event.getPassword());
eventBus.fireEvent(loginEvent);
}else if(errcode != null && errcode.length() > 0){
int ERR = Integer.parseInt(errcode);
switch(ERR){
case ErrorCode.ERROR_EMAIL_NOT_VALID:
errstr = "邮箱格式不正确,请重新输入";
break;
case ErrorCode.ERROR_EMAIL_EXIST:
errstr = "邮箱已存在,请直接登录";
break;
case ErrorCode.ERROR_CREATE_USER:
default:
errstr = "系统创建用户失败,请稍等后重新注册";
break;
}
getDisplay().getRegisterDialog().setTips("<label style=\"color:red\">" + errstr + "</label>");
return;
}
}
});
}
}));
registerHandler(getDisplay().getCityLink().addAttachHandler(new Handler() {
@Override
public void onAttachOrDetach(AttachEvent arg0) {
String autoCity = getAutoDetectedCity();
if (autoCity != null && !autoCity.isEmpty()) {
String city = autoCity.substring(0,autoCity.length()-1);
getDisplay().getCityLink().setText(city);
CityChangedEvent event = new CityChangedEvent();
event.setCityName(city);
eventBus.fireEvent(event);
}
}
}));
registerHandler(getDisplay().getCityLink().addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
CityWidget cityWidget = getDisplay().getCityWidget();
if(cityWidget.isVisible()) {
cityWidget.setVisible(false);
cityWidget.hide();
}
else {
cityWidget.setVisible(true);
cityWidget.show();
}
}
}));
registerHandler(getDisplay().getLoginLink().addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
LoginDialog dialog = getDisplay().getLoginDialog();
dialog.center();
dialog.show();
}
}));
registerHandler(getDisplay().getRegisterLink().addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
RegisterDialog dialog = getDisplay().getRegisterDialog();
dialog.center();
dialog.show();
}
})
);
registerHandler(getDisplay().getLogoutLink().addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
CookiesUtil.remove(UIConstatns.USER_ID);
CookiesUtil.remove(UIConstatns.USER_NAME);
getDisplay().getLoginDialog().clear();
getDisplay().getProfileLink().setVisible(false);
getDisplay().getLogoutLink().setVisible(false);
getDisplay().getLoginLink().setVisible(true);
getDisplay().getRegisterLink().setVisible(true);
}
}));
//have replaced the city select box with citywidget
// registerHandler(getDisplay().getCitySelect().addAttachHandler(
// new Handler() {
//
// @Override
// public void onAttachOrDetach(AttachEvent event) {
// dispatch.execute(new GetCityNames(),
// new SimpleCallback<CityNames>() {
//
// @Override
// public void onSuccess(CityNames result) {
// ArrayList<Item> cityList = result
// .getCityList();
// getDisplay().getCitySelect().clear();
// for (Item city : cityList) {
// getDisplay()
// .getCitySelect()
// .addItem(
// city.getDisplayName(),
// city.getValue());
// }
// // init the city
// initDefaultCitySelect();
//
// // // init execute query
// eventBus.fireEvent(new CityChangedEvent());
// // TODO: work around for IE
// getDisplay().getTabHeader()
// .selectTab(1);
// getDisplay().getTabHeader()
// .selectTab(0);
// }
// });
//
// }
// }));
//
// registerHandler(getDisplay().getCitySelect().addChangeHandler(
// new ChangeHandler() {
//
// @Override
// public void onChange(ChangeEvent event) {
// eventBus.fireEvent(new CityChangedEvent());
// }
// }));
registerHandler(getDisplay().getTabHeader().addSelectionHandler(
new SelectionHandler<Integer>() {
@Override
public void onSelection(SelectionEvent<Integer> event) {
Integer selectItem = event.getSelectedItem();
if (selectItem == 0) {
// mygroup
} else if (selectItem == 1) {
//
} else if (selectItem == 2) {
}
eventBus.fireEvent(new TabHeaderTabChangedEvent());
}
}));
}
private native String getAutoDetectedCity()/*-{
return $wnd.autoDetectedCity;
}-*/;
// private void initDefaultCitySelect() {
// String autoCity = getAutoDetectedCity();
// if (autoCity != null && !autoCity.isEmpty()) {
// int selectedIndex = getSelectedIndex(autoCity);
// if (selectedIndex != -1) {
// getDisplay().getCitySelect().setSelectedIndex(selectedIndex);
// }
// }
// }
//
// private int getSelectedIndex(String autoCity) {
// int selectedIndex = -1;
// int count = getDisplay().getCitySelect().getItemCount();
// for (int index = 0; index < count; index++) {
// String value = getDisplay().getCitySelect().getValue(index);
// if (!value.isEmpty()) {
// // TODO: some bug here.
// if (autoCity.contains(value)) {
// selectedIndex = index;
// break;
// }
// }
// }
// return selectedIndex;
// }
@Override
protected void onUnbind() {
// TODO Auto-generated method stub
}
@Override
protected void onRevealDisplay() {
// TODO Auto-generated method stub
}
}
| true | true | protected void onBind() {
loadCookies();
registerHandler(eventBus.addHandler(CityChangedEvent.getType(),
new CityChangedHandler() {
@Override
public void onChanged(CityChangedEvent event) {
getDisplay().getCityWidget().hide();
getDisplay().getCityLink().setText(event.getCityName());
}
}));
registerHandler(eventBus.addHandler(LoginSuccessEvent.getType(),
new LoginSuccessHandler() {
@Override
public void onEvent(LoginSuccessEvent event) {
final String userName = event.getUserName();
dispatch.execute(new GetUser(event.getUserName(), event.getPassword()),
new SimpleCallback<UserInfo>() {
@Override
public void onSuccess(UserInfo result) {
if (result == null) {
Window.alert("userInfo null");
return;
}
Window.alert(result.toString());
String userId = result.getUserId();
if(userId != null && userId.length() > 0) {
CookiesUtil.set(UIConstatns.USER_ID,userId);
CookiesUtil.set(UIConstatns.USER_NAME,userName);
getDisplay().getLoginDialog().hide();
getDisplay().getProfileLink().setText(userName);
getDisplay().getProfileLink().setVisible(true);
getDisplay().getLogoutLink().setVisible(true);
getDisplay().getLoginLink().setVisible(false);
getDisplay().getRegisterLink().setVisible(false);
}
}
});
}
}));
registerHandler(eventBus.addHandler(RegisterOKEvent.getType(),
new RegisterDialog.RegisterOKEventHandler() {
@Override
public void onEvent(final RegisterOKEvent event) {
dispatch.execute(new RegisterEmail(event.getUserName(), event.getPassword()),
new SimpleCallback<UserInfo>() {
@Override
public void onSuccess(UserInfo result) {
if (result == null) {
Window.alert("userInfo null");
return;
}
String userId = result.getUserId();
String errcode = result.getRtCode();
String errstr = null;
if(userId != null){
getDisplay()
.getRegisterDialog()
.setTips(
"<label style=\"color:green\">注册成功,正在登陆....</label>");
getDisplay().getRegisterDialog().setVisible(false);
LoginSuccessEvent loginEvent = new LoginSuccessEvent();
loginEvent.setUserName(event.getUserName());
loginEvent.setPassword(event.getPassword());
eventBus.fireEvent(loginEvent);
}else if(errcode != null && errcode.length() > 0){
int ERR = Integer.parseInt(errcode);
switch(ERR){
case ErrorCode.ERROR_EMAIL_NOT_VALID:
errstr = "邮箱格式不正确,请重新输入";
break;
case ErrorCode.ERROR_EMAIL_EXIST:
errstr = "邮箱已存在,请直接登录";
break;
case ErrorCode.ERROR_CREATE_USER:
default:
errstr = "系统创建用户失败,请稍等后重新注册";
break;
}
getDisplay().getRegisterDialog().setTips("<label style=\"color:red\">" + errstr + "</label>");
return;
}
}
});
}
}));
registerHandler(getDisplay().getCityLink().addAttachHandler(new Handler() {
@Override
public void onAttachOrDetach(AttachEvent arg0) {
String autoCity = getAutoDetectedCity();
if (autoCity != null && !autoCity.isEmpty()) {
String city = autoCity.substring(0,autoCity.length()-1);
getDisplay().getCityLink().setText(city);
CityChangedEvent event = new CityChangedEvent();
event.setCityName(city);
eventBus.fireEvent(event);
}
}
}));
registerHandler(getDisplay().getCityLink().addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
CityWidget cityWidget = getDisplay().getCityWidget();
if(cityWidget.isVisible()) {
cityWidget.setVisible(false);
cityWidget.hide();
}
else {
cityWidget.setVisible(true);
cityWidget.show();
}
}
}));
registerHandler(getDisplay().getLoginLink().addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
LoginDialog dialog = getDisplay().getLoginDialog();
dialog.center();
dialog.show();
}
}));
registerHandler(getDisplay().getRegisterLink().addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
RegisterDialog dialog = getDisplay().getRegisterDialog();
dialog.center();
dialog.show();
}
})
);
registerHandler(getDisplay().getLogoutLink().addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
CookiesUtil.remove(UIConstatns.USER_ID);
CookiesUtil.remove(UIConstatns.USER_NAME);
getDisplay().getLoginDialog().clear();
getDisplay().getProfileLink().setVisible(false);
getDisplay().getLogoutLink().setVisible(false);
getDisplay().getLoginLink().setVisible(true);
getDisplay().getRegisterLink().setVisible(true);
}
}));
//have replaced the city select box with citywidget
// registerHandler(getDisplay().getCitySelect().addAttachHandler(
// new Handler() {
//
// @Override
// public void onAttachOrDetach(AttachEvent event) {
// dispatch.execute(new GetCityNames(),
// new SimpleCallback<CityNames>() {
//
// @Override
// public void onSuccess(CityNames result) {
// ArrayList<Item> cityList = result
// .getCityList();
// getDisplay().getCitySelect().clear();
// for (Item city : cityList) {
// getDisplay()
// .getCitySelect()
// .addItem(
// city.getDisplayName(),
// city.getValue());
// }
// // init the city
// initDefaultCitySelect();
//
// // // init execute query
// eventBus.fireEvent(new CityChangedEvent());
// // TODO: work around for IE
// getDisplay().getTabHeader()
// .selectTab(1);
// getDisplay().getTabHeader()
// .selectTab(0);
// }
// });
//
// }
// }));
//
// registerHandler(getDisplay().getCitySelect().addChangeHandler(
// new ChangeHandler() {
//
// @Override
// public void onChange(ChangeEvent event) {
// eventBus.fireEvent(new CityChangedEvent());
// }
// }));
registerHandler(getDisplay().getTabHeader().addSelectionHandler(
new SelectionHandler<Integer>() {
@Override
public void onSelection(SelectionEvent<Integer> event) {
Integer selectItem = event.getSelectedItem();
if (selectItem == 0) {
// mygroup
} else if (selectItem == 1) {
//
} else if (selectItem == 2) {
}
eventBus.fireEvent(new TabHeaderTabChangedEvent());
}
}));
}
| protected void onBind() {
loadCookies();
registerHandler(eventBus.addHandler(CityChangedEvent.getType(),
new CityChangedHandler() {
@Override
public void onChanged(CityChangedEvent event) {
getDisplay().getCityWidget().hide();
getDisplay().getCityWidget().setVisible(false);
getDisplay().getCityLink().setText(event.getCityName());
}
}));
registerHandler(eventBus.addHandler(LoginSuccessEvent.getType(),
new LoginSuccessHandler() {
@Override
public void onEvent(LoginSuccessEvent event) {
final String userName = event.getUserName();
dispatch.execute(new GetUser(event.getUserName(), event.getPassword()),
new SimpleCallback<UserInfo>() {
@Override
public void onSuccess(UserInfo result) {
if (result == null) {
Window.alert("userInfo null");
return;
}
Window.alert(result.toString());
String userId = result.getUserId();
if(userId != null && userId.length() > 0) {
CookiesUtil.set(UIConstatns.USER_ID,userId);
CookiesUtil.set(UIConstatns.USER_NAME,userName);
getDisplay().getLoginDialog().hide();
getDisplay().getProfileLink().setText(userName);
getDisplay().getProfileLink().setVisible(true);
getDisplay().getLogoutLink().setVisible(true);
getDisplay().getLoginLink().setVisible(false);
getDisplay().getRegisterLink().setVisible(false);
}
}
});
}
}));
registerHandler(eventBus.addHandler(RegisterOKEvent.getType(),
new RegisterDialog.RegisterOKEventHandler() {
@Override
public void onEvent(final RegisterOKEvent event) {
dispatch.execute(new RegisterEmail(event.getUserName(), event.getPassword()),
new SimpleCallback<UserInfo>() {
@Override
public void onSuccess(UserInfo result) {
if (result == null) {
Window.alert("userInfo null");
return;
}
String userId = result.getUserId();
String errcode = result.getRtCode();
String errstr = null;
if(userId != null){
getDisplay()
.getRegisterDialog()
.setTips(
"<label style=\"color:green\">注册成功,正在登陆....</label>");
getDisplay().getRegisterDialog().setVisible(false);
LoginSuccessEvent loginEvent = new LoginSuccessEvent();
loginEvent.setUserName(event.getUserName());
loginEvent.setPassword(event.getPassword());
eventBus.fireEvent(loginEvent);
}else if(errcode != null && errcode.length() > 0){
int ERR = Integer.parseInt(errcode);
switch(ERR){
case ErrorCode.ERROR_EMAIL_NOT_VALID:
errstr = "邮箱格式不正确,请重新输入";
break;
case ErrorCode.ERROR_EMAIL_EXIST:
errstr = "邮箱已存在,请直接登录";
break;
case ErrorCode.ERROR_CREATE_USER:
default:
errstr = "系统创建用户失败,请稍等后重新注册";
break;
}
getDisplay().getRegisterDialog().setTips("<label style=\"color:red\">" + errstr + "</label>");
return;
}
}
});
}
}));
registerHandler(getDisplay().getCityLink().addAttachHandler(new Handler() {
@Override
public void onAttachOrDetach(AttachEvent arg0) {
String autoCity = getAutoDetectedCity();
if (autoCity != null && !autoCity.isEmpty()) {
String city = autoCity.substring(0,autoCity.length()-1);
getDisplay().getCityLink().setText(city);
CityChangedEvent event = new CityChangedEvent();
event.setCityName(city);
eventBus.fireEvent(event);
}
}
}));
registerHandler(getDisplay().getCityLink().addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
CityWidget cityWidget = getDisplay().getCityWidget();
if(cityWidget.isVisible()) {
cityWidget.setVisible(false);
cityWidget.hide();
}
else {
cityWidget.setVisible(true);
cityWidget.show();
}
}
}));
registerHandler(getDisplay().getLoginLink().addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
LoginDialog dialog = getDisplay().getLoginDialog();
dialog.center();
dialog.show();
}
}));
registerHandler(getDisplay().getRegisterLink().addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
RegisterDialog dialog = getDisplay().getRegisterDialog();
dialog.center();
dialog.show();
}
})
);
registerHandler(getDisplay().getLogoutLink().addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
CookiesUtil.remove(UIConstatns.USER_ID);
CookiesUtil.remove(UIConstatns.USER_NAME);
getDisplay().getLoginDialog().clear();
getDisplay().getProfileLink().setVisible(false);
getDisplay().getLogoutLink().setVisible(false);
getDisplay().getLoginLink().setVisible(true);
getDisplay().getRegisterLink().setVisible(true);
}
}));
//have replaced the city select box with citywidget
// registerHandler(getDisplay().getCitySelect().addAttachHandler(
// new Handler() {
//
// @Override
// public void onAttachOrDetach(AttachEvent event) {
// dispatch.execute(new GetCityNames(),
// new SimpleCallback<CityNames>() {
//
// @Override
// public void onSuccess(CityNames result) {
// ArrayList<Item> cityList = result
// .getCityList();
// getDisplay().getCitySelect().clear();
// for (Item city : cityList) {
// getDisplay()
// .getCitySelect()
// .addItem(
// city.getDisplayName(),
// city.getValue());
// }
// // init the city
// initDefaultCitySelect();
//
// // // init execute query
// eventBus.fireEvent(new CityChangedEvent());
// // TODO: work around for IE
// getDisplay().getTabHeader()
// .selectTab(1);
// getDisplay().getTabHeader()
// .selectTab(0);
// }
// });
//
// }
// }));
//
// registerHandler(getDisplay().getCitySelect().addChangeHandler(
// new ChangeHandler() {
//
// @Override
// public void onChange(ChangeEvent event) {
// eventBus.fireEvent(new CityChangedEvent());
// }
// }));
registerHandler(getDisplay().getTabHeader().addSelectionHandler(
new SelectionHandler<Integer>() {
@Override
public void onSelection(SelectionEvent<Integer> event) {
Integer selectItem = event.getSelectedItem();
if (selectItem == 0) {
// mygroup
} else if (selectItem == 1) {
//
} else if (selectItem == 2) {
}
eventBus.fireEvent(new TabHeaderTabChangedEvent());
}
}));
}
|
diff --git a/geopaparazzi.app/src/eu/hydrologis/geopaparazzi/maps/MapTagsActivity.java b/geopaparazzi.app/src/eu/hydrologis/geopaparazzi/maps/MapTagsActivity.java
index e6f42613..8acfe992 100755
--- a/geopaparazzi.app/src/eu/hydrologis/geopaparazzi/maps/MapTagsActivity.java
+++ b/geopaparazzi.app/src/eu/hydrologis/geopaparazzi/maps/MapTagsActivity.java
@@ -1,234 +1,235 @@
/*
* Geopaparazzi - Digital field mapping on Android based devices
* Copyright (C) 2010 HydroloGIS (www.hydrologis.com)
*
* 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 eu.hydrologis.geopaparazzi.maps;
import java.io.File;
import java.sql.Date;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.Toast;
import eu.geopaparazzi.library.camera.CameraActivity;
import eu.geopaparazzi.library.forms.FormActivity;
import eu.geopaparazzi.library.forms.TagsManager;
import eu.geopaparazzi.library.forms.TagsManager.TagObject;
import eu.geopaparazzi.library.util.LibraryConstants;
import eu.geopaparazzi.library.util.ResourcesManager;
import eu.geopaparazzi.library.util.Utilities;
import eu.geopaparazzi.library.util.activities.NoteActivity;
import eu.geopaparazzi.library.util.debug.Logger;
import eu.hydrologis.geopaparazzi.R;
import eu.hydrologis.geopaparazzi.database.DaoImages;
import eu.hydrologis.geopaparazzi.database.DaoNotes;
import eu.hydrologis.geopaparazzi.database.NoteType;
/**
* Osm tags adding activity.
*
* @author Andrea Antonello (www.hydrologis.com)
*/
public class MapTagsActivity extends Activity {
private static final int NOTE_RETURN_CODE = 666;
private static final int CAMERA_RETURN_CODE = 667;
private static final int FORM_RETURN_CODE = 668;
private EditText additionalInfoText;
private double latitude;
private double longitude;
private double elevation;
private String[] tagNamesArray;
public void onCreate( Bundle icicle ) {
super.onCreate(icicle);
setContentView(R.layout.tags);
Bundle extras = getIntent().getExtras();
if (extras != null) {
latitude = extras.getDouble(LibraryConstants.LATITUDE);
longitude = extras.getDouble(LibraryConstants.LONGITUDE);
elevation = extras.getDouble(LibraryConstants.ELEVATION);
}
additionalInfoText = (EditText) findViewById(R.id.osm_additionalinfo_id);
Button imageButton = (Button) findViewById(R.id.imagefromtag);
imageButton.setOnClickListener(new Button.OnClickListener(){
public void onClick( View v ) {
Intent intent = new Intent(MapTagsActivity.this, CameraActivity.class);
intent.putExtra(LibraryConstants.LONGITUDE, longitude);
intent.putExtra(LibraryConstants.LATITUDE, latitude);
intent.putExtra(LibraryConstants.ELEVATION, elevation);
MapTagsActivity.this.startActivityForResult(intent, CAMERA_RETURN_CODE);
}
});
Button noteButton = (Button) findViewById(R.id.notefromtag);
noteButton.setOnClickListener(new Button.OnClickListener(){
public void onClick( View v ) {
Intent intent = new Intent(MapTagsActivity.this, NoteActivity.class);
intent.putExtra(LibraryConstants.LONGITUDE, longitude);
intent.putExtra(LibraryConstants.LATITUDE, latitude);
intent.putExtra(LibraryConstants.ELEVATION, elevation);
MapTagsActivity.this.startActivityForResult(intent, NOTE_RETURN_CODE);
}
});
GridView buttonGridView = (GridView) findViewById(R.id.osmgridview);
try {
tagNamesArray = TagsManager.getInstance(this).getTagsArrays();
} catch (Exception e1) {
tagNamesArray = new String[]{getString(R.string.maptagsactivity_error_reading_tags)};
Logger.e(this, e1.getLocalizedMessage(), e1);
e1.printStackTrace();
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, R.layout.gpslog_row, tagNamesArray){
public View getView( final int position, View cView, ViewGroup parent ) {
Button osmButton = new Button(MapTagsActivity.this);
osmButton.setText(tagNamesArray[position]);
// osmButton.setImageResource(R.drawable.gps);
osmButton.setOnClickListener(new Button.OnClickListener(){
public void onClick( View v ) {
try {
Date sqlDate = new Date(System.currentTimeMillis());
StringBuilder sB = new StringBuilder(additionalInfoText.getText());
String infoString = sB.toString();
String name = tagNamesArray[position];
TagObject tag = TagsManager.getInstance(MapTagsActivity.this).getTagFromName(name);
String finalLongName = tag.longName;
if (infoString.length() != 0) {
String sep = ":"; //$NON-NLS-1$
if (finalLongName.indexOf(sep) != -1) {
sep = " "; //$NON-NLS-1$
}
finalLongName = finalLongName + sep + infoString;
}
if (tag.hasForm) {
// launch form activity
String jsonString = tag.jsonString;
Intent formIntent = new Intent(MapTagsActivity.this, FormActivity.class);
formIntent.putExtra(LibraryConstants.PREFS_KEY_FORM_JSON, jsonString);
formIntent.putExtra(LibraryConstants.PREFS_KEY_FORM_NAME, finalLongName); // tag.shortName);
formIntent.putExtra(LibraryConstants.LATITUDE, latitude);
formIntent.putExtra(LibraryConstants.LONGITUDE, longitude);
startActivityForResult(formIntent, FORM_RETURN_CODE);
} else {
// insert as it is
- DaoNotes.addNote(getContext(), longitude, latitude, -1.0, sqlDate, finalLongName, null,
+ DaoNotes.addNote(getContext(), longitude, latitude, -1.0, sqlDate, finalLongName, null,
NoteType.SIMPLE.getTypeNum());
+ finish();
}
} catch (Exception e) {
Logger.e(this, e.getLocalizedMessage(), e);
e.printStackTrace();
Toast.makeText(MapTagsActivity.this, R.string.notenonsaved, Toast.LENGTH_LONG).show();
}
}
});
return osmButton;
}
};
// setListAdapter(arrayAdapter);
buttonGridView.setAdapter(arrayAdapter);
}
protected void onActivityResult( int requestCode, int resultCode, Intent data ) {
super.onActivityResult(requestCode, resultCode, data);
switch( requestCode ) {
case (FORM_RETURN_CODE): {
if (resultCode == Activity.RESULT_OK) {
String[] formArray = data.getStringArrayExtra(LibraryConstants.PREFS_KEY_FORM);
if (formArray != null) {
try {
double lon = Double.parseDouble(formArray[0]);
double lat = Double.parseDouble(formArray[1]);
double elev = Double.parseDouble(formArray[2]);
java.util.Date date = LibraryConstants.TIME_FORMATTER_SQLITE.parse(formArray[3]);
DaoNotes.addNote(this, lon, lat, elev, new Date(date.getTime()), formArray[4], formArray[5],
NoteType.SIMPLE.getTypeNum());
} catch (Exception e) {
e.printStackTrace();
Utilities.messageDialog(this, eu.geopaparazzi.library.R.string.notenonsaved, null);
}
}
}
break;
}
case (NOTE_RETURN_CODE): {
if (resultCode == Activity.RESULT_OK) {
String[] noteArray = data.getStringArrayExtra(LibraryConstants.PREFS_KEY_NOTE);
if (noteArray != null) {
try {
double lon = Double.parseDouble(noteArray[0]);
double lat = Double.parseDouble(noteArray[1]);
double elev = Double.parseDouble(noteArray[2]);
java.util.Date date = LibraryConstants.TIME_FORMATTER.parse(noteArray[3]);
DaoNotes.addNote(this, lon, lat, elev, new Date(date.getTime()), noteArray[4], null,
NoteType.SIMPLE.getTypeNum());
} catch (Exception e) {
e.printStackTrace();
Utilities.messageDialog(this, eu.geopaparazzi.library.R.string.notenonsaved, null);
}
}
}
break;
}
case (CAMERA_RETURN_CODE): {
if (resultCode == Activity.RESULT_OK) {
String relativeImagePath = data.getStringExtra(LibraryConstants.PREFS_KEY_PATH);
if (relativeImagePath != null) {
File imgFile = new File(ResourcesManager.getInstance(this).getMediaDir().getParentFile(), relativeImagePath);
if (!imgFile.exists()) {
return;
}
try {
double lat = data.getDoubleExtra(LibraryConstants.LATITUDE, 0.0);
double lon = data.getDoubleExtra(LibraryConstants.LONGITUDE, 0.0);
double elev = data.getDoubleExtra(LibraryConstants.ELEVATION, 0.0);
double azim = data.getDoubleExtra(LibraryConstants.AZIMUTH, 0.0);
DaoImages.addImage(this, lon, lat, elev, azim, new Date(new java.util.Date().getTime()), "", //$NON-NLS-1$
relativeImagePath);
} catch (Exception e) {
e.printStackTrace();
Utilities.messageDialog(this, eu.geopaparazzi.library.R.string.notenonsaved, null);
}
}
}
break;
}
}
finish();
}
}
| false | true | public void onCreate( Bundle icicle ) {
super.onCreate(icicle);
setContentView(R.layout.tags);
Bundle extras = getIntent().getExtras();
if (extras != null) {
latitude = extras.getDouble(LibraryConstants.LATITUDE);
longitude = extras.getDouble(LibraryConstants.LONGITUDE);
elevation = extras.getDouble(LibraryConstants.ELEVATION);
}
additionalInfoText = (EditText) findViewById(R.id.osm_additionalinfo_id);
Button imageButton = (Button) findViewById(R.id.imagefromtag);
imageButton.setOnClickListener(new Button.OnClickListener(){
public void onClick( View v ) {
Intent intent = new Intent(MapTagsActivity.this, CameraActivity.class);
intent.putExtra(LibraryConstants.LONGITUDE, longitude);
intent.putExtra(LibraryConstants.LATITUDE, latitude);
intent.putExtra(LibraryConstants.ELEVATION, elevation);
MapTagsActivity.this.startActivityForResult(intent, CAMERA_RETURN_CODE);
}
});
Button noteButton = (Button) findViewById(R.id.notefromtag);
noteButton.setOnClickListener(new Button.OnClickListener(){
public void onClick( View v ) {
Intent intent = new Intent(MapTagsActivity.this, NoteActivity.class);
intent.putExtra(LibraryConstants.LONGITUDE, longitude);
intent.putExtra(LibraryConstants.LATITUDE, latitude);
intent.putExtra(LibraryConstants.ELEVATION, elevation);
MapTagsActivity.this.startActivityForResult(intent, NOTE_RETURN_CODE);
}
});
GridView buttonGridView = (GridView) findViewById(R.id.osmgridview);
try {
tagNamesArray = TagsManager.getInstance(this).getTagsArrays();
} catch (Exception e1) {
tagNamesArray = new String[]{getString(R.string.maptagsactivity_error_reading_tags)};
Logger.e(this, e1.getLocalizedMessage(), e1);
e1.printStackTrace();
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, R.layout.gpslog_row, tagNamesArray){
public View getView( final int position, View cView, ViewGroup parent ) {
Button osmButton = new Button(MapTagsActivity.this);
osmButton.setText(tagNamesArray[position]);
// osmButton.setImageResource(R.drawable.gps);
osmButton.setOnClickListener(new Button.OnClickListener(){
public void onClick( View v ) {
try {
Date sqlDate = new Date(System.currentTimeMillis());
StringBuilder sB = new StringBuilder(additionalInfoText.getText());
String infoString = sB.toString();
String name = tagNamesArray[position];
TagObject tag = TagsManager.getInstance(MapTagsActivity.this).getTagFromName(name);
String finalLongName = tag.longName;
if (infoString.length() != 0) {
String sep = ":"; //$NON-NLS-1$
if (finalLongName.indexOf(sep) != -1) {
sep = " "; //$NON-NLS-1$
}
finalLongName = finalLongName + sep + infoString;
}
if (tag.hasForm) {
// launch form activity
String jsonString = tag.jsonString;
Intent formIntent = new Intent(MapTagsActivity.this, FormActivity.class);
formIntent.putExtra(LibraryConstants.PREFS_KEY_FORM_JSON, jsonString);
formIntent.putExtra(LibraryConstants.PREFS_KEY_FORM_NAME, finalLongName); // tag.shortName);
formIntent.putExtra(LibraryConstants.LATITUDE, latitude);
formIntent.putExtra(LibraryConstants.LONGITUDE, longitude);
startActivityForResult(formIntent, FORM_RETURN_CODE);
} else {
// insert as it is
DaoNotes.addNote(getContext(), longitude, latitude, -1.0, sqlDate, finalLongName, null,
NoteType.SIMPLE.getTypeNum());
}
} catch (Exception e) {
Logger.e(this, e.getLocalizedMessage(), e);
e.printStackTrace();
Toast.makeText(MapTagsActivity.this, R.string.notenonsaved, Toast.LENGTH_LONG).show();
}
}
});
return osmButton;
}
};
// setListAdapter(arrayAdapter);
buttonGridView.setAdapter(arrayAdapter);
}
| public void onCreate( Bundle icicle ) {
super.onCreate(icicle);
setContentView(R.layout.tags);
Bundle extras = getIntent().getExtras();
if (extras != null) {
latitude = extras.getDouble(LibraryConstants.LATITUDE);
longitude = extras.getDouble(LibraryConstants.LONGITUDE);
elevation = extras.getDouble(LibraryConstants.ELEVATION);
}
additionalInfoText = (EditText) findViewById(R.id.osm_additionalinfo_id);
Button imageButton = (Button) findViewById(R.id.imagefromtag);
imageButton.setOnClickListener(new Button.OnClickListener(){
public void onClick( View v ) {
Intent intent = new Intent(MapTagsActivity.this, CameraActivity.class);
intent.putExtra(LibraryConstants.LONGITUDE, longitude);
intent.putExtra(LibraryConstants.LATITUDE, latitude);
intent.putExtra(LibraryConstants.ELEVATION, elevation);
MapTagsActivity.this.startActivityForResult(intent, CAMERA_RETURN_CODE);
}
});
Button noteButton = (Button) findViewById(R.id.notefromtag);
noteButton.setOnClickListener(new Button.OnClickListener(){
public void onClick( View v ) {
Intent intent = new Intent(MapTagsActivity.this, NoteActivity.class);
intent.putExtra(LibraryConstants.LONGITUDE, longitude);
intent.putExtra(LibraryConstants.LATITUDE, latitude);
intent.putExtra(LibraryConstants.ELEVATION, elevation);
MapTagsActivity.this.startActivityForResult(intent, NOTE_RETURN_CODE);
}
});
GridView buttonGridView = (GridView) findViewById(R.id.osmgridview);
try {
tagNamesArray = TagsManager.getInstance(this).getTagsArrays();
} catch (Exception e1) {
tagNamesArray = new String[]{getString(R.string.maptagsactivity_error_reading_tags)};
Logger.e(this, e1.getLocalizedMessage(), e1);
e1.printStackTrace();
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, R.layout.gpslog_row, tagNamesArray){
public View getView( final int position, View cView, ViewGroup parent ) {
Button osmButton = new Button(MapTagsActivity.this);
osmButton.setText(tagNamesArray[position]);
// osmButton.setImageResource(R.drawable.gps);
osmButton.setOnClickListener(new Button.OnClickListener(){
public void onClick( View v ) {
try {
Date sqlDate = new Date(System.currentTimeMillis());
StringBuilder sB = new StringBuilder(additionalInfoText.getText());
String infoString = sB.toString();
String name = tagNamesArray[position];
TagObject tag = TagsManager.getInstance(MapTagsActivity.this).getTagFromName(name);
String finalLongName = tag.longName;
if (infoString.length() != 0) {
String sep = ":"; //$NON-NLS-1$
if (finalLongName.indexOf(sep) != -1) {
sep = " "; //$NON-NLS-1$
}
finalLongName = finalLongName + sep + infoString;
}
if (tag.hasForm) {
// launch form activity
String jsonString = tag.jsonString;
Intent formIntent = new Intent(MapTagsActivity.this, FormActivity.class);
formIntent.putExtra(LibraryConstants.PREFS_KEY_FORM_JSON, jsonString);
formIntent.putExtra(LibraryConstants.PREFS_KEY_FORM_NAME, finalLongName); // tag.shortName);
formIntent.putExtra(LibraryConstants.LATITUDE, latitude);
formIntent.putExtra(LibraryConstants.LONGITUDE, longitude);
startActivityForResult(formIntent, FORM_RETURN_CODE);
} else {
// insert as it is
DaoNotes.addNote(getContext(), longitude, latitude, -1.0, sqlDate, finalLongName, null,
NoteType.SIMPLE.getTypeNum());
finish();
}
} catch (Exception e) {
Logger.e(this, e.getLocalizedMessage(), e);
e.printStackTrace();
Toast.makeText(MapTagsActivity.this, R.string.notenonsaved, Toast.LENGTH_LONG).show();
}
}
});
return osmButton;
}
};
// setListAdapter(arrayAdapter);
buttonGridView.setAdapter(arrayAdapter);
}
|
diff --git a/poulpe-view/poulpe-web-controller/src/main/java/org/jtalks/poulpe/web/controller/group/UserGroupVm.java b/poulpe-view/poulpe-web-controller/src/main/java/org/jtalks/poulpe/web/controller/group/UserGroupVm.java
index a7456589..515ce5c9 100644
--- a/poulpe-view/poulpe-web-controller/src/main/java/org/jtalks/poulpe/web/controller/group/UserGroupVm.java
+++ b/poulpe-view/poulpe-web-controller/src/main/java/org/jtalks/poulpe/web/controller/group/UserGroupVm.java
@@ -1,219 +1,220 @@
/**
* Copyright (C) 2011 JTalks.org Team
* 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 (at your option) 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. 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.jtalks.poulpe.web.controller.group;
import org.jtalks.common.model.entity.Group;
import org.jtalks.poulpe.service.GroupService;
import org.jtalks.poulpe.web.controller.SelectedEntity;
import org.jtalks.poulpe.web.controller.WindowManager;
import org.zkoss.bind.annotation.BindingParam;
import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.NotifyChange;
import org.zkoss.zul.ListModelList;
import javax.annotation.Nonnull;
/**
* View-model for 'User Groups' Is used to order to work with page that allows admin to manage groups(add, edit,
* delete). Also class provides access to Members edit window, presented by {@link EditGroupMembersVm}.
*
* @author Leonid Kazancev
*/
public class UserGroupVm {
private static final String SHOW_DELETE_DIALOG = "showDeleteDialog", SHOW_EDIT_DIALOG = "showEditDialog",
SHOW_NEW_DIALOG = "showNewDialog", SELECTED_GROUP = "selectedGroup";
//Injected
private GroupService groupService;
private final WindowManager windowManager;
private ListModelList<Group> groups;
private Group selectedGroup;
private SelectedEntity<Group> selectedEntity;
private String searchString = "";
private boolean showDeleteDialog;
private boolean showEditDialog;
private boolean showNewDialog;
/**
* Construct View-Model for 'User groups' view.
*
* @param groupService the group service instance
* @param selectedEntity the selected entity instance
* @param windowManager the window manager instance
*/
- public UserGroupVm(@Nonnull GroupService groupService, @Nonnull SelectedEntity<Group> selectedEntity, @Nonnull WindowManager windowManager) {
+ public UserGroupVm(@Nonnull GroupService groupService, @Nonnull SelectedEntity<Group> selectedEntity,
+ @Nonnull WindowManager windowManager) {
this.groupService = groupService;
this.selectedEntity = selectedEntity;
this.windowManager = windowManager;
this.groups = new ListModelList<Group>(groupService.getAll(), true);
}
/**
* Makes group list view actual.
*/
public void updateView() {
groups.clear();
groups.addAll(groupService.getAll());
}
// -- ZK Command bindings --------------------
/**
* Look for the users matching specified pattern from the search textbox.
*/
@Command
public void searchGroup() {
groups.clear();
groups.addAll(groupService.getAllMatchedByName(searchString));
}
/**
* Opens edit group members window.
*/
@Command
public void showGroupMemberEditWindow() {
selectedEntity.setEntity(selectedGroup);
EditGroupMembersVm.showDialog(windowManager);
}
/**
* Deletes selected group.
*/
@Command
@NotifyChange(SELECTED_GROUP)
public void deleteGroup() {
groupService.deleteGroup(selectedGroup);
closeDialog();
updateView();
}
/**
* Opens group adding dialog.
*/
@Command
@NotifyChange({SELECTED_GROUP, SHOW_NEW_DIALOG})
public void showNewGroupDialog() {
selectedGroup = new Group();
showNewDialog = true;
}
/**
* Saves group, closing group edit(add) dialog and updates view.
*
* @param group editing group
*/
@Command
@NotifyChange({SHOW_NEW_DIALOG, SHOW_DELETE_DIALOG, SHOW_EDIT_DIALOG})
public void saveGroup(@BindingParam(value = "group") Group group) {
groupService.saveGroup(group);
closeDialog();
updateView();
}
/**
* Close all dialogs by set visibility to false.
*/
@Command
@NotifyChange({SHOW_NEW_DIALOG, SHOW_DELETE_DIALOG, SHOW_EDIT_DIALOG})
public void closeDialog() {
showNewDialog = false;
showDeleteDialog = false;
showEditDialog = false;
}
// -- Getters/Setters --------------------
/**
* Gets visibility status of Delete dialog window.
*
* @return true if dialog is visible false if dialog is invisible
*/
public boolean isShowDeleteDialog() {
return showDeleteDialog;
}
/**
* Gets visibility status of Edit dialog window.
*
* @return true if dialog is visible false if dialog is invisible
*/
public boolean isShowEditDialog() {
return showEditDialog;
}
/**
* Gets visibility status of New group dialog window, boolean show added as fix for onClose action, which don't send
* anything to the server when closing window because of event.stopPropagation, so during next change notification
* ZK will think that we need to show that dialog again which is wrong.
*
* @return true if dialog is visible false if dialog is invisible
*/
public boolean isShowNewDialog() {
boolean show = showNewDialog;
showNewDialog = false;
return show;
}
/**
* Gets List of groups which shown at UI.
*
* @return Groups currently displayed at UI.
*/
@SuppressWarnings("unused")
public ListModelList<Group> getGroups() {
return groups;
}
/**
* Gets current selected group.
*
* @return Group selected at UI.
*/
@SuppressWarnings("unused")
public Group getSelectedGroup() {
return selectedGroup;
}
/**
* Sets current selected group.
*
* @param group selected at UI.
*/
public void setSelectedGroup(Group group) {
this.selectedGroup = group;
}
/**
* Sets List of groups which shown at UI.
*
* @param groups selected at UI.
*/
public void setGroups(ListModelList<Group> groups) {
this.groups = groups;
}
/**
* Sets Search string, used for group search.
*
* @param searchString string used for group search.
*/
public void setSearchString(String searchString) {
this.searchString = searchString;
}
}
| true | true | public UserGroupVm(@Nonnull GroupService groupService, @Nonnull SelectedEntity<Group> selectedEntity, @Nonnull WindowManager windowManager) {
this.groupService = groupService;
this.selectedEntity = selectedEntity;
this.windowManager = windowManager;
this.groups = new ListModelList<Group>(groupService.getAll(), true);
}
| public UserGroupVm(@Nonnull GroupService groupService, @Nonnull SelectedEntity<Group> selectedEntity,
@Nonnull WindowManager windowManager) {
this.groupService = groupService;
this.selectedEntity = selectedEntity;
this.windowManager = windowManager;
this.groups = new ListModelList<Group>(groupService.getAll(), true);
}
|
diff --git a/platform-ctk-plugin/src/main/java/com/atlassian/refapp/ctk/version/PlatformVersionTest.java b/platform-ctk-plugin/src/main/java/com/atlassian/refapp/ctk/version/PlatformVersionTest.java
index 437b911..582115e 100644
--- a/platform-ctk-plugin/src/main/java/com/atlassian/refapp/ctk/version/PlatformVersionTest.java
+++ b/platform-ctk-plugin/src/main/java/com/atlassian/refapp/ctk/version/PlatformVersionTest.java
@@ -1,109 +1,113 @@
package com.atlassian.refapp.ctk.version;
import com.atlassian.functest.junit.SpringAwareTestCase;
import com.atlassian.refapp.ctk.PlatformVersionSpecReader;
import com.atlassian.refapp.ctk.PlatformVersionSpecReader.VersionCheck;
import com.atlassian.refapp.ctk.PlatformVersionSpecReader.ExportVersionCheck;
import com.atlassian.refapp.ctk.PlatformVersionSpecReader.BundleVersionCheck;
import com.atlassian.refapp.ctk.VersionStringComparator;
import org.junit.Test;
import org.osgi.framework.Bundle;
import org.osgi.service.packageadmin.ExportedPackage;
import org.osgi.service.packageadmin.PackageAdmin;
import org.twdata.pkgscanner.DefaultOsgiVersionConverter;
import java.util.List;
import static org.junit.Assert.fail;
public class PlatformVersionTest extends SpringAwareTestCase
{
private static final DefaultOsgiVersionConverter VERSION_CONVERTER = new DefaultOsgiVersionConverter();
private PackageAdmin packageAdmin;
public void setPackageAdmin(PackageAdmin packageAdmin)
{
this.packageAdmin = packageAdmin;
}
@Test
public void testAtlassianPlatformModulesSuppliedAtCorrectVersions()
{
final String platformVersion = PlatformVersionSpecReader.getPlatformVersion();
List<VersionCheck> versionChecks = PlatformVersionSpecReader.getVersionChecks();
// this keeps all the errors found.
StringBuilder sb = new StringBuilder();
for (VersionCheck check : versionChecks)
{
if (check instanceof ExportVersionCheck)
{
ExportVersionCheck exportCheck = (ExportVersionCheck) check;
final ExportedPackage export = packageAdmin.getExportedPackage(exportCheck.getPkg());
if (export == null || !VersionStringComparator.isSameOrNewerVersion(getOsgiVersion(exportCheck.getVersion()), export.getVersion().toString()))
{
sb.append("Atlassian Platform ");
sb.append(platformVersion);
sb.append(" must have ");
sb.append(exportCheck.getModuleName());
sb.append(" version:");
sb.append(exportCheck.getVersion());
if (export != null)
{
sb.append(" current version:");
sb.append(export.getVersion());
}
+ else
+ {
+ sb.append(" (no current version)");
+ }
sb.append("\n");
}
}
else if (check instanceof BundleVersionCheck)
{
BundleVersionCheck bundleCheck = (BundleVersionCheck) check;
Bundle[] bundles = packageAdmin.getBundles(bundleCheck.getBundleName(), null);
boolean found = false;
if (bundles != null)
{
// the version we expect must be found.
for(Bundle bundle:bundles)
{
if (VersionStringComparator.isSameOrNewerVersion(getOsgiVersion(bundleCheck.getVersion()), bundle.getVersion().toString()))
{
found = true;
break;
}
}
}
if (!found)
{
sb.append("Atlassian Platform ");
sb.append(platformVersion);
sb.append(" must have ");
sb.append(bundleCheck.getModuleName());
sb.append(" version:");
sb.append(bundleCheck.getVersion());
sb.append("\n");
}
}
}
if (sb.length() > 0)
{
fail(sb.toString());
}
}
/**
* Converts a maven version to OSGi format.
*/
private static String getOsgiVersion(String version)
{
return VERSION_CONVERTER.getVersion(version);
}
}
| true | true | public void testAtlassianPlatformModulesSuppliedAtCorrectVersions()
{
final String platformVersion = PlatformVersionSpecReader.getPlatformVersion();
List<VersionCheck> versionChecks = PlatformVersionSpecReader.getVersionChecks();
// this keeps all the errors found.
StringBuilder sb = new StringBuilder();
for (VersionCheck check : versionChecks)
{
if (check instanceof ExportVersionCheck)
{
ExportVersionCheck exportCheck = (ExportVersionCheck) check;
final ExportedPackage export = packageAdmin.getExportedPackage(exportCheck.getPkg());
if (export == null || !VersionStringComparator.isSameOrNewerVersion(getOsgiVersion(exportCheck.getVersion()), export.getVersion().toString()))
{
sb.append("Atlassian Platform ");
sb.append(platformVersion);
sb.append(" must have ");
sb.append(exportCheck.getModuleName());
sb.append(" version:");
sb.append(exportCheck.getVersion());
if (export != null)
{
sb.append(" current version:");
sb.append(export.getVersion());
}
sb.append("\n");
}
}
else if (check instanceof BundleVersionCheck)
{
BundleVersionCheck bundleCheck = (BundleVersionCheck) check;
Bundle[] bundles = packageAdmin.getBundles(bundleCheck.getBundleName(), null);
boolean found = false;
if (bundles != null)
{
// the version we expect must be found.
for(Bundle bundle:bundles)
{
if (VersionStringComparator.isSameOrNewerVersion(getOsgiVersion(bundleCheck.getVersion()), bundle.getVersion().toString()))
{
found = true;
break;
}
}
}
if (!found)
{
sb.append("Atlassian Platform ");
sb.append(platformVersion);
sb.append(" must have ");
sb.append(bundleCheck.getModuleName());
sb.append(" version:");
sb.append(bundleCheck.getVersion());
sb.append("\n");
}
}
}
if (sb.length() > 0)
{
fail(sb.toString());
}
}
| public void testAtlassianPlatformModulesSuppliedAtCorrectVersions()
{
final String platformVersion = PlatformVersionSpecReader.getPlatformVersion();
List<VersionCheck> versionChecks = PlatformVersionSpecReader.getVersionChecks();
// this keeps all the errors found.
StringBuilder sb = new StringBuilder();
for (VersionCheck check : versionChecks)
{
if (check instanceof ExportVersionCheck)
{
ExportVersionCheck exportCheck = (ExportVersionCheck) check;
final ExportedPackage export = packageAdmin.getExportedPackage(exportCheck.getPkg());
if (export == null || !VersionStringComparator.isSameOrNewerVersion(getOsgiVersion(exportCheck.getVersion()), export.getVersion().toString()))
{
sb.append("Atlassian Platform ");
sb.append(platformVersion);
sb.append(" must have ");
sb.append(exportCheck.getModuleName());
sb.append(" version:");
sb.append(exportCheck.getVersion());
if (export != null)
{
sb.append(" current version:");
sb.append(export.getVersion());
}
else
{
sb.append(" (no current version)");
}
sb.append("\n");
}
}
else if (check instanceof BundleVersionCheck)
{
BundleVersionCheck bundleCheck = (BundleVersionCheck) check;
Bundle[] bundles = packageAdmin.getBundles(bundleCheck.getBundleName(), null);
boolean found = false;
if (bundles != null)
{
// the version we expect must be found.
for(Bundle bundle:bundles)
{
if (VersionStringComparator.isSameOrNewerVersion(getOsgiVersion(bundleCheck.getVersion()), bundle.getVersion().toString()))
{
found = true;
break;
}
}
}
if (!found)
{
sb.append("Atlassian Platform ");
sb.append(platformVersion);
sb.append(" must have ");
sb.append(bundleCheck.getModuleName());
sb.append(" version:");
sb.append(bundleCheck.getVersion());
sb.append("\n");
}
}
}
if (sb.length() > 0)
{
fail(sb.toString());
}
}
|
diff --git a/camera-app/src/main/java/com/sneakysquid/nova/app/TakePhoto.java b/camera-app/src/main/java/com/sneakysquid/nova/app/TakePhoto.java
index 46036a5..eb1b454 100644
--- a/camera-app/src/main/java/com/sneakysquid/nova/app/TakePhoto.java
+++ b/camera-app/src/main/java/com/sneakysquid/nova/app/TakePhoto.java
@@ -1,142 +1,142 @@
package com.sneakysquid.nova.app;
import android.app.Activity;
import android.hardware.Camera;
import com.sneakysquid.nova.link.NovaFlashCallback;
import com.sneakysquid.nova.link.NovaFlashCommand;
import com.sneakysquid.nova.link.NovaLink;
import com.sneakysquid.nova.link.NovaLinkStatus;
import static com.sneakysquid.nova.util.Debug.assertOnUiThread;
import static com.sneakysquid.nova.util.Debug.debug;
/**
* Runnable task that implements the asynchronous flow of steps required to take a photo.
* <p/>
* These are (each step can take some time):
* <ul>
* <li>Begin auto-focusing camera</li>
* <li>Wait for focus, then trigger flash</li>
* <li>Wait for flash ack, then take picture</li>
* <li>Wait for JPEG, then trigger external PictureCallback</li>
* </ul>
*
* @author Joe Walnes
*/
public class TakePhoto implements Runnable, Camera.AutoFocusCallback, NovaFlashCallback, Camera.ShutterCallback, Camera.PictureCallback {
private final Activity activity;
private final Camera camera;
private final NovaLink novaLink;
private final NovaFlashCommand flashCmd;
private final Callback result;
public interface Callback {
void onPhotoTaken(byte[] jpeg);
}
public TakePhoto(Activity activity,
Camera camera,
NovaLink novaLink,
NovaFlashCommand flashCmd,
Callback result) {
this.activity = activity;
this.camera = camera;
this.novaLink = novaLink;
this.flashCmd = flashCmd;
this.result = result;
}
@Override
public void run() {
takePhoto();
}
private void takePhoto() {
debug("takePhoto()");
assertOnUiThread();
// Step 1: Auto-focus
camera.autoFocus(this); // -> callback: onAutoFocus()
}
@Override
public void onAutoFocus(boolean success, Camera camera) {
debug("onAutoFocus(%s)", success);
assertOnUiThread();
// TODO: Handle success==false
// Step 1: Auto-focus DONE.
triggerFlash();
}
@SuppressWarnings("ConstantConditions")
private void triggerFlash() {
debug("triggerFlash(%s)", flashCmd);
assertOnUiThread();
if (flashCmd == null || flashCmd.isPointless()
|| novaLink.getStatus() != NovaLinkStatus.Ready) {
// Flash not needed, or not possible. Skip to step 3 and just take the photo.
- takePhoto();
+ takePicture();
} else {
// Step 2: Trigger flash
novaLink.flash(flashCmd, this); // -> callback: onNovaFlashAcknowledged
}
}
@Override
public void onNovaFlashAcknowledged(boolean success) {
debug("onNovaFlashAcknowledged(%s)", success);
assertOnUiThread();
// Step 2: Trigger flash DONE
// TODO: Handle success==false
takePicture();
}
private void takePicture() {
debug("takePicture()");
assertOnUiThread();
// Step 3: Take picture
camera.takePicture(this, null, this); // -> callback: onShutter(), and onPictureTaken()
}
@Override
public void onShutter() {
debug("onShutter()");
assertOnUiThread();
// TODO: Shutter finished. Deactivate flash ASAP
}
@Override
public void onPictureTaken(byte[] data, Camera camera) {
debug("onPictureTaken()");
assertOnUiThread();
// Step 3: Take picture DONE
// Step 4: Call result
result.onPhotoTaken(data);
}
private void delay(final int millis, final Runnable task) {
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
}
activity.runOnUiThread(task);
}
}).start();
}
}
| true | true | private void triggerFlash() {
debug("triggerFlash(%s)", flashCmd);
assertOnUiThread();
if (flashCmd == null || flashCmd.isPointless()
|| novaLink.getStatus() != NovaLinkStatus.Ready) {
// Flash not needed, or not possible. Skip to step 3 and just take the photo.
takePhoto();
} else {
// Step 2: Trigger flash
novaLink.flash(flashCmd, this); // -> callback: onNovaFlashAcknowledged
}
}
| private void triggerFlash() {
debug("triggerFlash(%s)", flashCmd);
assertOnUiThread();
if (flashCmd == null || flashCmd.isPointless()
|| novaLink.getStatus() != NovaLinkStatus.Ready) {
// Flash not needed, or not possible. Skip to step 3 and just take the photo.
takePicture();
} else {
// Step 2: Trigger flash
novaLink.flash(flashCmd, this); // -> callback: onNovaFlashAcknowledged
}
}
|
diff --git a/contrib/Brainfuck.java b/contrib/Brainfuck.java
index f26863a..5a57715 100644
--- a/contrib/Brainfuck.java
+++ b/contrib/Brainfuck.java
@@ -1,214 +1,214 @@
import uk.co.uwcs.choob.modules.*;
import uk.co.uwcs.choob.support.*;
import uk.co.uwcs.choob.support.events.*;
import java.util.*;
/**
* Brainfuck interpreter.
*
* This plugin implements a simple interpreter for the minimalistic Turing-complete
* programming language, Brainfuck.
*
* All Brainfuck op-codes are supported except "," (input character to memory address
* pointed to by the pointer) as it does not make sense in an IRC context. The memory
* size is 30,000 in accordance with the original Brainfuck specification. More
* informationi about Brainfuck, a quick tutorial as well as many external references
* may be found on Wikipedia[0].
*
* The plugin has two artificial limits in an attempt to prevent denial-of-service
* issues with other parts of the bot. Firstly, the total number of instructions the
* interpreter will execute can be specified with the 'MAX_INSTRUCTIONS' constant.
* This prevents (possibly accidental) "infinite" loops such as "+[]". If the
* maximum number is reached, an error message is displayed. Secondly, the maximum
* size of the interpreter's output can be specified with the 'MAX_OUTPUT' constant,
* pre-empting various issues related to the bot generating large amounts of output.
*
* [0] http://en.wikipedia.org/wiki/Brainfuck
*
* @author lamby
*/
public class Brainfuck
{
private static int MAX_INSTRUCTIONS = 9000;
private static int MAX_OUTPUT = 70;
private IRCInterface irc;
private Modules mods;
public Brainfuck(Modules mods, IRCInterface irc)
{
this.mods = mods;
this.irc = irc;
}
public String[] helpCommandCalc = {
"Evaluates a Brainfuck program.",
"<expr>",
"<expr> is a Brainfuck program"
};
public void commandEval( Message mes )
{
String reply;
try
{
reply = eval(mods.util.getParamString(mes));
if (reply.length() == 0)
{
reply = "(no output)";
}
}
catch (InstructionCountExceededException e)
{
reply = e.getMessage() + " (halted after " + MAX_INSTRUCTIONS + " instructions at offset " + e.getOffset() + ")";
}
catch (OutputLengthExceededException e)
{
reply = e.getMessage() + " (halted after " + MAX_OUTPUT + " chars of output at offset " + e.getOffset() + ")";
}
catch (BrainfuckException e)
{
reply = "Parse error at offset " + e.getOffset() + ": " + e.getMessage();
}
irc.sendContextReply(mes, reply);
}
public String eval(String expr) throws BrainfuckException
{
BrainfuckInterpreter interp = new BrainfuckInterpreter(expr, MAX_INSTRUCTIONS, MAX_OUTPUT);
return interp.eval();
}
}
class BrainfuckInterpreter
{
private byte[] mem = new byte[30000];
private int pc = 0;
private int ptr = 0;
private int count = 0;
private int max_output;
private int max_instructions;
private String expr;
public BrainfuckInterpreter(String expr, int max_instructions, int max_output)
{
this.expr = expr;
this.max_instructions = max_instructions;
this.max_output = max_output;
}
public String eval() throws BrainfuckException
{
StringBuilder output = new StringBuilder();
Stack<Integer> pc_stack = new Stack();
while (pc < expr.length())
{
++count;
if (count == max_instructions)
{
throw new InstructionCountExceededException(output.toString(), pc);
}
switch (expr.charAt(pc))
{
case '>':
++ptr;
break;
case '<':
--ptr;
break;
case '+':
++mem[ptr];
break;
case '-':
--mem[ptr];
break;
case '.':
- output.append((char) mem[ptr]);
+ output.append((char) (mem[ptr] & 0xFF));
if (output.length() == max_output)
{
throw new OutputLengthExceededException(output.toString(), pc);
}
break;
case '[':
pc_stack.push(pc);
break;
case ']':
try
{
if (mem[ptr] == 0)
{
pc_stack.pop();
}
else
{
pc = pc_stack.peek();
}
}
catch (EmptyStackException e)
{
throw new ParseErrorException(pc);
}
break;
default:
break;
}
++pc;
}
if (!pc_stack.isEmpty())
{
throw new ParseErrorException(pc);
}
return output.toString();
}
}
class BrainfuckException extends Exception
{
int offset;
public BrainfuckException(String message, int offset)
{
super(message);
this.offset = offset;
}
public int getOffset()
{
return offset;
}
}
class ParseErrorException extends BrainfuckException
{
public ParseErrorException(int offset)
{
super("Mismatched bracket", offset);
}
}
class InstructionCountExceededException extends BrainfuckException
{
public InstructionCountExceededException(String output, int offset)
{
super(output, offset);
}
}
class OutputLengthExceededException extends BrainfuckException
{
public OutputLengthExceededException(String output, int offset)
{
super(output, offset);
}
}
| true | true | public String eval() throws BrainfuckException
{
StringBuilder output = new StringBuilder();
Stack<Integer> pc_stack = new Stack();
while (pc < expr.length())
{
++count;
if (count == max_instructions)
{
throw new InstructionCountExceededException(output.toString(), pc);
}
switch (expr.charAt(pc))
{
case '>':
++ptr;
break;
case '<':
--ptr;
break;
case '+':
++mem[ptr];
break;
case '-':
--mem[ptr];
break;
case '.':
output.append((char) mem[ptr]);
if (output.length() == max_output)
{
throw new OutputLengthExceededException(output.toString(), pc);
}
break;
case '[':
pc_stack.push(pc);
break;
case ']':
try
{
if (mem[ptr] == 0)
{
pc_stack.pop();
}
else
{
pc = pc_stack.peek();
}
}
catch (EmptyStackException e)
{
throw new ParseErrorException(pc);
}
break;
default:
break;
}
++pc;
}
if (!pc_stack.isEmpty())
{
throw new ParseErrorException(pc);
}
return output.toString();
}
| public String eval() throws BrainfuckException
{
StringBuilder output = new StringBuilder();
Stack<Integer> pc_stack = new Stack();
while (pc < expr.length())
{
++count;
if (count == max_instructions)
{
throw new InstructionCountExceededException(output.toString(), pc);
}
switch (expr.charAt(pc))
{
case '>':
++ptr;
break;
case '<':
--ptr;
break;
case '+':
++mem[ptr];
break;
case '-':
--mem[ptr];
break;
case '.':
output.append((char) (mem[ptr] & 0xFF));
if (output.length() == max_output)
{
throw new OutputLengthExceededException(output.toString(), pc);
}
break;
case '[':
pc_stack.push(pc);
break;
case ']':
try
{
if (mem[ptr] == 0)
{
pc_stack.pop();
}
else
{
pc = pc_stack.peek();
}
}
catch (EmptyStackException e)
{
throw new ParseErrorException(pc);
}
break;
default:
break;
}
++pc;
}
if (!pc_stack.isEmpty())
{
throw new ParseErrorException(pc);
}
return output.toString();
}
|
diff --git a/java/tools/src/com/jopdesign/wcet/frontend/WcetAppInfo.java b/java/tools/src/com/jopdesign/wcet/frontend/WcetAppInfo.java
index 4f0b95c8..0c44744e 100644
--- a/java/tools/src/com/jopdesign/wcet/frontend/WcetAppInfo.java
+++ b/java/tools/src/com/jopdesign/wcet/frontend/WcetAppInfo.java
@@ -1,314 +1,314 @@
/*
This file is part of JOP, the Java Optimized Processor
see <http://www.jopdesign.com/>
Copyright (C) 2008, Benedikt Huber ([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 com.jopdesign.wcet.frontend;
import java.io.IOException;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.Vector;
import org.apache.bcel.generic.ConstantPoolGen;
import org.apache.bcel.generic.Instruction;
import org.apache.bcel.generic.InstructionHandle;
import org.apache.bcel.generic.InvokeInstruction;
import org.apache.log4j.Logger;
import com.jopdesign.build.AppInfo;
import com.jopdesign.build.ClassInfo;
import com.jopdesign.build.MethodInfo;
import com.jopdesign.dfa.framework.ContextMap;
import com.jopdesign.wcet.ProcessorModel;
import com.jopdesign.wcet.Project;
import com.jopdesign.wcet.Project.AnalysisError;
import com.jopdesign.wcet.frontend.SourceAnnotations.BadAnnotationException;
import com.jopdesign.wcet.frontend.SourceAnnotations.LoopBound;
import com.jopdesign.wcet.graphutils.TopOrder.BadGraphException;
/**
* AppInfo subclass for the WCET analysis.
* Provides a TypeGraph.
*
* @author Benedikt Huber, [email protected]
*/
public class WcetAppInfo {
private static final long serialVersionUID = 3L;
/* package logger */
public static final Logger logger = Logger.getLogger(WcetAppInfo.class.getPackage().toString());
/**
* Raised when we cannot find / fail to load a referenced method.
*/
public class MethodNotFoundException extends Exception {
private static final long serialVersionUID = 1L;
public MethodNotFoundException(String message) {
super(message);
}
}
private TypeGraph typeGraph;
private AppInfo ai;
private Map<MethodInfo, ControlFlowGraph> cfgs;
private List<ControlFlowGraph> cfgsByIndex;
private Map<InstructionHandle, ContextMap<String, String>> receiverAnalysis = null;
private ProcessorModel processor;
private Project project;
public WcetAppInfo(Project p, com.jopdesign.build.AppInfo ai, ProcessorModel processor) {
this.project = p;
this.ai = ai;
this.processor = processor;
this.typeGraph = new TypeGraph(this);
cfgsByIndex = new Vector<ControlFlowGraph>();
cfgs = new Hashtable<MethodInfo, ControlFlowGraph>();
}
/**
* @return A mapping from the name of a loaded class to {@link ClassInfo}.
*/
public Map<String, ? extends ClassInfo> getCliMap() {
return ai.cliMap;
}
public Project getProject() {
return project;
}
/**
* @return The typegraph of all loaded classes
*/
public TypeGraph getTypeGraph() {
return typeGraph;
}
/**
* @param className Name of the class to lookup
* @return the class info, or null if the class could'nt be found
*/
public ClassInfo getClassInfo(String className) {
return getCliMap().get(className);
}
/**
* Find the given method
* @param className The fully qualified name of the class the method is located in
* @param methodName The name of the method to be searched.
* Note that the signature is optional if the method name is unique.
* @return The method searched for, or null if it couldn't be found
* @throws MethodNotFoundException if the method couldn't be found or is ambiguous
*/
public MethodInfo searchMethod(String className, String methodName) throws MethodNotFoundException {
ClassInfo cli = getCliMap().get(className);
if(cli == null) throw new MethodNotFoundException("The class "+className+" couldn't be found");
return searchMethod(cli,methodName);
}
public MethodInfo searchMethod(ClassInfo cli, String methodName) throws MethodNotFoundException {
MethodInfo mi = null;
if(methodName.indexOf("(") > 0) {
mi = cli.getMethodInfo(methodName);
if(mi == null) {
throw new MethodNotFoundException("The fully qualified method '"+methodName+"' could not be found in "+
cli.getMethodInfoMap().keySet());
}
} else {
for(MethodInfo candidate : cli.getMethods()) {
if(methodName.equals(candidate.getMethod().getName())) {
if(mi == null) {
mi = candidate;
} else {
throw new MethodNotFoundException("The method name "+methodName+" is ambiguous."+
"Both "+mi.methodId+" and "+candidate.methodId+" match");
}
}
}
if(mi == null) {
Vector<String> candidates = new Vector<String>();
for(MethodInfo candidate : cli.getMethods()) {
candidates.add(candidate.getMethod().getName());
}
- throw new MethodNotFoundException("The method "+methodName+"could not be found in "+cli.toString()+". "+
+ throw new MethodNotFoundException("The method "+methodName+" could not be found in "+cli.toString()+". "+
"Candidates: "+candidates);
}
}
return mi;
}
/**
* Return the receiver name and method name of a
* method referenced by the given invoke instruction
* @param invokerCi the classinfo of the method which contains the {@link InvokeInstruciton}
* @param instr the invoke instruction
* @return A pair of class info and method name
*/
public MethodRef getReferenced(ClassInfo invokerCi, InvokeInstruction instr) {
ClassInfo refCi;
ConstantPoolGen cpg = new ConstantPoolGen(invokerCi.clazz.getConstantPool());
String classname = instr.getClassName(cpg );
String methodname = instr.getMethodName(cpg) + instr.getSignature(cpg);
refCi = getClassInfo(classname);
if(refCi == null) throw new AssertionError("Failed class lookup (invoke target): "+classname);
return new MethodRef(refCi,methodname);
}
public MethodRef getReferenced(MethodInfo method, InvokeInstruction instr) {
return getReferenced(method.getCli(),instr);
}
public MethodInfo findStaticImplementation(MethodRef ref) {
ClassInfo receiver = ref.getReceiver();
String methodId = ref.getMethodId();
MethodInfo staticImpl = ref.getReceiver().getMethodInfo(methodId);
if(staticImpl == null) {
ClassInfo superRec = receiver;
while(staticImpl == null && superRec != null) {
staticImpl = superRec.getMethodInfo(methodId);
try {
if(superRec.clazz.getSuperClass() == null) superRec = null;
else superRec = superRec.superClass;
} catch (ClassNotFoundException e) {
e.printStackTrace();
throw new Error();
}
}
}
return staticImpl;
}
/**
* Find possible implementations of the given method in the given class
* <p>
* For all candidates, check whether they implement the method.
* All subclasses of the receiver class are candidates. If the method isn't implemented
* in the receiver, the lowest superclass implementing the method is a candidate too.
* </p>
* @param receiver The class info of the receiver
* @param methodname The method name
* @return list of method infos that might be invoked
*/
public List<MethodInfo> findImplementations(MethodRef methodRef) {
Vector<MethodInfo> impls = new Vector<MethodInfo>(3);
tryAddImpl(impls,findStaticImplementation(methodRef));
for(ClassInfo subty : this.typeGraph.getStrictSubtypes(methodRef.getReceiver())) {
MethodInfo subtyImpl = subty.getMethodInfo(methodRef.getMethodId());
tryAddImpl(impls,subtyImpl);
}
return impls;
}
/**
* Variant operating on an instruction handle and therefore capable of
* using DFA analysis results.
* @param invInstr
* @return
*/
public List<MethodInfo> findImplementations(MethodInfo invokerM, InstructionHandle ih) {
MethodRef ref = this.getReferenced(invokerM, (InvokeInstruction) ih.getInstruction());
List<MethodInfo> staticImpls = findImplementations(ref);
staticImpls = dfaReceivers(ih, staticImpls);
return staticImpls;
}
// TODO: rather slow, for debugging purposes
private List<MethodInfo> dfaReceivers(InstructionHandle ih, List<MethodInfo> staticImpls) {
if(this.receiverAnalysis != null && receiverAnalysis.containsKey(ih)) {
ContextMap<String, String> receivers = receiverAnalysis.get(ih);
List<MethodInfo> dynImpls = new Vector<MethodInfo>();
Set<String> dynReceivers = receivers.keySet();
for(MethodInfo impl : staticImpls) {
if(dynReceivers.contains(impl.getFQMethodName())) {
dynReceivers.remove(impl.getFQMethodName());
dynImpls.add(impl);
} else {
logger.info("Static but not dynamic receiver: "+impl);
}
}
if(! dynReceivers.isEmpty()) {
throw new AssertionError("Bad receiver analysis ? Dynamic but not static receivers: "+dynReceivers);
}
return dynImpls;
} else {
return staticImpls;
}
}
/* helper to avoid code dupl */
private void tryAddImpl(List<MethodInfo> ms, MethodInfo m) {
if(m != null) {
if(! m.getMethod().isAbstract() && ! m.getMethod().isInterface()) {
ms.add(m);
}
}
}
public AppInfo getAppInfo() {
return this.ai;
}
public ControlFlowGraph getFlowGraph(int id) {
return cfgsByIndex.get(id);
}
public ControlFlowGraph getFlowGraph(MethodInfo m) {
if(cfgs.get(m) == null) {
try {
loadFlowGraph(m);
} catch (BadAnnotationException e) {
throw new AnalysisError("Bad Flow Fact Annotation: "+e.getMessage(),e);
} catch (IOException e) {
throw new AnalysisError("IO Exception",e);
} catch (BadGraphException e) {
throw new AnalysisError("Bad Flow Graph: "+e.getMessage(),e);
}
}
return cfgs.get(m);
}
private ControlFlowGraph loadFlowGraph(MethodInfo method) throws BadAnnotationException, IOException, BadGraphException {
SortedMap<Integer,LoopBound> wcaMap = project.getAnnotations(method.getCli());
assert(wcaMap != null);
if(method.getCode() == null) {
throw new BadGraphException("No implementation of "+method.getFQMethodName()+" available for the target processor");
}
ControlFlowGraph fg;
try {
fg = new ControlFlowGraph(cfgsByIndex.size(),project,method);
fg.loadAnnotations(project);
fg.resolveVirtualInvokes();
// fg.insertSplitNodes();
// fg.insertSummaryNodes();
fg.insertReturnNodes();
fg.insertContinueLoopNodes();
cfgsByIndex.add(fg);
cfgs.put(method,fg);
return fg;
} catch(BadGraphException e) {
logger.error("Bad flow graph: "+e);
throw e;
}
}
public void setReceivers(
Map<InstructionHandle, ContextMap<String, String>> receiverResults) {
this.receiverAnalysis = receiverResults;
}
public ProcessorModel getProcessorModel() {
return this.processor;
}
public MethodInfo getJavaImplementation(MethodInfo ctx, Instruction lastInstr) {
return this.processor.getJavaImplementation(this, ctx, lastInstr);
}
}
| true | true | public MethodInfo searchMethod(ClassInfo cli, String methodName) throws MethodNotFoundException {
MethodInfo mi = null;
if(methodName.indexOf("(") > 0) {
mi = cli.getMethodInfo(methodName);
if(mi == null) {
throw new MethodNotFoundException("The fully qualified method '"+methodName+"' could not be found in "+
cli.getMethodInfoMap().keySet());
}
} else {
for(MethodInfo candidate : cli.getMethods()) {
if(methodName.equals(candidate.getMethod().getName())) {
if(mi == null) {
mi = candidate;
} else {
throw new MethodNotFoundException("The method name "+methodName+" is ambiguous."+
"Both "+mi.methodId+" and "+candidate.methodId+" match");
}
}
}
if(mi == null) {
Vector<String> candidates = new Vector<String>();
for(MethodInfo candidate : cli.getMethods()) {
candidates.add(candidate.getMethod().getName());
}
throw new MethodNotFoundException("The method "+methodName+"could not be found in "+cli.toString()+". "+
"Candidates: "+candidates);
}
}
return mi;
}
| public MethodInfo searchMethod(ClassInfo cli, String methodName) throws MethodNotFoundException {
MethodInfo mi = null;
if(methodName.indexOf("(") > 0) {
mi = cli.getMethodInfo(methodName);
if(mi == null) {
throw new MethodNotFoundException("The fully qualified method '"+methodName+"' could not be found in "+
cli.getMethodInfoMap().keySet());
}
} else {
for(MethodInfo candidate : cli.getMethods()) {
if(methodName.equals(candidate.getMethod().getName())) {
if(mi == null) {
mi = candidate;
} else {
throw new MethodNotFoundException("The method name "+methodName+" is ambiguous."+
"Both "+mi.methodId+" and "+candidate.methodId+" match");
}
}
}
if(mi == null) {
Vector<String> candidates = new Vector<String>();
for(MethodInfo candidate : cli.getMethods()) {
candidates.add(candidate.getMethod().getName());
}
throw new MethodNotFoundException("The method "+methodName+" could not be found in "+cli.toString()+". "+
"Candidates: "+candidates);
}
}
return mi;
}
|
diff --git a/modules/activiti-cycle/src/test/java/org/activiti/cycle/impl/connector/demo/DemoConnectorTest.java b/modules/activiti-cycle/src/test/java/org/activiti/cycle/impl/connector/demo/DemoConnectorTest.java
index db78a982..fe5aa8d2 100644
--- a/modules/activiti-cycle/src/test/java/org/activiti/cycle/impl/connector/demo/DemoConnectorTest.java
+++ b/modules/activiti-cycle/src/test/java/org/activiti/cycle/impl/connector/demo/DemoConnectorTest.java
@@ -1,142 +1,142 @@
package org.activiti.cycle.impl.connector.demo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.activiti.cycle.Content;
import org.activiti.cycle.ContentRepresentation;
import org.activiti.cycle.CycleService;
import org.activiti.cycle.RepositoryArtifact;
import org.activiti.cycle.RepositoryFolder;
import org.activiti.cycle.RepositoryNode;
import org.activiti.cycle.impl.CycleServiceImpl;
import org.activiti.cycle.impl.conf.ConfigurationContainer;
import org.activiti.cycle.impl.conf.RepositoryConnectorConfiguration;
import org.activiti.cycle.impl.connector.demo.action.CopyArtifactAction;
import org.activiti.cycle.impl.plugin.PluginFinder;
import org.junit.Before;
import org.junit.Test;
public class DemoConnectorTest {
@Before
public void init() {
// TODO: Should be done in Bootstrapping
PluginFinder.checkPluginInitialization();
}
@Test
public void testFirstPlay() throws Exception {
// create demo connector but accessed via the customized view connector
ConfigurationContainer configurationContainer = new ConfigurationContainer("bernd");
RepositoryConnectorConfiguration configuration = new DemoConnectorConfiguration("demo");
configurationContainer.addRepositoryConnectorConfiguration(configuration);
CycleService cycleService = new CycleServiceImpl(configurationContainer.getConnectorList());
// TODO: Correct user / password handling!!!!
cycleService.login("bernd", "bernd");
List<RepositoryNode> childNodes = cycleService.getChildren("demo", "/").asList();
// assertEquals(1, childNodes.size());
// assertEquals("demo", childNodes.get(0).getCurrentPath());
// childNodes = cycleService.getChildren("demo", "/").asList();
assertEquals(2, childNodes.size());
assertTrue(childNodes.get(0) instanceof RepositoryFolder);
RepositoryFolder folder1 = (RepositoryFolder) childNodes.get(0);
assertEquals("/minutes", folder1.getNodeId());
// assertEquals("http://localhost:8080/activiti-cycle/demo/minutes",
// folder1.getClientUrl());
assertTrue(childNodes.get(1) instanceof RepositoryFolder);
RepositoryFolder folder2 = (RepositoryFolder) childNodes.get(1);
assertEquals("/BPMN", folder2.getNodeId());
// check sub elements of folder 1
childNodes = cycleService.getChildren("demo", folder1.getNodeId()).asList();
assertEquals(2, childNodes.size());
RepositoryArtifact file1 = (RepositoryArtifact) childNodes.get(0);
assertEquals("/minutes/20100701-KickOffMeeting.txt", file1.getNodeId());
RepositoryArtifact file2 = (RepositoryArtifact) childNodes.get(1);
assertEquals("/minutes/InitialMindmap.mm", file2.getNodeId());
// check sub elements of folder 2
childNodes = cycleService.getChildren("demo", folder2.getNodeId()).asList();
assertEquals(1, childNodes.size());
RepositoryFolder folder3 = (RepositoryFolder) childNodes.get(0);
assertEquals("/BPMN/Level3", folder3.getNodeId());
childNodes = cycleService.getChildren("demo", folder3.getNodeId()).asList();
assertEquals(1, childNodes.size());
RepositoryArtifact file3 = (RepositoryArtifact) childNodes.get(0);
assertEquals("/BPMN/Level3/InitialBpmnModel", file3.getNodeId());
assertEquals("InitialBpmnModel", file3.getMetadata().getName());
assertEquals("/BPMN/Level3", file3.getMetadata().setParentFolderId());
//
// System.out.println(folder2.getId() + " -> " + folder2.getClientUrl());
// System.out.println(folder3.getId() + " -> " + folder3.getClientUrl());
// System.out.println(file3.getId() + " -> " + file3.getClientUrl());
//
Collection<ContentRepresentation> contentRepresentations = file3.getArtifactType().getContentRepresentations();
for (ContentRepresentation contentRepresentation : contentRepresentations) {
Content content = cycleService.getContent("demo", file3.getNodeId(), contentRepresentation.getId());
assertNotNull(content);
assertNotNull(content.asByteArray());
}
assertEquals(6, DemoConnector.nodes.size());
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("targetName", "xxx.txt");
parameters.put("copyCount", 2);
parameters.put("targetConnectorId", "demo");
parameters.put("targetFolderId", "/minutes");
- cycleService.executeParameterizedAction("demo", file1.getNodeId(), CopyArtifactAction.class.getName(), parameters);
+ cycleService.executeParameterizedAction("demo", file1.getNodeId(), new CopyArtifactAction().getId(), parameters);
List<RepositoryNode> nodes = DemoConnector.nodes;
assertEquals(8, DemoConnector.nodes.size());
childNodes = cycleService.getChildren("demo", folder1.getNodeId()).asList();
assertEquals(4, childNodes.size());
assertEquals("/minutes/20100701-KickOffMeeting.txt", childNodes.get(0).getNodeId());
assertEquals("/minutes/InitialMindmap.mm", childNodes.get(1).getNodeId());
assertEquals("/minutes/xxx.txt0", childNodes.get(2).getNodeId());
assertEquals("xxx.txt0", childNodes.get(2).getMetadata().getName());
assertEquals("/minutes/xxx.txt1", childNodes.get(3).getNodeId());
assertEquals("xxx.txt1", childNodes.get(3).getMetadata().getName());
}
// @Test
public void testPlay() {
// ConfigurationContainer configuration = new
// ConfigurationContainer("bernd");
// configuration.addRepositoryConnectorConfiguration(new
// DemoConnectorConfiguration("demo"));
// configuration.addRepositoryConnectorConfiguration(new
// SignavioConnectorConfiguration("signavio",
// "http://localhost:8080/activiti-modeler/"));
// configuration.addRepositoryConnectorConfiguration(new
// FileSystemConnectorConfiguration("files", new File("C:/temp")));
//
// RepositoryConnector conn = new
// RootConnectorConfiguration(configuration).createConnector();
//
// RepositoryLogHelper.printNodes(conn, conn.getChildren("/").asList());
}
}
| true | true | public void testFirstPlay() throws Exception {
// create demo connector but accessed via the customized view connector
ConfigurationContainer configurationContainer = new ConfigurationContainer("bernd");
RepositoryConnectorConfiguration configuration = new DemoConnectorConfiguration("demo");
configurationContainer.addRepositoryConnectorConfiguration(configuration);
CycleService cycleService = new CycleServiceImpl(configurationContainer.getConnectorList());
// TODO: Correct user / password handling!!!!
cycleService.login("bernd", "bernd");
List<RepositoryNode> childNodes = cycleService.getChildren("demo", "/").asList();
// assertEquals(1, childNodes.size());
// assertEquals("demo", childNodes.get(0).getCurrentPath());
// childNodes = cycleService.getChildren("demo", "/").asList();
assertEquals(2, childNodes.size());
assertTrue(childNodes.get(0) instanceof RepositoryFolder);
RepositoryFolder folder1 = (RepositoryFolder) childNodes.get(0);
assertEquals("/minutes", folder1.getNodeId());
// assertEquals("http://localhost:8080/activiti-cycle/demo/minutes",
// folder1.getClientUrl());
assertTrue(childNodes.get(1) instanceof RepositoryFolder);
RepositoryFolder folder2 = (RepositoryFolder) childNodes.get(1);
assertEquals("/BPMN", folder2.getNodeId());
// check sub elements of folder 1
childNodes = cycleService.getChildren("demo", folder1.getNodeId()).asList();
assertEquals(2, childNodes.size());
RepositoryArtifact file1 = (RepositoryArtifact) childNodes.get(0);
assertEquals("/minutes/20100701-KickOffMeeting.txt", file1.getNodeId());
RepositoryArtifact file2 = (RepositoryArtifact) childNodes.get(1);
assertEquals("/minutes/InitialMindmap.mm", file2.getNodeId());
// check sub elements of folder 2
childNodes = cycleService.getChildren("demo", folder2.getNodeId()).asList();
assertEquals(1, childNodes.size());
RepositoryFolder folder3 = (RepositoryFolder) childNodes.get(0);
assertEquals("/BPMN/Level3", folder3.getNodeId());
childNodes = cycleService.getChildren("demo", folder3.getNodeId()).asList();
assertEquals(1, childNodes.size());
RepositoryArtifact file3 = (RepositoryArtifact) childNodes.get(0);
assertEquals("/BPMN/Level3/InitialBpmnModel", file3.getNodeId());
assertEquals("InitialBpmnModel", file3.getMetadata().getName());
assertEquals("/BPMN/Level3", file3.getMetadata().setParentFolderId());
//
// System.out.println(folder2.getId() + " -> " + folder2.getClientUrl());
// System.out.println(folder3.getId() + " -> " + folder3.getClientUrl());
// System.out.println(file3.getId() + " -> " + file3.getClientUrl());
//
Collection<ContentRepresentation> contentRepresentations = file3.getArtifactType().getContentRepresentations();
for (ContentRepresentation contentRepresentation : contentRepresentations) {
Content content = cycleService.getContent("demo", file3.getNodeId(), contentRepresentation.getId());
assertNotNull(content);
assertNotNull(content.asByteArray());
}
assertEquals(6, DemoConnector.nodes.size());
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("targetName", "xxx.txt");
parameters.put("copyCount", 2);
parameters.put("targetConnectorId", "demo");
parameters.put("targetFolderId", "/minutes");
cycleService.executeParameterizedAction("demo", file1.getNodeId(), CopyArtifactAction.class.getName(), parameters);
List<RepositoryNode> nodes = DemoConnector.nodes;
assertEquals(8, DemoConnector.nodes.size());
childNodes = cycleService.getChildren("demo", folder1.getNodeId()).asList();
assertEquals(4, childNodes.size());
assertEquals("/minutes/20100701-KickOffMeeting.txt", childNodes.get(0).getNodeId());
assertEquals("/minutes/InitialMindmap.mm", childNodes.get(1).getNodeId());
assertEquals("/minutes/xxx.txt0", childNodes.get(2).getNodeId());
assertEquals("xxx.txt0", childNodes.get(2).getMetadata().getName());
assertEquals("/minutes/xxx.txt1", childNodes.get(3).getNodeId());
assertEquals("xxx.txt1", childNodes.get(3).getMetadata().getName());
}
| public void testFirstPlay() throws Exception {
// create demo connector but accessed via the customized view connector
ConfigurationContainer configurationContainer = new ConfigurationContainer("bernd");
RepositoryConnectorConfiguration configuration = new DemoConnectorConfiguration("demo");
configurationContainer.addRepositoryConnectorConfiguration(configuration);
CycleService cycleService = new CycleServiceImpl(configurationContainer.getConnectorList());
// TODO: Correct user / password handling!!!!
cycleService.login("bernd", "bernd");
List<RepositoryNode> childNodes = cycleService.getChildren("demo", "/").asList();
// assertEquals(1, childNodes.size());
// assertEquals("demo", childNodes.get(0).getCurrentPath());
// childNodes = cycleService.getChildren("demo", "/").asList();
assertEquals(2, childNodes.size());
assertTrue(childNodes.get(0) instanceof RepositoryFolder);
RepositoryFolder folder1 = (RepositoryFolder) childNodes.get(0);
assertEquals("/minutes", folder1.getNodeId());
// assertEquals("http://localhost:8080/activiti-cycle/demo/minutes",
// folder1.getClientUrl());
assertTrue(childNodes.get(1) instanceof RepositoryFolder);
RepositoryFolder folder2 = (RepositoryFolder) childNodes.get(1);
assertEquals("/BPMN", folder2.getNodeId());
// check sub elements of folder 1
childNodes = cycleService.getChildren("demo", folder1.getNodeId()).asList();
assertEquals(2, childNodes.size());
RepositoryArtifact file1 = (RepositoryArtifact) childNodes.get(0);
assertEquals("/minutes/20100701-KickOffMeeting.txt", file1.getNodeId());
RepositoryArtifact file2 = (RepositoryArtifact) childNodes.get(1);
assertEquals("/minutes/InitialMindmap.mm", file2.getNodeId());
// check sub elements of folder 2
childNodes = cycleService.getChildren("demo", folder2.getNodeId()).asList();
assertEquals(1, childNodes.size());
RepositoryFolder folder3 = (RepositoryFolder) childNodes.get(0);
assertEquals("/BPMN/Level3", folder3.getNodeId());
childNodes = cycleService.getChildren("demo", folder3.getNodeId()).asList();
assertEquals(1, childNodes.size());
RepositoryArtifact file3 = (RepositoryArtifact) childNodes.get(0);
assertEquals("/BPMN/Level3/InitialBpmnModel", file3.getNodeId());
assertEquals("InitialBpmnModel", file3.getMetadata().getName());
assertEquals("/BPMN/Level3", file3.getMetadata().setParentFolderId());
//
// System.out.println(folder2.getId() + " -> " + folder2.getClientUrl());
// System.out.println(folder3.getId() + " -> " + folder3.getClientUrl());
// System.out.println(file3.getId() + " -> " + file3.getClientUrl());
//
Collection<ContentRepresentation> contentRepresentations = file3.getArtifactType().getContentRepresentations();
for (ContentRepresentation contentRepresentation : contentRepresentations) {
Content content = cycleService.getContent("demo", file3.getNodeId(), contentRepresentation.getId());
assertNotNull(content);
assertNotNull(content.asByteArray());
}
assertEquals(6, DemoConnector.nodes.size());
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("targetName", "xxx.txt");
parameters.put("copyCount", 2);
parameters.put("targetConnectorId", "demo");
parameters.put("targetFolderId", "/minutes");
cycleService.executeParameterizedAction("demo", file1.getNodeId(), new CopyArtifactAction().getId(), parameters);
List<RepositoryNode> nodes = DemoConnector.nodes;
assertEquals(8, DemoConnector.nodes.size());
childNodes = cycleService.getChildren("demo", folder1.getNodeId()).asList();
assertEquals(4, childNodes.size());
assertEquals("/minutes/20100701-KickOffMeeting.txt", childNodes.get(0).getNodeId());
assertEquals("/minutes/InitialMindmap.mm", childNodes.get(1).getNodeId());
assertEquals("/minutes/xxx.txt0", childNodes.get(2).getNodeId());
assertEquals("xxx.txt0", childNodes.get(2).getMetadata().getName());
assertEquals("/minutes/xxx.txt1", childNodes.get(3).getNodeId());
assertEquals("xxx.txt1", childNodes.get(3).getMetadata().getName());
}
|
diff --git a/src/java/net/sf/picard/sam/MergeSamFiles.java b/src/java/net/sf/picard/sam/MergeSamFiles.java
index 36e5c532..cf5ee1c6 100644
--- a/src/java/net/sf/picard/sam/MergeSamFiles.java
+++ b/src/java/net/sf/picard/sam/MergeSamFiles.java
@@ -1,228 +1,225 @@
/*
* The MIT License
*
* Copyright (c) 2009 The Broad Institute
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package net.sf.picard.sam;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import net.sf.picard.cmdline.CommandLineProgram;
import net.sf.picard.cmdline.Option;
import net.sf.picard.cmdline.Usage;
import net.sf.picard.cmdline.StandardOptionDefinitions;
import net.sf.picard.io.IoUtil;
import net.sf.picard.util.Log;
import net.sf.picard.PicardException;
import net.sf.samtools.*;
/**
* Reads a SAM or BAM file and combines the output to one file
*
* @author Tim Fennell
*/
public class MergeSamFiles extends CommandLineProgram {
private static final Log log = Log.getInstance(MergeSamFiles.class);
// Usage and parameters
@Usage
public String USAGE = "Merges multiple SAM/BAM files into one file.\n";
@Option(shortName="I", doc="SAM or BAM input file", minElements=1)
public List<File> INPUT = new ArrayList<File>();
@Option(shortName="O", doc="SAM or BAM file to write merged result to")
public File OUTPUT;
@Option(shortName=StandardOptionDefinitions.SORT_ORDER_SHORT_NAME, doc="Sort order of output file", optional=true)
public SAMFileHeader.SortOrder SORT_ORDER = SAMFileHeader.SortOrder.coordinate;
@Option(doc="If true, assume that the input files are in the same sort order as the requested output sort order, even if their headers say otherwise.",
shortName = StandardOptionDefinitions.ASSUME_SORTED_SHORT_NAME)
public boolean ASSUME_SORTED = false;
@Option(shortName="MSD", doc="Merge the seqeunce dictionaries", optional=true)
public boolean MERGE_SEQUENCE_DICTIONARIES = false;
@Option(doc="Option to enable a simple two-thread producer consumer version of the merge algorithm that " +
"uses one thread to read and merge the records from the input files and another thread to encode, " +
"compress and write to disk the output file. The threaded version uses about 20% more CPU and decreases " +
"runtime by ~20% when writing out a compressed BAM file.")
public boolean USE_THREADING = false;
@Option(doc="Comment(s) to include in the merged output file's header.", optional=true, shortName="CO")
public List<String> COMMENT = new ArrayList<String>();
private static final int PROGRESS_INTERVAL = 1000000;
/** Required main method implementation. */
public static void main(final String[] argv) {
System.exit(new MergeSamFiles().instanceMain(argv));
}
/** Combines multiple SAM/BAM files into one. */
@Override
protected int doWork() {
boolean matchedSortOrders = true;
// Open the files for reading and writing
final List<SAMFileReader> readers = new ArrayList<SAMFileReader>();
final List<SAMFileHeader> headers = new ArrayList<SAMFileHeader>();
{
SAMSequenceDictionary dict = null; // Used to try and reduce redundant SDs in memory
for (final File inFile : INPUT) {
IoUtil.assertFileIsReadable(inFile);
final SAMFileReader in = new SAMFileReader(inFile);
readers.add(in);
headers.add(in.getFileHeader());
// A slightly hackish attempt to keep memory consumption down when merging multiple files with
// large sequence dictionaries (10,000s of sequences). If the dictionaries are identical, then
// replace the duplicate copies with a single dictionary to reduce the memory footprint.
if (dict == null) {
dict = in.getFileHeader().getSequenceDictionary();
}
else if (dict.equals(in.getFileHeader().getSequenceDictionary())) {
in.getFileHeader().setSequenceDictionary(dict);
}
matchedSortOrders = matchedSortOrders && in.getFileHeader().getSortOrder() == SORT_ORDER;
}
}
// If all the input sort orders match the output sort order then just merge them and
// write on the fly, otherwise setup to merge and sort before writing out the final file
IoUtil.assertFileIsWritable(OUTPUT);
- final MergingSamRecordIterator iterator;
- final SAMFileWriter out;
+ final boolean presorted;
+ final SAMFileHeader.SortOrder headerMergerSortOrder;
+ final boolean mergingSamRecordIteratorAssumeSorted;
if (matchedSortOrders || SORT_ORDER == SAMFileHeader.SortOrder.unsorted || ASSUME_SORTED) {
log.info("Input files are in same order as output so sorting to temp directory is not needed.");
- final SamFileHeaderMerger headerMerger = new SamFileHeaderMerger(SORT_ORDER, headers, MERGE_SEQUENCE_DICTIONARIES);
- iterator = new MergingSamRecordIterator(headerMerger, readers, ASSUME_SORTED);
- final SAMFileHeader header = headerMerger.getMergedHeader();
- for (String comment : COMMENT) {
- header.addComment(comment);
- }
- out = new SAMFileWriterFactory().makeSAMOrBAMWriter(header, true, OUTPUT);
+ headerMergerSortOrder = SORT_ORDER;
+ mergingSamRecordIteratorAssumeSorted = ASSUME_SORTED;
+ presorted = true;
}
else {
log.info("Sorting input files using temp directory " + TMP_DIR);
- final SamFileHeaderMerger headerMerger = new SamFileHeaderMerger(SAMFileHeader.SortOrder.unsorted,
- headers,
- MERGE_SEQUENCE_DICTIONARIES);
- iterator = new MergingSamRecordIterator(headerMerger, readers, false);
- final SAMFileHeader header = headerMerger.getMergedHeader();
- header.setSortOrder(SORT_ORDER);
- for (String comment : COMMENT) {
- header.addComment(comment);
- }
- out = new SAMFileWriterFactory().makeSAMOrBAMWriter(header, false, OUTPUT);
+ headerMergerSortOrder = SAMFileHeader.SortOrder.unsorted;
+ mergingSamRecordIteratorAssumeSorted = false;
+ presorted = false;
+ }
+ final SamFileHeaderMerger headerMerger = new SamFileHeaderMerger(headerMergerSortOrder, headers, MERGE_SEQUENCE_DICTIONARIES);
+ final MergingSamRecordIterator iterator = new MergingSamRecordIterator(headerMerger, readers, mergingSamRecordIteratorAssumeSorted);
+ final SAMFileHeader header = headerMerger.getMergedHeader();
+ for (String comment : COMMENT) {
+ header.addComment(comment);
}
+ final SAMFileWriter out = new SAMFileWriterFactory().makeSAMOrBAMWriter(header, presorted, OUTPUT);
// Lastly loop through and write out the records
if (USE_THREADING) {
final BlockingQueue<SAMRecord> queue = new ArrayBlockingQueue<SAMRecord>(10000);
final AtomicBoolean producerSuccceeded = new AtomicBoolean(false);
final AtomicBoolean consumerSuccceeded = new AtomicBoolean(false);
Runnable producer = new Runnable() {
public void run() {
try {
while (iterator.hasNext()) {
queue.put(iterator.next());
}
producerSuccceeded.set(true);
}
catch (InterruptedException ie) {
throw new PicardException("Interrupted reading SAMRecord to merge.", ie);
}
}
};
Runnable consumer = new Runnable() {
public void run() {
try {
long i = 0;
SAMRecord rec = null;
while ((rec = queue.poll(15, TimeUnit.SECONDS)) != null) {
out.addAlignment(rec);
if (++i % PROGRESS_INTERVAL == 0) log.info(i + " records processed.");
}
consumerSuccceeded.set(true);
}
catch (InterruptedException ie) {
throw new PicardException("Interrupted writing SAMRecord to output file.", ie);
}
}
};
Thread producerThread = new Thread(producer);
Thread consumerThread = new Thread(consumer);
producerThread.start();
consumerThread.start();
try {
consumerThread.join();
producerThread.join();
}
catch (InterruptedException ie) {
throw new PicardException("Interrupted while waiting for threads to finished writing.", ie);
}
if (!producerSuccceeded.get()) {
throw new PicardException("Error reading or merging inputs.");
}
if (!consumerSuccceeded.get()) {
throw new PicardException("Error writing output");
}
}
else {
for (long numRecords = 1; iterator.hasNext(); ++numRecords) {
final SAMRecord record = iterator.next();
out.addAlignment(record);
if (numRecords % PROGRESS_INTERVAL == 0) {
log.info(numRecords + " records read.");
}
}
}
log.info("Finished reading inputs.");
out.close();
return 0;
}
@Override
protected String[] customCommandLineValidation() {
if (CREATE_INDEX && SORT_ORDER != SAMFileHeader.SortOrder.coordinate) {
return new String[]{"Can't CREATE_INDEX unless SORT_ORDER is coordinate"};
}
return null;
}
}
| false | true | protected int doWork() {
boolean matchedSortOrders = true;
// Open the files for reading and writing
final List<SAMFileReader> readers = new ArrayList<SAMFileReader>();
final List<SAMFileHeader> headers = new ArrayList<SAMFileHeader>();
{
SAMSequenceDictionary dict = null; // Used to try and reduce redundant SDs in memory
for (final File inFile : INPUT) {
IoUtil.assertFileIsReadable(inFile);
final SAMFileReader in = new SAMFileReader(inFile);
readers.add(in);
headers.add(in.getFileHeader());
// A slightly hackish attempt to keep memory consumption down when merging multiple files with
// large sequence dictionaries (10,000s of sequences). If the dictionaries are identical, then
// replace the duplicate copies with a single dictionary to reduce the memory footprint.
if (dict == null) {
dict = in.getFileHeader().getSequenceDictionary();
}
else if (dict.equals(in.getFileHeader().getSequenceDictionary())) {
in.getFileHeader().setSequenceDictionary(dict);
}
matchedSortOrders = matchedSortOrders && in.getFileHeader().getSortOrder() == SORT_ORDER;
}
}
// If all the input sort orders match the output sort order then just merge them and
// write on the fly, otherwise setup to merge and sort before writing out the final file
IoUtil.assertFileIsWritable(OUTPUT);
final MergingSamRecordIterator iterator;
final SAMFileWriter out;
if (matchedSortOrders || SORT_ORDER == SAMFileHeader.SortOrder.unsorted || ASSUME_SORTED) {
log.info("Input files are in same order as output so sorting to temp directory is not needed.");
final SamFileHeaderMerger headerMerger = new SamFileHeaderMerger(SORT_ORDER, headers, MERGE_SEQUENCE_DICTIONARIES);
iterator = new MergingSamRecordIterator(headerMerger, readers, ASSUME_SORTED);
final SAMFileHeader header = headerMerger.getMergedHeader();
for (String comment : COMMENT) {
header.addComment(comment);
}
out = new SAMFileWriterFactory().makeSAMOrBAMWriter(header, true, OUTPUT);
}
else {
log.info("Sorting input files using temp directory " + TMP_DIR);
final SamFileHeaderMerger headerMerger = new SamFileHeaderMerger(SAMFileHeader.SortOrder.unsorted,
headers,
MERGE_SEQUENCE_DICTIONARIES);
iterator = new MergingSamRecordIterator(headerMerger, readers, false);
final SAMFileHeader header = headerMerger.getMergedHeader();
header.setSortOrder(SORT_ORDER);
for (String comment : COMMENT) {
header.addComment(comment);
}
out = new SAMFileWriterFactory().makeSAMOrBAMWriter(header, false, OUTPUT);
}
// Lastly loop through and write out the records
if (USE_THREADING) {
final BlockingQueue<SAMRecord> queue = new ArrayBlockingQueue<SAMRecord>(10000);
final AtomicBoolean producerSuccceeded = new AtomicBoolean(false);
final AtomicBoolean consumerSuccceeded = new AtomicBoolean(false);
Runnable producer = new Runnable() {
public void run() {
try {
while (iterator.hasNext()) {
queue.put(iterator.next());
}
producerSuccceeded.set(true);
}
catch (InterruptedException ie) {
throw new PicardException("Interrupted reading SAMRecord to merge.", ie);
}
}
};
Runnable consumer = new Runnable() {
public void run() {
try {
long i = 0;
SAMRecord rec = null;
while ((rec = queue.poll(15, TimeUnit.SECONDS)) != null) {
out.addAlignment(rec);
if (++i % PROGRESS_INTERVAL == 0) log.info(i + " records processed.");
}
consumerSuccceeded.set(true);
}
catch (InterruptedException ie) {
throw new PicardException("Interrupted writing SAMRecord to output file.", ie);
}
}
};
Thread producerThread = new Thread(producer);
Thread consumerThread = new Thread(consumer);
producerThread.start();
consumerThread.start();
try {
consumerThread.join();
producerThread.join();
}
catch (InterruptedException ie) {
throw new PicardException("Interrupted while waiting for threads to finished writing.", ie);
}
if (!producerSuccceeded.get()) {
throw new PicardException("Error reading or merging inputs.");
}
if (!consumerSuccceeded.get()) {
throw new PicardException("Error writing output");
}
}
else {
for (long numRecords = 1; iterator.hasNext(); ++numRecords) {
final SAMRecord record = iterator.next();
out.addAlignment(record);
if (numRecords % PROGRESS_INTERVAL == 0) {
log.info(numRecords + " records read.");
}
}
}
log.info("Finished reading inputs.");
out.close();
return 0;
}
| protected int doWork() {
boolean matchedSortOrders = true;
// Open the files for reading and writing
final List<SAMFileReader> readers = new ArrayList<SAMFileReader>();
final List<SAMFileHeader> headers = new ArrayList<SAMFileHeader>();
{
SAMSequenceDictionary dict = null; // Used to try and reduce redundant SDs in memory
for (final File inFile : INPUT) {
IoUtil.assertFileIsReadable(inFile);
final SAMFileReader in = new SAMFileReader(inFile);
readers.add(in);
headers.add(in.getFileHeader());
// A slightly hackish attempt to keep memory consumption down when merging multiple files with
// large sequence dictionaries (10,000s of sequences). If the dictionaries are identical, then
// replace the duplicate copies with a single dictionary to reduce the memory footprint.
if (dict == null) {
dict = in.getFileHeader().getSequenceDictionary();
}
else if (dict.equals(in.getFileHeader().getSequenceDictionary())) {
in.getFileHeader().setSequenceDictionary(dict);
}
matchedSortOrders = matchedSortOrders && in.getFileHeader().getSortOrder() == SORT_ORDER;
}
}
// If all the input sort orders match the output sort order then just merge them and
// write on the fly, otherwise setup to merge and sort before writing out the final file
IoUtil.assertFileIsWritable(OUTPUT);
final boolean presorted;
final SAMFileHeader.SortOrder headerMergerSortOrder;
final boolean mergingSamRecordIteratorAssumeSorted;
if (matchedSortOrders || SORT_ORDER == SAMFileHeader.SortOrder.unsorted || ASSUME_SORTED) {
log.info("Input files are in same order as output so sorting to temp directory is not needed.");
headerMergerSortOrder = SORT_ORDER;
mergingSamRecordIteratorAssumeSorted = ASSUME_SORTED;
presorted = true;
}
else {
log.info("Sorting input files using temp directory " + TMP_DIR);
headerMergerSortOrder = SAMFileHeader.SortOrder.unsorted;
mergingSamRecordIteratorAssumeSorted = false;
presorted = false;
}
final SamFileHeaderMerger headerMerger = new SamFileHeaderMerger(headerMergerSortOrder, headers, MERGE_SEQUENCE_DICTIONARIES);
final MergingSamRecordIterator iterator = new MergingSamRecordIterator(headerMerger, readers, mergingSamRecordIteratorAssumeSorted);
final SAMFileHeader header = headerMerger.getMergedHeader();
for (String comment : COMMENT) {
header.addComment(comment);
}
final SAMFileWriter out = new SAMFileWriterFactory().makeSAMOrBAMWriter(header, presorted, OUTPUT);
// Lastly loop through and write out the records
if (USE_THREADING) {
final BlockingQueue<SAMRecord> queue = new ArrayBlockingQueue<SAMRecord>(10000);
final AtomicBoolean producerSuccceeded = new AtomicBoolean(false);
final AtomicBoolean consumerSuccceeded = new AtomicBoolean(false);
Runnable producer = new Runnable() {
public void run() {
try {
while (iterator.hasNext()) {
queue.put(iterator.next());
}
producerSuccceeded.set(true);
}
catch (InterruptedException ie) {
throw new PicardException("Interrupted reading SAMRecord to merge.", ie);
}
}
};
Runnable consumer = new Runnable() {
public void run() {
try {
long i = 0;
SAMRecord rec = null;
while ((rec = queue.poll(15, TimeUnit.SECONDS)) != null) {
out.addAlignment(rec);
if (++i % PROGRESS_INTERVAL == 0) log.info(i + " records processed.");
}
consumerSuccceeded.set(true);
}
catch (InterruptedException ie) {
throw new PicardException("Interrupted writing SAMRecord to output file.", ie);
}
}
};
Thread producerThread = new Thread(producer);
Thread consumerThread = new Thread(consumer);
producerThread.start();
consumerThread.start();
try {
consumerThread.join();
producerThread.join();
}
catch (InterruptedException ie) {
throw new PicardException("Interrupted while waiting for threads to finished writing.", ie);
}
if (!producerSuccceeded.get()) {
throw new PicardException("Error reading or merging inputs.");
}
if (!consumerSuccceeded.get()) {
throw new PicardException("Error writing output");
}
}
else {
for (long numRecords = 1; iterator.hasNext(); ++numRecords) {
final SAMRecord record = iterator.next();
out.addAlignment(record);
if (numRecords % PROGRESS_INTERVAL == 0) {
log.info(numRecords + " records read.");
}
}
}
log.info("Finished reading inputs.");
out.close();
return 0;
}
|
diff --git a/TFC_Shared/src/TFC/TFCItems.java b/TFC_Shared/src/TFC/TFCItems.java
index be84fe8a0..1a3ee9575 100644
--- a/TFC_Shared/src/TFC/TFCItems.java
+++ b/TFC_Shared/src/TFC/TFCItems.java
@@ -1,2023 +1,2023 @@
package TFC;
import java.io.File;
import net.minecraft.block.Block;
import net.minecraft.item.EnumArmorMaterial;
import net.minecraft.item.EnumToolMaterial;
import net.minecraft.item.Item;
import net.minecraft.item.ItemColored;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
import net.minecraftforge.common.Configuration;
import net.minecraftforge.common.EnumHelper;
import TFC.Core.Recipes;
import TFC.Core.TFCTabs;
import TFC.Core.TFC_Settings;
import TFC.Enums.EnumMetalType;
import TFC.Enums.EnumSize;
import TFC.Food.ItemMeal;
import TFC.Food.ItemTerraFood;
import TFC.Items.ItemBellows;
import TFC.Items.ItemBlueprint;
import TFC.Items.ItemCustomArmor;
import TFC.Items.ItemCustomMinecart;
import TFC.Items.ItemCustomPotion;
import TFC.Items.ItemCustomSeeds;
import TFC.Items.ItemDyeCustom;
import TFC.Items.ItemFlatLeather;
import TFC.Items.ItemFlatRock;
import TFC.Items.ItemFruitTreeSapling;
import TFC.Items.ItemGem;
import TFC.Items.ItemIngot;
import TFC.Items.ItemLogs;
import TFC.Items.ItemLooseRock;
import TFC.Items.ItemMeltedMetal;
import TFC.Items.ItemMetalSheet;
import TFC.Items.ItemMetalSheet2x;
import TFC.Items.ItemOre;
import TFC.Items.ItemOreSmall;
import TFC.Items.ItemPlank;
import TFC.Items.ItemSluice;
import TFC.Items.ItemStick;
import TFC.Items.ItemStoneBrick;
import TFC.Items.ItemTerra;
import TFC.Items.ItemUnfinishedArmor;
import TFC.Items.ItemBlocks.ItemWoodDoor;
import TFC.Items.Pottery.ItemPotteryBase;
import TFC.Items.Pottery.ItemPotteryJug;
import TFC.Items.Pottery.ItemPotteryLargeVessel;
import TFC.Items.Pottery.ItemPotteryPot;
import TFC.Items.Tools.ItemChisel;
import TFC.Items.Tools.ItemCustomAxe;
import TFC.Items.Tools.ItemCustomBlueSteelBucket;
import TFC.Items.Tools.ItemCustomBow;
import TFC.Items.Tools.ItemCustomBucket;
import TFC.Items.Tools.ItemCustomBucketMilk;
import TFC.Items.Tools.ItemCustomHoe;
import TFC.Items.Tools.ItemCustomKnife;
import TFC.Items.Tools.ItemCustomPickaxe;
import TFC.Items.Tools.ItemCustomRedSteelBucket;
import TFC.Items.Tools.ItemCustomSaw;
import TFC.Items.Tools.ItemCustomScythe;
import TFC.Items.Tools.ItemCustomShovel;
import TFC.Items.Tools.ItemCustomSword;
import TFC.Items.Tools.ItemFirestarter;
import TFC.Items.Tools.ItemFlintSteel;
import TFC.Items.Tools.ItemGoldPan;
import TFC.Items.Tools.ItemHammer;
import TFC.Items.Tools.ItemJavelin;
import TFC.Items.Tools.ItemMiscToolHead;
import TFC.Items.Tools.ItemPlan;
import TFC.Items.Tools.ItemProPick;
import TFC.Items.Tools.ItemSpindle;
import TFC.Items.Tools.ItemWritableBookTFC;
public class TFCItems
{
public static Item GemRuby;
public static Item GemSapphire;
public static Item GemEmerald;
public static Item GemTopaz;
public static Item GemGarnet;
public static Item GemOpal;
public static Item GemAmethyst;
public static Item GemJasper;
public static Item GemBeryl;
public static Item GemTourmaline;
public static Item GemJade;
public static Item GemAgate;
public static Item GemDiamond;
public static Item SulfurPowder;
public static Item SaltpeterPowder;
public static Item BismuthIngot;
public static Item BismuthBronzeIngot;
public static Item BlackBronzeIngot;
public static Item BlackSteelIngot;
public static Item HCBlackSteelIngot;
public static Item BlueSteelIngot;
public static Item WeakBlueSteelIngot;
public static Item HCBlueSteelIngot;
public static Item BrassIngot;
public static Item BronzeIngot;
public static Item CopperIngot;
public static Item GoldIngot;
public static Item WroughtIronIngot;
public static Item LeadIngot;
public static Item NickelIngot;
public static Item PigIronIngot;
public static Item PlatinumIngot;
public static Item RedSteelIngot;
public static Item WeakRedSteelIngot;
public static Item HCRedSteelIngot;
public static Item RoseGoldIngot;
public static Item SilverIngot;
public static Item SteelIngot;
public static Item WeakSteelIngot;
public static Item HCSteelIngot;
public static Item SterlingSilverIngot;
public static Item TinIngot;
public static Item ZincIngot;
public static Item BismuthIngot2x;
public static Item BismuthBronzeIngot2x;
public static Item BlackBronzeIngot2x;
public static Item BlackSteelIngot2x;
public static Item BlueSteelIngot2x;
public static Item BrassIngot2x;
public static Item BronzeIngot2x;
public static Item CopperIngot2x;
public static Item GoldIngot2x;
public static Item WroughtIronIngot2x;
public static Item LeadIngot2x;
public static Item NickelIngot2x;
public static Item PigIronIngot2x;
public static Item PlatinumIngot2x;
public static Item RedSteelIngot2x;
public static Item RoseGoldIngot2x;
public static Item SilverIngot2x;
public static Item SteelIngot2x;
public static Item SterlingSilverIngot2x;
public static Item TinIngot2x;
public static Item ZincIngot2x;
public static Item IgInShovel;
public static Item IgInAxe;
public static Item IgInHoe;
public static Item SedShovel;
public static Item SedAxe;
public static Item SedHoe;
public static Item IgExShovel;
public static Item IgExAxe;
public static Item IgExHoe;
public static Item MMShovel;
public static Item MMAxe;
public static Item MMHoe;
public static Item BismuthPick;
public static Item BismuthShovel;
public static Item BismuthAxe;
public static Item BismuthHoe;
public static Item BismuthBronzePick;
public static Item BismuthBronzeShovel;
public static Item BismuthBronzeAxe;
public static Item BismuthBronzeHoe;
public static Item BlackBronzePick;
public static Item BlackBronzeShovel;
public static Item BlackBronzeAxe;
public static Item BlackBronzeHoe;
public static Item BlackSteelPick;
public static Item BlackSteelShovel;
public static Item BlackSteelAxe;
public static Item BlackSteelHoe;
public static Item BlueSteelPick;
public static Item BlueSteelShovel;
public static Item BlueSteelAxe;
public static Item BlueSteelHoe;
public static Item BronzePick;
public static Item BronzeShovel;
public static Item BronzeAxe;
public static Item BronzeHoe;
public static Item CopperPick;
public static Item CopperShovel;
public static Item CopperAxe;
public static Item CopperHoe;
public static Item WroughtIronPick;
public static Item WroughtIronShovel;
public static Item WroughtIronAxe;
public static Item WroughtIronHoe;
public static Item RedSteelPick;
public static Item RedSteelShovel;
public static Item RedSteelAxe;
public static Item RedSteelHoe;
public static Item RoseGoldPick;
public static Item RoseGoldShovel;
public static Item RoseGoldAxe;
public static Item RoseGoldHoe;
public static Item SteelPick;
public static Item SteelShovel;
public static Item SteelAxe;
public static Item SteelHoe;
public static Item TinPick;
public static Item TinShovel;
public static Item TinAxe;
public static Item TinHoe;
public static Item ZincPick;
public static Item ZincShovel;
public static Item ZincAxe;
public static Item ZincHoe;
public static Item StoneChisel;
public static Item BismuthChisel;
public static Item BismuthBronzeChisel;
public static Item BlackBronzeChisel;
public static Item BlackSteelChisel;
public static Item BlueSteelChisel;
public static Item BronzeChisel;
public static Item CopperChisel;
public static Item WroughtIronChisel;
public static Item RedSteelChisel;
public static Item RoseGoldChisel;
public static Item SteelChisel;
public static Item TinChisel;
public static Item ZincChisel;
public static Item IgInStoneSword;
public static Item IgExStoneSword;
public static Item SedStoneSword;
public static Item MMStoneSword;
public static Item BismuthSword;
public static Item BismuthBronzeSword;
public static Item BlackBronzeSword;
public static Item BlackSteelSword;
public static Item BlueSteelSword;
public static Item BronzeSword;
public static Item CopperSword;
public static Item WroughtIronSword;
public static Item RedSteelSword;
public static Item RoseGoldSword;
public static Item SteelSword;
public static Item TinSword;
public static Item ZincSword;
public static Item IgInStoneMace;
public static Item IgExStoneMace;
public static Item SedStoneMace;
public static Item MMStoneMace;
public static Item BismuthMace;
public static Item BismuthBronzeMace;
public static Item BlackBronzeMace;
public static Item BlackSteelMace;
public static Item BlueSteelMace;
public static Item BronzeMace;
public static Item CopperMace;
public static Item WroughtIronMace;
public static Item RedSteelMace;
public static Item RoseGoldMace;
public static Item SteelMace;
public static Item TinMace;
public static Item ZincMace;
public static Item BismuthSaw;
public static Item BismuthBronzeSaw;
public static Item BlackBronzeSaw;
public static Item BlackSteelSaw;
public static Item BlueSteelSaw;
public static Item BronzeSaw;
public static Item CopperSaw;
public static Item WroughtIronSaw;
public static Item RedSteelSaw;
public static Item RoseGoldSaw;
public static Item SteelSaw;
public static Item TinSaw;
public static Item ZincSaw;
public static Item OreChunk;
public static Item Logs;
public static Item Barrel;
public static Item Javelin;
public static Item BismuthScythe;
public static Item BismuthBronzeScythe;
public static Item BlackBronzeScythe;
public static Item BlackSteelScythe;
public static Item BlueSteelScythe;
public static Item BronzeScythe;
public static Item CopperScythe;
public static Item WroughtIronScythe;
public static Item RedSteelScythe;
public static Item RoseGoldScythe;
public static Item SteelScythe;
public static Item TinScythe;
public static Item ZincScythe;
public static Item BismuthKnife;
public static Item BismuthBronzeKnife;
public static Item BlackBronzeKnife;
public static Item BlackSteelKnife;
public static Item BlueSteelKnife;
public static Item BronzeKnife;
public static Item CopperKnife;
public static Item WroughtIronKnife;
public static Item RedSteelKnife;
public static Item RoseGoldKnife;
public static Item SteelKnife;
public static Item TinKnife;
public static Item ZincKnife;
public static Item FireStarter;
public static Item BellowsItem;
public static Item StoneHammer;
public static Item BismuthHammer;
public static Item BismuthBronzeHammer;
public static Item BlackBronzeHammer;
public static Item BlackSteelHammer;
public static Item BlueSteelHammer;
public static Item BronzeHammer;
public static Item CopperHammer;
public static Item WroughtIronHammer;
public static Item RedSteelHammer;
public static Item RoseGoldHammer;
public static Item SteelHammer;
public static Item TinHammer;
public static Item ZincHammer;
public static Item BismuthUnshaped;
public static Item BismuthBronzeUnshaped;
public static Item BlackBronzeUnshaped;
public static Item BlackSteelUnshaped;
public static Item HCBlackSteelUnshaped;
public static Item BlueSteelUnshaped;
public static Item WeakBlueSteelUnshaped;
public static Item HCBlueSteelUnshaped;
public static Item BrassUnshaped;
public static Item BronzeUnshaped;
public static Item CopperUnshaped;
public static Item GoldUnshaped;
public static Item WroughtIronUnshaped;
public static Item LeadUnshaped;
public static Item NickelUnshaped;
public static Item PigIronUnshaped;
public static Item PlatinumUnshaped;
public static Item RedSteelUnshaped;
public static Item WeakRedSteelUnshaped;
public static Item HCRedSteelUnshaped;
public static Item RoseGoldUnshaped;
public static Item SilverUnshaped;
public static Item SteelUnshaped;
public static Item WeakSteelUnshaped;
public static Item HCSteelUnshaped;
public static Item SterlingSilverUnshaped;
public static Item TinUnshaped;
public static Item ZincUnshaped;
public static Item ClayMold;
public static Item CeramicMold;
public static Item terraMeltedUnknown;
public static Item terraSlag;
public static Item Ink;
//Plans
public static Item PickaxeHeadPlan;
public static Item ShovelHeadPlan;
public static Item HoeHeadPlan;
public static Item AxeHeadPlan;
public static Item HammerHeadPlan;
public static Item ChiselHeadPlan;
public static Item SwordBladePlan;
public static Item MaceHeadPlan;
public static Item SawBladePlan;
public static Item ProPickHeadPlan;
public static Item HelmetPlan;
public static Item ChestplatePlan;
public static Item GreavesPlan;
public static Item BootsPlan;
public static Item ScythePlan;
public static Item KnifePlan;
public static Item BucketPlan;
//Tool Heads
public static Item BismuthPickaxeHead;
public static Item BismuthBronzePickaxeHead;
public static Item BlackBronzePickaxeHead;
public static Item BlackSteelPickaxeHead;
public static Item BlueSteelPickaxeHead;
public static Item BronzePickaxeHead;
public static Item CopperPickaxeHead;
public static Item WroughtIronPickaxeHead;
public static Item RedSteelPickaxeHead;
public static Item RoseGoldPickaxeHead;
public static Item SteelPickaxeHead;
public static Item TinPickaxeHead;
public static Item ZincPickaxeHead;
public static Item BismuthShovelHead;
public static Item BismuthBronzeShovelHead;
public static Item BlackBronzeShovelHead;
public static Item BlackSteelShovelHead;
public static Item BlueSteelShovelHead;
public static Item BronzeShovelHead;
public static Item CopperShovelHead;
public static Item WroughtIronShovelHead;
public static Item RedSteelShovelHead;
public static Item RoseGoldShovelHead;
public static Item SilverShovelHead;
public static Item SteelShovelHead;
public static Item TinShovelHead;
public static Item ZincShovelHead;
public static Item BismuthHoeHead;
public static Item BismuthBronzeHoeHead;
public static Item BlackBronzeHoeHead;
public static Item BlackSteelHoeHead;
public static Item BlueSteelHoeHead;
public static Item BronzeHoeHead;
public static Item CopperHoeHead;
public static Item WroughtIronHoeHead;
public static Item RedSteelHoeHead;
public static Item RoseGoldHoeHead;
public static Item SteelHoeHead;
public static Item TinHoeHead;
public static Item ZincHoeHead;
public static Item BismuthAxeHead;
public static Item BismuthBronzeAxeHead;
public static Item BlackBronzeAxeHead;
public static Item BlackSteelAxeHead;
public static Item BlueSteelAxeHead;
public static Item BronzeAxeHead;
public static Item CopperAxeHead;
public static Item WroughtIronAxeHead;
public static Item RedSteelAxeHead;
public static Item RoseGoldAxeHead;
public static Item SteelAxeHead;
public static Item TinAxeHead;
public static Item ZincAxeHead;
public static Item BismuthHammerHead;
public static Item BismuthBronzeHammerHead;
public static Item BlackBronzeHammerHead;
public static Item BlackSteelHammerHead;
public static Item BlueSteelHammerHead;
public static Item BronzeHammerHead;
public static Item CopperHammerHead;
public static Item WroughtIronHammerHead;
public static Item RedSteelHammerHead;
public static Item RoseGoldHammerHead;
public static Item SteelHammerHead;
public static Item TinHammerHead;
public static Item ZincHammerHead;
public static Item BismuthChiselHead;
public static Item BismuthBronzeChiselHead;
public static Item BlackBronzeChiselHead;
public static Item BlackSteelChiselHead;
public static Item BlueSteelChiselHead;
public static Item BronzeChiselHead;
public static Item CopperChiselHead;
public static Item WroughtIronChiselHead;
public static Item RedSteelChiselHead;
public static Item RoseGoldChiselHead;
public static Item SteelChiselHead;
public static Item TinChiselHead;
public static Item ZincChiselHead;
public static Item BismuthSwordHead;
public static Item BismuthBronzeSwordHead;
public static Item BlackBronzeSwordHead;
public static Item BlackSteelSwordHead;
public static Item BlueSteelSwordHead;
public static Item BronzeSwordHead;
public static Item CopperSwordHead;
public static Item WroughtIronSwordHead;
public static Item RedSteelSwordHead;
public static Item RoseGoldSwordHead;
public static Item SteelSwordHead;
public static Item TinSwordHead;
public static Item ZincSwordHead;
public static Item BismuthMaceHead;
public static Item BismuthBronzeMaceHead;
public static Item BlackBronzeMaceHead;
public static Item BlackSteelMaceHead;
public static Item BlueSteelMaceHead;
public static Item BronzeMaceHead;
public static Item CopperMaceHead;
public static Item WroughtIronMaceHead;
public static Item RedSteelMaceHead;
public static Item RoseGoldMaceHead;
public static Item SteelMaceHead;
public static Item TinMaceHead;
public static Item ZincMaceHead;
public static Item BismuthSawHead;
public static Item BismuthBronzeSawHead;
public static Item BlackBronzeSawHead;
public static Item BlackSteelSawHead;
public static Item BlueSteelSawHead;
public static Item BronzeSawHead;
public static Item CopperSawHead;
public static Item WroughtIronSawHead;
public static Item RedSteelSawHead;
public static Item RoseGoldSawHead;
public static Item SteelSawHead;
public static Item TinSawHead;
public static Item ZincSawHead;
public static Item BismuthProPickHead;
public static Item BismuthBronzeProPickHead;
public static Item BlackBronzeProPickHead;
public static Item BlackSteelProPickHead;
public static Item BlueSteelProPickHead;
public static Item BronzeProPickHead;
public static Item CopperProPickHead;
public static Item WroughtIronProPickHead;
public static Item RedSteelProPickHead;
public static Item RoseGoldProPickHead;
public static Item SteelProPickHead;
public static Item TinProPickHead;
public static Item ZincProPickHead;
public static Item BismuthScytheHead;
public static Item BismuthBronzeScytheHead;
public static Item BlackBronzeScytheHead;
public static Item BlackSteelScytheHead;
public static Item BlueSteelScytheHead;
public static Item BronzeScytheHead;
public static Item CopperScytheHead;
public static Item WroughtIronScytheHead;
public static Item RedSteelScytheHead;
public static Item RoseGoldScytheHead;
public static Item SteelScytheHead;
public static Item TinScytheHead;
public static Item ZincScytheHead;
public static Item BismuthKnifeHead;
public static Item BismuthBronzeKnifeHead;
public static Item BlackBronzeKnifeHead;
public static Item BlackSteelKnifeHead;
public static Item BlueSteelKnifeHead;
public static Item BronzeKnifeHead;
public static Item CopperKnifeHead;
public static Item WroughtIronKnifeHead;
public static Item RedSteelKnifeHead;
public static Item RoseGoldKnifeHead;
public static Item SteelKnifeHead;
public static Item TinKnifeHead;
public static Item ZincKnifeHead;
public static Item Coke;
public static Item Flux;
//Formerly TFC_Mining
public static Item GoldPan;
public static Item SluiceItem;
public static Item ProPickStone;
public static Item ProPickBismuth;
public static Item ProPickBismuthBronze;
public static Item ProPickBlackBronze;
public static Item ProPickBlackSteel;
public static Item ProPickBlueSteel;
public static Item ProPickBronze;
public static Item ProPickCopper;
public static Item ProPickIron;
public static Item ProPickRedSteel;
public static Item ProPickRoseGold;
public static Item ProPickSteel;
public static Item ProPickTin;
public static Item ProPickZinc;
/**Armor Crafting related items*/
public static Item BismuthSheet;
public static Item BismuthBronzeSheet;
public static Item BlackBronzeSheet;
public static Item BlackSteelSheet;
public static Item BlueSteelSheet;
public static Item BronzeSheet;
public static Item CopperSheet;
public static Item WroughtIronSheet;
public static Item RedSteelSheet;
public static Item RoseGoldSheet;
public static Item SteelSheet;
public static Item TinSheet;
public static Item ZincSheet;
public static Item BrassSheet;
public static Item GoldSheet;
public static Item LeadSheet;
public static Item NickelSheet;
public static Item PigIronSheet;
public static Item PlatinumSheet;
public static Item SilverSheet;
public static Item SterlingSilverSheet;
public static Item BismuthSheet2x;
public static Item BismuthBronzeSheet2x;
public static Item BlackBronzeSheet2x;
public static Item BlackSteelSheet2x;
public static Item BlueSteelSheet2x;
public static Item BronzeSheet2x;
public static Item CopperSheet2x;
public static Item WroughtIronSheet2x;
public static Item RedSteelSheet2x;
public static Item RoseGoldSheet2x;
public static Item SteelSheet2x;
public static Item TinSheet2x;
public static Item ZincSheet2x;
public static Item BrassSheet2x;
public static Item GoldSheet2x;
public static Item LeadSheet2x;
public static Item NickelSheet2x;
public static Item PigIronSheet2x;
public static Item PlatinumSheet2x;
public static Item SilverSheet2x;
public static Item SterlingSilverSheet2x;
public static Item BismuthUnfinishedChestplate;
public static Item BismuthBronzeUnfinishedChestplate;
public static Item BlackBronzeUnfinishedChestplate;
public static Item BlackSteelUnfinishedChestplate;
public static Item BlueSteelUnfinishedChestplate;
public static Item BronzeUnfinishedChestplate;
public static Item CopperUnfinishedChestplate;
public static Item WroughtIronUnfinishedChestplate;
public static Item RedSteelUnfinishedChestplate;
public static Item RoseGoldUnfinishedChestplate;
public static Item SteelUnfinishedChestplate;
public static Item TinUnfinishedChestplate;
public static Item ZincUnfinishedChestplate;
public static Item BismuthUnfinishedGreaves;
public static Item BismuthBronzeUnfinishedGreaves;
public static Item BlackBronzeUnfinishedGreaves;
public static Item BlackSteelUnfinishedGreaves;
public static Item BlueSteelUnfinishedGreaves;
public static Item BronzeUnfinishedGreaves;
public static Item CopperUnfinishedGreaves;
public static Item WroughtIronUnfinishedGreaves;
public static Item RedSteelUnfinishedGreaves;
public static Item RoseGoldUnfinishedGreaves;
public static Item SteelUnfinishedGreaves;
public static Item TinUnfinishedGreaves;
public static Item ZincUnfinishedGreaves;
public static Item BismuthUnfinishedBoots;
public static Item BismuthBronzeUnfinishedBoots;
public static Item BlackBronzeUnfinishedBoots;
public static Item BlackSteelUnfinishedBoots;
public static Item BlueSteelUnfinishedBoots;
public static Item BronzeUnfinishedBoots;
public static Item CopperUnfinishedBoots;
public static Item WroughtIronUnfinishedBoots;
public static Item RedSteelUnfinishedBoots;
public static Item RoseGoldUnfinishedBoots;
public static Item SteelUnfinishedBoots;
public static Item TinUnfinishedBoots;
public static Item ZincUnfinishedBoots;
public static Item BismuthUnfinishedHelmet;
public static Item BismuthBronzeUnfinishedHelmet;
public static Item BlackBronzeUnfinishedHelmet;
public static Item BlackSteelUnfinishedHelmet;
public static Item BlueSteelUnfinishedHelmet;
public static Item BronzeUnfinishedHelmet;
public static Item CopperUnfinishedHelmet;
public static Item WroughtIronUnfinishedHelmet;
public static Item RedSteelUnfinishedHelmet;
public static Item RoseGoldUnfinishedHelmet;
public static Item SteelUnfinishedHelmet;
public static Item TinUnfinishedHelmet;
public static Item ZincUnfinishedHelmet;
public static Item BismuthChestplate;
public static Item BismuthBronzeChestplate;
public static Item BlackBronzeChestplate;
public static Item BlackSteelChestplate;
public static Item BlueSteelChestplate;
public static Item BronzeChestplate;
public static Item CopperChestplate;
public static Item WroughtIronChestplate;
public static Item RedSteelChestplate;
public static Item RoseGoldChestplate;
public static Item SteelChestplate;
public static Item TinChestplate;
public static Item ZincChestplate;
public static Item BismuthGreaves;
public static Item BismuthBronzeGreaves;
public static Item BlackBronzeGreaves;
public static Item BlackSteelGreaves;
public static Item BlueSteelGreaves;
public static Item BronzeGreaves;
public static Item CopperGreaves;
public static Item WroughtIronGreaves;
public static Item RedSteelGreaves;
public static Item RoseGoldGreaves;
public static Item SteelGreaves;
public static Item TinGreaves;
public static Item ZincGreaves;
public static Item BismuthBoots;
public static Item BismuthBronzeBoots;
public static Item BlackBronzeBoots;
public static Item BlackSteelBoots;
public static Item BlueSteelBoots;
public static Item BronzeBoots;
public static Item CopperBoots;
public static Item WroughtIronBoots;
public static Item RedSteelBoots;
public static Item RoseGoldBoots;
public static Item SteelBoots;
public static Item TinBoots;
public static Item ZincBoots;
public static Item BismuthHelmet;
public static Item BismuthBronzeHelmet;
public static Item BlackBronzeHelmet;
public static Item BlackSteelHelmet;
public static Item BlueSteelHelmet;
public static Item BronzeHelmet;
public static Item CopperHelmet;
public static Item WroughtIronHelmet;
public static Item RedSteelHelmet;
public static Item RoseGoldHelmet;
public static Item SteelHelmet;
public static Item TinHelmet;
public static Item ZincHelmet;
public static Item WoodenBucketEmpty;
public static Item WoodenBucketWater;
public static Item WoodenBucketMilk;
/**Food Related Items and Blocks*/
public static Item SeedsWheat;
public static Item SeedsMelon;
public static Item SeedsPumpkin;
public static Item SeedsMaize;
public static Item SeedsTomato;
public static Item SeedsBarley;
public static Item SeedsRye;
public static Item SeedsOat;
public static Item SeedsRice;
public static Item SeedsPotato;
public static Item SeedsOnion;
public static Item SeedsCabbage;
public static Item SeedsGarlic;
public static Item SeedsCarrot;
public static Item SeedsSugarcane;
public static Item SeedsHemp;
public static Item SeedsYellowBellPepper;
public static Item SeedsRedBellPepper;
public static Item SeedsSoybean;
public static Item SeedsGreenbean;
public static Item SeedsSquash;
public static Item FruitTreeSapling1;
public static Item FruitTreeSapling2;
public static Item RedApple;
public static Item GreenApple;
public static Item Banana;
public static Item Orange;
public static Item Lemon;
public static Item Olive;
public static Item Cherry;
public static Item Peach;
public static Item Plum;
public static Item Egg;
public static Item EggCooked;
public static Item WheatGrain;
public static Item BarleyGrain;
public static Item OatGrain;
public static Item RyeGrain;
public static Item RiceGrain;
public static Item MaizeEar;
public static Item Tomato;
public static Item Potato;
public static Item Onion;
public static Item Cabbage;
public static Item Garlic;
public static Item Carrot;
public static Item Sugarcane;
public static Item Hemp;
public static Item Soybean;
public static Item Greenbeans;
public static Item GreenBellPepper;
public static Item YellowBellPepper;
public static Item RedBellPepper;
public static Item Squash;
public static Item WheatGround;
public static Item BarleyGround;
public static Item OatGround;
public static Item RyeGround;
public static Item RiceGround;
public static Item CornmealGround;
public static Item WheatDough;
public static Item BarleyDough;
public static Item OatDough;
public static Item RyeDough;
public static Item RiceDough;
public static Item CornmealDough;
public static Item BarleyBread;
public static Item OatBread;
public static Item RyeBread;
public static Item RiceBread;
public static Item CornBread;
public static Item WheatWhole;
public static Item BarleyWhole;
public static Item OatWhole;
public static Item RyeWhole;
public static Item RiceWhole;
public static Item LooseRock;
public static Item FlatRock;
public static Item IgInStoneShovelHead;
public static Item SedStoneShovelHead;
public static Item IgExStoneShovelHead;
public static Item MMStoneShovelHead;
public static Item IgInStoneAxeHead;
public static Item SedStoneAxeHead;
public static Item IgExStoneAxeHead;
public static Item MMStoneAxeHead;
public static Item IgInStoneHoeHead;
public static Item SedStoneHoeHead;
public static Item IgExStoneHoeHead;
public static Item MMStoneHoeHead;
public static Item StoneKnife;
public static Item StoneKnifeHead;
public static Item StoneHammerHead;
public static Item SmallOreChunk;
public static Item SinglePlank;
public static Item minecartEmpty;
public static Item minecartCrate;
public static Item RedSteelBucketEmpty;
public static Item RedSteelBucketWater;
public static Item BlueSteelBucketEmpty;
public static Item BlueSteelBucketLava;
public static Item MealGeneric;
public static Item MealMoveSpeed;
public static Item MealDigSpeed;
public static Item MealDamageBoost;
public static Item MealJump;
public static Item MealDamageResist;
public static Item MealFireResist;
public static Item MealWaterBreathing;
public static Item MealNightVision;
public static Item Quern;
public static Item FlintSteel;
public static Item DoorOak;
public static Item DoorAspen;
public static Item DoorBirch;
public static Item DoorChestnut;
public static Item DoorDouglasFir;
public static Item DoorHickory;
public static Item DoorMaple;
public static Item DoorAsh;
public static Item DoorPine;
public static Item DoorSequoia;
public static Item DoorSpruce;
public static Item DoorSycamore;
public static Item DoorWhiteCedar;
public static Item DoorWhiteElm;
public static Item DoorWillow;
public static Item DoorKapok;
public static Item Blueprint;
public static Item writabeBookTFC;
public static Item WoolYarn;
public static Item Wool;
public static Item WoolCloth;
public static Item Spindle;
public static Item ClaySpindle;
public static Item SpindleHead;
public static Item StoneBrick;
public static Item Mortar;
public static Item Limewater;
public static Item Hide;
public static Item SoakedHide;
public static Item ScrapedHide;
public static Item PrepHide;
public static Item SheepSkin;
public static Item TerraLeather;
public static Item muttonRaw;
public static Item muttonCooked;
public static Item FlatLeather;
public static Item Beer;
public static Item PotteryJug;
public static Item PotteryPot;
public static Item PotteryAmphora;
public static Item PotterySmallVessel;
public static Item PotteryLargeVessel;
public static Item KilnRack;
public static Item Straw;
/**
* Item Uses Setup
* */
public static int IgInStoneUses = 60;
public static int IgExStoneUses = 70;
public static int SedStoneUses = 50;
public static int MMStoneUses = 55;
//Tier 0
public static int BismuthUses = 300;
public static int TinUses = 290;
public static int ZincUses = 250;
//Tier 1
public static int CopperUses = 600;
//Tier 2
public static int BronzeUses = 1300;
public static int RoseGoldUses = 1140;
public static int BismuthBronzeUses = 1200;
public static int BlackBronzeUses = 1460;
//Tier 3
public static int WroughtIronUses = 2200;
//Tier 4
public static int SteelUses = 3300;
//Tier 5
public static int BlackSteelUses = 4200;
//Tier 6
public static int BlueSteelUses = 6500;
public static int RedSteelUses = 6500;
//Tier 0
public static float BismuthEff = 11;
public static float TinEff = 10.5f;
public static float ZincEff = 10;
//Tier 1
public static float CopperEff = 12;
//Tier 2
public static float BronzeEff = 15;
public static float RoseGoldEff = 13;
public static float BismuthBronzeEff = 14;
public static float BlackBronzeEff = 16;
//Tier 3
public static float WroughtIronEff = 16;
//Tier 4
public static float SteelEff = 17;
//Tier 5
public static float BlackSteelEff = 18;
//Tier 6
public static float BlueSteelEff = 21;
public static float RedSteelEff = 21;
public static EnumToolMaterial IgInToolMaterial;
public static EnumToolMaterial SedToolMaterial;
public static EnumToolMaterial IgExToolMaterial;
public static EnumToolMaterial MMToolMaterial;
public static EnumToolMaterial BismuthToolMaterial;
public static EnumToolMaterial BismuthBronzeToolMaterial;
public static EnumToolMaterial BlackBronzeToolMaterial;
public static EnumToolMaterial BlackSteelToolMaterial;
public static EnumToolMaterial BlueSteelToolMaterial;
public static EnumToolMaterial BronzeToolMaterial;
public static EnumToolMaterial CopperToolMaterial;
public static EnumToolMaterial IronToolMaterial;
public static EnumToolMaterial RedSteelToolMaterial;
public static EnumToolMaterial RoseGoldToolMaterial;
public static EnumToolMaterial SteelToolMaterial;
public static EnumToolMaterial TinToolMaterial;
public static EnumToolMaterial ZincToolMaterial;
static Configuration config;
public static void Setup()
{
try
{
config = new net.minecraftforge.common.Configuration(
new File(TerraFirmaCraft.proxy.getMinecraftDir(), "/config/TFC.cfg"));
config.load();
} catch (Exception e) {
System.out.println(new StringBuilder().append("[TFC] Error while trying to access item configuration!").toString());
config = null;
}
IgInToolMaterial = EnumHelper.addToolMaterial("IgIn", 1, IgInStoneUses, 7F, 10, 5);
SedToolMaterial = EnumHelper.addToolMaterial("Sed", 1, SedStoneUses, 6F, 10, 5);
IgExToolMaterial = EnumHelper.addToolMaterial("IgEx", 1, IgExStoneUses, 7F, 10, 5);
MMToolMaterial = EnumHelper.addToolMaterial("MM", 1, MMStoneUses, 6.5F, 10, 5);
BismuthToolMaterial = EnumHelper.addToolMaterial("Bismuth", 2, BismuthUses, BismuthEff, 65, 10);
BismuthBronzeToolMaterial = EnumHelper.addToolMaterial("BismuthBronze", 2, BismuthBronzeUses, BismuthBronzeEff, 85, 10);
BlackBronzeToolMaterial = EnumHelper.addToolMaterial("BlackBronze", 2, BlackBronzeUses, BlackBronzeEff, 100, 10);
BlackSteelToolMaterial = EnumHelper.addToolMaterial("BlackSteel", 2, BlackSteelUses, BlackSteelEff, 165, 12);
BlueSteelToolMaterial = EnumHelper.addToolMaterial("BlueSteel", 3, BlueSteelUses, BlueSteelEff, 185, 22);
BronzeToolMaterial = EnumHelper.addToolMaterial("Bronze", 2, BronzeUses, BronzeEff, 100, 13);
CopperToolMaterial = EnumHelper.addToolMaterial("Copper", 2, CopperUses, CopperEff, 85, 8);
IronToolMaterial = EnumHelper.addToolMaterial("Iron", 2, WroughtIronUses, WroughtIronEff, 135, 10);
RedSteelToolMaterial = EnumHelper.addToolMaterial("RedSteel", 3, RedSteelUses, RedSteelEff, 185, 22);
RoseGoldToolMaterial = EnumHelper.addToolMaterial("RoseGold", 2, RoseGoldUses, RoseGoldEff, 100, 20);
SteelToolMaterial = EnumHelper.addToolMaterial("Steel", 2, SteelUses, SteelEff, 150, 10);
TinToolMaterial = EnumHelper.addToolMaterial("Tin", 2, TinUses, TinEff, 65, 8);
ZincToolMaterial = EnumHelper.addToolMaterial("Zinc", 2, ZincUses, ZincEff, 65, 8);
System.out.println(new StringBuilder().append("[TFC] Loading Items").toString());
//Replace any vanilla Items here
Item.itemsList[Item.coal.itemID] = null; Item.itemsList[Item.coal.itemID] = (new TFC.Items.ItemCoal(7)).setUnlocalizedName("coal");
Item.itemsList[Item.stick.itemID] = null; Item.itemsList[Item.stick.itemID] = new ItemStick(24).setFull3D().setUnlocalizedName("stick");
Item.itemsList[Item.leather.itemID] = null; Item.itemsList[Item.leather.itemID] = new ItemTerra(Item.leather.itemID).setFull3D().setUnlocalizedName("leather");
Item.itemsList[Block.vine.blockID] = new ItemColored(Block.vine.blockID - 256, false);
minecartCrate = (new ItemCustomMinecart(TFC_Settings.getIntFor(config,"item","minecartCrate",16000), 1)).setUnlocalizedName("minecartChest");
Item.itemsList[5+256] = null; Item.itemsList[5+256] = (new ItemCustomBow(5)).setUnlocalizedName("bow");
Item.itemsList[63+256] = null; Item.itemsList[63+256] = new ItemTerra(63).setUnlocalizedName("porkchopRaw");
Item.itemsList[64+256] = null; Item.itemsList[64+256] = new ItemTerraFood(64, 35, 0.8F, true, 38).setFolder("").setUnlocalizedName("porkchopCooked");
Item.itemsList[93+256] = null; Item.itemsList[93+256] = new ItemTerra(93).setUnlocalizedName("fishRaw");
Item.itemsList[94+256] = null; Item.itemsList[94+256] = new ItemTerraFood(94, 30, 0.6F, true, 39).setFolder("").setUnlocalizedName("fishCooked");
Item.itemsList[107+256] = null; Item.itemsList[107+256] = new ItemTerra(107).setUnlocalizedName("beefRaw");
Item.itemsList[108+256] = null; Item.itemsList[108+256] = new ItemTerraFood(108, 40, 0.8F, true, 40).setFolder("").setUnlocalizedName("beefCooked");
Item.itemsList[109+256] = null; Item.itemsList[109+256] = new ItemTerra(109).setUnlocalizedName("chickenRaw");
Item.itemsList[110+256] = null; Item.itemsList[110+256] = new ItemTerraFood(110, 35, 0.6F, true, 41).setFolder("").setUnlocalizedName("chickenCooked");
Item.itemsList[41+256] = null; Item.itemsList[41+256] = (new ItemTerraFood(41, 25, 0.6F, false, 42)).setFolder("").setUnlocalizedName("bread");
Item.itemsList[88+256] = null; Item.itemsList[88+256] = (new ItemTerra(88)).setUnlocalizedName("egg");
Item.itemsList[Item.dyePowder.itemID] = null; Item.itemsList[Item.dyePowder.itemID] = new ItemDyeCustom(95).setUnlocalizedName("dyePowder");
Item.itemsList[Item.potion.itemID] = null; Item.itemsList[Item.potion.itemID] = (new ItemCustomPotion(117)).setUnlocalizedName("potion");
Item.itemsList[Block.tallGrass.blockID] = null; Item.itemsList[Block.tallGrass.blockID] = (new ItemColored(Block.tallGrass.blockID - 256, true)).setBlockNames(new String[] {"shrub", "grass", "fern"});
GoldPan = new ItemGoldPan(TFC_Settings.getIntFor(config,"item","terraGoldPan",16001)).setUnlocalizedName("GoldPan");
SluiceItem = new ItemSluice(TFC_Settings.getIntFor(config,"item","terraSluiceItem",16002)).setFolder("devices/").setUnlocalizedName("SluiceItem");
ProPickBismuth = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickBismuth",16004)).setUnlocalizedName("Bismuth ProPick").setMaxDamage(BismuthUses);
ProPickBismuthBronze = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickBismuthBronze",16005)).setUnlocalizedName("Bismuth Bronze ProPick").setMaxDamage(BismuthBronzeUses);
ProPickBlackBronze = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickBlackBronze",16006)).setUnlocalizedName("Black Bronze ProPick").setMaxDamage(BlackBronzeUses);
ProPickBlackSteel = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickBlackSteel",16007)).setUnlocalizedName("Black Steel ProPick").setMaxDamage(BlackSteelUses);
ProPickBlueSteel = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickBlueSteel",16008)).setUnlocalizedName("Blue Steel ProPick").setMaxDamage(BlueSteelUses);
ProPickBronze = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickBronze",16009)).setUnlocalizedName("Bronze ProPick").setMaxDamage(BronzeUses);
ProPickCopper = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickCopper",16010)).setUnlocalizedName("Copper ProPick").setMaxDamage(CopperUses);
ProPickIron = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickWroughtIron",16012)).setUnlocalizedName("Wrought Iron ProPick").setMaxDamage(WroughtIronUses);
ProPickRedSteel = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickRedSteel",16016)).setUnlocalizedName("Red Steel ProPick").setMaxDamage(RedSteelUses);
ProPickRoseGold = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickRoseGold",16017)).setUnlocalizedName("Rose Gold ProPick").setMaxDamage(RoseGoldUses);
ProPickSteel = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickSteel",16019)).setUnlocalizedName("Steel ProPick").setMaxDamage(SteelUses);
ProPickTin = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickTin",16021)).setUnlocalizedName("Tin ProPick").setMaxDamage(TinUses);
ProPickZinc = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickZinc",16022)).setUnlocalizedName("Zinc ProPick").setMaxDamage(ZincUses);
BismuthIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","BismuthIngot",16028), EnumMetalType.BISMUTH).setUnlocalizedName("Bismuth Ingot");
BismuthBronzeIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","BismuthBronzeIngot",16029), EnumMetalType.BISMUTHBRONZE).setUnlocalizedName("Bismuth Bronze Ingot");
BlackBronzeIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","BlackBronzeIngot",16030), EnumMetalType.BLACKBRONZE).setUnlocalizedName("Black Bronze Ingot");
BlackSteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","BlackSteelIngot",16031), EnumMetalType.BLACKSTEEL).setUnlocalizedName("Black Steel Ingot");
BlueSteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","BlueSteelIngot",16032), EnumMetalType.BLUESTEEL).setUnlocalizedName("Blue Steel Ingot");
BrassIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","BrassIngot",16033), EnumMetalType.BRASS).setUnlocalizedName("Brass Ingot");
BronzeIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","BronzeIngot",16034), EnumMetalType.BRONZE).setUnlocalizedName("Bronze Ingot");
CopperIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","CopperIngot",16035), EnumMetalType.COPPER).setUnlocalizedName("Copper Ingot");
GoldIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","GoldIngot",16036), EnumMetalType.GOLD).setUnlocalizedName("Gold Ingot");
WroughtIronIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","WroughtIronIngot",16037), EnumMetalType.WROUGHTIRON).setUnlocalizedName("Wrought Iron Ingot");
LeadIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","LeadIngot",16038), EnumMetalType.LEAD).setUnlocalizedName("Lead Ingot");
NickelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","NickelIngot",16039), EnumMetalType.NICKEL).setUnlocalizedName("Nickel Ingot");
PigIronIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","PigIronIngot",16040), EnumMetalType.PIGIRON).setUnlocalizedName("Pig Iron Ingot");
PlatinumIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","PlatinumIngot",16041), EnumMetalType.PLATINUM).setUnlocalizedName("Platinum Ingot");
RedSteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","RedSteelIngot",16042), EnumMetalType.REDSTEEL).setUnlocalizedName("Red Steel Ingot");
RoseGoldIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","RoseGoldIngot",16043), EnumMetalType.ROSEGOLD).setUnlocalizedName("Rose Gold Ingot");
SilverIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","SilverIngot",16044), EnumMetalType.SILVER).setUnlocalizedName("Silver Ingot");
SteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","SteelIngot",16045), EnumMetalType.STEEL).setUnlocalizedName("Steel Ingot");
SterlingSilverIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","SterlingSilverIngot",16046), EnumMetalType.STERLINGSILVER).setUnlocalizedName("Sterling Silver Ingot");
TinIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","TinIngot",16047), EnumMetalType.TIN).setUnlocalizedName("Tin Ingot");
ZincIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","ZincIngot",16048), EnumMetalType.ZINC).setUnlocalizedName("Zinc Ingot");
BismuthIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","BismuthIngot2x",16049), EnumMetalType.BISMUTH).setUnlocalizedName("Bismuth Double Ingot")).setSize(EnumSize.LARGE);
BismuthBronzeIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","BismuthBronzeIngot2x",16050), EnumMetalType.BISMUTHBRONZE).setUnlocalizedName("Bismuth Bronze Double Ingot")).setSize(EnumSize.LARGE);
BlackBronzeIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","BlackBronzeIngot2x",16051), EnumMetalType.BLACKBRONZE).setUnlocalizedName("Black Bronze Double Ingot")).setSize(EnumSize.LARGE);
BlackSteelIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","BlackSteelIngot2x",16052), EnumMetalType.BLACKSTEEL).setUnlocalizedName("Black Steel Double Ingot")).setSize(EnumSize.LARGE);
BlueSteelIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","BlueSteelIngot2x",16053), EnumMetalType.BLUESTEEL).setUnlocalizedName("Blue Steel Double Ingot")).setSize(EnumSize.LARGE);
BrassIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","BrassIngot2x",16054), EnumMetalType.BRASS).setUnlocalizedName("Brass Double Ingot")).setSize(EnumSize.LARGE);
BronzeIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","BronzeIngot2x",16055), EnumMetalType.BRONZE).setUnlocalizedName("Bronze Double Ingot")).setSize(EnumSize.LARGE);
CopperIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","CopperIngot2x",16056), EnumMetalType.COPPER).setUnlocalizedName("Copper Double Ingot")).setSize(EnumSize.LARGE);
GoldIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","GoldIngot2x",16057), EnumMetalType.GOLD).setUnlocalizedName("Gold Double Ingot")).setSize(EnumSize.LARGE);
WroughtIronIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","WroughtIronIngot2x",16058), EnumMetalType.WROUGHTIRON).setUnlocalizedName("Wrought Iron Double Ingot")).setSize(EnumSize.LARGE);
LeadIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","LeadIngot2x",16059), EnumMetalType.LEAD).setUnlocalizedName("Lead Double Ingot")).setSize(EnumSize.LARGE);
NickelIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","NickelIngot2x",16060), EnumMetalType.NICKEL).setUnlocalizedName("Nickel Double Ingot")).setSize(EnumSize.LARGE);
PigIronIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","PigIronIngot2x",16061), EnumMetalType.PIGIRON).setUnlocalizedName("Pig Iron Double Ingot")).setSize(EnumSize.LARGE);
PlatinumIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","PlatinumIngot2x",16062), EnumMetalType.PLATINUM).setUnlocalizedName("Platinum Double Ingot")).setSize(EnumSize.LARGE);
RedSteelIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","RedSteelIngot2x",16063), EnumMetalType.REDSTEEL).setUnlocalizedName("Red Steel Double Ingot")).setSize(EnumSize.LARGE);
RoseGoldIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","RoseGoldIngot2x",16064), EnumMetalType.ROSEGOLD).setUnlocalizedName("Rose Gold Double Ingot")).setSize(EnumSize.LARGE);
SilverIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","SilverIngot2x",16065), EnumMetalType.SILVER).setUnlocalizedName("Silver Double Ingot")).setSize(EnumSize.LARGE);
SteelIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","SteelIngot2x",16066), EnumMetalType.STEEL).setUnlocalizedName("Steel Double Ingot")).setSize(EnumSize.LARGE);
SterlingSilverIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","SterlingSilverIngot2x",16067), EnumMetalType.STERLINGSILVER).setUnlocalizedName("Sterling Silver Double Ingot")).setSize(EnumSize.LARGE);
TinIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","TinIngot2x",16068), EnumMetalType.TIN).setUnlocalizedName("Tin Double Ingot")).setSize(EnumSize.LARGE);
ZincIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","ZincIngot2x",16069), EnumMetalType.ZINC).setUnlocalizedName("Zinc Double Ingot")).setSize(EnumSize.LARGE);
SulfurPowder = new ItemTerra(TFC_Settings.getIntFor(config,"item","SulfurPowder",16070)).setUnlocalizedName("Sulfur Powder");
SaltpeterPowder = new ItemTerra(TFC_Settings.getIntFor(config,"item","SaltpeterPowder",16071)).setUnlocalizedName("Saltpeter Powder");
GemRuby = new ItemGem(TFC_Settings.getIntFor(config,"item","GemRuby",16080)).setUnlocalizedName("Ruby");
GemSapphire = new ItemGem(TFC_Settings.getIntFor(config,"item","GemSapphire",16081)).setUnlocalizedName("Sapphire");
GemEmerald = new ItemGem(TFC_Settings.getIntFor(config,"item","GemEmerald",16082)).setUnlocalizedName("Emerald");
GemTopaz = new ItemGem(TFC_Settings.getIntFor(config,"item","GemTopaz",16083)).setUnlocalizedName("Topaz");
GemTourmaline = new ItemGem(TFC_Settings.getIntFor(config,"item","GemTourmaline",16084)).setUnlocalizedName("Tourmaline");
GemJade = new ItemGem(TFC_Settings.getIntFor(config,"item","GemJade",16085)).setUnlocalizedName("Jade");
GemBeryl = new ItemGem(TFC_Settings.getIntFor(config,"item","GemBeryl",16086)).setUnlocalizedName("Beryl");
GemAgate = new ItemGem(TFC_Settings.getIntFor(config,"item","GemAgate",16087)).setUnlocalizedName("Agate");
GemOpal = new ItemGem(TFC_Settings.getIntFor(config,"item","GemOpal",16088)).setUnlocalizedName("Opal");
GemGarnet = new ItemGem(TFC_Settings.getIntFor(config,"item","GemGarnet",16089)).setUnlocalizedName("Garnet");
GemJasper = new ItemGem(TFC_Settings.getIntFor(config,"item","GemJasper",16090)).setUnlocalizedName("Jasper");
GemAmethyst = new ItemGem(TFC_Settings.getIntFor(config,"item","GemAmethyst",16091)).setUnlocalizedName("Amethyst");
GemDiamond = new ItemGem(TFC_Settings.getIntFor(config,"item","GemDiamond",16092)).setUnlocalizedName("Diamond");
//Tools
IgInShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","IgInShovel",16101),IgInToolMaterial).setUnlocalizedName("Stone Shovel").setMaxDamage(IgInStoneUses);
IgInAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","IgInAxe",16102),IgInToolMaterial).setUnlocalizedName("Stone Axe").setMaxDamage(IgInStoneUses);
IgInHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","IgInHoe",16103),IgInToolMaterial).setUnlocalizedName("Stone Hoe").setMaxDamage(IgInStoneUses);
SedShovel= new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","SedShovel",16105),SedToolMaterial).setUnlocalizedName("Stone Shovel").setMaxDamage(SedStoneUses);
SedAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","SedAxe",16106),SedToolMaterial).setUnlocalizedName("Stone Axe").setMaxDamage(SedStoneUses);
SedHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","SedHoe",16107),SedToolMaterial).setUnlocalizedName("Stone Hoe").setMaxDamage(SedStoneUses);
IgExShovel= new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","IgExShovel",16109),IgExToolMaterial).setUnlocalizedName("Stone Shovel").setMaxDamage(IgExStoneUses);
IgExAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","IgExAxe",16110),IgExToolMaterial).setUnlocalizedName("Stone Axe").setMaxDamage(IgExStoneUses);
IgExHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","IgExHoe",16111),IgExToolMaterial).setUnlocalizedName("Stone Hoe").setMaxDamage(IgExStoneUses);
MMShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","MMShovel",16113),MMToolMaterial).setUnlocalizedName("Stone Shovel").setMaxDamage(MMStoneUses);
MMAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","MMAxe",16114),MMToolMaterial).setUnlocalizedName("Stone Axe").setMaxDamage(MMStoneUses);
MMHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","MMHoe",16115),MMToolMaterial).setUnlocalizedName("Stone Hoe").setMaxDamage(MMStoneUses);
BismuthPick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","BismuthPick",16116),BismuthToolMaterial).setUnlocalizedName("Bismuth Pick").setMaxDamage(BismuthUses);
BismuthShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","BismuthShovel",16117),BismuthToolMaterial).setUnlocalizedName("Bismuth Shovel").setMaxDamage(BismuthUses);
BismuthAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","BismuthAxe",16118),BismuthToolMaterial).setUnlocalizedName("Bismuth Axe").setMaxDamage(BismuthUses);
BismuthHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","BismuthHoe",16119),BismuthToolMaterial).setUnlocalizedName("Bismuth Hoe").setMaxDamage(BismuthUses);
BismuthBronzePick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","BismuthBronzePick",16120),BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Pick").setMaxDamage(BismuthBronzeUses);
BismuthBronzeShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","BismuthBronzeShovel",16121),BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Shovel").setMaxDamage(BismuthBronzeUses);
BismuthBronzeAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","BismuthBronzeAxe",16122),BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Axe").setMaxDamage(BismuthBronzeUses);
BismuthBronzeHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","BismuthBronzeHoe",16123),BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Hoe").setMaxDamage(BismuthBronzeUses);
BlackBronzePick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","BlackBronzePick",16124),BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Pick").setMaxDamage(BlackBronzeUses);
BlackBronzeShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","BlackBronzeShovel",16125),BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Shovel").setMaxDamage(BlackBronzeUses);
BlackBronzeAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","BlackBronzeAxe",16126),BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Axe").setMaxDamage(BlackBronzeUses);
BlackBronzeHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","BlackBronzeHoe",16127),BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Hoe").setMaxDamage(BlackBronzeUses);
BlackSteelPick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","BlackSteelPick",16128),BlackSteelToolMaterial).setUnlocalizedName("Black Steel Pick").setMaxDamage(BlackSteelUses);
BlackSteelShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","BlackSteelShovel",16129),BlackSteelToolMaterial).setUnlocalizedName("Black Steel Shovel").setMaxDamage(BlackSteelUses);
BlackSteelAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","BlackSteelAxe",16130),BlackSteelToolMaterial).setUnlocalizedName("Black Steel Axe").setMaxDamage(BlackSteelUses);
BlackSteelHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","BlackSteelHoe",16131),BlackSteelToolMaterial).setUnlocalizedName("Black Steel Hoe").setMaxDamage(BlackSteelUses);
BlueSteelPick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","BlueSteelPick",16132),BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Pick").setMaxDamage(BlueSteelUses);
BlueSteelShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","BlueSteelShovel",16133),BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Shovel").setMaxDamage(BlueSteelUses);
BlueSteelAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","BlueSteelAxe",16134),BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Axe").setMaxDamage(BlueSteelUses);
BlueSteelHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","BlueSteelHoe",16135),BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Hoe").setMaxDamage(BlueSteelUses);
BronzePick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","BronzePick",16136),BronzeToolMaterial).setUnlocalizedName("Bronze Pick").setMaxDamage(BronzeUses);
BronzeShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","BronzeShovel",16137),BronzeToolMaterial).setUnlocalizedName("Bronze Shovel").setMaxDamage(BronzeUses);
BronzeAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","BronzeAxe",16138),BronzeToolMaterial).setUnlocalizedName("Bronze Axe").setMaxDamage(BronzeUses);
BronzeHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","BronzeHoe",16139),BronzeToolMaterial).setUnlocalizedName("Bronze Hoe").setMaxDamage(BronzeUses);
CopperPick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","CopperPick",16140),CopperToolMaterial).setUnlocalizedName("Copper Pick").setMaxDamage(CopperUses);
CopperShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","CopperShovel",16141),CopperToolMaterial).setUnlocalizedName("Copper Shovel").setMaxDamage(CopperUses);
CopperAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","CopperAxe",16142),CopperToolMaterial).setUnlocalizedName("Copper Axe").setMaxDamage(CopperUses);
CopperHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","CopperHoe",16143),CopperToolMaterial).setUnlocalizedName("Copper Hoe").setMaxDamage(CopperUses);
WroughtIronPick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","WroughtIronPick",16148),IronToolMaterial).setUnlocalizedName("Wrought Iron Pick").setMaxDamage(WroughtIronUses);
WroughtIronShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","WroughtIronShovel",16149),IronToolMaterial).setUnlocalizedName("Wrought Iron Shovel").setMaxDamage(WroughtIronUses);
WroughtIronAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","WroughtIronAxe",16150),IronToolMaterial).setUnlocalizedName("Wrought Iron Axe").setMaxDamage(WroughtIronUses);
WroughtIronHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","WroughtIronHoe",16151),IronToolMaterial).setUnlocalizedName("Wrought Iron Hoe").setMaxDamage(WroughtIronUses);;
RedSteelPick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","RedSteelPick",16168),RedSteelToolMaterial).setUnlocalizedName("Red Steel Pick").setMaxDamage(RedSteelUses);
RedSteelShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","RedSteelShovel",16169),RedSteelToolMaterial).setUnlocalizedName("Red Steel Shovel").setMaxDamage(RedSteelUses);
RedSteelAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","RedSteelAxe",16170),RedSteelToolMaterial).setUnlocalizedName("Red Steel Axe").setMaxDamage(RedSteelUses);
RedSteelHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","RedSteelHoe",16171),RedSteelToolMaterial).setUnlocalizedName("Red Steel Hoe").setMaxDamage(RedSteelUses);
RoseGoldPick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","RoseGoldPick",16172),RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Pick").setMaxDamage(RoseGoldUses);
RoseGoldShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","RoseGoldShovel",16173),RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Shovel").setMaxDamage(RoseGoldUses);
RoseGoldAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","RoseGoldAxe",16174),RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Axe").setMaxDamage(RoseGoldUses);
RoseGoldHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","RoseGoldHoe",16175),RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Hoe").setMaxDamage(RoseGoldUses);
SteelPick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","SteelPick",16180),SteelToolMaterial).setUnlocalizedName("Steel Pick").setMaxDamage(SteelUses);
SteelShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","SteelShovel",16181),SteelToolMaterial).setUnlocalizedName("Steel Shovel").setMaxDamage(SteelUses);
SteelAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","SteelAxe",16182),SteelToolMaterial).setUnlocalizedName("Steel Axe").setMaxDamage(SteelUses);
SteelHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","SteelHoe",16183),SteelToolMaterial).setUnlocalizedName("Steel Hoe").setMaxDamage(SteelUses);
TinPick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","TinPick",16188),TinToolMaterial).setUnlocalizedName("Tin Pick").setMaxDamage(TinUses);
TinShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","TinShovel",16189),TinToolMaterial).setUnlocalizedName("Tin Shovel").setMaxDamage(TinUses);
TinAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","TinAxe",16190),TinToolMaterial).setUnlocalizedName("Tin Axe").setMaxDamage(TinUses);
TinHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","TinHoe",16191),TinToolMaterial).setUnlocalizedName("Tin Hoe").setMaxDamage(TinUses);
ZincPick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","ZincPick",16192),ZincToolMaterial).setUnlocalizedName("Zinc Pick").setMaxDamage(ZincUses);
ZincShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","ZincShovel",16193),ZincToolMaterial).setUnlocalizedName("Zinc Shovel").setMaxDamage(ZincUses);
ZincAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","ZincAxe",16194),ZincToolMaterial).setUnlocalizedName("Zinc Axe").setMaxDamage(ZincUses);
ZincHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","ZincHoe",16195),ZincToolMaterial).setUnlocalizedName("Zinc Hoe").setMaxDamage(ZincUses);
//chisels
BismuthChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","BismuthChisel",16226),BismuthToolMaterial).setUnlocalizedName("Bismuth Chisel").setMaxDamage(BismuthUses);
BismuthBronzeChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","BismuthBronzeChisel",16227),BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Chisel").setMaxDamage(BismuthBronzeUses);
BlackBronzeChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","BlackBronzeChisel",16228),BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Chisel").setMaxDamage(BlackBronzeUses);
BlackSteelChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","BlackSteelChisel",16230),BlackSteelToolMaterial).setUnlocalizedName("Black Steel Chisel").setMaxDamage(BlackSteelUses);
BlueSteelChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","BlueSteelChisel",16231),BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Chisel").setMaxDamage(BlueSteelUses);
BronzeChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","BronzeChisel",16232),BronzeToolMaterial).setUnlocalizedName("Bronze Chisel").setMaxDamage(BronzeUses);
CopperChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","CopperChisel",16233),CopperToolMaterial).setUnlocalizedName("Copper Chisel").setMaxDamage(CopperUses);
WroughtIronChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","WroughtIronChisel",16234),IronToolMaterial).setUnlocalizedName("Wrought Iron Chisel").setMaxDamage(WroughtIronUses);
RedSteelChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","RedSteelChisel",16235),RedSteelToolMaterial).setUnlocalizedName("Red Steel Chisel").setMaxDamage(RedSteelUses);
RoseGoldChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","RoseGoldChisel",16236),RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Chisel").setMaxDamage(RoseGoldUses);
SteelChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","SteelChisel",16237),SteelToolMaterial).setUnlocalizedName("Steel Chisel").setMaxDamage(SteelUses);
TinChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","TinChisel",16238),TinToolMaterial).setUnlocalizedName("Tin Chisel").setMaxDamage(TinUses);
ZincChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","ZincChisel",16239),ZincToolMaterial).setUnlocalizedName("Zinc Chisel").setMaxDamage(ZincUses);
StoneChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","StoneChisel",16240),IgInToolMaterial).setUnlocalizedName("Stone Chisel").setMaxDamage(IgInStoneUses);
BismuthSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BismuthSword",16245),BismuthToolMaterial).setUnlocalizedName("Bismuth Sword").setMaxDamage(BismuthUses);
BismuthBronzeSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BismuthBronzeSword",16246),BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Sword").setMaxDamage(BismuthBronzeUses);
BlackBronzeSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BlackBronzeSword",16247),BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Sword").setMaxDamage(BlackBronzeUses);
BlackSteelSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BlackSteelSword",16248),BlackSteelToolMaterial).setUnlocalizedName("Black Steel Sword").setMaxDamage(BlackSteelUses);
BlueSteelSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BlueSteelSword",16249),BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Sword").setMaxDamage(BlueSteelUses);
BronzeSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BronzeSword",16250),BronzeToolMaterial).setUnlocalizedName("Bronze Sword").setMaxDamage(BronzeUses);
CopperSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","CopperSword",16251),CopperToolMaterial).setUnlocalizedName("Copper Sword").setMaxDamage(CopperUses);
WroughtIronSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","WroughtIronSword",16252),IronToolMaterial).setUnlocalizedName("Wrought Iron Sword").setMaxDamage(WroughtIronUses);
RedSteelSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","RedSteelSword",16253),RedSteelToolMaterial).setUnlocalizedName("Red Steel Sword").setMaxDamage(RedSteelUses);
RoseGoldSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","RoseGoldSword",16254),RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Sword").setMaxDamage(RoseGoldUses);
SteelSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","SteelSword",16255),SteelToolMaterial).setUnlocalizedName("Steel Sword").setMaxDamage(SteelUses);
TinSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","TinSword",16256),TinToolMaterial).setUnlocalizedName("Tin Sword").setMaxDamage(TinUses);
ZincSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","ZincSword",16257),ZincToolMaterial).setUnlocalizedName("Zinc Sword").setMaxDamage(ZincUses);
BismuthMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BismuthMace",16262),BismuthToolMaterial).setUnlocalizedName("Bismuth Mace").setMaxDamage(BismuthUses);
BismuthBronzeMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BismuthBronzeMace",16263),BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Mace").setMaxDamage(BismuthBronzeUses);
BlackBronzeMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BlackBronzeMace",16264),BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Mace").setMaxDamage(BlackBronzeUses);
BlackSteelMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BlackSteelMace",16265),BlackSteelToolMaterial).setUnlocalizedName("Black Steel Mace").setMaxDamage(BlackSteelUses);
BlueSteelMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BlueSteelMace",16266),BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Mace").setMaxDamage(BlueSteelUses);
BronzeMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BronzeMace",16267),BronzeToolMaterial).setUnlocalizedName("Bronze Mace").setMaxDamage(BronzeUses);
CopperMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","CopperMace",16268),CopperToolMaterial).setUnlocalizedName("Copper Mace").setMaxDamage(CopperUses);
WroughtIronMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","WroughtIronMace",16269),IronToolMaterial).setUnlocalizedName("Wrought Iron Mace").setMaxDamage(WroughtIronUses);
RedSteelMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","RedSteelMace",16270),RedSteelToolMaterial).setUnlocalizedName("Red Steel Mace").setMaxDamage(RedSteelUses);
RoseGoldMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","RoseGoldMace",16271),RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Mace").setMaxDamage(RoseGoldUses);
SteelMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","SteelMace",16272),SteelToolMaterial).setUnlocalizedName("Steel Mace").setMaxDamage(SteelUses);
TinMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","TinMace",16273),TinToolMaterial).setUnlocalizedName("Tin Mace").setMaxDamage(TinUses);
ZincMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","ZincMace",16274),ZincToolMaterial).setUnlocalizedName("Zinc Mace").setMaxDamage(ZincUses);
BismuthSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","BismuthSaw",16275),BismuthToolMaterial).setUnlocalizedName("Bismuth Saw").setMaxDamage(BismuthUses);
BismuthBronzeSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","BismuthBronzeSaw",16276),BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Saw").setMaxDamage(BismuthBronzeUses);
BlackBronzeSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","BlackBronzeSaw",16277),BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Saw").setMaxDamage(BlackBronzeUses);
BlackSteelSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","BlackSteelSaw",16278),BlackSteelToolMaterial).setUnlocalizedName("Black Steel Saw").setMaxDamage(BlackSteelUses);
BlueSteelSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","BlueSteelSaw",16279),BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Saw").setMaxDamage(BlueSteelUses);
BronzeSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","BronzeSaw",16280),BronzeToolMaterial).setUnlocalizedName("Bronze Saw").setMaxDamage(BronzeUses);
CopperSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","CopperSaw",16281),CopperToolMaterial).setUnlocalizedName("Copper Saw").setMaxDamage(CopperUses);
WroughtIronSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","WroughtIronSaw",16282),IronToolMaterial).setUnlocalizedName("Wrought Iron Saw").setMaxDamage(WroughtIronUses);
RedSteelSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","RedSteelSaw",16283),RedSteelToolMaterial).setUnlocalizedName("Red Steel Saw").setMaxDamage(RedSteelUses);
RoseGoldSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","RoseGoldSaw",16284),RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Saw").setMaxDamage(RoseGoldUses);
SteelSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","SteelSaw",16285),SteelToolMaterial).setUnlocalizedName("Steel Saw").setMaxDamage(SteelUses);
TinSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","TinSaw",16286),TinToolMaterial).setUnlocalizedName("Tin Saw").setMaxDamage(TinUses);
ZincSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","ZincSaw",16287),ZincToolMaterial).setUnlocalizedName("Zinc Saw").setMaxDamage(ZincUses);
HCBlackSteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","HCBlackSteelIngot",16290), EnumMetalType.BLACKSTEEL).setUnlocalizedName("HC Black Steel Ingot");
WeakBlueSteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","WeakBlueSteelIngot",16291),EnumMetalType.BLUESTEEL).setUnlocalizedName("Weak Blue Steel Ingot");
WeakRedSteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","WeakRedSteelIngot",16292),EnumMetalType.REDSTEEL).setUnlocalizedName("Weak Red Steel Ingot");
WeakSteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","WeakSteelIngot",16293),EnumMetalType.STEEL).setUnlocalizedName("Weak Steel Ingot");
HCBlueSteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","HCBlueSteelIngot",16294), EnumMetalType.BLUESTEEL).setUnlocalizedName("HC Blue Steel Ingot");
HCRedSteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","HCRedSteelIngot",16295), EnumMetalType.REDSTEEL).setUnlocalizedName("HC Red Steel Ingot");
HCSteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","HCSteelIngot",16296), EnumMetalType.STEEL).setUnlocalizedName("HC Steel Ingot");
OreChunk = new ItemOre(TFC_Settings.getIntFor(config,"item","OreChunk",16297)).setFolder("ore/").setUnlocalizedName("Ore");
Logs = new ItemLogs(TFC_Settings.getIntFor(config,"item","Logs",16298)).setUnlocalizedName("Log");
Javelin = new ItemJavelin(TFC_Settings.getIntFor(config,"item","javelin",16318)).setUnlocalizedName("javelin");
BismuthUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedBismuth",16350)).setUnlocalizedName("Bismuth Unshaped");
BismuthBronzeUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedBismuthBronze",16351)).setUnlocalizedName("Bismuth Bronze Unshaped");
BlackBronzeUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedBlackBronze",16352)).setUnlocalizedName("Black Bronze Unshaped");
BlackSteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedBlackSteel",16353)).setUnlocalizedName("Black Steel Unshaped");
BlueSteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedBlueSteel",16354)).setUnlocalizedName("Blue Steel Unshaped");
BrassUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedBrass",16355)).setUnlocalizedName("Brass Unshaped");
BronzeUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedBronze",16356)).setUnlocalizedName("Bronze Unshaped");
CopperUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedCopper",16357)).setUnlocalizedName("Copper Unshaped");
GoldUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedGold",16358)).setUnlocalizedName("Gold Unshaped");
WroughtIronUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedIron",16359)).setUnlocalizedName("Wrought Iron Unshaped");
LeadUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedLead",16360)).setUnlocalizedName("Lead Unshaped");
NickelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedNickel",16361)).setUnlocalizedName("Nickel Unshaped");
PigIronUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedPigIron",16362)).setUnlocalizedName("Pig Iron Unshaped");
PlatinumUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedPlatinum",16363)).setUnlocalizedName("Platinum Unshaped");
RedSteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedRedSteel",16364)).setUnlocalizedName("Red Steel Unshaped");
RoseGoldUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedRoseGold",16365)).setUnlocalizedName("Rose Gold Unshaped");
SilverUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedSilver",16366)).setUnlocalizedName("Silver Unshaped");
SteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedSteel",16367)).setUnlocalizedName("Steel Unshaped");
SterlingSilverUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedSterlingSilver",16368)).setUnlocalizedName("Sterling Silver Unshaped");
TinUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedTin",16369)).setUnlocalizedName("Tin Unshaped");
ZincUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedZinc",16370)).setUnlocalizedName("Zinc Unshaped");
//Hammers
StoneHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","terraStoneHammer",16371),TFCItems.IgInToolMaterial).setUnlocalizedName("Stone Hammer").setMaxDamage(TFCItems.IgInStoneUses);
BismuthHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","terraBismuthHammer",16372),TFCItems.BismuthToolMaterial).setUnlocalizedName("Bismuth Hammer").setMaxDamage(TFCItems.BismuthUses);
BismuthBronzeHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","terraBismuthBronzeHammer",16373),TFCItems.BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Hammer").setMaxDamage(TFCItems.BismuthBronzeUses);
BlackBronzeHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","terraBlackBronzeHammer",16374),TFCItems.BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Hammer").setMaxDamage(TFCItems.BlackBronzeUses);
BlackSteelHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","terraBlackSteelHammer",16375),TFCItems.BlackSteelToolMaterial).setUnlocalizedName("Black Steel Hammer").setMaxDamage(TFCItems.BlackSteelUses);
BlueSteelHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","terraBlueSteelHammer",16376),TFCItems.BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Hammer").setMaxDamage(TFCItems.BlueSteelUses);
BronzeHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","terraBronzeHammer",16377),TFCItems.BronzeToolMaterial).setUnlocalizedName("Bronze Hammer").setMaxDamage(TFCItems.BronzeUses);
CopperHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","terraCopperHammer",16378),TFCItems.CopperToolMaterial).setUnlocalizedName("Copper Hammer").setMaxDamage(TFCItems.CopperUses);
WroughtIronHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","terraWroughtIronHammer",16379),TFCItems.IronToolMaterial).setUnlocalizedName("Wrought Iron Hammer").setMaxDamage(TFCItems.WroughtIronUses);
RedSteelHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","terraRedSteelHammer",16380),TFCItems.RedSteelToolMaterial).setUnlocalizedName("Red Steel Hammer").setMaxDamage(TFCItems.RedSteelUses);
RoseGoldHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","terraRoseGoldHammer",16381),TFCItems.RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Hammer").setMaxDamage(TFCItems.RoseGoldUses);
SteelHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","terraSteelHammer",16382),TFCItems.SteelToolMaterial).setUnlocalizedName("Steel Hammer").setMaxDamage(TFCItems.SteelUses);
TinHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","terraTinHammer",16383),TFCItems.TinToolMaterial).setUnlocalizedName("Tin Hammer").setMaxDamage(TFCItems.TinUses);
ZincHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","terraZincHammer",16384),TFCItems.ZincToolMaterial).setUnlocalizedName("Zinc Hammer").setMaxDamage(TFCItems.ZincUses);
Ink = new ItemTerra(TFC_Settings.getIntFor(config,"item","Ink",16391)).setUnlocalizedName("Ink");
BellowsItem = new ItemBellows(TFC_Settings.getIntFor(config,"item","terraBellowsItem",16406)).setUnlocalizedName("Bellows");
FireStarter = new ItemFirestarter(TFC_Settings.getIntFor(config,"item","terraFireStarter",16407)).setFolder("tools/").setUnlocalizedName("Firestarter");
ClayMold = new ItemTerra(TFC_Settings.getIntFor(config,"item","terraClayMold",16408)).setUnlocalizedName("Clay Mold");
CeramicMold = new ItemTerra(TFC_Settings.getIntFor(config,"item","terraFiredClayMold",16409)).setUnlocalizedName("Ceramic Mold");
//Tool heads
BismuthPickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthPickaxeHead",16500)).setUnlocalizedName("Bismuth Pick Head");
BismuthBronzePickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzePickaxeHead",16501)).setUnlocalizedName("Bismuth Bronze Pick Head");
BlackBronzePickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzePickaxeHead",16502)).setUnlocalizedName("Black Bronze Pick Head");
BlackSteelPickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelPickaxeHead",16503)).setUnlocalizedName("Black Steel Pick Head");
BlueSteelPickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelPickaxeHead",16504)).setUnlocalizedName("Blue Steel Pick Head");
BronzePickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzePickaxeHead",16505)).setUnlocalizedName("Bronze Pick Head");
CopperPickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperPickaxeHead",16506)).setUnlocalizedName("Copper Pick Head");
WroughtIronPickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronPickaxeHead",16507)).setUnlocalizedName("Wrought Iron Pick Head");
RedSteelPickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelPickaxeHead",16508)).setUnlocalizedName("Red Steel Pick Head");
RoseGoldPickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldPickaxeHead",16509)).setUnlocalizedName("Rose Gold Pick Head");
SteelPickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelPickaxeHead",16510)).setUnlocalizedName("Steel Pick Head");
TinPickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinPickaxeHead",16511)).setUnlocalizedName("Tin Pick Head");
ZincPickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincPickaxeHead",16512)).setUnlocalizedName("Zinc Pick Head");
BismuthShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthShovelHead",16513)).setUnlocalizedName("Bismuth Shovel Head");
BismuthBronzeShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeShovelHead",16514)).setUnlocalizedName("Bismuth Bronze Shovel Head");
BlackBronzeShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeShovelHead",16515)).setUnlocalizedName("Black Bronze Shovel Head");
BlackSteelShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelShovelHead",16516)).setUnlocalizedName("Black Steel Shovel Head");
BlueSteelShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelShovelHead",16517)).setUnlocalizedName("Blue Steel Shovel Head");
BronzeShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeShovelHead",16518)).setUnlocalizedName("Bronze Shovel Head");
CopperShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperShovelHead",16519)).setUnlocalizedName("Copper Shovel Head");
WroughtIronShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronShovelHead",16520)).setUnlocalizedName("Wrought Iron Shovel Head");
RedSteelShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelShovelHead",16521)).setUnlocalizedName("Red Steel Shovel Head");
RoseGoldShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldShovelHead",16522)).setUnlocalizedName("Rose Gold Shovel Head");
SteelShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelShovelHead",16523)).setUnlocalizedName("Steel Shovel Head");
TinShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinShovelHead",16524)).setUnlocalizedName("Tin Shovel Head");
ZincShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincShovelHead",16525)).setUnlocalizedName("Zinc Shovel Head");
BismuthHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthHoeHead",16526)).setUnlocalizedName("Bismuth Hoe Head");
BismuthBronzeHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeHoeHead",16527)).setUnlocalizedName("Bismuth Bronze Hoe Head");
BlackBronzeHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeHoeHead",16528)).setUnlocalizedName("Black Bronze Hoe Head");
BlackSteelHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelHoeHead",16529)).setUnlocalizedName("Black Steel Hoe Head");
BlueSteelHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelHoeHead",16530)).setUnlocalizedName("Blue Steel Hoe Head");
BronzeHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeHoeHead",16531)).setUnlocalizedName("Bronze Hoe Head");
CopperHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperHoeHead",16532)).setUnlocalizedName("Copper Hoe Head");
WroughtIronHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronHoeHead",16533)).setUnlocalizedName("Wrought Iron Hoe Head");
RedSteelHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelHoeHead",16534)).setUnlocalizedName("Red Steel Hoe Head");
RoseGoldHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldHoeHead",16535)).setUnlocalizedName("Rose Gold Hoe Head");
SteelHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelHoeHead",16536)).setUnlocalizedName("Steel Hoe Head");
TinHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinHoeHead",16537)).setUnlocalizedName("Tin Hoe Head");
ZincHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincHoeHead",16538)).setUnlocalizedName("Zinc Hoe Head");
BismuthAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthAxeHead",16539)).setUnlocalizedName("Bismuth Axe Head");
BismuthBronzeAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeAxeHead",16540)).setUnlocalizedName("Bismuth Bronze Axe Head");
BlackBronzeAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeAxeHead",16541)).setUnlocalizedName("Black Bronze Axe Head");
BlackSteelAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelAxeHead",16542)).setUnlocalizedName("Black Steel Axe Head");
BlueSteelAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelAxeHead",16543)).setUnlocalizedName("Blue Steel Axe Head");
BronzeAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeAxeHead",16544)).setUnlocalizedName("Bronze Axe Head");
CopperAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperAxeHead",16545)).setUnlocalizedName("Copper Axe Head");
WroughtIronAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronAxeHead",16546)).setUnlocalizedName("Wrought Iron Axe Head");
RedSteelAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelAxeHead",16547)).setUnlocalizedName("Red Steel Axe Head");
RoseGoldAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldAxeHead",16548)).setUnlocalizedName("Rose Gold Axe Head");
SteelAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelAxeHead",16549)).setUnlocalizedName("Steel Axe Head");
TinAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinAxeHead",16550)).setUnlocalizedName("Tin Axe Head");
ZincAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincAxeHead",16551)).setUnlocalizedName("Zinc Axe Head");
BismuthHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthHammerHead",16552)).setUnlocalizedName("Bismuth Hammer Head");
BismuthBronzeHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeHammerHead",16553)).setUnlocalizedName("Bismuth Bronze Hammer Head");
BlackBronzeHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeHammerHead",16554)).setUnlocalizedName("Black Bronze Hammer Head");
BlackSteelHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelHammerHead",16555)).setUnlocalizedName("Black Steel Hammer Head");
BlueSteelHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelHammerHead",16556)).setUnlocalizedName("Blue Steel Hammer Head");
BronzeHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeHammerHead",16557)).setUnlocalizedName("Bronze Hammer Head");
CopperHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperHammerHead",16558)).setUnlocalizedName("Copper Hammer Head");
WroughtIronHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronHammerHead",16559)).setUnlocalizedName("Wrought Iron Hammer Head");
RedSteelHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelHammerHead",16560)).setUnlocalizedName("Red Steel Hammer Head");
RoseGoldHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldHammerHead",16561)).setUnlocalizedName("Rose Gold Hammer Head");
SteelHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelHammerHead",16562)).setUnlocalizedName("Steel Hammer Head");
TinHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinHammerHead",16563)).setUnlocalizedName("Tin Hammer Head");
ZincHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincHammerHead",16564)).setUnlocalizedName("Zinc Hammer Head");
//chisel heads
BismuthChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthChiselHead",16565)).setUnlocalizedName("Bismuth Chisel Head");
BismuthBronzeChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeChiselHead",16566)).setUnlocalizedName("Bismuth Bronze Chisel Head");
BlackBronzeChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeChiselHead",16567)).setUnlocalizedName("Black Bronze Chisel Head");
BlackSteelChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelChiselHead",16568)).setUnlocalizedName("Black Steel Chisel Head");
BlueSteelChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelChiselHead",16569)).setUnlocalizedName("Blue Steel Chisel Head");
BronzeChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeChiselHead",16570)).setUnlocalizedName("Bronze Chisel Head");
CopperChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperChiselHead",16571)).setUnlocalizedName("Copper Chisel Head");
WroughtIronChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronChiselHead",16572)).setUnlocalizedName("Wrought Iron Chisel Head");
RedSteelChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelChiselHead",16573)).setUnlocalizedName("Red Steel Chisel Head");
RoseGoldChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldChiselHead",16574)).setUnlocalizedName("Rose Gold Chisel Head");
SteelChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelChiselHead",16575)).setUnlocalizedName("Steel Chisel Head");
TinChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinChiselHead",16576)).setUnlocalizedName("Tin Chisel Head");
ZincChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincChiselHead",16577)).setUnlocalizedName("Zinc Chisel Head");
BismuthSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthSwordHead",16578)).setUnlocalizedName("Bismuth Sword Blade");
BismuthBronzeSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeSwordHead",16579)).setUnlocalizedName("Bismuth Bronze Sword Blade");
BlackBronzeSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeSwordHead",16580)).setUnlocalizedName("Black Bronze Sword Blade");
BlackSteelSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelSwordHead",16581)).setUnlocalizedName("Black Steel Sword Blade");
BlueSteelSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelSwordHead",16582)).setUnlocalizedName("Blue Steel Sword Blade");
BronzeSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeSwordHead",16583)).setUnlocalizedName("Bronze Sword Blade");
CopperSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperSwordHead",16584)).setUnlocalizedName("Copper Sword Blade");
WroughtIronSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronSwordHead",16585)).setUnlocalizedName("Wrought Iron Sword Blade");
RedSteelSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelSwordHead",16586)).setUnlocalizedName("Red Steel Sword Blade");
RoseGoldSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldSwordHead",16587)).setUnlocalizedName("Rose Gold Sword Blade");
SteelSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelSwordHead",16588)).setUnlocalizedName("Steel Sword Blade");
TinSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinSwordHead",16589)).setUnlocalizedName("Tin Sword Blade");
ZincSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincSwordHead",16590)).setUnlocalizedName("Zinc Sword Blade");
BismuthMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthMaceHead",16591)).setUnlocalizedName("Bismuth Mace Head");
BismuthBronzeMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeMaceHead",16592)).setUnlocalizedName("Bismuth Bronze Mace Head");
BlackBronzeMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeMaceHead",16593)).setUnlocalizedName("Black Bronze Mace Head");
BlackSteelMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelMaceHead",16594)).setUnlocalizedName("Black Steel Mace Head");
BlueSteelMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelMaceHead",16595)).setUnlocalizedName("Blue Steel Mace Head");
BronzeMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeMaceHead",16596)).setUnlocalizedName("Bronze Mace Head");
CopperMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperMaceHead",16597)).setUnlocalizedName("Copper Mace Head");
WroughtIronMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronMaceHead",16598)).setUnlocalizedName("Wrought Iron Mace Head");
RedSteelMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelMaceHead",16599)).setUnlocalizedName("Red Steel Mace Head");
RoseGoldMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldMaceHead",16600)).setUnlocalizedName("Rose Gold Mace Head");
SteelMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelMaceHead",16601)).setUnlocalizedName("Steel Mace Head");
TinMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinMaceHead",16602)).setUnlocalizedName("Tin Mace Head");
ZincMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincMaceHead",16603)).setUnlocalizedName("Zinc Mace Head");
BismuthSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthSawHead",16604)).setUnlocalizedName("Bismuth Saw Blade");
BismuthBronzeSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeSawHead",16605)).setUnlocalizedName("Bismuth Bronze Saw Blade");
BlackBronzeSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeSawHead",16606)).setUnlocalizedName("Black Bronze Saw Blade");
BlackSteelSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelSawHead",16607)).setUnlocalizedName("Black Steel Saw Blade");
BlueSteelSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelSawHead",16608)).setUnlocalizedName("Blue Steel Saw Blade");
BronzeSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeSawHead",16609)).setUnlocalizedName("Bronze Saw Blade");
CopperSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperSawHead",16610)).setUnlocalizedName("Copper Saw Blade");
WroughtIronSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronSawHead",16611)).setUnlocalizedName("Wrought Iron Saw Blade");
RedSteelSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelSawHead",16612)).setUnlocalizedName("Red Steel Saw Blade");
RoseGoldSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldSawHead",16613)).setUnlocalizedName("Rose Gold Saw Blade");
SteelSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelSawHead",16614)).setUnlocalizedName("Steel Saw Blade");
TinSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinSawHead",16615)).setUnlocalizedName("Tin Saw Blade");
ZincSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincSawHead",16616)).setUnlocalizedName("Zinc Saw Blade");
HCBlackSteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedHCBlackSteel",16617)).setUnlocalizedName("HC Black Steel Unshaped");
WeakBlueSteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedWeakBlueSteel",16618)).setUnlocalizedName("Weak Blue Steel Unshaped");
HCBlueSteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedHCBlueSteel",16619)).setUnlocalizedName("HC Blue Steel Unshaped");
WeakRedSteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedWeakRedSteel",16621)).setUnlocalizedName("Weak Red Steel Unshaped");
HCRedSteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedHCRedSteel",16622)).setUnlocalizedName("HC Red Steel Unshaped");
WeakSteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedWeakSteel",16623)).setUnlocalizedName("Weak Steel Unshaped");
HCSteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedHCSteel",16624)).setUnlocalizedName("HC Steel Unshaped");
Coke = (new ItemTerra(TFC_Settings.getIntFor(config,"item","Coke",16625)).setUnlocalizedName("Coke"));
BismuthProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthProPickHead",16626)).setUnlocalizedName("Bismuth ProPick Head");
BismuthBronzeProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeProPickHead",16627)).setUnlocalizedName("Bismuth Bronze ProPick Head");
BlackBronzeProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeProPickHead",16628)).setUnlocalizedName("Black Bronze ProPick Head");
BlackSteelProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelProPickHead",16629)).setUnlocalizedName("Black Steel ProPick Head");
BlueSteelProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelProPickHead",16630)).setUnlocalizedName("Blue Steel ProPick Head");
BronzeProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeProPickHead",16631)).setUnlocalizedName("Bronze ProPick Head");
CopperProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperProPickHead",16632)).setUnlocalizedName("Copper ProPick Head");
WroughtIronProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronProPickHead",16633)).setUnlocalizedName("Wrought Iron ProPick Head");
RedSteelProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelProPickHead",16634)).setUnlocalizedName("Red Steel ProPick Head");
RoseGoldProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldProPickHead",16635)).setUnlocalizedName("Rose Gold ProPick Head");
SteelProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelProPickHead",16636)).setUnlocalizedName("Steel ProPick Head");
TinProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinProPickHead",16637)).setUnlocalizedName("Tin ProPick Head");
ZincProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincProPickHead",16638)).setUnlocalizedName("Zinc ProPick Head");
Flux = (new ItemTerra(TFC_Settings.getIntFor(config,"item","Flux",16639)).setUnlocalizedName("Flux"));
/**
* Scythe
* */
int num = 16643;
BismuthScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","BismuthScythe",num),BismuthToolMaterial).setUnlocalizedName("Bismuth Scythe").setMaxDamage(BismuthUses);num++;
BismuthBronzeScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","BismuthBronzeScythe",num),BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Scythe").setMaxDamage(BismuthBronzeUses);num++;
BlackBronzeScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","BlackBronzeScythe",num),BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Scythe").setMaxDamage(BlackBronzeUses);num++;
BlackSteelScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","BlackSteelScythe",num),BlackSteelToolMaterial).setUnlocalizedName("Black Steel Scythe").setMaxDamage(BlackSteelUses);num++;
BlueSteelScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","BlueSteelScythe",num),BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Scythe").setMaxDamage(BlueSteelUses);num++;
BronzeScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","BronzeScythe",num),BronzeToolMaterial).setUnlocalizedName("Bronze Scythe").setMaxDamage(BronzeUses);num++;
CopperScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","CopperScythe",num),CopperToolMaterial).setUnlocalizedName("Copper Scythe").setMaxDamage(CopperUses);num++;
WroughtIronScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","WroughtIronScythe",num),IronToolMaterial).setUnlocalizedName("Wrought Iron Scythe").setMaxDamage(WroughtIronUses);num++;
RedSteelScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","RedSteelScythe",num),RedSteelToolMaterial).setUnlocalizedName("Red Steel Scythe").setMaxDamage(RedSteelUses);num++;
RoseGoldScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","RoseGoldScythe",num),RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Scythe").setMaxDamage(RoseGoldUses);num++;
SteelScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","SteelScythe",num),SteelToolMaterial).setUnlocalizedName("Steel Scythe").setMaxDamage(SteelUses);num++;
TinScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","TinScythe",num),TinToolMaterial).setUnlocalizedName("Tin Scythe").setMaxDamage(TinUses);num++;
ZincScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","ZincScythe",num),ZincToolMaterial).setUnlocalizedName("Zinc Scythe").setMaxDamage(ZincUses);num++;
BismuthScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthScytheHead",num)).setUnlocalizedName("Bismuth Scythe Blade");num++;
BismuthBronzeScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeScytheHead",num)).setUnlocalizedName("Bismuth Bronze Scythe Blade");num++;
BlackBronzeScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeScytheHead",num)).setUnlocalizedName("Black Bronze Scythe Blade");num++;
BlackSteelScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelScytheHead",num)).setUnlocalizedName("Black Steel Scythe Blade");num++;
BlueSteelScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelScytheHead",num)).setUnlocalizedName("Blue Steel Scythe Blade");num++;
BronzeScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeScytheHead",num)).setUnlocalizedName("Bronze Scythe Blade");num++;
CopperScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperScytheHead",num)).setUnlocalizedName("Copper Scythe Blade");num++;
WroughtIronScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronScytheHead",num)).setUnlocalizedName("Wrought Iron Scythe Blade");num++;
RedSteelScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelScytheHead",num)).setUnlocalizedName("Red Steel Scythe Blade");num++;
RoseGoldScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldScytheHead",num)).setUnlocalizedName("Rose Gold Scythe Blade");num++;
SteelScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelScytheHead",num)).setUnlocalizedName("Steel Scythe Blade");num++;
TinScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinScytheHead",num)).setUnlocalizedName("Tin Scythe Blade");num++;
ZincScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincScytheHead",num)).setUnlocalizedName("Zinc Scythe Blade");num++;
WoodenBucketEmpty = (new ItemCustomBucket(TFC_Settings.getIntFor(config,"item","WoodenBucketEmpty",num), 0)).setUnlocalizedName("Wooden Bucket Empty");num++;
WoodenBucketWater = (new ItemCustomBucket(TFC_Settings.getIntFor(config,"item","WoodenBucketWater",num), TFCBlocks.finiteWater.blockID)).setUnlocalizedName("Wooden Bucket Water").setContainerItem(WoodenBucketEmpty);num++;
WoodenBucketMilk = (new ItemCustomBucketMilk(TFC_Settings.getIntFor(config,"item","WoodenBucketMilk",num))).setUnlocalizedName("Wooden Bucket Milk").setContainerItem(WoodenBucketEmpty);num++;
BismuthKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthKnifeHead",num)).setUnlocalizedName("Bismuth Knife Blade");num++;
BismuthBronzeKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeKnifeHead",num)).setUnlocalizedName("Bismuth Bronze Knife Blade");num++;
BlackBronzeKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeKnifeHead",num)).setUnlocalizedName("Black Bronze Knife Blade");num++;
BlackSteelKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelKnifeHead",num)).setUnlocalizedName("Black Steel Knife Blade");num++;
BlueSteelKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelKnifeHead",num)).setUnlocalizedName("Blue Steel Knife Blade");num++;
BronzeKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeKnifeHead",num)).setUnlocalizedName("Bronze Knife Blade");num++;
CopperKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperKnifeHead",num)).setUnlocalizedName("Copper Knife Blade");num++;
WroughtIronKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronKnifeHead",num)).setUnlocalizedName("Wrought Iron Knife Blade");num++;
RedSteelKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelKnifeHead",num)).setUnlocalizedName("Red Steel Knife Blade");num++;
RoseGoldKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldKnifeHead",num)).setUnlocalizedName("Rose Gold Knife Blade");num++;
SteelKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelKnifeHead",num)).setUnlocalizedName("Steel Knife Blade");num++;
TinKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinKnifeHead",num)).setUnlocalizedName("Tin Knife Blade");num++;
ZincKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincKnifeHead",num)).setUnlocalizedName("Zinc Knife Blade");num++;
BismuthKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","BismuthKnife",num),BismuthToolMaterial).setUnlocalizedName("Bismuth Knife").setMaxDamage(BismuthUses);num++;
BismuthBronzeKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","BismuthBronzeKnife",num),BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Knife").setMaxDamage(BismuthBronzeUses);num++;
BlackBronzeKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","BlackBronzeKnife",num),BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Knife").setMaxDamage(BlackBronzeUses);num++;
BlackSteelKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","BlackSteelKnife",num),BlackSteelToolMaterial).setUnlocalizedName("Black Steel Knife").setMaxDamage(BlackSteelUses);num++;
BlueSteelKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","BlueSteelKnife",num),BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Knife").setMaxDamage(BlueSteelUses);num++;
BronzeKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","BronzeKnife",num),BronzeToolMaterial).setUnlocalizedName("Bronze Knife").setMaxDamage(BronzeUses);num++;
CopperKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","CopperKnife",num),CopperToolMaterial).setUnlocalizedName("Copper Knife").setMaxDamage(CopperUses);num++;
WroughtIronKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","WroughtIronKnife",num),IronToolMaterial).setUnlocalizedName("Wrought Iron Knife").setMaxDamage(WroughtIronUses);num++;
RedSteelKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","RedSteelKnife",num),RedSteelToolMaterial).setUnlocalizedName("Red Steel Knife").setMaxDamage(RedSteelUses);num++;
RoseGoldKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","RoseGoldKnife",num),RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Knife").setMaxDamage(RoseGoldUses);num++;
SteelKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","SteelKnife",num),SteelToolMaterial).setUnlocalizedName("Steel Knife").setMaxDamage(SteelUses);num++;
TinKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","TinKnife",num),TinToolMaterial).setUnlocalizedName("Tin Knife").setMaxDamage(TinUses);num++;
ZincKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","ZincKnife",num),ZincToolMaterial).setUnlocalizedName("Zinc Knife").setMaxDamage(ZincUses);num++;
LooseRock = (new ItemLooseRock(TFC_Settings.getIntFor(config,"item","LooseRock",num)).setUnlocalizedName("LooseRock"));num++;
FlatRock = (new ItemFlatRock(TFC_Settings.getIntFor(config,"item","FlatRock",num)).setUnlocalizedName("FlatRock"));num++;
IgInStoneShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","IgInStoneShovelHead",num)).setUnlocalizedName("Stone Shovel Head");num++;
SedStoneShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SedStoneShovelHead",num)).setUnlocalizedName("Stone Shovel Head");num++;
IgExStoneShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","IgExStoneShovelHead",num)).setUnlocalizedName("Stone Shovel Head");num++;
MMStoneShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","MMStoneShovelHead",num)).setUnlocalizedName("Stone Shovel Head");num++;
IgInStoneAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","IgInStoneAxeHead",num)).setUnlocalizedName("Stone Axe Head");num++;
SedStoneAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SedStoneAxeHead",num)).setUnlocalizedName("Stone Axe Head");num++;
IgExStoneAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","IgExStoneAxeHead",num)).setUnlocalizedName("Stone Axe Head");num++;
MMStoneAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","MMStoneAxeHead",num)).setUnlocalizedName("Stone Axe Head");num++;
IgInStoneHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","IgInStoneHoeHead",num)).setUnlocalizedName("Stone Hoe Head");num++;
SedStoneHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SedStoneHoeHead",num)).setUnlocalizedName("Stone Hoe Head");num++;
IgExStoneHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","IgExStoneHoeHead",num)).setUnlocalizedName("Stone Hoe Head");num++;
MMStoneHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","MMStoneHoeHead",num)).setUnlocalizedName("Stone Hoe Head");num++;
StoneKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","StoneKnifeHead",num)).setUnlocalizedName("Stone Knife Blade");num++;
StoneHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","StoneHammerHead",num)).setUnlocalizedName("Stone Hammer Head");num++;
StoneKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","StoneKnife",num),IgExToolMaterial).setUnlocalizedName("Stone Knife").setMaxDamage(IgExStoneUses);num++;
SmallOreChunk = new ItemOreSmall(TFC_Settings.getIntFor(config,"item","SmallOreChunk",num++)).setUnlocalizedName("Small Ore");
SinglePlank = new ItemPlank(TFC_Settings.getIntFor(config,"item","SinglePlank",num++)).setUnlocalizedName("SinglePlank");
RedSteelBucketEmpty = (new ItemCustomRedSteelBucket(TFC_Settings.getIntFor(config,"item","RedSteelBucketEmpty",num++), 0)).setUnlocalizedName("Red Steel Bucket Empty");
- RedSteelBucketWater = (new ItemCustomRedSteelBucket(TFC_Settings.getIntFor(config,"item","RedSteelBucketWater",num++), Block.waterMoving.blockID)).setUnlocalizedName("Red Steel Bucket Water");
+ RedSteelBucketWater = (new ItemCustomRedSteelBucket(TFC_Settings.getIntFor(config,"item","RedSteelBucketWater",num++), Block.waterMoving.blockID)).setUnlocalizedName("Red Steel Bucket Water").setContainerItem(RedSteelBucketEmpty);
BlueSteelBucketEmpty = (new ItemCustomBlueSteelBucket(TFC_Settings.getIntFor(config,"item","BlueSteelBucketEmpty",num++), 0)).setUnlocalizedName("Blue Steel Bucket Empty");
- BlueSteelBucketLava = (new ItemCustomBlueSteelBucket(TFC_Settings.getIntFor(config,"item","BlueSteelBucketLava",num++), Block.lavaMoving.blockID)).setUnlocalizedName("Blue Steel Bucket Lava");
+ BlueSteelBucketLava = (new ItemCustomBlueSteelBucket(TFC_Settings.getIntFor(config,"item","BlueSteelBucketLava",num++), Block.lavaMoving.blockID)).setUnlocalizedName("Blue Steel Bucket Lava").setContainerItem(BlueSteelBucketEmpty);
Quern = new ItemTerra(TFC_Settings.getIntFor(config,"item","Quern",num++)).setUnlocalizedName("Quern").setMaxDamage(250);
FlintSteel = new ItemFlintSteel(TFC_Settings.getIntFor(config,"item","FlintSteel",num++)).setUnlocalizedName("flintAndSteel").setMaxDamage(200);
DoorOak = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorOak", num++), 0).setUnlocalizedName("Oak Door");
DoorAspen = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorAspen", num++), 1).setUnlocalizedName("Aspen Door");
DoorBirch = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorBirch", num++), 2).setUnlocalizedName("Birch Door");
DoorChestnut = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorChestnut", num++), 3).setUnlocalizedName("Chestnut Door");
DoorDouglasFir = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorDouglasFir", num++), 4).setUnlocalizedName("Douglas Fir Door");
DoorHickory = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorHickory", num++), 5).setUnlocalizedName("Hickory Door");
DoorMaple = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorMaple", num++), 6).setUnlocalizedName("Maple Door");
DoorAsh = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorAsh", num++), 7).setUnlocalizedName("Ash Door");
DoorPine = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorPine", num++), 8).setUnlocalizedName("Pine Door");
DoorSequoia = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorSequoia", num++), 9).setUnlocalizedName("Sequoia Door");
DoorSpruce = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorSpruce", num++), 10).setUnlocalizedName("Spruce Door");
DoorSycamore = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorSycamore", num++), 11).setUnlocalizedName("Sycamore Door");
DoorWhiteCedar = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorWhiteCedar", num++), 12).setUnlocalizedName("White Cedar Door");
DoorWhiteElm = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorWhiteElm", num++), 13).setUnlocalizedName("White Elm Door");
DoorWillow = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorWillow", num++), 14).setUnlocalizedName("Willow Door");
DoorKapok = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorKapok", num++), 15).setUnlocalizedName("Kapok Door");
Blueprint = new ItemBlueprint(TFC_Settings.getIntFor(config,"item","Blueprint", num++));
writabeBookTFC = new ItemWritableBookTFC(TFC_Settings.getIntFor(config,"item","WritableBookTFC", num++),"Fix Me I'm Broken").setUnlocalizedName("book");
WoolYarn = new ItemTerra(TFC_Settings.getIntFor(config, "item", "WoolYarn", num++)).setUnlocalizedName("WoolYarn").setCreativeTab(TFCTabs.TFCMaterials);
Wool = new ItemTerra(TFC_Settings.getIntFor(config,"item","Wool",num++)).setUnlocalizedName("Wool").setCreativeTab(TFCTabs.TFCMaterials);
WoolCloth = new ItemTerra(TFC_Settings.getIntFor(config, "item", "WoolCloth", num++)).setUnlocalizedName("WoolCloth").setCreativeTab(TFCTabs.TFCMaterials);
Spindle = new ItemSpindle(TFC_Settings.getIntFor(config,"item","Spindle",num++),SedToolMaterial).setUnlocalizedName("Spindle").setCreativeTab(TFCTabs.TFCMaterials);
ClaySpindle = new ItemTerra(TFC_Settings.getIntFor(config, "item", "ClaySpindle", num++)).setFolder("tools/").setUnlocalizedName("Clay Spindle").setCreativeTab(TFCTabs.TFCMaterials);
SpindleHead = new ItemTerra(TFC_Settings.getIntFor(config, "item", "SpindleHead", num++)).setFolder("toolheads/").setUnlocalizedName("Spindle Head").setCreativeTab(TFCTabs.TFCMaterials);
StoneBrick = (new ItemStoneBrick(TFC_Settings.getIntFor(config,"item","ItemStoneBrick2",num++)).setFolder("tools/").setUnlocalizedName("ItemStoneBrick"));
Mortar = new ItemTerra(TFC_Settings.getIntFor(config,"item","Mortar",num++)).setFolder("tools/").setUnlocalizedName("Mortar").setCreativeTab(TFCTabs.TFCMaterials);
Limewater = new ItemCustomBucket(TFC_Settings.getIntFor(config,"item","Limewater",num++),0).setFolder("tools/").setUnlocalizedName("Lime Water").setContainerItem(WoodenBucketEmpty).setCreativeTab(TFCTabs.TFCMaterials);
Hide = new ItemTerra(TFC_Settings.getIntFor(config,"item","Hide",num++)).setFolder("tools/").setUnlocalizedName("Hide").setCreativeTab(TFCTabs.TFCMaterials);
SoakedHide = new ItemTerra(TFC_Settings.getIntFor(config,"item","SoakedHide",num++)).setFolder("tools/").setUnlocalizedName("Soaked Hide").setCreativeTab(TFCTabs.TFCMaterials);
ScrapedHide = new ItemTerra(TFC_Settings.getIntFor(config,"item","ScrapedHide",num++)).setFolder("tools/").setUnlocalizedName("Scraped Hide").setCreativeTab(TFCTabs.TFCMaterials);
PrepHide = new ItemTerra(TFC_Settings.getIntFor(config,"item","PrepHide",num++)).setFolder("tools/").setFolder("tools/").setUnlocalizedName("Prep Hide").setCreativeTab(TFCTabs.TFCMaterials);
TerraLeather = new ItemTerra(TFC_Settings.getIntFor(config,"item","TFCLeather",num++)).setFolder("tools/").setUnlocalizedName("TFC Leather").setCreativeTab(TFCTabs.TFCMaterials);
SheepSkin = new ItemTerra(TFC_Settings.getIntFor(config,"item","SheepSkin",num++)).setFolder("tools/").setUnlocalizedName("Sheep Skin").setCreativeTab(TFCTabs.TFCMaterials);
muttonRaw = new ItemTerra(TFC_Settings.getIntFor(config,"item","muttonRaw",num++)).setFolder("food/").setUnlocalizedName("Mutton Raw");
muttonCooked = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","muttonCooked",num++), 40, 0.8F, true, 48).setUnlocalizedName("Mutton Cooked");
FlatLeather = (new ItemFlatLeather(TFC_Settings.getIntFor(config,"items","FlatLeather2",num++)).setFolder("tools/").setUnlocalizedName("Flat Leather"));
PotteryJug = new ItemPotteryJug(TFC_Settings.getIntFor(config,"items","PotteryJug",num++)).setUnlocalizedName("Jug");
PotterySmallVessel = new ItemPotteryBase(TFC_Settings.getIntFor(config,"items","PotterySmallVessel",num++)).setUnlocalizedName("Small Vessel");
PotteryLargeVessel = new ItemPotteryLargeVessel(TFC_Settings.getIntFor(config,"items","PotteryLargeVessel",num++)).setUnlocalizedName("Large Vessel");
PotteryPot = new ItemPotteryPot(TFC_Settings.getIntFor(config,"items","PotteryPot",num++)).setUnlocalizedName("Pot");
Straw = new ItemTerra(TFC_Settings.getIntFor(config,"items","Straw",num++)).setFolder("plants/").setUnlocalizedName("Straw");
/**Plans*/
num = 20000;
SetupPlans(num);
/**Food related items*/
num = 18000;
SetupFood(num);
/**Armor Crafting related items*/
num = 19000;
SetupArmor(num);
Recipes.Doors = new Item[]{DoorOak, DoorAspen, DoorBirch, DoorChestnut, DoorDouglasFir,
DoorHickory, DoorMaple, DoorAsh, DoorPine, DoorSequoia, DoorSpruce, DoorSycamore,
DoorWhiteCedar, DoorWhiteElm, DoorWillow, DoorKapok};
Recipes.Axes = new Item[]{SedAxe,IgInAxe,IgExAxe,MMAxe,
BismuthAxe,BismuthBronzeAxe,BlackBronzeAxe,
BlackSteelAxe,BlueSteelAxe,BronzeAxe,CopperAxe,
WroughtIronAxe,RedSteelAxe,RoseGoldAxe,SteelAxe,
TinAxe,ZincAxe};
Recipes.Chisels = new Item[]{BismuthChisel,BismuthBronzeChisel,BlackBronzeChisel,
BlackSteelChisel,BlueSteelChisel,BronzeChisel,CopperChisel,
WroughtIronChisel,RedSteelChisel,RoseGoldChisel,SteelChisel,
TinChisel,ZincChisel};
Recipes.Saws = new Item[]{BismuthSaw,BismuthBronzeSaw,BlackBronzeSaw,
BlackSteelSaw,BlueSteelSaw,BronzeSaw,CopperSaw,
WroughtIronSaw,RedSteelSaw,RoseGoldSaw,SteelSaw,
TinSaw,ZincSaw};
Recipes.Knives = new Item[]{StoneKnife,BismuthKnife,BismuthBronzeKnife,BlackBronzeKnife,
BlackSteelKnife,BlueSteelKnife,BronzeKnife,CopperKnife,
WroughtIronKnife,RedSteelKnife,RoseGoldKnife,SteelKnife,
TinKnife,ZincKnife};
Recipes.MeltedMetal = new Item[]{BismuthUnshaped, BismuthBronzeUnshaped,BlackBronzeUnshaped,
TFCItems.BlackSteelUnshaped,TFCItems.BlueSteelUnshaped,TFCItems.BrassUnshaped,TFCItems.BronzeUnshaped,
TFCItems.CopperUnshaped,TFCItems.GoldUnshaped,
TFCItems.WroughtIronUnshaped,TFCItems.LeadUnshaped,TFCItems.NickelUnshaped,TFCItems.PigIronUnshaped,
TFCItems.PlatinumUnshaped,TFCItems.RedSteelUnshaped,TFCItems.RoseGoldUnshaped,TFCItems.SilverUnshaped,
TFCItems.SteelUnshaped,TFCItems.SterlingSilverUnshaped,
TFCItems.TinUnshaped,TFCItems.ZincUnshaped, TFCItems.HCSteelUnshaped, TFCItems.WeakSteelUnshaped,
TFCItems.HCBlackSteelUnshaped, TFCItems.HCBlueSteelUnshaped, TFCItems.HCRedSteelUnshaped,
TFCItems.WeakBlueSteelUnshaped, TFCItems.WeakRedSteelUnshaped};
Recipes.Hammers = new Item[]{TFCItems.StoneHammer,TFCItems.BismuthHammer,TFCItems.BismuthBronzeHammer,TFCItems.BlackBronzeHammer,
TFCItems.BlackSteelHammer,TFCItems.BlueSteelHammer,TFCItems.BronzeHammer,TFCItems.CopperHammer,
TFCItems.WroughtIronHammer,TFCItems.RedSteelHammer,TFCItems.RoseGoldHammer,TFCItems.SteelHammer,
TFCItems.TinHammer,TFCItems.ZincHammer};
Recipes.Spindle = new Item[]{TFCItems.Spindle};
Recipes.Gems = new Item[]{TFCItems.GemAgate, TFCItems.GemAmethyst, TFCItems.GemBeryl, TFCItems.GemDiamond, TFCItems.GemEmerald, TFCItems.GemGarnet,
TFCItems.GemJade, TFCItems.GemJasper, TFCItems.GemOpal,TFCItems.GemRuby,TFCItems.GemSapphire,TFCItems.GemTopaz,TFCItems.GemTourmaline};
Meals = new Item[]{MealMoveSpeed, MealDigSpeed, MealDamageBoost, MealJump, MealDamageResist,
MealFireResist, MealWaterBreathing, MealNightVision};
((TFCTabs)TFCTabs.TFCTools).setTabIconItemIndex(TFCItems.RoseGoldHammer.itemID);
((TFCTabs)TFCTabs.TFCMaterials).setTabIconItemIndex(TFCItems.Spindle.itemID);
((TFCTabs)TFCTabs.TFCUnfinished).setTabIconItemIndex(TFCItems.RoseGoldHammerHead.itemID);
((TFCTabs)TFCTabs.TFCArmor).setTabIconItemIndex(TFCItems.SteelHelmet.itemID);
System.out.println(new StringBuilder().append("[TFC] Done Loading Items").toString());
if (config != null) {
config.save();
}
}
public static void SetupPlans(int num)
{
PickaxeHeadPlan = new ItemPlan(TFC_Settings.getIntFor(config,"item","PickaxeHeadPlan",num)).setUnlocalizedName("PickaxeHeadPlan");num++;
ShovelHeadPlan = new ItemPlan(TFC_Settings.getIntFor(config,"item","ShovelHeadPlan",num)).setUnlocalizedName("ShovelHeadPlan");num++;
HoeHeadPlan = new ItemPlan(TFC_Settings.getIntFor(config,"item","HoeHeadPlan",num)).setUnlocalizedName("HoeHeadPlan");num++;
AxeHeadPlan = new ItemPlan(TFC_Settings.getIntFor(config,"item","AxeHeadPlan",num)).setUnlocalizedName("AxeHeadPlan");num++;
HammerHeadPlan = new ItemPlan(TFC_Settings.getIntFor(config,"item","HammerHeadPlan",num)).setUnlocalizedName("HammerHeadPlan");num++;
ChiselHeadPlan = new ItemPlan(TFC_Settings.getIntFor(config,"item","ChiselHeadPlan",num)).setUnlocalizedName("ChiselHeadPlan");num++;
SwordBladePlan = new ItemPlan(TFC_Settings.getIntFor(config,"item","SwordBladePlan",num)).setUnlocalizedName("SwordBladePlan");num++;
MaceHeadPlan = new ItemPlan(TFC_Settings.getIntFor(config,"item","MaceHeadPlan",num)).setUnlocalizedName("MaceHeadPlan");num++;
SawBladePlan = new ItemPlan(TFC_Settings.getIntFor(config,"item","SawBladePlan",num)).setUnlocalizedName("SawBladePlan");num++;
ProPickHeadPlan = new ItemPlan(TFC_Settings.getIntFor(config,"item","ProPickHeadPlan",num)).setUnlocalizedName("ProPickHeadPlan");num++;
HelmetPlan = new ItemPlan(TFC_Settings.getIntFor(config,"item","HelmetPlan",num)).setUnlocalizedName("HelmetPlan");num++;
ChestplatePlan = new ItemPlan(TFC_Settings.getIntFor(config,"item","ChestplatePlan",num)).setUnlocalizedName("ChestplatePlan");num++;
GreavesPlan = new ItemPlan(TFC_Settings.getIntFor(config,"item","GreavesPlan",num)).setUnlocalizedName("GreavesPlan");num++;
BootsPlan = new ItemPlan(TFC_Settings.getIntFor(config,"item","BootsPlan",num)).setUnlocalizedName("BootsPlan");num++;
ScythePlan = new ItemPlan(TFC_Settings.getIntFor(config,"item","ScythePlan",num)).setUnlocalizedName("ScythePlan");num++;
KnifePlan = new ItemPlan(TFC_Settings.getIntFor(config,"item","KnifePlan",num)).setUnlocalizedName("KnifePlan");num++;
BucketPlan = new ItemPlan(TFC_Settings.getIntFor(config,"item","BucketPlan",num)).setUnlocalizedName("BucketPlan");num++;
}
public static void SetupFood(int num)
{
FruitTreeSapling1 = new ItemFruitTreeSapling(TFC_Settings.getIntFor(config,"item","FruitSapling1", num), 0).setUnlocalizedName("FruitSapling1");num++;
FruitTreeSapling2 = new ItemFruitTreeSapling(TFC_Settings.getIntFor(config,"item","FruitSapling2", num), 8).setUnlocalizedName("FruitSapling2");num++;
RedApple = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","Fruit.Red Apple",num), 15, 0.1F, false, 2).setUnlocalizedName("Red Apple");num++;
Banana = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","Fruit.Banana",num), 10, 0.1F, false, 3).setUnlocalizedName("Banana");num++;
Orange = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","Fruit.Orange",num), 10, 0.1F, false, 4).setUnlocalizedName("Orange");num++;
GreenApple = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","Fruit.Green Apple",num), 15, 0.1F, false, 5).setUnlocalizedName("Green Apple");num++;
Lemon = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","Fruit.Lemon",num), 10, 0.03F, false, 6).setUnlocalizedName("Lemon");num++;
Olive = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","Fruit.Olive",num), 10, 0.05F, false, 7).setUnlocalizedName("Olive");num++;
Cherry = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","Fruit.Cherry",num), 10, 0.03F, false, 8).setUnlocalizedName("Cherry");num++;
Peach = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","Fruit.Peach",num), 12, 0.1F, false, 9).setUnlocalizedName("Peach");num++;
Plum = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","Fruit.Plum",num), 10, 0.1F, false, 10).setUnlocalizedName("Plum");num++;
EggCooked = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","Meat.EggCooked",num), 25, 0.4F, false, 11).setUnlocalizedName("Egg Cooked");num++;
WheatGrain = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","WheatGrain",num++), 1, 0.4F, false, 12).setUnlocalizedName("Wheat Grain");
BarleyGrain = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","BarleyGrain",num++), 1, 0.4F, false, 14).setUnlocalizedName("Barley Grain");
OatGrain = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","OatGrain",num++), 1, 0.4F, false, 16).setUnlocalizedName("Oat Grain");
RyeGrain = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","RyeGrain",num++), 1, 0.4F, false, 18).setUnlocalizedName("Rye Grain");
RiceGrain = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","RiceGrain",num++), 1, 0.4F, false, 20).setUnlocalizedName("Rice Grain");
MaizeEar = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","MaizeEar",num++), 10, 0.4F, false, 22).setUnlocalizedName("Maize Ear");
Tomato = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","Tomato",num++), 15, 0.4F, false, 24).setUnlocalizedName("Tomato");
Potato = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","Potato",num++), 22, 0.4F, false, 25).setUnlocalizedName("Potato");
Onion = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","Onion",num++), 10, 0.4F, false, 27).setUnlocalizedName("Onion");
Cabbage = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","Cabbage",num++), 20, 0.4F, false, 28).setUnlocalizedName("Cabbage");
Garlic = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","Garlic",num++), 10, 0.4F, false, 29).setUnlocalizedName("Garlic");
Carrot = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","Carrot",num++), 5, 0.4F, false, 30).setUnlocalizedName("Carrot");
Sugarcane = new ItemTerra(TFC_Settings.getIntFor(config,"item","Sugarcane",num++)).setFolder("plants/").setUnlocalizedName("Sugarcane");
Hemp = new ItemTerra(TFC_Settings.getIntFor(config,"item","Hemp",num++)).setFolder("plants/").setUnlocalizedName("Hemp");
Soybean = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","Soybeans",num++), 10, 0.4F, false, 31).setUnlocalizedName("Soybeans");
Greenbeans = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","Greenbeans",num++), 10, 0.4F, false, 32).setUnlocalizedName("Greenbeans");
GreenBellPepper = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","GreenBellPepper",num++), 10, 0.4F, false, 34).setUnlocalizedName("Green Bell Pepper");
YellowBellPepper = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","YellowBellPepper",num++), 10, 0.4F, false, 35).setUnlocalizedName("Yellow Bell Pepper");
RedBellPepper = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","RedBellPepper",num++), 10, 0.4F, false, 36).setUnlocalizedName("Red Bell Pepper");
Squash = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","Squash",num++), 12, 0.4F, false, 37).setUnlocalizedName("Squash");
WheatWhole = new ItemTerra(TFC_Settings.getIntFor(config,"item","WheatWhole",num++)).setFolder("food/").setUnlocalizedName("Wheat Whole");
BarleyWhole = new ItemTerra(TFC_Settings.getIntFor(config,"item","BarleyWhole",num++)).setFolder("food/").setUnlocalizedName("Barley Whole");
OatWhole = new ItemTerra(TFC_Settings.getIntFor(config,"item","OatWhole",num++)).setFolder("food/").setUnlocalizedName("Oat Whole");
RyeWhole = new ItemTerra(TFC_Settings.getIntFor(config,"item","RyeWhole",num++)).setFolder("food/").setUnlocalizedName("Rye Whole");
RiceWhole = new ItemTerra(TFC_Settings.getIntFor(config,"item","RiceWhole",num++)).setFolder("food/").setUnlocalizedName("Rice Whole");
MealGeneric = new ItemMeal(TFC_Settings.getIntFor(config,"item","MealGeneric",num++)).setUnlocalizedName("MealGeneric");
MealMoveSpeed = new ItemMeal(TFC_Settings.getIntFor(config,"item","MealMoveSpeed",num++)).setPotionEffect(new PotionEffect(Potion.moveSpeed.id,8000,4)).setUnlocalizedName("MealGeneric");
MealDigSpeed = new ItemMeal(TFC_Settings.getIntFor(config,"item","MealDigSpeed",num++)).setPotionEffect(new PotionEffect(Potion.digSpeed.id,8000,4)).setUnlocalizedName("MealGeneric");
MealDamageBoost = new ItemMeal(TFC_Settings.getIntFor(config,"item","MealDamageBoost",num++)).setPotionEffect(new PotionEffect(Potion.damageBoost.id,4000,4)).setUnlocalizedName("MealGeneric");
MealJump = new ItemMeal(TFC_Settings.getIntFor(config,"item","MealJump",num++)).setPotionEffect(new PotionEffect(Potion.jump.id,8000,4)).setUnlocalizedName("MealGeneric");
MealDamageResist = new ItemMeal(TFC_Settings.getIntFor(config,"item","MealDamageResist",num++)).setPotionEffect(new PotionEffect(Potion.resistance.id,8000,4)).setUnlocalizedName("MealGeneric");
MealFireResist = new ItemMeal(TFC_Settings.getIntFor(config,"item","MealFireResist",num++)).setPotionEffect(new PotionEffect(Potion.fireResistance.id,8000,4)).setUnlocalizedName("MealGeneric");
MealWaterBreathing = new ItemMeal(TFC_Settings.getIntFor(config,"item","MealWaterBreathing",num++)).setPotionEffect(new PotionEffect(Potion.waterBreathing.id,8000,4)).setUnlocalizedName("MealGeneric");
MealNightVision = new ItemMeal(TFC_Settings.getIntFor(config,"item","MealNightVision",num++)).setPotionEffect(new PotionEffect(Potion.nightVision.id,4000,4)).setUnlocalizedName("MealGeneric");
WheatGround = new ItemTerra(TFC_Settings.getIntFor(config,"item","WheatGround",num++)).setFolder("food/").setUnlocalizedName("Wheat Ground");
BarleyGround = new ItemTerra(TFC_Settings.getIntFor(config,"item","BarleyGround",num++)).setFolder("food/").setUnlocalizedName("Barley Ground");
OatGround = new ItemTerra(TFC_Settings.getIntFor(config,"item","OatGround",num++)).setFolder("food/").setUnlocalizedName("Oat Ground");
RyeGround = new ItemTerra(TFC_Settings.getIntFor(config,"item","RyeGround",num++)).setFolder("food/").setUnlocalizedName("Rye Ground");
RiceGround = new ItemTerra(TFC_Settings.getIntFor(config,"item","RiceGround",num++)).setFolder("food/").setUnlocalizedName("Rice Ground");
CornmealGround = new ItemTerra(TFC_Settings.getIntFor(config,"item","CornmealGround",num++)).setFolder("food/").setUnlocalizedName("Cornmeal Ground");
WheatDough = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","WheatDough",num++), 1, 0.0F, false, 0).setUnlocalizedName("Wheat Dough");
BarleyDough = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","BarleyDough",num++), 1, 0.0F, false, 0).setUnlocalizedName("Barley Dough");
OatDough = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","OatDough",num++), 1, 0.0F, false, 0).setUnlocalizedName("Oat Dough");
RyeDough = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","RyeDough",num++), 1, 0.0F, false, 0).setUnlocalizedName("Rye Dough");
RiceDough = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","RiceDough",num++), 1, 0.0F, false, 0).setUnlocalizedName("Rice Dough");
CornmealDough = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","CornmealDough",num++), 1, 0.0F, false, 0).setUnlocalizedName("Cornmeal Dough");
BarleyBread = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","BarleyBread",num++), 25, 0.6F, false, 43).setUnlocalizedName("Barley Bread");
OatBread = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","OatBread",num++), 25, 0.6F, false, 44).setUnlocalizedName("Oat Bread");
RyeBread = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","RyeBread",num++), 25, 0.6F, false, 45).setUnlocalizedName("Rye Bread");
RiceBread = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","RiceBread",num++), 25, 0.6F, false, 46).setUnlocalizedName("Rice Bread");
CornBread = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","CornBread",num++), 25, 0.6F, false, 47).setUnlocalizedName("Corn Bread");
num = 18900;
SeedsWheat = new ItemCustomSeeds(TFC_Settings.getIntFor(config,"item","SeedsWheat",num++),0).setUnlocalizedName("Seeds Wheat");
SeedsBarley = new ItemCustomSeeds(TFC_Settings.getIntFor(config,"item","SeedsBarley",num++),5).setUnlocalizedName("Seeds Barley");
SeedsRye = new ItemCustomSeeds(TFC_Settings.getIntFor(config,"item","SeedsRye",num++),7).setUnlocalizedName("Seeds Rye");
SeedsOat = new ItemCustomSeeds(TFC_Settings.getIntFor(config,"item","SeedsOat",num++),9).setUnlocalizedName("Seeds Oat");
SeedsRice = new ItemCustomSeeds(TFC_Settings.getIntFor(config,"item","SeedsRice",num++),11).setUnlocalizedName("Seeds Rice");
SeedsMaize = new ItemCustomSeeds(TFC_Settings.getIntFor(config,"item","SeedsMaize",num++),2).setUnlocalizedName("Seeds Maize");
SeedsPotato = new ItemCustomSeeds(TFC_Settings.getIntFor(config,"item","SeedsPotato",num++),13).setUnlocalizedName("Seeds Potato");
SeedsOnion = new ItemCustomSeeds(TFC_Settings.getIntFor(config,"item","SeedsOnion",num++),15).setUnlocalizedName("Seeds Onion");
SeedsCabbage = new ItemCustomSeeds(TFC_Settings.getIntFor(config,"item","SeedsCabbage",num++),16).setUnlocalizedName("Seeds Cabbage");
SeedsGarlic = new ItemCustomSeeds(TFC_Settings.getIntFor(config,"item","SeedsGarlic",num++),17).setUnlocalizedName("Seeds Garlic");
SeedsCarrot = new ItemCustomSeeds(TFC_Settings.getIntFor(config,"item","SeedsCarrot",num++),18).setUnlocalizedName("Seeds Carrot");
SeedsSugarcane = new ItemCustomSeeds(TFC_Settings.getIntFor(config,"item","SeedsSugarcane",num++),21).setUnlocalizedName("Seeds Sugarcane");
SeedsHemp = new ItemCustomSeeds(TFC_Settings.getIntFor(config,"item","SeedsHemp",num++),22).setUnlocalizedName("Seeds Hemp");
SeedsTomato = new ItemCustomSeeds(TFC_Settings.getIntFor(config,"item","SeedsTomato",num++),4).setUnlocalizedName("Seeds Tomato");
SeedsYellowBellPepper = new ItemCustomSeeds(TFC_Settings.getIntFor(config,"item","SeedsYellowBellPepper",num++),19).setUnlocalizedName("Seeds Yellow Bell Pepper");
SeedsRedBellPepper = new ItemCustomSeeds(TFC_Settings.getIntFor(config,"item","SeedsRedBellPepper",num++),20).setUnlocalizedName("Seeds Red Bell Pepper");
SeedsSoybean = new ItemCustomSeeds(TFC_Settings.getIntFor(config,"item","SeedsSoybean",num++),21).setUnlocalizedName("Seeds Soybean");
SeedsGreenbean = new ItemCustomSeeds(TFC_Settings.getIntFor(config,"item","SeedsGreenbean",num++),22).setUnlocalizedName("Seeds Greenbean");
SeedsSquash = new ItemCustomSeeds(TFC_Settings.getIntFor(config,"item","SeedsSquash",num++),23).setUnlocalizedName("Seeds Squash");
}
public static void SetupArmor(int num)
{
BismuthArmorMaterial = EnumHelper.addArmorMaterial("Bismuth", 200, new int[] {2,4,3,2}, 1);
BismuthBronzeArmorMaterial = EnumHelper.addArmorMaterial("BismuthBronze", 400, new int[] {4,6,5,4}, 1);
BlackBronzeArmorMaterial = EnumHelper.addArmorMaterial("BlackBronze", 400, new int[] {4,6,5,4}, 1);
BlackSteelArmorMaterial = EnumHelper.addArmorMaterial("BlackSteel", 700, new int[] {6,8,7,6}, 1);
BlueSteelArmorMaterial = EnumHelper.addArmorMaterial("BlueSteel", 800, new int[] {7,8,8,7}, 1);
BronzeArmorMaterial = EnumHelper.addArmorMaterial("Bronze", 420, new int[] {4,6,5,4}, 1);
CopperArmorMaterial = EnumHelper.addArmorMaterial("Copper", 300, new int[] {3,5,4,3}, 1);
IronArmorMaterial = EnumHelper.addArmorMaterial("Iron", 500, new int[] {5,7,6,5}, 1);
RedSteelArmorMaterial = EnumHelper.addArmorMaterial("RedSteel", 800, new int[] {7,8,8,7}, 1);
RoseGoldArmorMaterial = EnumHelper.addArmorMaterial("RoseGold", 400, new int[] {4,6,5,4}, 1);
SteelArmorMaterial = EnumHelper.addArmorMaterial("Steel", 600, new int[] {6,8,7,6}, 1);
TinArmorMaterial = EnumHelper.addArmorMaterial("Tin", 200, new int[] {2,4,3,2}, 1);
ZincArmorMaterial = EnumHelper.addArmorMaterial("Zinc", 200, new int[] {2,4,3,2}, 1);
String[] Names = {"Bismuth", "Bismuth Bronze", "Black Bronze", "Black Steel", "Blue Steel", "Bronze", "Copper", "Wrought Iron", "Red Steel", "Rose Gold", "Steel", "Tin", "Zinc"};
String[] NamesNS = {"Bismuth", "BismuthBronze", "BlackBronze", "BlackSteel", "BlueSteel", "Bronze", "Copper", "WroughtIron", "RedSteel", "RoseGold", "Steel", "Tin", "Zinc"};
String[] NamesNSO = {"Brass", "Gold", "Lead", "Nickel", "Pig Iron", "Platinum", "Silver", "Sterling Silver"};
CommonProxy proxy = TerraFirmaCraft.proxy;
EnumArmorMaterial[] mats = new EnumArmorMaterial[]{TFCItems.BismuthArmorMaterial,TFCItems.BismuthBronzeArmorMaterial,TFCItems.BlackBronzeArmorMaterial,TFCItems.BlackSteelArmorMaterial,TFCItems.BlueSteelArmorMaterial,
TFCItems.BronzeArmorMaterial,TFCItems.CopperArmorMaterial,TFCItems.IronArmorMaterial,TFCItems.RedSteelArmorMaterial,TFCItems.RoseGoldArmorMaterial,
TFCItems.SteelArmorMaterial,TFCItems.TinArmorMaterial,TFCItems.ZincArmorMaterial};
int i = 0;
TFCItems.BismuthSheet = (new ItemMetalSheet(TFC_Settings.getIntFor(config,"item",NamesNS[i++]+" Sheet",num)).setUnlocalizedName("Bismuth Sheet"));num++;
TFCItems.BismuthBronzeSheet = (new ItemMetalSheet(TFC_Settings.getIntFor(config,"item",NamesNS[i++]+" Sheet",num)).setUnlocalizedName("Bismuth Bronze Sheet"));num++;
TFCItems.BlackBronzeSheet = (new ItemMetalSheet(TFC_Settings.getIntFor(config,"item",NamesNS[i++]+" Sheet",num)).setUnlocalizedName("Black Bronze Sheet"));num++;
TFCItems.BlackSteelSheet = (new ItemMetalSheet(TFC_Settings.getIntFor(config,"item",NamesNS[i++]+" Sheet",num)).setUnlocalizedName("Black Steel Sheet"));num++;
TFCItems.BlueSteelSheet = (new ItemMetalSheet(TFC_Settings.getIntFor(config,"item",NamesNS[i++]+" Sheet",num)).setUnlocalizedName("Blue Steel Sheet"));num++;
TFCItems.BronzeSheet = (new ItemMetalSheet(TFC_Settings.getIntFor(config,"item",NamesNS[i++]+" Sheet",num)).setUnlocalizedName("Bronze Sheet"));num++;
TFCItems.CopperSheet = (new ItemMetalSheet(TFC_Settings.getIntFor(config,"item",NamesNS[i++]+" Sheet",num)).setUnlocalizedName("Copper Sheet"));num++;
TFCItems.WroughtIronSheet = (new ItemMetalSheet(TFC_Settings.getIntFor(config,"item",NamesNS[i++]+" Sheet",num)).setUnlocalizedName("Wrought Iron Sheet"));num++;
TFCItems.RedSteelSheet = (new ItemMetalSheet(TFC_Settings.getIntFor(config,"item",NamesNS[i++]+" Sheet",num)).setUnlocalizedName("Red Steel Sheet"));num++;
TFCItems.RoseGoldSheet = (new ItemMetalSheet(TFC_Settings.getIntFor(config,"item",NamesNS[i++]+" Sheet",num)).setUnlocalizedName("Rose Gold Sheet"));num++;
TFCItems.SteelSheet = (new ItemMetalSheet(TFC_Settings.getIntFor(config,"item",NamesNS[i++]+" Sheet",num)).setUnlocalizedName("Steel Sheet"));num++;
TFCItems.TinSheet = (new ItemMetalSheet(TFC_Settings.getIntFor(config,"item",NamesNS[i++]+" Sheet",num)).setUnlocalizedName("Tin Sheet"));num++;
TFCItems.ZincSheet = (new ItemMetalSheet(TFC_Settings.getIntFor(config,"item",NamesNS[i++]+" Sheet",num)).setUnlocalizedName("Zinc Sheet"));num++;
i = 0;
TFCItems.BismuthSheet2x = (new ItemMetalSheet2x(TFC_Settings.getIntFor(config,"item",NamesNS[i++]+"Sheet2x",num)).setUnlocalizedName("Bismuth Double Sheet"));num++;
TFCItems.BismuthBronzeSheet2x = (new ItemMetalSheet2x(TFC_Settings.getIntFor(config,"item",NamesNS[i++]+"Sheet2x",num)).setUnlocalizedName("Bismuth Bronze Double Sheet"));num++;
TFCItems.BlackBronzeSheet2x = (new ItemMetalSheet2x(TFC_Settings.getIntFor(config,"item",NamesNS[i++]+"Sheet2x",num)).setUnlocalizedName("Black Bronze Double Sheet"));num++;
TFCItems.BlackSteelSheet2x = (new ItemMetalSheet2x(TFC_Settings.getIntFor(config,"item",NamesNS[i++]+"Sheet2x",num)).setUnlocalizedName("Black Steel Double Sheet"));num++;
TFCItems.BlueSteelSheet2x = (new ItemMetalSheet2x(TFC_Settings.getIntFor(config,"item",NamesNS[i++]+"Sheet2x",num)).setUnlocalizedName("Blue Steel Double Sheet"));num++;
TFCItems.BronzeSheet2x = (new ItemMetalSheet2x(TFC_Settings.getIntFor(config,"item",NamesNS[i++]+"Sheet2x",num)).setUnlocalizedName("Bronze Double Sheet"));num++;
TFCItems.CopperSheet2x = (new ItemMetalSheet2x(TFC_Settings.getIntFor(config,"item",NamesNS[i++]+"Sheet2x",num)).setUnlocalizedName("Copper Double Sheet"));num++;
TFCItems.WroughtIronSheet2x = (new ItemMetalSheet2x(TFC_Settings.getIntFor(config,"item",NamesNS[i++]+"Sheet2x",num)).setUnlocalizedName("Wrought Iron Double Sheet"));num++;
TFCItems.RedSteelSheet2x = (new ItemMetalSheet2x(TFC_Settings.getIntFor(config,"item",NamesNS[i++]+"Sheet2x",num)).setUnlocalizedName("Red Steel Double Sheet"));num++;
TFCItems.RoseGoldSheet2x = (new ItemMetalSheet2x(TFC_Settings.getIntFor(config,"item",NamesNS[i++]+"Sheet2x",num)).setUnlocalizedName("Rose Gold Double Sheet"));num++;
TFCItems.SteelSheet2x = (new ItemMetalSheet2x(TFC_Settings.getIntFor(config,"item",NamesNS[i++]+"Sheet2x",num)).setUnlocalizedName("Steel Double Sheet"));num++;
TFCItems.TinSheet2x = (new ItemMetalSheet2x(TFC_Settings.getIntFor(config,"item",NamesNS[i++]+"Sheet2x",num)).setUnlocalizedName("Tin Double Sheet"));num++;
TFCItems.ZincSheet2x = (new ItemMetalSheet2x(TFC_Settings.getIntFor(config,"item",NamesNS[i++]+"Sheet2x",num)).setUnlocalizedName("Zinc Double Sheet"));num++;
i = 0;
TFCItems.BismuthUnfinishedBoots = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Boots",num)).setUnlocalizedName(Names[i]+" Unfinished Boots")); num++;i++;
TFCItems.BismuthBronzeUnfinishedBoots = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Boots",num)).setUnlocalizedName(Names[i]+" Unfinished Boots")); num++;i++;
TFCItems.BlackBronzeUnfinishedBoots = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Boots",num)).setUnlocalizedName(Names[i]+" Unfinished Boots")); num++;i++;
TFCItems.BlackSteelUnfinishedBoots = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Boots",num)).setUnlocalizedName(Names[i]+" Unfinished Boots")); num++;i++;
TFCItems.BlueSteelUnfinishedBoots = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Boots",num)).setUnlocalizedName(Names[i]+" Unfinished Boots")); num++;i++;
TFCItems.BronzeUnfinishedBoots = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Boots",num)).setUnlocalizedName(Names[i]+" Unfinished Boots")); num++;i++;
TFCItems.CopperUnfinishedBoots = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Boots",num)).setUnlocalizedName(Names[i]+" Unfinished Boots")); num++;i++;
TFCItems.WroughtIronUnfinishedBoots = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Boots",num)).setUnlocalizedName(Names[i]+" Unfinished Boots")); num++;i++;
TFCItems.RedSteelUnfinishedBoots = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Boots",num)).setUnlocalizedName(Names[i]+" Unfinished Boots")); num++;i++;
TFCItems.RoseGoldUnfinishedBoots = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Boots",num)).setUnlocalizedName(Names[i]+" Unfinished Boots")); num++;i++;
TFCItems.SteelUnfinishedBoots = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Boots",num)).setUnlocalizedName(Names[i]+" Unfinished Boots")); num++;i++;
TFCItems.TinUnfinishedBoots = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Boots",num)).setUnlocalizedName(Names[i]+" Unfinished Boots")); num++;i++;
TFCItems.ZincUnfinishedBoots = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Boots",num)).setUnlocalizedName(Names[i]+" Unfinished Boots")); num++;i++;
i = 0;
TFCItems.BismuthBoots = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Boots",num),mats[i], proxy.getArmorRenderID(i), 3).setUnlocalizedName(Names[i]+" Boots")); num++;i++;
TFCItems.BismuthBronzeBoots = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Boots",num),mats[i], proxy.getArmorRenderID(i), 3).setUnlocalizedName(Names[i]+" Boots")); num++;i++;
TFCItems.BlackBronzeBoots = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Boots",num),mats[i], proxy.getArmorRenderID(i), 3).setUnlocalizedName(Names[i]+" Boots")); num++;i++;
TFCItems.BlackSteelBoots = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Boots",num),mats[i], proxy.getArmorRenderID(i), 3).setUnlocalizedName(Names[i]+" Boots")); num++;i++;
TFCItems.BlueSteelBoots = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Boots",num),mats[i], proxy.getArmorRenderID(i), 3).setUnlocalizedName(Names[i]+" Boots")); num++;i++;
TFCItems.BronzeBoots = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Boots",num),mats[i], proxy.getArmorRenderID(i), 3).setUnlocalizedName(Names[i]+" Boots")); num++;i++;
TFCItems.CopperBoots = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Boots",num),mats[i], proxy.getArmorRenderID(i), 3).setUnlocalizedName(Names[i]+" Boots")); num++;i++;
TFCItems.WroughtIronBoots = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Boots",num),mats[i], proxy.getArmorRenderID(i), 3).setUnlocalizedName(Names[i]+" Boots")); num++;i++;
TFCItems.RedSteelBoots = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Boots",num),mats[i], proxy.getArmorRenderID(i), 3).setUnlocalizedName(Names[i]+" Boots")); num++;i++;
TFCItems.RoseGoldBoots = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Boots",num),mats[i], proxy.getArmorRenderID(i), 3).setUnlocalizedName(Names[i]+" Boots")); num++;i++;
TFCItems.SteelBoots = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Boots",num),mats[i], proxy.getArmorRenderID(i), 3).setUnlocalizedName(Names[i]+" Boots")); num++;i++;
TFCItems.TinBoots = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Boots",num),mats[i], proxy.getArmorRenderID(i), 3).setUnlocalizedName(Names[i]+" Boots")); num++;i++;
TFCItems.ZincBoots = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Boots",num),mats[i], proxy.getArmorRenderID(i), 3).setUnlocalizedName(Names[i]+" Boots")); num++;i++;
i = 0;
TFCItems.BismuthUnfinishedGreaves = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Greaves",num)).setUnlocalizedName(Names[i]+" Unfinished Greaves")); num++;i++;
TFCItems.BismuthBronzeUnfinishedGreaves = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Greaves",num)).setUnlocalizedName(Names[i]+" Unfinished Greaves")); num++;i++;
TFCItems.BlackBronzeUnfinishedGreaves = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Greaves",num)).setUnlocalizedName(Names[i]+" Unfinished Greaves")); num++;i++;
TFCItems.BlackSteelUnfinishedGreaves = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Greaves",num)).setUnlocalizedName(Names[i]+" Unfinished Greaves")); num++;i++;
TFCItems.BlueSteelUnfinishedGreaves = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Greaves",num)).setUnlocalizedName(Names[i]+" Unfinished Greaves")); num++;i++;
TFCItems.BronzeUnfinishedGreaves = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Greaves",num)).setUnlocalizedName(Names[i]+" Unfinished Greaves")); num++;i++;
TFCItems.CopperUnfinishedGreaves = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Greaves",num)).setUnlocalizedName(Names[i]+" Unfinished Greaves")); num++;i++;
TFCItems.WroughtIronUnfinishedGreaves = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Greaves",num)).setUnlocalizedName(Names[i]+" Unfinished Greaves")); num++;i++;
TFCItems.RedSteelUnfinishedGreaves = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Greaves",num)).setUnlocalizedName(Names[i]+" Unfinished Greaves")); num++;i++;
TFCItems.RoseGoldUnfinishedGreaves = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Greaves",num)).setUnlocalizedName(Names[i]+" Unfinished Greaves")); num++;i++;
TFCItems.SteelUnfinishedGreaves = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Greaves",num)).setUnlocalizedName(Names[i]+" Unfinished Greaves")); num++;i++;
TFCItems.TinUnfinishedGreaves = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Greaves",num)).setUnlocalizedName(Names[i]+" Unfinished Greaves")); num++;i++;
TFCItems.ZincUnfinishedGreaves = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Greaves",num)).setUnlocalizedName(Names[i]+" Unfinished Greaves")); num++;i++;
i = 0;
TFCItems.BismuthGreaves = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Greaves",num),mats[i], proxy.getArmorRenderID(i), 2).setUnlocalizedName(Names[i]+" Greaves")); num++;i++;
TFCItems.BismuthBronzeGreaves = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Greaves",num),mats[i], proxy.getArmorRenderID(i), 2).setUnlocalizedName(Names[i]+" Greaves")); num++;i++;
TFCItems.BlackBronzeGreaves = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Greaves",num),mats[i], proxy.getArmorRenderID(i), 2).setUnlocalizedName(Names[i]+" Greaves")); num++;i++;
TFCItems.BlackSteelGreaves = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Greaves",num),mats[i], proxy.getArmorRenderID(i), 2).setUnlocalizedName(Names[i]+" Greaves")); num++;i++;
TFCItems.BlueSteelGreaves = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Greaves",num),mats[i], proxy.getArmorRenderID(i), 2).setUnlocalizedName(Names[i]+" Greaves")); num++;i++;
TFCItems.BronzeGreaves = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Greaves",num),mats[i], proxy.getArmorRenderID(i), 2).setUnlocalizedName(Names[i]+" Greaves")); num++;i++;
TFCItems.CopperGreaves = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Greaves",num),mats[i], proxy.getArmorRenderID(i), 2).setUnlocalizedName(Names[i]+" Greaves")); num++;i++;
TFCItems.WroughtIronGreaves = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Greaves",num),mats[i], proxy.getArmorRenderID(i), 2).setUnlocalizedName(Names[i]+" Greaves")); num++;i++;
TFCItems.RedSteelGreaves = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Greaves",num),mats[i], proxy.getArmorRenderID(i), 2).setUnlocalizedName(Names[i]+" Greaves")); num++;i++;
TFCItems.RoseGoldGreaves = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Greaves",num),mats[i], proxy.getArmorRenderID(i), 2).setUnlocalizedName(Names[i]+" Greaves")); num++;i++;
TFCItems.SteelGreaves = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Greaves",num),mats[i], proxy.getArmorRenderID(i), 2).setUnlocalizedName(Names[i]+" Greaves")); num++;i++;
TFCItems.TinGreaves = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Greaves",num),mats[i], proxy.getArmorRenderID(i), 2).setUnlocalizedName(Names[i]+" Greaves")); num++;i++;
TFCItems.ZincGreaves = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Greaves",num),mats[i], proxy.getArmorRenderID(i), 2).setUnlocalizedName(Names[i]+" Greaves")); num++;i++;
i = 0;
TFCItems.BismuthUnfinishedChestplate = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Chestplate",num)).setUnlocalizedName(Names[i]+" Unfinished Chestplate")); num++;i++;
TFCItems.BismuthBronzeUnfinishedChestplate = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Chestplate",num)).setUnlocalizedName(Names[i]+" Unfinished Chestplate")); num++;i++;
TFCItems.BlackBronzeUnfinishedChestplate = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Chestplate",num)).setUnlocalizedName(Names[i]+" Unfinished Chestplate")); num++;i++;
TFCItems.BlackSteelUnfinishedChestplate = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Chestplate",num)).setUnlocalizedName(Names[i]+" Unfinished Chestplate")); num++;i++;
TFCItems.BlueSteelUnfinishedChestplate = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Chestplate",num)).setUnlocalizedName(Names[i]+" Unfinished Chestplate")); num++;i++;
TFCItems.BronzeUnfinishedChestplate = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Chestplate",num)).setUnlocalizedName(Names[i]+" Unfinished Chestplate")); num++;i++;
TFCItems.CopperUnfinishedChestplate = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Chestplate",num)).setUnlocalizedName(Names[i]+" Unfinished Chestplate")); num++;i++;
TFCItems.WroughtIronUnfinishedChestplate = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Chestplate",num)).setUnlocalizedName(Names[i]+" Unfinished Chestplate")); num++;i++;
TFCItems.RedSteelUnfinishedChestplate = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Chestplate",num)).setUnlocalizedName(Names[i]+" Unfinished Chestplate")); num++;i++;
TFCItems.RoseGoldUnfinishedChestplate = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Chestplate",num)).setUnlocalizedName(Names[i]+" Unfinished Chestplate")); num++;i++;
TFCItems.SteelUnfinishedChestplate = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Chestplate",num)).setUnlocalizedName(Names[i]+" Unfinished Chestplate")); num++;i++;
TFCItems.TinUnfinishedChestplate = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Chestplate",num)).setUnlocalizedName(Names[i]+" Unfinished Chestplate")); num++;i++;
TFCItems.ZincUnfinishedChestplate = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Chestplate",num)).setUnlocalizedName(Names[i]+" Unfinished Chestplate")); num++;i++;
i = 0;
TFCItems.BismuthChestplate = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Chestplate",num),mats[i], proxy.getArmorRenderID(i), 1).setUnlocalizedName(Names[i]+" Chestplate")); num++;i++;
TFCItems.BismuthBronzeChestplate = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Chestplate",num),mats[i], proxy.getArmorRenderID(i), 1).setUnlocalizedName(Names[i]+" Chestplate")); num++;i++;
TFCItems.BlackBronzeChestplate = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Chestplate",num),mats[i], proxy.getArmorRenderID(i), 1).setUnlocalizedName(Names[i]+" Chestplate")); num++;i++;
TFCItems.BlackSteelChestplate = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Chestplate",num),mats[i], proxy.getArmorRenderID(i), 1).setUnlocalizedName(Names[i]+" Chestplate")); num++;i++;
TFCItems.BlueSteelChestplate = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Chestplate",num),mats[i], proxy.getArmorRenderID(i), 1).setUnlocalizedName(Names[i]+" Chestplate")); num++;i++;
TFCItems.BronzeChestplate = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Chestplate",num),mats[i], proxy.getArmorRenderID(i), 1).setUnlocalizedName(Names[i]+" Chestplate")); num++;i++;
TFCItems.CopperChestplate = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Chestplate",num),mats[i], proxy.getArmorRenderID(i), 1).setUnlocalizedName(Names[i]+" Chestplate")); num++;i++;
TFCItems.WroughtIronChestplate = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Chestplate",num),mats[i], proxy.getArmorRenderID(i), 1).setUnlocalizedName(Names[i]+" Chestplate")); num++;i++;
TFCItems.RedSteelChestplate = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Chestplate",num),mats[i], proxy.getArmorRenderID(i), 1).setUnlocalizedName(Names[i]+" Chestplate")); num++;i++;
TFCItems.RoseGoldChestplate = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Chestplate",num),mats[i], proxy.getArmorRenderID(i), 1).setUnlocalizedName(Names[i]+" Chestplate")); num++;i++;
TFCItems.SteelChestplate = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Chestplate",num),mats[i], proxy.getArmorRenderID(i), 1).setUnlocalizedName(Names[i]+" Chestplate")); num++;i++;
TFCItems.TinChestplate = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Chestplate",num),mats[i], proxy.getArmorRenderID(i), 1).setUnlocalizedName(Names[i]+" Chestplate")); num++;i++;
TFCItems.ZincChestplate = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Chestplate",num),mats[i], proxy.getArmorRenderID(i), 1).setUnlocalizedName(Names[i]+" Chestplate")); num++;i++;
i = 0;
TFCItems.BismuthUnfinishedHelmet = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Helmet",num)).setUnlocalizedName(Names[i]+" Unfinished Helmet")); num++;i++;
TFCItems.BismuthBronzeUnfinishedHelmet = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Helmet",num)).setUnlocalizedName(Names[i]+" Unfinished Helmet")); num++;i++;
TFCItems.BlackBronzeUnfinishedHelmet = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Helmet",num)).setUnlocalizedName(Names[i]+" Unfinished Helmet")); num++;i++;
TFCItems.BlackSteelUnfinishedHelmet = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Helmet",num)).setUnlocalizedName(Names[i]+" Unfinished Helmet")); num++;i++;
TFCItems.BlueSteelUnfinishedHelmet = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Helmet",num)).setUnlocalizedName(Names[i]+" Unfinished Helmet")); num++;i++;
TFCItems.BronzeUnfinishedHelmet = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Helmet",num)).setUnlocalizedName(Names[i]+" Unfinished Helmet")); num++;i++;
TFCItems.CopperUnfinishedHelmet = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Helmet",num)).setUnlocalizedName(Names[i]+" Unfinished Helmet")); num++;i++;
TFCItems.WroughtIronUnfinishedHelmet = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Helmet",num)).setUnlocalizedName(Names[i]+" Unfinished Helmet")); num++;i++;
TFCItems.RedSteelUnfinishedHelmet = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Helmet",num)).setUnlocalizedName(Names[i]+" Unfinished Helmet")); num++;i++;
TFCItems.RoseGoldUnfinishedHelmet = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Helmet",num)).setUnlocalizedName(Names[i]+" Unfinished Helmet")); num++;i++;
TFCItems.SteelUnfinishedHelmet = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Helmet",num)).setUnlocalizedName(Names[i]+" Unfinished Helmet")); num++;i++;
TFCItems.TinUnfinishedHelmet = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Helmet",num)).setUnlocalizedName(Names[i]+" Unfinished Helmet")); num++;i++;
TFCItems.ZincUnfinishedHelmet = (new ItemUnfinishedArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Unfinished Helmet",num)).setUnlocalizedName(Names[i]+" Unfinished Helmet")); num++;i++;
i = 0;
TFCItems.BismuthHelmet = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Helmet",num),mats[i], proxy.getArmorRenderID(i), 0).setUnlocalizedName(Names[i]+" Helmet")); num++;i++;
TFCItems.BismuthBronzeHelmet = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Helmet",num),mats[i], proxy.getArmorRenderID(i), 0).setUnlocalizedName(Names[i]+" Helmet")); num++;i++;
TFCItems.BlackBronzeHelmet = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Helmet",num),mats[i], proxy.getArmorRenderID(i), 0).setUnlocalizedName(Names[i]+" Helmet")); num++;i++;
TFCItems.BlackSteelHelmet = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Helmet",num),mats[i], proxy.getArmorRenderID(i), 0).setUnlocalizedName(Names[i]+" Helmet")); num++;i++;
TFCItems.BlueSteelHelmet = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Helmet",num),mats[i], proxy.getArmorRenderID(i), 0).setUnlocalizedName(Names[i]+" Helmet")); num++;i++;
TFCItems.BronzeHelmet = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Helmet",num),mats[i], proxy.getArmorRenderID(i), 0).setUnlocalizedName(Names[i]+" Helmet")); num++;i++;
TFCItems.CopperHelmet = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Helmet",num),mats[i], proxy.getArmorRenderID(i), 0).setUnlocalizedName(Names[i]+" Helmet")); num++;i++;
TFCItems.WroughtIronHelmet = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Helmet",num),mats[i], proxy.getArmorRenderID(i), 0).setUnlocalizedName(Names[i]+" Helmet")); num++;i++;
TFCItems.RedSteelHelmet = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Helmet",num),mats[i], proxy.getArmorRenderID(i), 0).setUnlocalizedName(Names[i]+" Helmet")); num++;i++;
TFCItems.RoseGoldHelmet = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Helmet",num),mats[i], proxy.getArmorRenderID(i), 0).setUnlocalizedName(Names[i]+" Helmet")); num++;i++;
TFCItems.SteelHelmet = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Helmet",num),mats[i], proxy.getArmorRenderID(i), 0).setUnlocalizedName(Names[i]+" Helmet")); num++;i++;
TFCItems.TinHelmet = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Helmet",num),mats[i], proxy.getArmorRenderID(i), 0).setUnlocalizedName(Names[i]+" Helmet")); num++;i++;
TFCItems.ZincHelmet = (new ItemCustomArmor(TFC_Settings.getIntFor(config,"item",NamesNS[i]+" Helmet",num),mats[i], proxy.getArmorRenderID(i), 0).setUnlocalizedName(Names[i]+" Helmet")); num++;i++;
i = 0;
TFCItems.BrassSheet = new ItemMetalSheet(TFC_Settings.getIntFor(config,"item",NamesNSO[i]+" Sheet",num++)).setUnlocalizedName(NamesNSO[i++]+" Sheet");
TFCItems.GoldSheet = new ItemMetalSheet(TFC_Settings.getIntFor(config,"item",NamesNSO[i]+" Sheet",num++)).setUnlocalizedName(NamesNSO[i++]+" Sheet");
TFCItems.LeadSheet = new ItemMetalSheet(TFC_Settings.getIntFor(config,"item",NamesNSO[i]+" Sheet",num++)).setUnlocalizedName(NamesNSO[i++]+" Sheet");
TFCItems.NickelSheet = new ItemMetalSheet(TFC_Settings.getIntFor(config,"item",NamesNSO[i]+" Sheet",num++)).setUnlocalizedName(NamesNSO[i++]+" Sheet");
TFCItems.PigIronSheet = new ItemMetalSheet(TFC_Settings.getIntFor(config,"item",NamesNSO[i]+" Sheet",num++)).setUnlocalizedName(NamesNSO[i++]+" Sheet");
TFCItems.PlatinumSheet = new ItemMetalSheet(TFC_Settings.getIntFor(config,"item",NamesNSO[i]+" Sheet",num++)).setUnlocalizedName(NamesNSO[i++]+" Sheet");
TFCItems.SilverSheet = new ItemMetalSheet(TFC_Settings.getIntFor(config,"item",NamesNSO[i]+" Sheet",num++)).setUnlocalizedName(NamesNSO[i++]+" Sheet");
TFCItems.SterlingSilverSheet = new ItemMetalSheet(TFC_Settings.getIntFor(config,"item",NamesNSO[i]+" Sheet",num++)).setUnlocalizedName(NamesNSO[i++]+" Sheet");
i = 0;
TFCItems.BrassSheet2x = new ItemMetalSheet2x(TFC_Settings.getIntFor(config,"item",NamesNSO[i]+"Sheet2x",num++)).setUnlocalizedName(NamesNSO[i++]+" Double Sheet");
TFCItems.GoldSheet2x = new ItemMetalSheet2x(TFC_Settings.getIntFor(config,"item",NamesNSO[i]+"Sheet2x",num++)).setUnlocalizedName(NamesNSO[i++]+" Double Sheet");
TFCItems.LeadSheet2x = new ItemMetalSheet2x(TFC_Settings.getIntFor(config,"item",NamesNSO[i]+"Sheet2x",num++)).setUnlocalizedName(NamesNSO[i++]+" Double Sheet");
TFCItems.NickelSheet2x = new ItemMetalSheet2x(TFC_Settings.getIntFor(config,"item",NamesNSO[i]+"Sheet2x",num++)).setUnlocalizedName(NamesNSO[i++]+" Double Sheet");
TFCItems.PigIronSheet2x = new ItemMetalSheet2x(TFC_Settings.getIntFor(config,"item",NamesNSO[i]+"Sheet2x",num++)).setUnlocalizedName(NamesNSO[i++]+" Double Sheet");
TFCItems.PlatinumSheet2x = new ItemMetalSheet2x(TFC_Settings.getIntFor(config,"item",NamesNSO[i]+"Sheet2x",num++)).setUnlocalizedName(NamesNSO[i++]+" Double Sheet");
TFCItems.SilverSheet2x = new ItemMetalSheet2x(TFC_Settings.getIntFor(config,"item",NamesNSO[i]+"Sheet2x",num++)).setUnlocalizedName(NamesNSO[i++]+" Double Sheet");
TFCItems.SterlingSilverSheet2x = new ItemMetalSheet2x(TFC_Settings.getIntFor(config,"item",NamesNSO[i]+"Sheet2x",num++)).setUnlocalizedName(NamesNSO[i++]+" Double Sheet");
}
public static Item[] Meals;
public static EnumArmorMaterial BismuthArmorMaterial;
public static EnumArmorMaterial BismuthBronzeArmorMaterial;
public static EnumArmorMaterial BlackBronzeArmorMaterial;
public static EnumArmorMaterial BlackSteelArmorMaterial;
public static EnumArmorMaterial BlueSteelArmorMaterial;
public static EnumArmorMaterial BronzeArmorMaterial;
public static EnumArmorMaterial CopperArmorMaterial;
public static EnumArmorMaterial IronArmorMaterial;
public static EnumArmorMaterial RedSteelArmorMaterial;
public static EnumArmorMaterial RoseGoldArmorMaterial;
public static EnumArmorMaterial SteelArmorMaterial;
public static EnumArmorMaterial TinArmorMaterial;
public static EnumArmorMaterial ZincArmorMaterial;
}
| false | true | public static void Setup()
{
try
{
config = new net.minecraftforge.common.Configuration(
new File(TerraFirmaCraft.proxy.getMinecraftDir(), "/config/TFC.cfg"));
config.load();
} catch (Exception e) {
System.out.println(new StringBuilder().append("[TFC] Error while trying to access item configuration!").toString());
config = null;
}
IgInToolMaterial = EnumHelper.addToolMaterial("IgIn", 1, IgInStoneUses, 7F, 10, 5);
SedToolMaterial = EnumHelper.addToolMaterial("Sed", 1, SedStoneUses, 6F, 10, 5);
IgExToolMaterial = EnumHelper.addToolMaterial("IgEx", 1, IgExStoneUses, 7F, 10, 5);
MMToolMaterial = EnumHelper.addToolMaterial("MM", 1, MMStoneUses, 6.5F, 10, 5);
BismuthToolMaterial = EnumHelper.addToolMaterial("Bismuth", 2, BismuthUses, BismuthEff, 65, 10);
BismuthBronzeToolMaterial = EnumHelper.addToolMaterial("BismuthBronze", 2, BismuthBronzeUses, BismuthBronzeEff, 85, 10);
BlackBronzeToolMaterial = EnumHelper.addToolMaterial("BlackBronze", 2, BlackBronzeUses, BlackBronzeEff, 100, 10);
BlackSteelToolMaterial = EnumHelper.addToolMaterial("BlackSteel", 2, BlackSteelUses, BlackSteelEff, 165, 12);
BlueSteelToolMaterial = EnumHelper.addToolMaterial("BlueSteel", 3, BlueSteelUses, BlueSteelEff, 185, 22);
BronzeToolMaterial = EnumHelper.addToolMaterial("Bronze", 2, BronzeUses, BronzeEff, 100, 13);
CopperToolMaterial = EnumHelper.addToolMaterial("Copper", 2, CopperUses, CopperEff, 85, 8);
IronToolMaterial = EnumHelper.addToolMaterial("Iron", 2, WroughtIronUses, WroughtIronEff, 135, 10);
RedSteelToolMaterial = EnumHelper.addToolMaterial("RedSteel", 3, RedSteelUses, RedSteelEff, 185, 22);
RoseGoldToolMaterial = EnumHelper.addToolMaterial("RoseGold", 2, RoseGoldUses, RoseGoldEff, 100, 20);
SteelToolMaterial = EnumHelper.addToolMaterial("Steel", 2, SteelUses, SteelEff, 150, 10);
TinToolMaterial = EnumHelper.addToolMaterial("Tin", 2, TinUses, TinEff, 65, 8);
ZincToolMaterial = EnumHelper.addToolMaterial("Zinc", 2, ZincUses, ZincEff, 65, 8);
System.out.println(new StringBuilder().append("[TFC] Loading Items").toString());
//Replace any vanilla Items here
Item.itemsList[Item.coal.itemID] = null; Item.itemsList[Item.coal.itemID] = (new TFC.Items.ItemCoal(7)).setUnlocalizedName("coal");
Item.itemsList[Item.stick.itemID] = null; Item.itemsList[Item.stick.itemID] = new ItemStick(24).setFull3D().setUnlocalizedName("stick");
Item.itemsList[Item.leather.itemID] = null; Item.itemsList[Item.leather.itemID] = new ItemTerra(Item.leather.itemID).setFull3D().setUnlocalizedName("leather");
Item.itemsList[Block.vine.blockID] = new ItemColored(Block.vine.blockID - 256, false);
minecartCrate = (new ItemCustomMinecart(TFC_Settings.getIntFor(config,"item","minecartCrate",16000), 1)).setUnlocalizedName("minecartChest");
Item.itemsList[5+256] = null; Item.itemsList[5+256] = (new ItemCustomBow(5)).setUnlocalizedName("bow");
Item.itemsList[63+256] = null; Item.itemsList[63+256] = new ItemTerra(63).setUnlocalizedName("porkchopRaw");
Item.itemsList[64+256] = null; Item.itemsList[64+256] = new ItemTerraFood(64, 35, 0.8F, true, 38).setFolder("").setUnlocalizedName("porkchopCooked");
Item.itemsList[93+256] = null; Item.itemsList[93+256] = new ItemTerra(93).setUnlocalizedName("fishRaw");
Item.itemsList[94+256] = null; Item.itemsList[94+256] = new ItemTerraFood(94, 30, 0.6F, true, 39).setFolder("").setUnlocalizedName("fishCooked");
Item.itemsList[107+256] = null; Item.itemsList[107+256] = new ItemTerra(107).setUnlocalizedName("beefRaw");
Item.itemsList[108+256] = null; Item.itemsList[108+256] = new ItemTerraFood(108, 40, 0.8F, true, 40).setFolder("").setUnlocalizedName("beefCooked");
Item.itemsList[109+256] = null; Item.itemsList[109+256] = new ItemTerra(109).setUnlocalizedName("chickenRaw");
Item.itemsList[110+256] = null; Item.itemsList[110+256] = new ItemTerraFood(110, 35, 0.6F, true, 41).setFolder("").setUnlocalizedName("chickenCooked");
Item.itemsList[41+256] = null; Item.itemsList[41+256] = (new ItemTerraFood(41, 25, 0.6F, false, 42)).setFolder("").setUnlocalizedName("bread");
Item.itemsList[88+256] = null; Item.itemsList[88+256] = (new ItemTerra(88)).setUnlocalizedName("egg");
Item.itemsList[Item.dyePowder.itemID] = null; Item.itemsList[Item.dyePowder.itemID] = new ItemDyeCustom(95).setUnlocalizedName("dyePowder");
Item.itemsList[Item.potion.itemID] = null; Item.itemsList[Item.potion.itemID] = (new ItemCustomPotion(117)).setUnlocalizedName("potion");
Item.itemsList[Block.tallGrass.blockID] = null; Item.itemsList[Block.tallGrass.blockID] = (new ItemColored(Block.tallGrass.blockID - 256, true)).setBlockNames(new String[] {"shrub", "grass", "fern"});
GoldPan = new ItemGoldPan(TFC_Settings.getIntFor(config,"item","terraGoldPan",16001)).setUnlocalizedName("GoldPan");
SluiceItem = new ItemSluice(TFC_Settings.getIntFor(config,"item","terraSluiceItem",16002)).setFolder("devices/").setUnlocalizedName("SluiceItem");
ProPickBismuth = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickBismuth",16004)).setUnlocalizedName("Bismuth ProPick").setMaxDamage(BismuthUses);
ProPickBismuthBronze = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickBismuthBronze",16005)).setUnlocalizedName("Bismuth Bronze ProPick").setMaxDamage(BismuthBronzeUses);
ProPickBlackBronze = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickBlackBronze",16006)).setUnlocalizedName("Black Bronze ProPick").setMaxDamage(BlackBronzeUses);
ProPickBlackSteel = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickBlackSteel",16007)).setUnlocalizedName("Black Steel ProPick").setMaxDamage(BlackSteelUses);
ProPickBlueSteel = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickBlueSteel",16008)).setUnlocalizedName("Blue Steel ProPick").setMaxDamage(BlueSteelUses);
ProPickBronze = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickBronze",16009)).setUnlocalizedName("Bronze ProPick").setMaxDamage(BronzeUses);
ProPickCopper = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickCopper",16010)).setUnlocalizedName("Copper ProPick").setMaxDamage(CopperUses);
ProPickIron = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickWroughtIron",16012)).setUnlocalizedName("Wrought Iron ProPick").setMaxDamage(WroughtIronUses);
ProPickRedSteel = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickRedSteel",16016)).setUnlocalizedName("Red Steel ProPick").setMaxDamage(RedSteelUses);
ProPickRoseGold = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickRoseGold",16017)).setUnlocalizedName("Rose Gold ProPick").setMaxDamage(RoseGoldUses);
ProPickSteel = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickSteel",16019)).setUnlocalizedName("Steel ProPick").setMaxDamage(SteelUses);
ProPickTin = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickTin",16021)).setUnlocalizedName("Tin ProPick").setMaxDamage(TinUses);
ProPickZinc = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickZinc",16022)).setUnlocalizedName("Zinc ProPick").setMaxDamage(ZincUses);
BismuthIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","BismuthIngot",16028), EnumMetalType.BISMUTH).setUnlocalizedName("Bismuth Ingot");
BismuthBronzeIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","BismuthBronzeIngot",16029), EnumMetalType.BISMUTHBRONZE).setUnlocalizedName("Bismuth Bronze Ingot");
BlackBronzeIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","BlackBronzeIngot",16030), EnumMetalType.BLACKBRONZE).setUnlocalizedName("Black Bronze Ingot");
BlackSteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","BlackSteelIngot",16031), EnumMetalType.BLACKSTEEL).setUnlocalizedName("Black Steel Ingot");
BlueSteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","BlueSteelIngot",16032), EnumMetalType.BLUESTEEL).setUnlocalizedName("Blue Steel Ingot");
BrassIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","BrassIngot",16033), EnumMetalType.BRASS).setUnlocalizedName("Brass Ingot");
BronzeIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","BronzeIngot",16034), EnumMetalType.BRONZE).setUnlocalizedName("Bronze Ingot");
CopperIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","CopperIngot",16035), EnumMetalType.COPPER).setUnlocalizedName("Copper Ingot");
GoldIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","GoldIngot",16036), EnumMetalType.GOLD).setUnlocalizedName("Gold Ingot");
WroughtIronIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","WroughtIronIngot",16037), EnumMetalType.WROUGHTIRON).setUnlocalizedName("Wrought Iron Ingot");
LeadIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","LeadIngot",16038), EnumMetalType.LEAD).setUnlocalizedName("Lead Ingot");
NickelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","NickelIngot",16039), EnumMetalType.NICKEL).setUnlocalizedName("Nickel Ingot");
PigIronIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","PigIronIngot",16040), EnumMetalType.PIGIRON).setUnlocalizedName("Pig Iron Ingot");
PlatinumIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","PlatinumIngot",16041), EnumMetalType.PLATINUM).setUnlocalizedName("Platinum Ingot");
RedSteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","RedSteelIngot",16042), EnumMetalType.REDSTEEL).setUnlocalizedName("Red Steel Ingot");
RoseGoldIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","RoseGoldIngot",16043), EnumMetalType.ROSEGOLD).setUnlocalizedName("Rose Gold Ingot");
SilverIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","SilverIngot",16044), EnumMetalType.SILVER).setUnlocalizedName("Silver Ingot");
SteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","SteelIngot",16045), EnumMetalType.STEEL).setUnlocalizedName("Steel Ingot");
SterlingSilverIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","SterlingSilverIngot",16046), EnumMetalType.STERLINGSILVER).setUnlocalizedName("Sterling Silver Ingot");
TinIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","TinIngot",16047), EnumMetalType.TIN).setUnlocalizedName("Tin Ingot");
ZincIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","ZincIngot",16048), EnumMetalType.ZINC).setUnlocalizedName("Zinc Ingot");
BismuthIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","BismuthIngot2x",16049), EnumMetalType.BISMUTH).setUnlocalizedName("Bismuth Double Ingot")).setSize(EnumSize.LARGE);
BismuthBronzeIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","BismuthBronzeIngot2x",16050), EnumMetalType.BISMUTHBRONZE).setUnlocalizedName("Bismuth Bronze Double Ingot")).setSize(EnumSize.LARGE);
BlackBronzeIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","BlackBronzeIngot2x",16051), EnumMetalType.BLACKBRONZE).setUnlocalizedName("Black Bronze Double Ingot")).setSize(EnumSize.LARGE);
BlackSteelIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","BlackSteelIngot2x",16052), EnumMetalType.BLACKSTEEL).setUnlocalizedName("Black Steel Double Ingot")).setSize(EnumSize.LARGE);
BlueSteelIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","BlueSteelIngot2x",16053), EnumMetalType.BLUESTEEL).setUnlocalizedName("Blue Steel Double Ingot")).setSize(EnumSize.LARGE);
BrassIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","BrassIngot2x",16054), EnumMetalType.BRASS).setUnlocalizedName("Brass Double Ingot")).setSize(EnumSize.LARGE);
BronzeIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","BronzeIngot2x",16055), EnumMetalType.BRONZE).setUnlocalizedName("Bronze Double Ingot")).setSize(EnumSize.LARGE);
CopperIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","CopperIngot2x",16056), EnumMetalType.COPPER).setUnlocalizedName("Copper Double Ingot")).setSize(EnumSize.LARGE);
GoldIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","GoldIngot2x",16057), EnumMetalType.GOLD).setUnlocalizedName("Gold Double Ingot")).setSize(EnumSize.LARGE);
WroughtIronIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","WroughtIronIngot2x",16058), EnumMetalType.WROUGHTIRON).setUnlocalizedName("Wrought Iron Double Ingot")).setSize(EnumSize.LARGE);
LeadIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","LeadIngot2x",16059), EnumMetalType.LEAD).setUnlocalizedName("Lead Double Ingot")).setSize(EnumSize.LARGE);
NickelIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","NickelIngot2x",16060), EnumMetalType.NICKEL).setUnlocalizedName("Nickel Double Ingot")).setSize(EnumSize.LARGE);
PigIronIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","PigIronIngot2x",16061), EnumMetalType.PIGIRON).setUnlocalizedName("Pig Iron Double Ingot")).setSize(EnumSize.LARGE);
PlatinumIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","PlatinumIngot2x",16062), EnumMetalType.PLATINUM).setUnlocalizedName("Platinum Double Ingot")).setSize(EnumSize.LARGE);
RedSteelIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","RedSteelIngot2x",16063), EnumMetalType.REDSTEEL).setUnlocalizedName("Red Steel Double Ingot")).setSize(EnumSize.LARGE);
RoseGoldIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","RoseGoldIngot2x",16064), EnumMetalType.ROSEGOLD).setUnlocalizedName("Rose Gold Double Ingot")).setSize(EnumSize.LARGE);
SilverIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","SilverIngot2x",16065), EnumMetalType.SILVER).setUnlocalizedName("Silver Double Ingot")).setSize(EnumSize.LARGE);
SteelIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","SteelIngot2x",16066), EnumMetalType.STEEL).setUnlocalizedName("Steel Double Ingot")).setSize(EnumSize.LARGE);
SterlingSilverIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","SterlingSilverIngot2x",16067), EnumMetalType.STERLINGSILVER).setUnlocalizedName("Sterling Silver Double Ingot")).setSize(EnumSize.LARGE);
TinIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","TinIngot2x",16068), EnumMetalType.TIN).setUnlocalizedName("Tin Double Ingot")).setSize(EnumSize.LARGE);
ZincIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","ZincIngot2x",16069), EnumMetalType.ZINC).setUnlocalizedName("Zinc Double Ingot")).setSize(EnumSize.LARGE);
SulfurPowder = new ItemTerra(TFC_Settings.getIntFor(config,"item","SulfurPowder",16070)).setUnlocalizedName("Sulfur Powder");
SaltpeterPowder = new ItemTerra(TFC_Settings.getIntFor(config,"item","SaltpeterPowder",16071)).setUnlocalizedName("Saltpeter Powder");
GemRuby = new ItemGem(TFC_Settings.getIntFor(config,"item","GemRuby",16080)).setUnlocalizedName("Ruby");
GemSapphire = new ItemGem(TFC_Settings.getIntFor(config,"item","GemSapphire",16081)).setUnlocalizedName("Sapphire");
GemEmerald = new ItemGem(TFC_Settings.getIntFor(config,"item","GemEmerald",16082)).setUnlocalizedName("Emerald");
GemTopaz = new ItemGem(TFC_Settings.getIntFor(config,"item","GemTopaz",16083)).setUnlocalizedName("Topaz");
GemTourmaline = new ItemGem(TFC_Settings.getIntFor(config,"item","GemTourmaline",16084)).setUnlocalizedName("Tourmaline");
GemJade = new ItemGem(TFC_Settings.getIntFor(config,"item","GemJade",16085)).setUnlocalizedName("Jade");
GemBeryl = new ItemGem(TFC_Settings.getIntFor(config,"item","GemBeryl",16086)).setUnlocalizedName("Beryl");
GemAgate = new ItemGem(TFC_Settings.getIntFor(config,"item","GemAgate",16087)).setUnlocalizedName("Agate");
GemOpal = new ItemGem(TFC_Settings.getIntFor(config,"item","GemOpal",16088)).setUnlocalizedName("Opal");
GemGarnet = new ItemGem(TFC_Settings.getIntFor(config,"item","GemGarnet",16089)).setUnlocalizedName("Garnet");
GemJasper = new ItemGem(TFC_Settings.getIntFor(config,"item","GemJasper",16090)).setUnlocalizedName("Jasper");
GemAmethyst = new ItemGem(TFC_Settings.getIntFor(config,"item","GemAmethyst",16091)).setUnlocalizedName("Amethyst");
GemDiamond = new ItemGem(TFC_Settings.getIntFor(config,"item","GemDiamond",16092)).setUnlocalizedName("Diamond");
//Tools
IgInShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","IgInShovel",16101),IgInToolMaterial).setUnlocalizedName("Stone Shovel").setMaxDamage(IgInStoneUses);
IgInAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","IgInAxe",16102),IgInToolMaterial).setUnlocalizedName("Stone Axe").setMaxDamage(IgInStoneUses);
IgInHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","IgInHoe",16103),IgInToolMaterial).setUnlocalizedName("Stone Hoe").setMaxDamage(IgInStoneUses);
SedShovel= new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","SedShovel",16105),SedToolMaterial).setUnlocalizedName("Stone Shovel").setMaxDamage(SedStoneUses);
SedAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","SedAxe",16106),SedToolMaterial).setUnlocalizedName("Stone Axe").setMaxDamage(SedStoneUses);
SedHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","SedHoe",16107),SedToolMaterial).setUnlocalizedName("Stone Hoe").setMaxDamage(SedStoneUses);
IgExShovel= new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","IgExShovel",16109),IgExToolMaterial).setUnlocalizedName("Stone Shovel").setMaxDamage(IgExStoneUses);
IgExAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","IgExAxe",16110),IgExToolMaterial).setUnlocalizedName("Stone Axe").setMaxDamage(IgExStoneUses);
IgExHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","IgExHoe",16111),IgExToolMaterial).setUnlocalizedName("Stone Hoe").setMaxDamage(IgExStoneUses);
MMShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","MMShovel",16113),MMToolMaterial).setUnlocalizedName("Stone Shovel").setMaxDamage(MMStoneUses);
MMAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","MMAxe",16114),MMToolMaterial).setUnlocalizedName("Stone Axe").setMaxDamage(MMStoneUses);
MMHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","MMHoe",16115),MMToolMaterial).setUnlocalizedName("Stone Hoe").setMaxDamage(MMStoneUses);
BismuthPick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","BismuthPick",16116),BismuthToolMaterial).setUnlocalizedName("Bismuth Pick").setMaxDamage(BismuthUses);
BismuthShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","BismuthShovel",16117),BismuthToolMaterial).setUnlocalizedName("Bismuth Shovel").setMaxDamage(BismuthUses);
BismuthAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","BismuthAxe",16118),BismuthToolMaterial).setUnlocalizedName("Bismuth Axe").setMaxDamage(BismuthUses);
BismuthHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","BismuthHoe",16119),BismuthToolMaterial).setUnlocalizedName("Bismuth Hoe").setMaxDamage(BismuthUses);
BismuthBronzePick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","BismuthBronzePick",16120),BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Pick").setMaxDamage(BismuthBronzeUses);
BismuthBronzeShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","BismuthBronzeShovel",16121),BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Shovel").setMaxDamage(BismuthBronzeUses);
BismuthBronzeAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","BismuthBronzeAxe",16122),BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Axe").setMaxDamage(BismuthBronzeUses);
BismuthBronzeHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","BismuthBronzeHoe",16123),BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Hoe").setMaxDamage(BismuthBronzeUses);
BlackBronzePick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","BlackBronzePick",16124),BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Pick").setMaxDamage(BlackBronzeUses);
BlackBronzeShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","BlackBronzeShovel",16125),BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Shovel").setMaxDamage(BlackBronzeUses);
BlackBronzeAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","BlackBronzeAxe",16126),BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Axe").setMaxDamage(BlackBronzeUses);
BlackBronzeHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","BlackBronzeHoe",16127),BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Hoe").setMaxDamage(BlackBronzeUses);
BlackSteelPick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","BlackSteelPick",16128),BlackSteelToolMaterial).setUnlocalizedName("Black Steel Pick").setMaxDamage(BlackSteelUses);
BlackSteelShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","BlackSteelShovel",16129),BlackSteelToolMaterial).setUnlocalizedName("Black Steel Shovel").setMaxDamage(BlackSteelUses);
BlackSteelAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","BlackSteelAxe",16130),BlackSteelToolMaterial).setUnlocalizedName("Black Steel Axe").setMaxDamage(BlackSteelUses);
BlackSteelHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","BlackSteelHoe",16131),BlackSteelToolMaterial).setUnlocalizedName("Black Steel Hoe").setMaxDamage(BlackSteelUses);
BlueSteelPick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","BlueSteelPick",16132),BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Pick").setMaxDamage(BlueSteelUses);
BlueSteelShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","BlueSteelShovel",16133),BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Shovel").setMaxDamage(BlueSteelUses);
BlueSteelAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","BlueSteelAxe",16134),BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Axe").setMaxDamage(BlueSteelUses);
BlueSteelHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","BlueSteelHoe",16135),BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Hoe").setMaxDamage(BlueSteelUses);
BronzePick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","BronzePick",16136),BronzeToolMaterial).setUnlocalizedName("Bronze Pick").setMaxDamage(BronzeUses);
BronzeShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","BronzeShovel",16137),BronzeToolMaterial).setUnlocalizedName("Bronze Shovel").setMaxDamage(BronzeUses);
BronzeAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","BronzeAxe",16138),BronzeToolMaterial).setUnlocalizedName("Bronze Axe").setMaxDamage(BronzeUses);
BronzeHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","BronzeHoe",16139),BronzeToolMaterial).setUnlocalizedName("Bronze Hoe").setMaxDamage(BronzeUses);
CopperPick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","CopperPick",16140),CopperToolMaterial).setUnlocalizedName("Copper Pick").setMaxDamage(CopperUses);
CopperShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","CopperShovel",16141),CopperToolMaterial).setUnlocalizedName("Copper Shovel").setMaxDamage(CopperUses);
CopperAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","CopperAxe",16142),CopperToolMaterial).setUnlocalizedName("Copper Axe").setMaxDamage(CopperUses);
CopperHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","CopperHoe",16143),CopperToolMaterial).setUnlocalizedName("Copper Hoe").setMaxDamage(CopperUses);
WroughtIronPick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","WroughtIronPick",16148),IronToolMaterial).setUnlocalizedName("Wrought Iron Pick").setMaxDamage(WroughtIronUses);
WroughtIronShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","WroughtIronShovel",16149),IronToolMaterial).setUnlocalizedName("Wrought Iron Shovel").setMaxDamage(WroughtIronUses);
WroughtIronAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","WroughtIronAxe",16150),IronToolMaterial).setUnlocalizedName("Wrought Iron Axe").setMaxDamage(WroughtIronUses);
WroughtIronHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","WroughtIronHoe",16151),IronToolMaterial).setUnlocalizedName("Wrought Iron Hoe").setMaxDamage(WroughtIronUses);;
RedSteelPick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","RedSteelPick",16168),RedSteelToolMaterial).setUnlocalizedName("Red Steel Pick").setMaxDamage(RedSteelUses);
RedSteelShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","RedSteelShovel",16169),RedSteelToolMaterial).setUnlocalizedName("Red Steel Shovel").setMaxDamage(RedSteelUses);
RedSteelAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","RedSteelAxe",16170),RedSteelToolMaterial).setUnlocalizedName("Red Steel Axe").setMaxDamage(RedSteelUses);
RedSteelHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","RedSteelHoe",16171),RedSteelToolMaterial).setUnlocalizedName("Red Steel Hoe").setMaxDamage(RedSteelUses);
RoseGoldPick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","RoseGoldPick",16172),RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Pick").setMaxDamage(RoseGoldUses);
RoseGoldShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","RoseGoldShovel",16173),RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Shovel").setMaxDamage(RoseGoldUses);
RoseGoldAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","RoseGoldAxe",16174),RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Axe").setMaxDamage(RoseGoldUses);
RoseGoldHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","RoseGoldHoe",16175),RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Hoe").setMaxDamage(RoseGoldUses);
SteelPick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","SteelPick",16180),SteelToolMaterial).setUnlocalizedName("Steel Pick").setMaxDamage(SteelUses);
SteelShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","SteelShovel",16181),SteelToolMaterial).setUnlocalizedName("Steel Shovel").setMaxDamage(SteelUses);
SteelAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","SteelAxe",16182),SteelToolMaterial).setUnlocalizedName("Steel Axe").setMaxDamage(SteelUses);
SteelHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","SteelHoe",16183),SteelToolMaterial).setUnlocalizedName("Steel Hoe").setMaxDamage(SteelUses);
TinPick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","TinPick",16188),TinToolMaterial).setUnlocalizedName("Tin Pick").setMaxDamage(TinUses);
TinShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","TinShovel",16189),TinToolMaterial).setUnlocalizedName("Tin Shovel").setMaxDamage(TinUses);
TinAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","TinAxe",16190),TinToolMaterial).setUnlocalizedName("Tin Axe").setMaxDamage(TinUses);
TinHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","TinHoe",16191),TinToolMaterial).setUnlocalizedName("Tin Hoe").setMaxDamage(TinUses);
ZincPick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","ZincPick",16192),ZincToolMaterial).setUnlocalizedName("Zinc Pick").setMaxDamage(ZincUses);
ZincShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","ZincShovel",16193),ZincToolMaterial).setUnlocalizedName("Zinc Shovel").setMaxDamage(ZincUses);
ZincAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","ZincAxe",16194),ZincToolMaterial).setUnlocalizedName("Zinc Axe").setMaxDamage(ZincUses);
ZincHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","ZincHoe",16195),ZincToolMaterial).setUnlocalizedName("Zinc Hoe").setMaxDamage(ZincUses);
//chisels
BismuthChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","BismuthChisel",16226),BismuthToolMaterial).setUnlocalizedName("Bismuth Chisel").setMaxDamage(BismuthUses);
BismuthBronzeChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","BismuthBronzeChisel",16227),BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Chisel").setMaxDamage(BismuthBronzeUses);
BlackBronzeChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","BlackBronzeChisel",16228),BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Chisel").setMaxDamage(BlackBronzeUses);
BlackSteelChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","BlackSteelChisel",16230),BlackSteelToolMaterial).setUnlocalizedName("Black Steel Chisel").setMaxDamage(BlackSteelUses);
BlueSteelChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","BlueSteelChisel",16231),BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Chisel").setMaxDamage(BlueSteelUses);
BronzeChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","BronzeChisel",16232),BronzeToolMaterial).setUnlocalizedName("Bronze Chisel").setMaxDamage(BronzeUses);
CopperChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","CopperChisel",16233),CopperToolMaterial).setUnlocalizedName("Copper Chisel").setMaxDamage(CopperUses);
WroughtIronChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","WroughtIronChisel",16234),IronToolMaterial).setUnlocalizedName("Wrought Iron Chisel").setMaxDamage(WroughtIronUses);
RedSteelChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","RedSteelChisel",16235),RedSteelToolMaterial).setUnlocalizedName("Red Steel Chisel").setMaxDamage(RedSteelUses);
RoseGoldChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","RoseGoldChisel",16236),RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Chisel").setMaxDamage(RoseGoldUses);
SteelChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","SteelChisel",16237),SteelToolMaterial).setUnlocalizedName("Steel Chisel").setMaxDamage(SteelUses);
TinChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","TinChisel",16238),TinToolMaterial).setUnlocalizedName("Tin Chisel").setMaxDamage(TinUses);
ZincChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","ZincChisel",16239),ZincToolMaterial).setUnlocalizedName("Zinc Chisel").setMaxDamage(ZincUses);
StoneChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","StoneChisel",16240),IgInToolMaterial).setUnlocalizedName("Stone Chisel").setMaxDamage(IgInStoneUses);
BismuthSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BismuthSword",16245),BismuthToolMaterial).setUnlocalizedName("Bismuth Sword").setMaxDamage(BismuthUses);
BismuthBronzeSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BismuthBronzeSword",16246),BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Sword").setMaxDamage(BismuthBronzeUses);
BlackBronzeSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BlackBronzeSword",16247),BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Sword").setMaxDamage(BlackBronzeUses);
BlackSteelSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BlackSteelSword",16248),BlackSteelToolMaterial).setUnlocalizedName("Black Steel Sword").setMaxDamage(BlackSteelUses);
BlueSteelSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BlueSteelSword",16249),BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Sword").setMaxDamage(BlueSteelUses);
BronzeSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BronzeSword",16250),BronzeToolMaterial).setUnlocalizedName("Bronze Sword").setMaxDamage(BronzeUses);
CopperSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","CopperSword",16251),CopperToolMaterial).setUnlocalizedName("Copper Sword").setMaxDamage(CopperUses);
WroughtIronSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","WroughtIronSword",16252),IronToolMaterial).setUnlocalizedName("Wrought Iron Sword").setMaxDamage(WroughtIronUses);
RedSteelSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","RedSteelSword",16253),RedSteelToolMaterial).setUnlocalizedName("Red Steel Sword").setMaxDamage(RedSteelUses);
RoseGoldSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","RoseGoldSword",16254),RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Sword").setMaxDamage(RoseGoldUses);
SteelSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","SteelSword",16255),SteelToolMaterial).setUnlocalizedName("Steel Sword").setMaxDamage(SteelUses);
TinSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","TinSword",16256),TinToolMaterial).setUnlocalizedName("Tin Sword").setMaxDamage(TinUses);
ZincSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","ZincSword",16257),ZincToolMaterial).setUnlocalizedName("Zinc Sword").setMaxDamage(ZincUses);
BismuthMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BismuthMace",16262),BismuthToolMaterial).setUnlocalizedName("Bismuth Mace").setMaxDamage(BismuthUses);
BismuthBronzeMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BismuthBronzeMace",16263),BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Mace").setMaxDamage(BismuthBronzeUses);
BlackBronzeMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BlackBronzeMace",16264),BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Mace").setMaxDamage(BlackBronzeUses);
BlackSteelMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BlackSteelMace",16265),BlackSteelToolMaterial).setUnlocalizedName("Black Steel Mace").setMaxDamage(BlackSteelUses);
BlueSteelMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BlueSteelMace",16266),BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Mace").setMaxDamage(BlueSteelUses);
BronzeMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BronzeMace",16267),BronzeToolMaterial).setUnlocalizedName("Bronze Mace").setMaxDamage(BronzeUses);
CopperMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","CopperMace",16268),CopperToolMaterial).setUnlocalizedName("Copper Mace").setMaxDamage(CopperUses);
WroughtIronMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","WroughtIronMace",16269),IronToolMaterial).setUnlocalizedName("Wrought Iron Mace").setMaxDamage(WroughtIronUses);
RedSteelMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","RedSteelMace",16270),RedSteelToolMaterial).setUnlocalizedName("Red Steel Mace").setMaxDamage(RedSteelUses);
RoseGoldMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","RoseGoldMace",16271),RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Mace").setMaxDamage(RoseGoldUses);
SteelMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","SteelMace",16272),SteelToolMaterial).setUnlocalizedName("Steel Mace").setMaxDamage(SteelUses);
TinMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","TinMace",16273),TinToolMaterial).setUnlocalizedName("Tin Mace").setMaxDamage(TinUses);
ZincMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","ZincMace",16274),ZincToolMaterial).setUnlocalizedName("Zinc Mace").setMaxDamage(ZincUses);
BismuthSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","BismuthSaw",16275),BismuthToolMaterial).setUnlocalizedName("Bismuth Saw").setMaxDamage(BismuthUses);
BismuthBronzeSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","BismuthBronzeSaw",16276),BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Saw").setMaxDamage(BismuthBronzeUses);
BlackBronzeSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","BlackBronzeSaw",16277),BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Saw").setMaxDamage(BlackBronzeUses);
BlackSteelSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","BlackSteelSaw",16278),BlackSteelToolMaterial).setUnlocalizedName("Black Steel Saw").setMaxDamage(BlackSteelUses);
BlueSteelSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","BlueSteelSaw",16279),BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Saw").setMaxDamage(BlueSteelUses);
BronzeSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","BronzeSaw",16280),BronzeToolMaterial).setUnlocalizedName("Bronze Saw").setMaxDamage(BronzeUses);
CopperSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","CopperSaw",16281),CopperToolMaterial).setUnlocalizedName("Copper Saw").setMaxDamage(CopperUses);
WroughtIronSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","WroughtIronSaw",16282),IronToolMaterial).setUnlocalizedName("Wrought Iron Saw").setMaxDamage(WroughtIronUses);
RedSteelSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","RedSteelSaw",16283),RedSteelToolMaterial).setUnlocalizedName("Red Steel Saw").setMaxDamage(RedSteelUses);
RoseGoldSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","RoseGoldSaw",16284),RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Saw").setMaxDamage(RoseGoldUses);
SteelSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","SteelSaw",16285),SteelToolMaterial).setUnlocalizedName("Steel Saw").setMaxDamage(SteelUses);
TinSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","TinSaw",16286),TinToolMaterial).setUnlocalizedName("Tin Saw").setMaxDamage(TinUses);
ZincSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","ZincSaw",16287),ZincToolMaterial).setUnlocalizedName("Zinc Saw").setMaxDamage(ZincUses);
HCBlackSteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","HCBlackSteelIngot",16290), EnumMetalType.BLACKSTEEL).setUnlocalizedName("HC Black Steel Ingot");
WeakBlueSteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","WeakBlueSteelIngot",16291),EnumMetalType.BLUESTEEL).setUnlocalizedName("Weak Blue Steel Ingot");
WeakRedSteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","WeakRedSteelIngot",16292),EnumMetalType.REDSTEEL).setUnlocalizedName("Weak Red Steel Ingot");
WeakSteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","WeakSteelIngot",16293),EnumMetalType.STEEL).setUnlocalizedName("Weak Steel Ingot");
HCBlueSteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","HCBlueSteelIngot",16294), EnumMetalType.BLUESTEEL).setUnlocalizedName("HC Blue Steel Ingot");
HCRedSteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","HCRedSteelIngot",16295), EnumMetalType.REDSTEEL).setUnlocalizedName("HC Red Steel Ingot");
HCSteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","HCSteelIngot",16296), EnumMetalType.STEEL).setUnlocalizedName("HC Steel Ingot");
OreChunk = new ItemOre(TFC_Settings.getIntFor(config,"item","OreChunk",16297)).setFolder("ore/").setUnlocalizedName("Ore");
Logs = new ItemLogs(TFC_Settings.getIntFor(config,"item","Logs",16298)).setUnlocalizedName("Log");
Javelin = new ItemJavelin(TFC_Settings.getIntFor(config,"item","javelin",16318)).setUnlocalizedName("javelin");
BismuthUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedBismuth",16350)).setUnlocalizedName("Bismuth Unshaped");
BismuthBronzeUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedBismuthBronze",16351)).setUnlocalizedName("Bismuth Bronze Unshaped");
BlackBronzeUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedBlackBronze",16352)).setUnlocalizedName("Black Bronze Unshaped");
BlackSteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedBlackSteel",16353)).setUnlocalizedName("Black Steel Unshaped");
BlueSteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedBlueSteel",16354)).setUnlocalizedName("Blue Steel Unshaped");
BrassUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedBrass",16355)).setUnlocalizedName("Brass Unshaped");
BronzeUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedBronze",16356)).setUnlocalizedName("Bronze Unshaped");
CopperUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedCopper",16357)).setUnlocalizedName("Copper Unshaped");
GoldUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedGold",16358)).setUnlocalizedName("Gold Unshaped");
WroughtIronUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedIron",16359)).setUnlocalizedName("Wrought Iron Unshaped");
LeadUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedLead",16360)).setUnlocalizedName("Lead Unshaped");
NickelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedNickel",16361)).setUnlocalizedName("Nickel Unshaped");
PigIronUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedPigIron",16362)).setUnlocalizedName("Pig Iron Unshaped");
PlatinumUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedPlatinum",16363)).setUnlocalizedName("Platinum Unshaped");
RedSteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedRedSteel",16364)).setUnlocalizedName("Red Steel Unshaped");
RoseGoldUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedRoseGold",16365)).setUnlocalizedName("Rose Gold Unshaped");
SilverUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedSilver",16366)).setUnlocalizedName("Silver Unshaped");
SteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedSteel",16367)).setUnlocalizedName("Steel Unshaped");
SterlingSilverUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedSterlingSilver",16368)).setUnlocalizedName("Sterling Silver Unshaped");
TinUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedTin",16369)).setUnlocalizedName("Tin Unshaped");
ZincUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedZinc",16370)).setUnlocalizedName("Zinc Unshaped");
//Hammers
StoneHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","terraStoneHammer",16371),TFCItems.IgInToolMaterial).setUnlocalizedName("Stone Hammer").setMaxDamage(TFCItems.IgInStoneUses);
BismuthHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","terraBismuthHammer",16372),TFCItems.BismuthToolMaterial).setUnlocalizedName("Bismuth Hammer").setMaxDamage(TFCItems.BismuthUses);
BismuthBronzeHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","terraBismuthBronzeHammer",16373),TFCItems.BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Hammer").setMaxDamage(TFCItems.BismuthBronzeUses);
BlackBronzeHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","terraBlackBronzeHammer",16374),TFCItems.BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Hammer").setMaxDamage(TFCItems.BlackBronzeUses);
BlackSteelHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","terraBlackSteelHammer",16375),TFCItems.BlackSteelToolMaterial).setUnlocalizedName("Black Steel Hammer").setMaxDamage(TFCItems.BlackSteelUses);
BlueSteelHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","terraBlueSteelHammer",16376),TFCItems.BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Hammer").setMaxDamage(TFCItems.BlueSteelUses);
BronzeHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","terraBronzeHammer",16377),TFCItems.BronzeToolMaterial).setUnlocalizedName("Bronze Hammer").setMaxDamage(TFCItems.BronzeUses);
CopperHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","terraCopperHammer",16378),TFCItems.CopperToolMaterial).setUnlocalizedName("Copper Hammer").setMaxDamage(TFCItems.CopperUses);
WroughtIronHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","terraWroughtIronHammer",16379),TFCItems.IronToolMaterial).setUnlocalizedName("Wrought Iron Hammer").setMaxDamage(TFCItems.WroughtIronUses);
RedSteelHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","terraRedSteelHammer",16380),TFCItems.RedSteelToolMaterial).setUnlocalizedName("Red Steel Hammer").setMaxDamage(TFCItems.RedSteelUses);
RoseGoldHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","terraRoseGoldHammer",16381),TFCItems.RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Hammer").setMaxDamage(TFCItems.RoseGoldUses);
SteelHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","terraSteelHammer",16382),TFCItems.SteelToolMaterial).setUnlocalizedName("Steel Hammer").setMaxDamage(TFCItems.SteelUses);
TinHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","terraTinHammer",16383),TFCItems.TinToolMaterial).setUnlocalizedName("Tin Hammer").setMaxDamage(TFCItems.TinUses);
ZincHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","terraZincHammer",16384),TFCItems.ZincToolMaterial).setUnlocalizedName("Zinc Hammer").setMaxDamage(TFCItems.ZincUses);
Ink = new ItemTerra(TFC_Settings.getIntFor(config,"item","Ink",16391)).setUnlocalizedName("Ink");
BellowsItem = new ItemBellows(TFC_Settings.getIntFor(config,"item","terraBellowsItem",16406)).setUnlocalizedName("Bellows");
FireStarter = new ItemFirestarter(TFC_Settings.getIntFor(config,"item","terraFireStarter",16407)).setFolder("tools/").setUnlocalizedName("Firestarter");
ClayMold = new ItemTerra(TFC_Settings.getIntFor(config,"item","terraClayMold",16408)).setUnlocalizedName("Clay Mold");
CeramicMold = new ItemTerra(TFC_Settings.getIntFor(config,"item","terraFiredClayMold",16409)).setUnlocalizedName("Ceramic Mold");
//Tool heads
BismuthPickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthPickaxeHead",16500)).setUnlocalizedName("Bismuth Pick Head");
BismuthBronzePickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzePickaxeHead",16501)).setUnlocalizedName("Bismuth Bronze Pick Head");
BlackBronzePickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzePickaxeHead",16502)).setUnlocalizedName("Black Bronze Pick Head");
BlackSteelPickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelPickaxeHead",16503)).setUnlocalizedName("Black Steel Pick Head");
BlueSteelPickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelPickaxeHead",16504)).setUnlocalizedName("Blue Steel Pick Head");
BronzePickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzePickaxeHead",16505)).setUnlocalizedName("Bronze Pick Head");
CopperPickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperPickaxeHead",16506)).setUnlocalizedName("Copper Pick Head");
WroughtIronPickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronPickaxeHead",16507)).setUnlocalizedName("Wrought Iron Pick Head");
RedSteelPickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelPickaxeHead",16508)).setUnlocalizedName("Red Steel Pick Head");
RoseGoldPickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldPickaxeHead",16509)).setUnlocalizedName("Rose Gold Pick Head");
SteelPickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelPickaxeHead",16510)).setUnlocalizedName("Steel Pick Head");
TinPickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinPickaxeHead",16511)).setUnlocalizedName("Tin Pick Head");
ZincPickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincPickaxeHead",16512)).setUnlocalizedName("Zinc Pick Head");
BismuthShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthShovelHead",16513)).setUnlocalizedName("Bismuth Shovel Head");
BismuthBronzeShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeShovelHead",16514)).setUnlocalizedName("Bismuth Bronze Shovel Head");
BlackBronzeShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeShovelHead",16515)).setUnlocalizedName("Black Bronze Shovel Head");
BlackSteelShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelShovelHead",16516)).setUnlocalizedName("Black Steel Shovel Head");
BlueSteelShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelShovelHead",16517)).setUnlocalizedName("Blue Steel Shovel Head");
BronzeShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeShovelHead",16518)).setUnlocalizedName("Bronze Shovel Head");
CopperShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperShovelHead",16519)).setUnlocalizedName("Copper Shovel Head");
WroughtIronShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronShovelHead",16520)).setUnlocalizedName("Wrought Iron Shovel Head");
RedSteelShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelShovelHead",16521)).setUnlocalizedName("Red Steel Shovel Head");
RoseGoldShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldShovelHead",16522)).setUnlocalizedName("Rose Gold Shovel Head");
SteelShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelShovelHead",16523)).setUnlocalizedName("Steel Shovel Head");
TinShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinShovelHead",16524)).setUnlocalizedName("Tin Shovel Head");
ZincShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincShovelHead",16525)).setUnlocalizedName("Zinc Shovel Head");
BismuthHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthHoeHead",16526)).setUnlocalizedName("Bismuth Hoe Head");
BismuthBronzeHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeHoeHead",16527)).setUnlocalizedName("Bismuth Bronze Hoe Head");
BlackBronzeHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeHoeHead",16528)).setUnlocalizedName("Black Bronze Hoe Head");
BlackSteelHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelHoeHead",16529)).setUnlocalizedName("Black Steel Hoe Head");
BlueSteelHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelHoeHead",16530)).setUnlocalizedName("Blue Steel Hoe Head");
BronzeHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeHoeHead",16531)).setUnlocalizedName("Bronze Hoe Head");
CopperHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperHoeHead",16532)).setUnlocalizedName("Copper Hoe Head");
WroughtIronHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronHoeHead",16533)).setUnlocalizedName("Wrought Iron Hoe Head");
RedSteelHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelHoeHead",16534)).setUnlocalizedName("Red Steel Hoe Head");
RoseGoldHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldHoeHead",16535)).setUnlocalizedName("Rose Gold Hoe Head");
SteelHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelHoeHead",16536)).setUnlocalizedName("Steel Hoe Head");
TinHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinHoeHead",16537)).setUnlocalizedName("Tin Hoe Head");
ZincHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincHoeHead",16538)).setUnlocalizedName("Zinc Hoe Head");
BismuthAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthAxeHead",16539)).setUnlocalizedName("Bismuth Axe Head");
BismuthBronzeAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeAxeHead",16540)).setUnlocalizedName("Bismuth Bronze Axe Head");
BlackBronzeAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeAxeHead",16541)).setUnlocalizedName("Black Bronze Axe Head");
BlackSteelAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelAxeHead",16542)).setUnlocalizedName("Black Steel Axe Head");
BlueSteelAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelAxeHead",16543)).setUnlocalizedName("Blue Steel Axe Head");
BronzeAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeAxeHead",16544)).setUnlocalizedName("Bronze Axe Head");
CopperAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperAxeHead",16545)).setUnlocalizedName("Copper Axe Head");
WroughtIronAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronAxeHead",16546)).setUnlocalizedName("Wrought Iron Axe Head");
RedSteelAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelAxeHead",16547)).setUnlocalizedName("Red Steel Axe Head");
RoseGoldAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldAxeHead",16548)).setUnlocalizedName("Rose Gold Axe Head");
SteelAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelAxeHead",16549)).setUnlocalizedName("Steel Axe Head");
TinAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinAxeHead",16550)).setUnlocalizedName("Tin Axe Head");
ZincAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincAxeHead",16551)).setUnlocalizedName("Zinc Axe Head");
BismuthHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthHammerHead",16552)).setUnlocalizedName("Bismuth Hammer Head");
BismuthBronzeHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeHammerHead",16553)).setUnlocalizedName("Bismuth Bronze Hammer Head");
BlackBronzeHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeHammerHead",16554)).setUnlocalizedName("Black Bronze Hammer Head");
BlackSteelHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelHammerHead",16555)).setUnlocalizedName("Black Steel Hammer Head");
BlueSteelHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelHammerHead",16556)).setUnlocalizedName("Blue Steel Hammer Head");
BronzeHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeHammerHead",16557)).setUnlocalizedName("Bronze Hammer Head");
CopperHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperHammerHead",16558)).setUnlocalizedName("Copper Hammer Head");
WroughtIronHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronHammerHead",16559)).setUnlocalizedName("Wrought Iron Hammer Head");
RedSteelHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelHammerHead",16560)).setUnlocalizedName("Red Steel Hammer Head");
RoseGoldHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldHammerHead",16561)).setUnlocalizedName("Rose Gold Hammer Head");
SteelHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelHammerHead",16562)).setUnlocalizedName("Steel Hammer Head");
TinHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinHammerHead",16563)).setUnlocalizedName("Tin Hammer Head");
ZincHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincHammerHead",16564)).setUnlocalizedName("Zinc Hammer Head");
//chisel heads
BismuthChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthChiselHead",16565)).setUnlocalizedName("Bismuth Chisel Head");
BismuthBronzeChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeChiselHead",16566)).setUnlocalizedName("Bismuth Bronze Chisel Head");
BlackBronzeChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeChiselHead",16567)).setUnlocalizedName("Black Bronze Chisel Head");
BlackSteelChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelChiselHead",16568)).setUnlocalizedName("Black Steel Chisel Head");
BlueSteelChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelChiselHead",16569)).setUnlocalizedName("Blue Steel Chisel Head");
BronzeChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeChiselHead",16570)).setUnlocalizedName("Bronze Chisel Head");
CopperChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperChiselHead",16571)).setUnlocalizedName("Copper Chisel Head");
WroughtIronChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronChiselHead",16572)).setUnlocalizedName("Wrought Iron Chisel Head");
RedSteelChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelChiselHead",16573)).setUnlocalizedName("Red Steel Chisel Head");
RoseGoldChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldChiselHead",16574)).setUnlocalizedName("Rose Gold Chisel Head");
SteelChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelChiselHead",16575)).setUnlocalizedName("Steel Chisel Head");
TinChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinChiselHead",16576)).setUnlocalizedName("Tin Chisel Head");
ZincChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincChiselHead",16577)).setUnlocalizedName("Zinc Chisel Head");
BismuthSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthSwordHead",16578)).setUnlocalizedName("Bismuth Sword Blade");
BismuthBronzeSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeSwordHead",16579)).setUnlocalizedName("Bismuth Bronze Sword Blade");
BlackBronzeSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeSwordHead",16580)).setUnlocalizedName("Black Bronze Sword Blade");
BlackSteelSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelSwordHead",16581)).setUnlocalizedName("Black Steel Sword Blade");
BlueSteelSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelSwordHead",16582)).setUnlocalizedName("Blue Steel Sword Blade");
BronzeSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeSwordHead",16583)).setUnlocalizedName("Bronze Sword Blade");
CopperSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperSwordHead",16584)).setUnlocalizedName("Copper Sword Blade");
WroughtIronSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronSwordHead",16585)).setUnlocalizedName("Wrought Iron Sword Blade");
RedSteelSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelSwordHead",16586)).setUnlocalizedName("Red Steel Sword Blade");
RoseGoldSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldSwordHead",16587)).setUnlocalizedName("Rose Gold Sword Blade");
SteelSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelSwordHead",16588)).setUnlocalizedName("Steel Sword Blade");
TinSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinSwordHead",16589)).setUnlocalizedName("Tin Sword Blade");
ZincSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincSwordHead",16590)).setUnlocalizedName("Zinc Sword Blade");
BismuthMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthMaceHead",16591)).setUnlocalizedName("Bismuth Mace Head");
BismuthBronzeMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeMaceHead",16592)).setUnlocalizedName("Bismuth Bronze Mace Head");
BlackBronzeMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeMaceHead",16593)).setUnlocalizedName("Black Bronze Mace Head");
BlackSteelMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelMaceHead",16594)).setUnlocalizedName("Black Steel Mace Head");
BlueSteelMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelMaceHead",16595)).setUnlocalizedName("Blue Steel Mace Head");
BronzeMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeMaceHead",16596)).setUnlocalizedName("Bronze Mace Head");
CopperMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperMaceHead",16597)).setUnlocalizedName("Copper Mace Head");
WroughtIronMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronMaceHead",16598)).setUnlocalizedName("Wrought Iron Mace Head");
RedSteelMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelMaceHead",16599)).setUnlocalizedName("Red Steel Mace Head");
RoseGoldMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldMaceHead",16600)).setUnlocalizedName("Rose Gold Mace Head");
SteelMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelMaceHead",16601)).setUnlocalizedName("Steel Mace Head");
TinMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinMaceHead",16602)).setUnlocalizedName("Tin Mace Head");
ZincMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincMaceHead",16603)).setUnlocalizedName("Zinc Mace Head");
BismuthSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthSawHead",16604)).setUnlocalizedName("Bismuth Saw Blade");
BismuthBronzeSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeSawHead",16605)).setUnlocalizedName("Bismuth Bronze Saw Blade");
BlackBronzeSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeSawHead",16606)).setUnlocalizedName("Black Bronze Saw Blade");
BlackSteelSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelSawHead",16607)).setUnlocalizedName("Black Steel Saw Blade");
BlueSteelSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelSawHead",16608)).setUnlocalizedName("Blue Steel Saw Blade");
BronzeSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeSawHead",16609)).setUnlocalizedName("Bronze Saw Blade");
CopperSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperSawHead",16610)).setUnlocalizedName("Copper Saw Blade");
WroughtIronSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronSawHead",16611)).setUnlocalizedName("Wrought Iron Saw Blade");
RedSteelSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelSawHead",16612)).setUnlocalizedName("Red Steel Saw Blade");
RoseGoldSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldSawHead",16613)).setUnlocalizedName("Rose Gold Saw Blade");
SteelSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelSawHead",16614)).setUnlocalizedName("Steel Saw Blade");
TinSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinSawHead",16615)).setUnlocalizedName("Tin Saw Blade");
ZincSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincSawHead",16616)).setUnlocalizedName("Zinc Saw Blade");
HCBlackSteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedHCBlackSteel",16617)).setUnlocalizedName("HC Black Steel Unshaped");
WeakBlueSteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedWeakBlueSteel",16618)).setUnlocalizedName("Weak Blue Steel Unshaped");
HCBlueSteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedHCBlueSteel",16619)).setUnlocalizedName("HC Blue Steel Unshaped");
WeakRedSteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedWeakRedSteel",16621)).setUnlocalizedName("Weak Red Steel Unshaped");
HCRedSteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedHCRedSteel",16622)).setUnlocalizedName("HC Red Steel Unshaped");
WeakSteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedWeakSteel",16623)).setUnlocalizedName("Weak Steel Unshaped");
HCSteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedHCSteel",16624)).setUnlocalizedName("HC Steel Unshaped");
Coke = (new ItemTerra(TFC_Settings.getIntFor(config,"item","Coke",16625)).setUnlocalizedName("Coke"));
BismuthProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthProPickHead",16626)).setUnlocalizedName("Bismuth ProPick Head");
BismuthBronzeProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeProPickHead",16627)).setUnlocalizedName("Bismuth Bronze ProPick Head");
BlackBronzeProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeProPickHead",16628)).setUnlocalizedName("Black Bronze ProPick Head");
BlackSteelProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelProPickHead",16629)).setUnlocalizedName("Black Steel ProPick Head");
BlueSteelProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelProPickHead",16630)).setUnlocalizedName("Blue Steel ProPick Head");
BronzeProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeProPickHead",16631)).setUnlocalizedName("Bronze ProPick Head");
CopperProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperProPickHead",16632)).setUnlocalizedName("Copper ProPick Head");
WroughtIronProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronProPickHead",16633)).setUnlocalizedName("Wrought Iron ProPick Head");
RedSteelProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelProPickHead",16634)).setUnlocalizedName("Red Steel ProPick Head");
RoseGoldProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldProPickHead",16635)).setUnlocalizedName("Rose Gold ProPick Head");
SteelProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelProPickHead",16636)).setUnlocalizedName("Steel ProPick Head");
TinProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinProPickHead",16637)).setUnlocalizedName("Tin ProPick Head");
ZincProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincProPickHead",16638)).setUnlocalizedName("Zinc ProPick Head");
Flux = (new ItemTerra(TFC_Settings.getIntFor(config,"item","Flux",16639)).setUnlocalizedName("Flux"));
/**
* Scythe
* */
int num = 16643;
BismuthScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","BismuthScythe",num),BismuthToolMaterial).setUnlocalizedName("Bismuth Scythe").setMaxDamage(BismuthUses);num++;
BismuthBronzeScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","BismuthBronzeScythe",num),BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Scythe").setMaxDamage(BismuthBronzeUses);num++;
BlackBronzeScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","BlackBronzeScythe",num),BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Scythe").setMaxDamage(BlackBronzeUses);num++;
BlackSteelScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","BlackSteelScythe",num),BlackSteelToolMaterial).setUnlocalizedName("Black Steel Scythe").setMaxDamage(BlackSteelUses);num++;
BlueSteelScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","BlueSteelScythe",num),BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Scythe").setMaxDamage(BlueSteelUses);num++;
BronzeScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","BronzeScythe",num),BronzeToolMaterial).setUnlocalizedName("Bronze Scythe").setMaxDamage(BronzeUses);num++;
CopperScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","CopperScythe",num),CopperToolMaterial).setUnlocalizedName("Copper Scythe").setMaxDamage(CopperUses);num++;
WroughtIronScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","WroughtIronScythe",num),IronToolMaterial).setUnlocalizedName("Wrought Iron Scythe").setMaxDamage(WroughtIronUses);num++;
RedSteelScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","RedSteelScythe",num),RedSteelToolMaterial).setUnlocalizedName("Red Steel Scythe").setMaxDamage(RedSteelUses);num++;
RoseGoldScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","RoseGoldScythe",num),RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Scythe").setMaxDamage(RoseGoldUses);num++;
SteelScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","SteelScythe",num),SteelToolMaterial).setUnlocalizedName("Steel Scythe").setMaxDamage(SteelUses);num++;
TinScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","TinScythe",num),TinToolMaterial).setUnlocalizedName("Tin Scythe").setMaxDamage(TinUses);num++;
ZincScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","ZincScythe",num),ZincToolMaterial).setUnlocalizedName("Zinc Scythe").setMaxDamage(ZincUses);num++;
BismuthScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthScytheHead",num)).setUnlocalizedName("Bismuth Scythe Blade");num++;
BismuthBronzeScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeScytheHead",num)).setUnlocalizedName("Bismuth Bronze Scythe Blade");num++;
BlackBronzeScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeScytheHead",num)).setUnlocalizedName("Black Bronze Scythe Blade");num++;
BlackSteelScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelScytheHead",num)).setUnlocalizedName("Black Steel Scythe Blade");num++;
BlueSteelScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelScytheHead",num)).setUnlocalizedName("Blue Steel Scythe Blade");num++;
BronzeScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeScytheHead",num)).setUnlocalizedName("Bronze Scythe Blade");num++;
CopperScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperScytheHead",num)).setUnlocalizedName("Copper Scythe Blade");num++;
WroughtIronScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronScytheHead",num)).setUnlocalizedName("Wrought Iron Scythe Blade");num++;
RedSteelScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelScytheHead",num)).setUnlocalizedName("Red Steel Scythe Blade");num++;
RoseGoldScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldScytheHead",num)).setUnlocalizedName("Rose Gold Scythe Blade");num++;
SteelScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelScytheHead",num)).setUnlocalizedName("Steel Scythe Blade");num++;
TinScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinScytheHead",num)).setUnlocalizedName("Tin Scythe Blade");num++;
ZincScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincScytheHead",num)).setUnlocalizedName("Zinc Scythe Blade");num++;
WoodenBucketEmpty = (new ItemCustomBucket(TFC_Settings.getIntFor(config,"item","WoodenBucketEmpty",num), 0)).setUnlocalizedName("Wooden Bucket Empty");num++;
WoodenBucketWater = (new ItemCustomBucket(TFC_Settings.getIntFor(config,"item","WoodenBucketWater",num), TFCBlocks.finiteWater.blockID)).setUnlocalizedName("Wooden Bucket Water").setContainerItem(WoodenBucketEmpty);num++;
WoodenBucketMilk = (new ItemCustomBucketMilk(TFC_Settings.getIntFor(config,"item","WoodenBucketMilk",num))).setUnlocalizedName("Wooden Bucket Milk").setContainerItem(WoodenBucketEmpty);num++;
BismuthKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthKnifeHead",num)).setUnlocalizedName("Bismuth Knife Blade");num++;
BismuthBronzeKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeKnifeHead",num)).setUnlocalizedName("Bismuth Bronze Knife Blade");num++;
BlackBronzeKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeKnifeHead",num)).setUnlocalizedName("Black Bronze Knife Blade");num++;
BlackSteelKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelKnifeHead",num)).setUnlocalizedName("Black Steel Knife Blade");num++;
BlueSteelKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelKnifeHead",num)).setUnlocalizedName("Blue Steel Knife Blade");num++;
BronzeKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeKnifeHead",num)).setUnlocalizedName("Bronze Knife Blade");num++;
CopperKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperKnifeHead",num)).setUnlocalizedName("Copper Knife Blade");num++;
WroughtIronKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronKnifeHead",num)).setUnlocalizedName("Wrought Iron Knife Blade");num++;
RedSteelKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelKnifeHead",num)).setUnlocalizedName("Red Steel Knife Blade");num++;
RoseGoldKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldKnifeHead",num)).setUnlocalizedName("Rose Gold Knife Blade");num++;
SteelKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelKnifeHead",num)).setUnlocalizedName("Steel Knife Blade");num++;
TinKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinKnifeHead",num)).setUnlocalizedName("Tin Knife Blade");num++;
ZincKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincKnifeHead",num)).setUnlocalizedName("Zinc Knife Blade");num++;
BismuthKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","BismuthKnife",num),BismuthToolMaterial).setUnlocalizedName("Bismuth Knife").setMaxDamage(BismuthUses);num++;
BismuthBronzeKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","BismuthBronzeKnife",num),BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Knife").setMaxDamage(BismuthBronzeUses);num++;
BlackBronzeKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","BlackBronzeKnife",num),BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Knife").setMaxDamage(BlackBronzeUses);num++;
BlackSteelKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","BlackSteelKnife",num),BlackSteelToolMaterial).setUnlocalizedName("Black Steel Knife").setMaxDamage(BlackSteelUses);num++;
BlueSteelKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","BlueSteelKnife",num),BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Knife").setMaxDamage(BlueSteelUses);num++;
BronzeKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","BronzeKnife",num),BronzeToolMaterial).setUnlocalizedName("Bronze Knife").setMaxDamage(BronzeUses);num++;
CopperKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","CopperKnife",num),CopperToolMaterial).setUnlocalizedName("Copper Knife").setMaxDamage(CopperUses);num++;
WroughtIronKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","WroughtIronKnife",num),IronToolMaterial).setUnlocalizedName("Wrought Iron Knife").setMaxDamage(WroughtIronUses);num++;
RedSteelKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","RedSteelKnife",num),RedSteelToolMaterial).setUnlocalizedName("Red Steel Knife").setMaxDamage(RedSteelUses);num++;
RoseGoldKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","RoseGoldKnife",num),RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Knife").setMaxDamage(RoseGoldUses);num++;
SteelKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","SteelKnife",num),SteelToolMaterial).setUnlocalizedName("Steel Knife").setMaxDamage(SteelUses);num++;
TinKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","TinKnife",num),TinToolMaterial).setUnlocalizedName("Tin Knife").setMaxDamage(TinUses);num++;
ZincKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","ZincKnife",num),ZincToolMaterial).setUnlocalizedName("Zinc Knife").setMaxDamage(ZincUses);num++;
LooseRock = (new ItemLooseRock(TFC_Settings.getIntFor(config,"item","LooseRock",num)).setUnlocalizedName("LooseRock"));num++;
FlatRock = (new ItemFlatRock(TFC_Settings.getIntFor(config,"item","FlatRock",num)).setUnlocalizedName("FlatRock"));num++;
IgInStoneShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","IgInStoneShovelHead",num)).setUnlocalizedName("Stone Shovel Head");num++;
SedStoneShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SedStoneShovelHead",num)).setUnlocalizedName("Stone Shovel Head");num++;
IgExStoneShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","IgExStoneShovelHead",num)).setUnlocalizedName("Stone Shovel Head");num++;
MMStoneShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","MMStoneShovelHead",num)).setUnlocalizedName("Stone Shovel Head");num++;
IgInStoneAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","IgInStoneAxeHead",num)).setUnlocalizedName("Stone Axe Head");num++;
SedStoneAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SedStoneAxeHead",num)).setUnlocalizedName("Stone Axe Head");num++;
IgExStoneAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","IgExStoneAxeHead",num)).setUnlocalizedName("Stone Axe Head");num++;
MMStoneAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","MMStoneAxeHead",num)).setUnlocalizedName("Stone Axe Head");num++;
IgInStoneHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","IgInStoneHoeHead",num)).setUnlocalizedName("Stone Hoe Head");num++;
SedStoneHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SedStoneHoeHead",num)).setUnlocalizedName("Stone Hoe Head");num++;
IgExStoneHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","IgExStoneHoeHead",num)).setUnlocalizedName("Stone Hoe Head");num++;
MMStoneHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","MMStoneHoeHead",num)).setUnlocalizedName("Stone Hoe Head");num++;
StoneKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","StoneKnifeHead",num)).setUnlocalizedName("Stone Knife Blade");num++;
StoneHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","StoneHammerHead",num)).setUnlocalizedName("Stone Hammer Head");num++;
StoneKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","StoneKnife",num),IgExToolMaterial).setUnlocalizedName("Stone Knife").setMaxDamage(IgExStoneUses);num++;
SmallOreChunk = new ItemOreSmall(TFC_Settings.getIntFor(config,"item","SmallOreChunk",num++)).setUnlocalizedName("Small Ore");
SinglePlank = new ItemPlank(TFC_Settings.getIntFor(config,"item","SinglePlank",num++)).setUnlocalizedName("SinglePlank");
RedSteelBucketEmpty = (new ItemCustomRedSteelBucket(TFC_Settings.getIntFor(config,"item","RedSteelBucketEmpty",num++), 0)).setUnlocalizedName("Red Steel Bucket Empty");
RedSteelBucketWater = (new ItemCustomRedSteelBucket(TFC_Settings.getIntFor(config,"item","RedSteelBucketWater",num++), Block.waterMoving.blockID)).setUnlocalizedName("Red Steel Bucket Water");
BlueSteelBucketEmpty = (new ItemCustomBlueSteelBucket(TFC_Settings.getIntFor(config,"item","BlueSteelBucketEmpty",num++), 0)).setUnlocalizedName("Blue Steel Bucket Empty");
BlueSteelBucketLava = (new ItemCustomBlueSteelBucket(TFC_Settings.getIntFor(config,"item","BlueSteelBucketLava",num++), Block.lavaMoving.blockID)).setUnlocalizedName("Blue Steel Bucket Lava");
Quern = new ItemTerra(TFC_Settings.getIntFor(config,"item","Quern",num++)).setUnlocalizedName("Quern").setMaxDamage(250);
FlintSteel = new ItemFlintSteel(TFC_Settings.getIntFor(config,"item","FlintSteel",num++)).setUnlocalizedName("flintAndSteel").setMaxDamage(200);
DoorOak = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorOak", num++), 0).setUnlocalizedName("Oak Door");
DoorAspen = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorAspen", num++), 1).setUnlocalizedName("Aspen Door");
DoorBirch = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorBirch", num++), 2).setUnlocalizedName("Birch Door");
DoorChestnut = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorChestnut", num++), 3).setUnlocalizedName("Chestnut Door");
DoorDouglasFir = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorDouglasFir", num++), 4).setUnlocalizedName("Douglas Fir Door");
DoorHickory = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorHickory", num++), 5).setUnlocalizedName("Hickory Door");
DoorMaple = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorMaple", num++), 6).setUnlocalizedName("Maple Door");
DoorAsh = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorAsh", num++), 7).setUnlocalizedName("Ash Door");
DoorPine = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorPine", num++), 8).setUnlocalizedName("Pine Door");
DoorSequoia = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorSequoia", num++), 9).setUnlocalizedName("Sequoia Door");
DoorSpruce = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorSpruce", num++), 10).setUnlocalizedName("Spruce Door");
DoorSycamore = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorSycamore", num++), 11).setUnlocalizedName("Sycamore Door");
DoorWhiteCedar = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorWhiteCedar", num++), 12).setUnlocalizedName("White Cedar Door");
DoorWhiteElm = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorWhiteElm", num++), 13).setUnlocalizedName("White Elm Door");
DoorWillow = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorWillow", num++), 14).setUnlocalizedName("Willow Door");
DoorKapok = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorKapok", num++), 15).setUnlocalizedName("Kapok Door");
Blueprint = new ItemBlueprint(TFC_Settings.getIntFor(config,"item","Blueprint", num++));
writabeBookTFC = new ItemWritableBookTFC(TFC_Settings.getIntFor(config,"item","WritableBookTFC", num++),"Fix Me I'm Broken").setUnlocalizedName("book");
WoolYarn = new ItemTerra(TFC_Settings.getIntFor(config, "item", "WoolYarn", num++)).setUnlocalizedName("WoolYarn").setCreativeTab(TFCTabs.TFCMaterials);
Wool = new ItemTerra(TFC_Settings.getIntFor(config,"item","Wool",num++)).setUnlocalizedName("Wool").setCreativeTab(TFCTabs.TFCMaterials);
WoolCloth = new ItemTerra(TFC_Settings.getIntFor(config, "item", "WoolCloth", num++)).setUnlocalizedName("WoolCloth").setCreativeTab(TFCTabs.TFCMaterials);
Spindle = new ItemSpindle(TFC_Settings.getIntFor(config,"item","Spindle",num++),SedToolMaterial).setUnlocalizedName("Spindle").setCreativeTab(TFCTabs.TFCMaterials);
ClaySpindle = new ItemTerra(TFC_Settings.getIntFor(config, "item", "ClaySpindle", num++)).setFolder("tools/").setUnlocalizedName("Clay Spindle").setCreativeTab(TFCTabs.TFCMaterials);
SpindleHead = new ItemTerra(TFC_Settings.getIntFor(config, "item", "SpindleHead", num++)).setFolder("toolheads/").setUnlocalizedName("Spindle Head").setCreativeTab(TFCTabs.TFCMaterials);
StoneBrick = (new ItemStoneBrick(TFC_Settings.getIntFor(config,"item","ItemStoneBrick2",num++)).setFolder("tools/").setUnlocalizedName("ItemStoneBrick"));
Mortar = new ItemTerra(TFC_Settings.getIntFor(config,"item","Mortar",num++)).setFolder("tools/").setUnlocalizedName("Mortar").setCreativeTab(TFCTabs.TFCMaterials);
Limewater = new ItemCustomBucket(TFC_Settings.getIntFor(config,"item","Limewater",num++),0).setFolder("tools/").setUnlocalizedName("Lime Water").setContainerItem(WoodenBucketEmpty).setCreativeTab(TFCTabs.TFCMaterials);
Hide = new ItemTerra(TFC_Settings.getIntFor(config,"item","Hide",num++)).setFolder("tools/").setUnlocalizedName("Hide").setCreativeTab(TFCTabs.TFCMaterials);
SoakedHide = new ItemTerra(TFC_Settings.getIntFor(config,"item","SoakedHide",num++)).setFolder("tools/").setUnlocalizedName("Soaked Hide").setCreativeTab(TFCTabs.TFCMaterials);
ScrapedHide = new ItemTerra(TFC_Settings.getIntFor(config,"item","ScrapedHide",num++)).setFolder("tools/").setUnlocalizedName("Scraped Hide").setCreativeTab(TFCTabs.TFCMaterials);
PrepHide = new ItemTerra(TFC_Settings.getIntFor(config,"item","PrepHide",num++)).setFolder("tools/").setFolder("tools/").setUnlocalizedName("Prep Hide").setCreativeTab(TFCTabs.TFCMaterials);
TerraLeather = new ItemTerra(TFC_Settings.getIntFor(config,"item","TFCLeather",num++)).setFolder("tools/").setUnlocalizedName("TFC Leather").setCreativeTab(TFCTabs.TFCMaterials);
SheepSkin = new ItemTerra(TFC_Settings.getIntFor(config,"item","SheepSkin",num++)).setFolder("tools/").setUnlocalizedName("Sheep Skin").setCreativeTab(TFCTabs.TFCMaterials);
muttonRaw = new ItemTerra(TFC_Settings.getIntFor(config,"item","muttonRaw",num++)).setFolder("food/").setUnlocalizedName("Mutton Raw");
muttonCooked = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","muttonCooked",num++), 40, 0.8F, true, 48).setUnlocalizedName("Mutton Cooked");
FlatLeather = (new ItemFlatLeather(TFC_Settings.getIntFor(config,"items","FlatLeather2",num++)).setFolder("tools/").setUnlocalizedName("Flat Leather"));
PotteryJug = new ItemPotteryJug(TFC_Settings.getIntFor(config,"items","PotteryJug",num++)).setUnlocalizedName("Jug");
PotterySmallVessel = new ItemPotteryBase(TFC_Settings.getIntFor(config,"items","PotterySmallVessel",num++)).setUnlocalizedName("Small Vessel");
PotteryLargeVessel = new ItemPotteryLargeVessel(TFC_Settings.getIntFor(config,"items","PotteryLargeVessel",num++)).setUnlocalizedName("Large Vessel");
PotteryPot = new ItemPotteryPot(TFC_Settings.getIntFor(config,"items","PotteryPot",num++)).setUnlocalizedName("Pot");
Straw = new ItemTerra(TFC_Settings.getIntFor(config,"items","Straw",num++)).setFolder("plants/").setUnlocalizedName("Straw");
/**Plans*/
num = 20000;
SetupPlans(num);
/**Food related items*/
num = 18000;
SetupFood(num);
/**Armor Crafting related items*/
num = 19000;
SetupArmor(num);
Recipes.Doors = new Item[]{DoorOak, DoorAspen, DoorBirch, DoorChestnut, DoorDouglasFir,
DoorHickory, DoorMaple, DoorAsh, DoorPine, DoorSequoia, DoorSpruce, DoorSycamore,
DoorWhiteCedar, DoorWhiteElm, DoorWillow, DoorKapok};
Recipes.Axes = new Item[]{SedAxe,IgInAxe,IgExAxe,MMAxe,
BismuthAxe,BismuthBronzeAxe,BlackBronzeAxe,
BlackSteelAxe,BlueSteelAxe,BronzeAxe,CopperAxe,
WroughtIronAxe,RedSteelAxe,RoseGoldAxe,SteelAxe,
TinAxe,ZincAxe};
Recipes.Chisels = new Item[]{BismuthChisel,BismuthBronzeChisel,BlackBronzeChisel,
BlackSteelChisel,BlueSteelChisel,BronzeChisel,CopperChisel,
WroughtIronChisel,RedSteelChisel,RoseGoldChisel,SteelChisel,
TinChisel,ZincChisel};
Recipes.Saws = new Item[]{BismuthSaw,BismuthBronzeSaw,BlackBronzeSaw,
BlackSteelSaw,BlueSteelSaw,BronzeSaw,CopperSaw,
WroughtIronSaw,RedSteelSaw,RoseGoldSaw,SteelSaw,
TinSaw,ZincSaw};
Recipes.Knives = new Item[]{StoneKnife,BismuthKnife,BismuthBronzeKnife,BlackBronzeKnife,
BlackSteelKnife,BlueSteelKnife,BronzeKnife,CopperKnife,
WroughtIronKnife,RedSteelKnife,RoseGoldKnife,SteelKnife,
TinKnife,ZincKnife};
Recipes.MeltedMetal = new Item[]{BismuthUnshaped, BismuthBronzeUnshaped,BlackBronzeUnshaped,
TFCItems.BlackSteelUnshaped,TFCItems.BlueSteelUnshaped,TFCItems.BrassUnshaped,TFCItems.BronzeUnshaped,
TFCItems.CopperUnshaped,TFCItems.GoldUnshaped,
TFCItems.WroughtIronUnshaped,TFCItems.LeadUnshaped,TFCItems.NickelUnshaped,TFCItems.PigIronUnshaped,
TFCItems.PlatinumUnshaped,TFCItems.RedSteelUnshaped,TFCItems.RoseGoldUnshaped,TFCItems.SilverUnshaped,
TFCItems.SteelUnshaped,TFCItems.SterlingSilverUnshaped,
TFCItems.TinUnshaped,TFCItems.ZincUnshaped, TFCItems.HCSteelUnshaped, TFCItems.WeakSteelUnshaped,
TFCItems.HCBlackSteelUnshaped, TFCItems.HCBlueSteelUnshaped, TFCItems.HCRedSteelUnshaped,
TFCItems.WeakBlueSteelUnshaped, TFCItems.WeakRedSteelUnshaped};
Recipes.Hammers = new Item[]{TFCItems.StoneHammer,TFCItems.BismuthHammer,TFCItems.BismuthBronzeHammer,TFCItems.BlackBronzeHammer,
TFCItems.BlackSteelHammer,TFCItems.BlueSteelHammer,TFCItems.BronzeHammer,TFCItems.CopperHammer,
TFCItems.WroughtIronHammer,TFCItems.RedSteelHammer,TFCItems.RoseGoldHammer,TFCItems.SteelHammer,
TFCItems.TinHammer,TFCItems.ZincHammer};
Recipes.Spindle = new Item[]{TFCItems.Spindle};
Recipes.Gems = new Item[]{TFCItems.GemAgate, TFCItems.GemAmethyst, TFCItems.GemBeryl, TFCItems.GemDiamond, TFCItems.GemEmerald, TFCItems.GemGarnet,
TFCItems.GemJade, TFCItems.GemJasper, TFCItems.GemOpal,TFCItems.GemRuby,TFCItems.GemSapphire,TFCItems.GemTopaz,TFCItems.GemTourmaline};
Meals = new Item[]{MealMoveSpeed, MealDigSpeed, MealDamageBoost, MealJump, MealDamageResist,
MealFireResist, MealWaterBreathing, MealNightVision};
((TFCTabs)TFCTabs.TFCTools).setTabIconItemIndex(TFCItems.RoseGoldHammer.itemID);
((TFCTabs)TFCTabs.TFCMaterials).setTabIconItemIndex(TFCItems.Spindle.itemID);
((TFCTabs)TFCTabs.TFCUnfinished).setTabIconItemIndex(TFCItems.RoseGoldHammerHead.itemID);
((TFCTabs)TFCTabs.TFCArmor).setTabIconItemIndex(TFCItems.SteelHelmet.itemID);
System.out.println(new StringBuilder().append("[TFC] Done Loading Items").toString());
if (config != null) {
config.save();
}
}
| public static void Setup()
{
try
{
config = new net.minecraftforge.common.Configuration(
new File(TerraFirmaCraft.proxy.getMinecraftDir(), "/config/TFC.cfg"));
config.load();
} catch (Exception e) {
System.out.println(new StringBuilder().append("[TFC] Error while trying to access item configuration!").toString());
config = null;
}
IgInToolMaterial = EnumHelper.addToolMaterial("IgIn", 1, IgInStoneUses, 7F, 10, 5);
SedToolMaterial = EnumHelper.addToolMaterial("Sed", 1, SedStoneUses, 6F, 10, 5);
IgExToolMaterial = EnumHelper.addToolMaterial("IgEx", 1, IgExStoneUses, 7F, 10, 5);
MMToolMaterial = EnumHelper.addToolMaterial("MM", 1, MMStoneUses, 6.5F, 10, 5);
BismuthToolMaterial = EnumHelper.addToolMaterial("Bismuth", 2, BismuthUses, BismuthEff, 65, 10);
BismuthBronzeToolMaterial = EnumHelper.addToolMaterial("BismuthBronze", 2, BismuthBronzeUses, BismuthBronzeEff, 85, 10);
BlackBronzeToolMaterial = EnumHelper.addToolMaterial("BlackBronze", 2, BlackBronzeUses, BlackBronzeEff, 100, 10);
BlackSteelToolMaterial = EnumHelper.addToolMaterial("BlackSteel", 2, BlackSteelUses, BlackSteelEff, 165, 12);
BlueSteelToolMaterial = EnumHelper.addToolMaterial("BlueSteel", 3, BlueSteelUses, BlueSteelEff, 185, 22);
BronzeToolMaterial = EnumHelper.addToolMaterial("Bronze", 2, BronzeUses, BronzeEff, 100, 13);
CopperToolMaterial = EnumHelper.addToolMaterial("Copper", 2, CopperUses, CopperEff, 85, 8);
IronToolMaterial = EnumHelper.addToolMaterial("Iron", 2, WroughtIronUses, WroughtIronEff, 135, 10);
RedSteelToolMaterial = EnumHelper.addToolMaterial("RedSteel", 3, RedSteelUses, RedSteelEff, 185, 22);
RoseGoldToolMaterial = EnumHelper.addToolMaterial("RoseGold", 2, RoseGoldUses, RoseGoldEff, 100, 20);
SteelToolMaterial = EnumHelper.addToolMaterial("Steel", 2, SteelUses, SteelEff, 150, 10);
TinToolMaterial = EnumHelper.addToolMaterial("Tin", 2, TinUses, TinEff, 65, 8);
ZincToolMaterial = EnumHelper.addToolMaterial("Zinc", 2, ZincUses, ZincEff, 65, 8);
System.out.println(new StringBuilder().append("[TFC] Loading Items").toString());
//Replace any vanilla Items here
Item.itemsList[Item.coal.itemID] = null; Item.itemsList[Item.coal.itemID] = (new TFC.Items.ItemCoal(7)).setUnlocalizedName("coal");
Item.itemsList[Item.stick.itemID] = null; Item.itemsList[Item.stick.itemID] = new ItemStick(24).setFull3D().setUnlocalizedName("stick");
Item.itemsList[Item.leather.itemID] = null; Item.itemsList[Item.leather.itemID] = new ItemTerra(Item.leather.itemID).setFull3D().setUnlocalizedName("leather");
Item.itemsList[Block.vine.blockID] = new ItemColored(Block.vine.blockID - 256, false);
minecartCrate = (new ItemCustomMinecart(TFC_Settings.getIntFor(config,"item","minecartCrate",16000), 1)).setUnlocalizedName("minecartChest");
Item.itemsList[5+256] = null; Item.itemsList[5+256] = (new ItemCustomBow(5)).setUnlocalizedName("bow");
Item.itemsList[63+256] = null; Item.itemsList[63+256] = new ItemTerra(63).setUnlocalizedName("porkchopRaw");
Item.itemsList[64+256] = null; Item.itemsList[64+256] = new ItemTerraFood(64, 35, 0.8F, true, 38).setFolder("").setUnlocalizedName("porkchopCooked");
Item.itemsList[93+256] = null; Item.itemsList[93+256] = new ItemTerra(93).setUnlocalizedName("fishRaw");
Item.itemsList[94+256] = null; Item.itemsList[94+256] = new ItemTerraFood(94, 30, 0.6F, true, 39).setFolder("").setUnlocalizedName("fishCooked");
Item.itemsList[107+256] = null; Item.itemsList[107+256] = new ItemTerra(107).setUnlocalizedName("beefRaw");
Item.itemsList[108+256] = null; Item.itemsList[108+256] = new ItemTerraFood(108, 40, 0.8F, true, 40).setFolder("").setUnlocalizedName("beefCooked");
Item.itemsList[109+256] = null; Item.itemsList[109+256] = new ItemTerra(109).setUnlocalizedName("chickenRaw");
Item.itemsList[110+256] = null; Item.itemsList[110+256] = new ItemTerraFood(110, 35, 0.6F, true, 41).setFolder("").setUnlocalizedName("chickenCooked");
Item.itemsList[41+256] = null; Item.itemsList[41+256] = (new ItemTerraFood(41, 25, 0.6F, false, 42)).setFolder("").setUnlocalizedName("bread");
Item.itemsList[88+256] = null; Item.itemsList[88+256] = (new ItemTerra(88)).setUnlocalizedName("egg");
Item.itemsList[Item.dyePowder.itemID] = null; Item.itemsList[Item.dyePowder.itemID] = new ItemDyeCustom(95).setUnlocalizedName("dyePowder");
Item.itemsList[Item.potion.itemID] = null; Item.itemsList[Item.potion.itemID] = (new ItemCustomPotion(117)).setUnlocalizedName("potion");
Item.itemsList[Block.tallGrass.blockID] = null; Item.itemsList[Block.tallGrass.blockID] = (new ItemColored(Block.tallGrass.blockID - 256, true)).setBlockNames(new String[] {"shrub", "grass", "fern"});
GoldPan = new ItemGoldPan(TFC_Settings.getIntFor(config,"item","terraGoldPan",16001)).setUnlocalizedName("GoldPan");
SluiceItem = new ItemSluice(TFC_Settings.getIntFor(config,"item","terraSluiceItem",16002)).setFolder("devices/").setUnlocalizedName("SluiceItem");
ProPickBismuth = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickBismuth",16004)).setUnlocalizedName("Bismuth ProPick").setMaxDamage(BismuthUses);
ProPickBismuthBronze = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickBismuthBronze",16005)).setUnlocalizedName("Bismuth Bronze ProPick").setMaxDamage(BismuthBronzeUses);
ProPickBlackBronze = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickBlackBronze",16006)).setUnlocalizedName("Black Bronze ProPick").setMaxDamage(BlackBronzeUses);
ProPickBlackSteel = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickBlackSteel",16007)).setUnlocalizedName("Black Steel ProPick").setMaxDamage(BlackSteelUses);
ProPickBlueSteel = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickBlueSteel",16008)).setUnlocalizedName("Blue Steel ProPick").setMaxDamage(BlueSteelUses);
ProPickBronze = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickBronze",16009)).setUnlocalizedName("Bronze ProPick").setMaxDamage(BronzeUses);
ProPickCopper = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickCopper",16010)).setUnlocalizedName("Copper ProPick").setMaxDamage(CopperUses);
ProPickIron = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickWroughtIron",16012)).setUnlocalizedName("Wrought Iron ProPick").setMaxDamage(WroughtIronUses);
ProPickRedSteel = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickRedSteel",16016)).setUnlocalizedName("Red Steel ProPick").setMaxDamage(RedSteelUses);
ProPickRoseGold = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickRoseGold",16017)).setUnlocalizedName("Rose Gold ProPick").setMaxDamage(RoseGoldUses);
ProPickSteel = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickSteel",16019)).setUnlocalizedName("Steel ProPick").setMaxDamage(SteelUses);
ProPickTin = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickTin",16021)).setUnlocalizedName("Tin ProPick").setMaxDamage(TinUses);
ProPickZinc = new ItemProPick(TFC_Settings.getIntFor(config,"item","ProPickZinc",16022)).setUnlocalizedName("Zinc ProPick").setMaxDamage(ZincUses);
BismuthIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","BismuthIngot",16028), EnumMetalType.BISMUTH).setUnlocalizedName("Bismuth Ingot");
BismuthBronzeIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","BismuthBronzeIngot",16029), EnumMetalType.BISMUTHBRONZE).setUnlocalizedName("Bismuth Bronze Ingot");
BlackBronzeIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","BlackBronzeIngot",16030), EnumMetalType.BLACKBRONZE).setUnlocalizedName("Black Bronze Ingot");
BlackSteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","BlackSteelIngot",16031), EnumMetalType.BLACKSTEEL).setUnlocalizedName("Black Steel Ingot");
BlueSteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","BlueSteelIngot",16032), EnumMetalType.BLUESTEEL).setUnlocalizedName("Blue Steel Ingot");
BrassIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","BrassIngot",16033), EnumMetalType.BRASS).setUnlocalizedName("Brass Ingot");
BronzeIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","BronzeIngot",16034), EnumMetalType.BRONZE).setUnlocalizedName("Bronze Ingot");
CopperIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","CopperIngot",16035), EnumMetalType.COPPER).setUnlocalizedName("Copper Ingot");
GoldIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","GoldIngot",16036), EnumMetalType.GOLD).setUnlocalizedName("Gold Ingot");
WroughtIronIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","WroughtIronIngot",16037), EnumMetalType.WROUGHTIRON).setUnlocalizedName("Wrought Iron Ingot");
LeadIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","LeadIngot",16038), EnumMetalType.LEAD).setUnlocalizedName("Lead Ingot");
NickelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","NickelIngot",16039), EnumMetalType.NICKEL).setUnlocalizedName("Nickel Ingot");
PigIronIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","PigIronIngot",16040), EnumMetalType.PIGIRON).setUnlocalizedName("Pig Iron Ingot");
PlatinumIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","PlatinumIngot",16041), EnumMetalType.PLATINUM).setUnlocalizedName("Platinum Ingot");
RedSteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","RedSteelIngot",16042), EnumMetalType.REDSTEEL).setUnlocalizedName("Red Steel Ingot");
RoseGoldIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","RoseGoldIngot",16043), EnumMetalType.ROSEGOLD).setUnlocalizedName("Rose Gold Ingot");
SilverIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","SilverIngot",16044), EnumMetalType.SILVER).setUnlocalizedName("Silver Ingot");
SteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","SteelIngot",16045), EnumMetalType.STEEL).setUnlocalizedName("Steel Ingot");
SterlingSilverIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","SterlingSilverIngot",16046), EnumMetalType.STERLINGSILVER).setUnlocalizedName("Sterling Silver Ingot");
TinIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","TinIngot",16047), EnumMetalType.TIN).setUnlocalizedName("Tin Ingot");
ZincIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","ZincIngot",16048), EnumMetalType.ZINC).setUnlocalizedName("Zinc Ingot");
BismuthIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","BismuthIngot2x",16049), EnumMetalType.BISMUTH).setUnlocalizedName("Bismuth Double Ingot")).setSize(EnumSize.LARGE);
BismuthBronzeIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","BismuthBronzeIngot2x",16050), EnumMetalType.BISMUTHBRONZE).setUnlocalizedName("Bismuth Bronze Double Ingot")).setSize(EnumSize.LARGE);
BlackBronzeIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","BlackBronzeIngot2x",16051), EnumMetalType.BLACKBRONZE).setUnlocalizedName("Black Bronze Double Ingot")).setSize(EnumSize.LARGE);
BlackSteelIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","BlackSteelIngot2x",16052), EnumMetalType.BLACKSTEEL).setUnlocalizedName("Black Steel Double Ingot")).setSize(EnumSize.LARGE);
BlueSteelIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","BlueSteelIngot2x",16053), EnumMetalType.BLUESTEEL).setUnlocalizedName("Blue Steel Double Ingot")).setSize(EnumSize.LARGE);
BrassIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","BrassIngot2x",16054), EnumMetalType.BRASS).setUnlocalizedName("Brass Double Ingot")).setSize(EnumSize.LARGE);
BronzeIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","BronzeIngot2x",16055), EnumMetalType.BRONZE).setUnlocalizedName("Bronze Double Ingot")).setSize(EnumSize.LARGE);
CopperIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","CopperIngot2x",16056), EnumMetalType.COPPER).setUnlocalizedName("Copper Double Ingot")).setSize(EnumSize.LARGE);
GoldIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","GoldIngot2x",16057), EnumMetalType.GOLD).setUnlocalizedName("Gold Double Ingot")).setSize(EnumSize.LARGE);
WroughtIronIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","WroughtIronIngot2x",16058), EnumMetalType.WROUGHTIRON).setUnlocalizedName("Wrought Iron Double Ingot")).setSize(EnumSize.LARGE);
LeadIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","LeadIngot2x",16059), EnumMetalType.LEAD).setUnlocalizedName("Lead Double Ingot")).setSize(EnumSize.LARGE);
NickelIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","NickelIngot2x",16060), EnumMetalType.NICKEL).setUnlocalizedName("Nickel Double Ingot")).setSize(EnumSize.LARGE);
PigIronIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","PigIronIngot2x",16061), EnumMetalType.PIGIRON).setUnlocalizedName("Pig Iron Double Ingot")).setSize(EnumSize.LARGE);
PlatinumIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","PlatinumIngot2x",16062), EnumMetalType.PLATINUM).setUnlocalizedName("Platinum Double Ingot")).setSize(EnumSize.LARGE);
RedSteelIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","RedSteelIngot2x",16063), EnumMetalType.REDSTEEL).setUnlocalizedName("Red Steel Double Ingot")).setSize(EnumSize.LARGE);
RoseGoldIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","RoseGoldIngot2x",16064), EnumMetalType.ROSEGOLD).setUnlocalizedName("Rose Gold Double Ingot")).setSize(EnumSize.LARGE);
SilverIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","SilverIngot2x",16065), EnumMetalType.SILVER).setUnlocalizedName("Silver Double Ingot")).setSize(EnumSize.LARGE);
SteelIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","SteelIngot2x",16066), EnumMetalType.STEEL).setUnlocalizedName("Steel Double Ingot")).setSize(EnumSize.LARGE);
SterlingSilverIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","SterlingSilverIngot2x",16067), EnumMetalType.STERLINGSILVER).setUnlocalizedName("Sterling Silver Double Ingot")).setSize(EnumSize.LARGE);
TinIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","TinIngot2x",16068), EnumMetalType.TIN).setUnlocalizedName("Tin Double Ingot")).setSize(EnumSize.LARGE);
ZincIngot2x = ((ItemIngot)new ItemIngot(TFC_Settings.getIntFor(config,"item","ZincIngot2x",16069), EnumMetalType.ZINC).setUnlocalizedName("Zinc Double Ingot")).setSize(EnumSize.LARGE);
SulfurPowder = new ItemTerra(TFC_Settings.getIntFor(config,"item","SulfurPowder",16070)).setUnlocalizedName("Sulfur Powder");
SaltpeterPowder = new ItemTerra(TFC_Settings.getIntFor(config,"item","SaltpeterPowder",16071)).setUnlocalizedName("Saltpeter Powder");
GemRuby = new ItemGem(TFC_Settings.getIntFor(config,"item","GemRuby",16080)).setUnlocalizedName("Ruby");
GemSapphire = new ItemGem(TFC_Settings.getIntFor(config,"item","GemSapphire",16081)).setUnlocalizedName("Sapphire");
GemEmerald = new ItemGem(TFC_Settings.getIntFor(config,"item","GemEmerald",16082)).setUnlocalizedName("Emerald");
GemTopaz = new ItemGem(TFC_Settings.getIntFor(config,"item","GemTopaz",16083)).setUnlocalizedName("Topaz");
GemTourmaline = new ItemGem(TFC_Settings.getIntFor(config,"item","GemTourmaline",16084)).setUnlocalizedName("Tourmaline");
GemJade = new ItemGem(TFC_Settings.getIntFor(config,"item","GemJade",16085)).setUnlocalizedName("Jade");
GemBeryl = new ItemGem(TFC_Settings.getIntFor(config,"item","GemBeryl",16086)).setUnlocalizedName("Beryl");
GemAgate = new ItemGem(TFC_Settings.getIntFor(config,"item","GemAgate",16087)).setUnlocalizedName("Agate");
GemOpal = new ItemGem(TFC_Settings.getIntFor(config,"item","GemOpal",16088)).setUnlocalizedName("Opal");
GemGarnet = new ItemGem(TFC_Settings.getIntFor(config,"item","GemGarnet",16089)).setUnlocalizedName("Garnet");
GemJasper = new ItemGem(TFC_Settings.getIntFor(config,"item","GemJasper",16090)).setUnlocalizedName("Jasper");
GemAmethyst = new ItemGem(TFC_Settings.getIntFor(config,"item","GemAmethyst",16091)).setUnlocalizedName("Amethyst");
GemDiamond = new ItemGem(TFC_Settings.getIntFor(config,"item","GemDiamond",16092)).setUnlocalizedName("Diamond");
//Tools
IgInShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","IgInShovel",16101),IgInToolMaterial).setUnlocalizedName("Stone Shovel").setMaxDamage(IgInStoneUses);
IgInAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","IgInAxe",16102),IgInToolMaterial).setUnlocalizedName("Stone Axe").setMaxDamage(IgInStoneUses);
IgInHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","IgInHoe",16103),IgInToolMaterial).setUnlocalizedName("Stone Hoe").setMaxDamage(IgInStoneUses);
SedShovel= new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","SedShovel",16105),SedToolMaterial).setUnlocalizedName("Stone Shovel").setMaxDamage(SedStoneUses);
SedAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","SedAxe",16106),SedToolMaterial).setUnlocalizedName("Stone Axe").setMaxDamage(SedStoneUses);
SedHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","SedHoe",16107),SedToolMaterial).setUnlocalizedName("Stone Hoe").setMaxDamage(SedStoneUses);
IgExShovel= new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","IgExShovel",16109),IgExToolMaterial).setUnlocalizedName("Stone Shovel").setMaxDamage(IgExStoneUses);
IgExAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","IgExAxe",16110),IgExToolMaterial).setUnlocalizedName("Stone Axe").setMaxDamage(IgExStoneUses);
IgExHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","IgExHoe",16111),IgExToolMaterial).setUnlocalizedName("Stone Hoe").setMaxDamage(IgExStoneUses);
MMShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","MMShovel",16113),MMToolMaterial).setUnlocalizedName("Stone Shovel").setMaxDamage(MMStoneUses);
MMAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","MMAxe",16114),MMToolMaterial).setUnlocalizedName("Stone Axe").setMaxDamage(MMStoneUses);
MMHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","MMHoe",16115),MMToolMaterial).setUnlocalizedName("Stone Hoe").setMaxDamage(MMStoneUses);
BismuthPick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","BismuthPick",16116),BismuthToolMaterial).setUnlocalizedName("Bismuth Pick").setMaxDamage(BismuthUses);
BismuthShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","BismuthShovel",16117),BismuthToolMaterial).setUnlocalizedName("Bismuth Shovel").setMaxDamage(BismuthUses);
BismuthAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","BismuthAxe",16118),BismuthToolMaterial).setUnlocalizedName("Bismuth Axe").setMaxDamage(BismuthUses);
BismuthHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","BismuthHoe",16119),BismuthToolMaterial).setUnlocalizedName("Bismuth Hoe").setMaxDamage(BismuthUses);
BismuthBronzePick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","BismuthBronzePick",16120),BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Pick").setMaxDamage(BismuthBronzeUses);
BismuthBronzeShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","BismuthBronzeShovel",16121),BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Shovel").setMaxDamage(BismuthBronzeUses);
BismuthBronzeAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","BismuthBronzeAxe",16122),BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Axe").setMaxDamage(BismuthBronzeUses);
BismuthBronzeHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","BismuthBronzeHoe",16123),BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Hoe").setMaxDamage(BismuthBronzeUses);
BlackBronzePick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","BlackBronzePick",16124),BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Pick").setMaxDamage(BlackBronzeUses);
BlackBronzeShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","BlackBronzeShovel",16125),BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Shovel").setMaxDamage(BlackBronzeUses);
BlackBronzeAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","BlackBronzeAxe",16126),BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Axe").setMaxDamage(BlackBronzeUses);
BlackBronzeHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","BlackBronzeHoe",16127),BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Hoe").setMaxDamage(BlackBronzeUses);
BlackSteelPick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","BlackSteelPick",16128),BlackSteelToolMaterial).setUnlocalizedName("Black Steel Pick").setMaxDamage(BlackSteelUses);
BlackSteelShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","BlackSteelShovel",16129),BlackSteelToolMaterial).setUnlocalizedName("Black Steel Shovel").setMaxDamage(BlackSteelUses);
BlackSteelAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","BlackSteelAxe",16130),BlackSteelToolMaterial).setUnlocalizedName("Black Steel Axe").setMaxDamage(BlackSteelUses);
BlackSteelHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","BlackSteelHoe",16131),BlackSteelToolMaterial).setUnlocalizedName("Black Steel Hoe").setMaxDamage(BlackSteelUses);
BlueSteelPick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","BlueSteelPick",16132),BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Pick").setMaxDamage(BlueSteelUses);
BlueSteelShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","BlueSteelShovel",16133),BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Shovel").setMaxDamage(BlueSteelUses);
BlueSteelAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","BlueSteelAxe",16134),BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Axe").setMaxDamage(BlueSteelUses);
BlueSteelHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","BlueSteelHoe",16135),BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Hoe").setMaxDamage(BlueSteelUses);
BronzePick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","BronzePick",16136),BronzeToolMaterial).setUnlocalizedName("Bronze Pick").setMaxDamage(BronzeUses);
BronzeShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","BronzeShovel",16137),BronzeToolMaterial).setUnlocalizedName("Bronze Shovel").setMaxDamage(BronzeUses);
BronzeAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","BronzeAxe",16138),BronzeToolMaterial).setUnlocalizedName("Bronze Axe").setMaxDamage(BronzeUses);
BronzeHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","BronzeHoe",16139),BronzeToolMaterial).setUnlocalizedName("Bronze Hoe").setMaxDamage(BronzeUses);
CopperPick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","CopperPick",16140),CopperToolMaterial).setUnlocalizedName("Copper Pick").setMaxDamage(CopperUses);
CopperShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","CopperShovel",16141),CopperToolMaterial).setUnlocalizedName("Copper Shovel").setMaxDamage(CopperUses);
CopperAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","CopperAxe",16142),CopperToolMaterial).setUnlocalizedName("Copper Axe").setMaxDamage(CopperUses);
CopperHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","CopperHoe",16143),CopperToolMaterial).setUnlocalizedName("Copper Hoe").setMaxDamage(CopperUses);
WroughtIronPick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","WroughtIronPick",16148),IronToolMaterial).setUnlocalizedName("Wrought Iron Pick").setMaxDamage(WroughtIronUses);
WroughtIronShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","WroughtIronShovel",16149),IronToolMaterial).setUnlocalizedName("Wrought Iron Shovel").setMaxDamage(WroughtIronUses);
WroughtIronAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","WroughtIronAxe",16150),IronToolMaterial).setUnlocalizedName("Wrought Iron Axe").setMaxDamage(WroughtIronUses);
WroughtIronHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","WroughtIronHoe",16151),IronToolMaterial).setUnlocalizedName("Wrought Iron Hoe").setMaxDamage(WroughtIronUses);;
RedSteelPick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","RedSteelPick",16168),RedSteelToolMaterial).setUnlocalizedName("Red Steel Pick").setMaxDamage(RedSteelUses);
RedSteelShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","RedSteelShovel",16169),RedSteelToolMaterial).setUnlocalizedName("Red Steel Shovel").setMaxDamage(RedSteelUses);
RedSteelAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","RedSteelAxe",16170),RedSteelToolMaterial).setUnlocalizedName("Red Steel Axe").setMaxDamage(RedSteelUses);
RedSteelHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","RedSteelHoe",16171),RedSteelToolMaterial).setUnlocalizedName("Red Steel Hoe").setMaxDamage(RedSteelUses);
RoseGoldPick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","RoseGoldPick",16172),RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Pick").setMaxDamage(RoseGoldUses);
RoseGoldShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","RoseGoldShovel",16173),RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Shovel").setMaxDamage(RoseGoldUses);
RoseGoldAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","RoseGoldAxe",16174),RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Axe").setMaxDamage(RoseGoldUses);
RoseGoldHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","RoseGoldHoe",16175),RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Hoe").setMaxDamage(RoseGoldUses);
SteelPick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","SteelPick",16180),SteelToolMaterial).setUnlocalizedName("Steel Pick").setMaxDamage(SteelUses);
SteelShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","SteelShovel",16181),SteelToolMaterial).setUnlocalizedName("Steel Shovel").setMaxDamage(SteelUses);
SteelAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","SteelAxe",16182),SteelToolMaterial).setUnlocalizedName("Steel Axe").setMaxDamage(SteelUses);
SteelHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","SteelHoe",16183),SteelToolMaterial).setUnlocalizedName("Steel Hoe").setMaxDamage(SteelUses);
TinPick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","TinPick",16188),TinToolMaterial).setUnlocalizedName("Tin Pick").setMaxDamage(TinUses);
TinShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","TinShovel",16189),TinToolMaterial).setUnlocalizedName("Tin Shovel").setMaxDamage(TinUses);
TinAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","TinAxe",16190),TinToolMaterial).setUnlocalizedName("Tin Axe").setMaxDamage(TinUses);
TinHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","TinHoe",16191),TinToolMaterial).setUnlocalizedName("Tin Hoe").setMaxDamage(TinUses);
ZincPick = new ItemCustomPickaxe(TFC_Settings.getIntFor(config,"item","ZincPick",16192),ZincToolMaterial).setUnlocalizedName("Zinc Pick").setMaxDamage(ZincUses);
ZincShovel = new ItemCustomShovel(TFC_Settings.getIntFor(config,"item","ZincShovel",16193),ZincToolMaterial).setUnlocalizedName("Zinc Shovel").setMaxDamage(ZincUses);
ZincAxe = new ItemCustomAxe(TFC_Settings.getIntFor(config,"item","ZincAxe",16194),ZincToolMaterial).setUnlocalizedName("Zinc Axe").setMaxDamage(ZincUses);
ZincHoe = new ItemCustomHoe(TFC_Settings.getIntFor(config,"item","ZincHoe",16195),ZincToolMaterial).setUnlocalizedName("Zinc Hoe").setMaxDamage(ZincUses);
//chisels
BismuthChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","BismuthChisel",16226),BismuthToolMaterial).setUnlocalizedName("Bismuth Chisel").setMaxDamage(BismuthUses);
BismuthBronzeChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","BismuthBronzeChisel",16227),BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Chisel").setMaxDamage(BismuthBronzeUses);
BlackBronzeChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","BlackBronzeChisel",16228),BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Chisel").setMaxDamage(BlackBronzeUses);
BlackSteelChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","BlackSteelChisel",16230),BlackSteelToolMaterial).setUnlocalizedName("Black Steel Chisel").setMaxDamage(BlackSteelUses);
BlueSteelChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","BlueSteelChisel",16231),BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Chisel").setMaxDamage(BlueSteelUses);
BronzeChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","BronzeChisel",16232),BronzeToolMaterial).setUnlocalizedName("Bronze Chisel").setMaxDamage(BronzeUses);
CopperChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","CopperChisel",16233),CopperToolMaterial).setUnlocalizedName("Copper Chisel").setMaxDamage(CopperUses);
WroughtIronChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","WroughtIronChisel",16234),IronToolMaterial).setUnlocalizedName("Wrought Iron Chisel").setMaxDamage(WroughtIronUses);
RedSteelChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","RedSteelChisel",16235),RedSteelToolMaterial).setUnlocalizedName("Red Steel Chisel").setMaxDamage(RedSteelUses);
RoseGoldChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","RoseGoldChisel",16236),RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Chisel").setMaxDamage(RoseGoldUses);
SteelChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","SteelChisel",16237),SteelToolMaterial).setUnlocalizedName("Steel Chisel").setMaxDamage(SteelUses);
TinChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","TinChisel",16238),TinToolMaterial).setUnlocalizedName("Tin Chisel").setMaxDamage(TinUses);
ZincChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","ZincChisel",16239),ZincToolMaterial).setUnlocalizedName("Zinc Chisel").setMaxDamage(ZincUses);
StoneChisel = new ItemChisel(TFC_Settings.getIntFor(config,"item","StoneChisel",16240),IgInToolMaterial).setUnlocalizedName("Stone Chisel").setMaxDamage(IgInStoneUses);
BismuthSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BismuthSword",16245),BismuthToolMaterial).setUnlocalizedName("Bismuth Sword").setMaxDamage(BismuthUses);
BismuthBronzeSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BismuthBronzeSword",16246),BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Sword").setMaxDamage(BismuthBronzeUses);
BlackBronzeSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BlackBronzeSword",16247),BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Sword").setMaxDamage(BlackBronzeUses);
BlackSteelSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BlackSteelSword",16248),BlackSteelToolMaterial).setUnlocalizedName("Black Steel Sword").setMaxDamage(BlackSteelUses);
BlueSteelSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BlueSteelSword",16249),BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Sword").setMaxDamage(BlueSteelUses);
BronzeSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BronzeSword",16250),BronzeToolMaterial).setUnlocalizedName("Bronze Sword").setMaxDamage(BronzeUses);
CopperSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","CopperSword",16251),CopperToolMaterial).setUnlocalizedName("Copper Sword").setMaxDamage(CopperUses);
WroughtIronSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","WroughtIronSword",16252),IronToolMaterial).setUnlocalizedName("Wrought Iron Sword").setMaxDamage(WroughtIronUses);
RedSteelSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","RedSteelSword",16253),RedSteelToolMaterial).setUnlocalizedName("Red Steel Sword").setMaxDamage(RedSteelUses);
RoseGoldSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","RoseGoldSword",16254),RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Sword").setMaxDamage(RoseGoldUses);
SteelSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","SteelSword",16255),SteelToolMaterial).setUnlocalizedName("Steel Sword").setMaxDamage(SteelUses);
TinSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","TinSword",16256),TinToolMaterial).setUnlocalizedName("Tin Sword").setMaxDamage(TinUses);
ZincSword = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","ZincSword",16257),ZincToolMaterial).setUnlocalizedName("Zinc Sword").setMaxDamage(ZincUses);
BismuthMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BismuthMace",16262),BismuthToolMaterial).setUnlocalizedName("Bismuth Mace").setMaxDamage(BismuthUses);
BismuthBronzeMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BismuthBronzeMace",16263),BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Mace").setMaxDamage(BismuthBronzeUses);
BlackBronzeMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BlackBronzeMace",16264),BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Mace").setMaxDamage(BlackBronzeUses);
BlackSteelMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BlackSteelMace",16265),BlackSteelToolMaterial).setUnlocalizedName("Black Steel Mace").setMaxDamage(BlackSteelUses);
BlueSteelMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BlueSteelMace",16266),BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Mace").setMaxDamage(BlueSteelUses);
BronzeMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","BronzeMace",16267),BronzeToolMaterial).setUnlocalizedName("Bronze Mace").setMaxDamage(BronzeUses);
CopperMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","CopperMace",16268),CopperToolMaterial).setUnlocalizedName("Copper Mace").setMaxDamage(CopperUses);
WroughtIronMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","WroughtIronMace",16269),IronToolMaterial).setUnlocalizedName("Wrought Iron Mace").setMaxDamage(WroughtIronUses);
RedSteelMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","RedSteelMace",16270),RedSteelToolMaterial).setUnlocalizedName("Red Steel Mace").setMaxDamage(RedSteelUses);
RoseGoldMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","RoseGoldMace",16271),RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Mace").setMaxDamage(RoseGoldUses);
SteelMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","SteelMace",16272),SteelToolMaterial).setUnlocalizedName("Steel Mace").setMaxDamage(SteelUses);
TinMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","TinMace",16273),TinToolMaterial).setUnlocalizedName("Tin Mace").setMaxDamage(TinUses);
ZincMace = new ItemCustomSword(TFC_Settings.getIntFor(config,"item","ZincMace",16274),ZincToolMaterial).setUnlocalizedName("Zinc Mace").setMaxDamage(ZincUses);
BismuthSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","BismuthSaw",16275),BismuthToolMaterial).setUnlocalizedName("Bismuth Saw").setMaxDamage(BismuthUses);
BismuthBronzeSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","BismuthBronzeSaw",16276),BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Saw").setMaxDamage(BismuthBronzeUses);
BlackBronzeSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","BlackBronzeSaw",16277),BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Saw").setMaxDamage(BlackBronzeUses);
BlackSteelSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","BlackSteelSaw",16278),BlackSteelToolMaterial).setUnlocalizedName("Black Steel Saw").setMaxDamage(BlackSteelUses);
BlueSteelSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","BlueSteelSaw",16279),BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Saw").setMaxDamage(BlueSteelUses);
BronzeSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","BronzeSaw",16280),BronzeToolMaterial).setUnlocalizedName("Bronze Saw").setMaxDamage(BronzeUses);
CopperSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","CopperSaw",16281),CopperToolMaterial).setUnlocalizedName("Copper Saw").setMaxDamage(CopperUses);
WroughtIronSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","WroughtIronSaw",16282),IronToolMaterial).setUnlocalizedName("Wrought Iron Saw").setMaxDamage(WroughtIronUses);
RedSteelSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","RedSteelSaw",16283),RedSteelToolMaterial).setUnlocalizedName("Red Steel Saw").setMaxDamage(RedSteelUses);
RoseGoldSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","RoseGoldSaw",16284),RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Saw").setMaxDamage(RoseGoldUses);
SteelSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","SteelSaw",16285),SteelToolMaterial).setUnlocalizedName("Steel Saw").setMaxDamage(SteelUses);
TinSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","TinSaw",16286),TinToolMaterial).setUnlocalizedName("Tin Saw").setMaxDamage(TinUses);
ZincSaw = new ItemCustomSaw(TFC_Settings.getIntFor(config,"item","ZincSaw",16287),ZincToolMaterial).setUnlocalizedName("Zinc Saw").setMaxDamage(ZincUses);
HCBlackSteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","HCBlackSteelIngot",16290), EnumMetalType.BLACKSTEEL).setUnlocalizedName("HC Black Steel Ingot");
WeakBlueSteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","WeakBlueSteelIngot",16291),EnumMetalType.BLUESTEEL).setUnlocalizedName("Weak Blue Steel Ingot");
WeakRedSteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","WeakRedSteelIngot",16292),EnumMetalType.REDSTEEL).setUnlocalizedName("Weak Red Steel Ingot");
WeakSteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","WeakSteelIngot",16293),EnumMetalType.STEEL).setUnlocalizedName("Weak Steel Ingot");
HCBlueSteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","HCBlueSteelIngot",16294), EnumMetalType.BLUESTEEL).setUnlocalizedName("HC Blue Steel Ingot");
HCRedSteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","HCRedSteelIngot",16295), EnumMetalType.REDSTEEL).setUnlocalizedName("HC Red Steel Ingot");
HCSteelIngot = new ItemIngot(TFC_Settings.getIntFor(config,"item","HCSteelIngot",16296), EnumMetalType.STEEL).setUnlocalizedName("HC Steel Ingot");
OreChunk = new ItemOre(TFC_Settings.getIntFor(config,"item","OreChunk",16297)).setFolder("ore/").setUnlocalizedName("Ore");
Logs = new ItemLogs(TFC_Settings.getIntFor(config,"item","Logs",16298)).setUnlocalizedName("Log");
Javelin = new ItemJavelin(TFC_Settings.getIntFor(config,"item","javelin",16318)).setUnlocalizedName("javelin");
BismuthUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedBismuth",16350)).setUnlocalizedName("Bismuth Unshaped");
BismuthBronzeUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedBismuthBronze",16351)).setUnlocalizedName("Bismuth Bronze Unshaped");
BlackBronzeUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedBlackBronze",16352)).setUnlocalizedName("Black Bronze Unshaped");
BlackSteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedBlackSteel",16353)).setUnlocalizedName("Black Steel Unshaped");
BlueSteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedBlueSteel",16354)).setUnlocalizedName("Blue Steel Unshaped");
BrassUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedBrass",16355)).setUnlocalizedName("Brass Unshaped");
BronzeUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedBronze",16356)).setUnlocalizedName("Bronze Unshaped");
CopperUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedCopper",16357)).setUnlocalizedName("Copper Unshaped");
GoldUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedGold",16358)).setUnlocalizedName("Gold Unshaped");
WroughtIronUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedIron",16359)).setUnlocalizedName("Wrought Iron Unshaped");
LeadUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedLead",16360)).setUnlocalizedName("Lead Unshaped");
NickelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedNickel",16361)).setUnlocalizedName("Nickel Unshaped");
PigIronUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedPigIron",16362)).setUnlocalizedName("Pig Iron Unshaped");
PlatinumUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedPlatinum",16363)).setUnlocalizedName("Platinum Unshaped");
RedSteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedRedSteel",16364)).setUnlocalizedName("Red Steel Unshaped");
RoseGoldUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedRoseGold",16365)).setUnlocalizedName("Rose Gold Unshaped");
SilverUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedSilver",16366)).setUnlocalizedName("Silver Unshaped");
SteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedSteel",16367)).setUnlocalizedName("Steel Unshaped");
SterlingSilverUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedSterlingSilver",16368)).setUnlocalizedName("Sterling Silver Unshaped");
TinUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedTin",16369)).setUnlocalizedName("Tin Unshaped");
ZincUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedZinc",16370)).setUnlocalizedName("Zinc Unshaped");
//Hammers
StoneHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","terraStoneHammer",16371),TFCItems.IgInToolMaterial).setUnlocalizedName("Stone Hammer").setMaxDamage(TFCItems.IgInStoneUses);
BismuthHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","terraBismuthHammer",16372),TFCItems.BismuthToolMaterial).setUnlocalizedName("Bismuth Hammer").setMaxDamage(TFCItems.BismuthUses);
BismuthBronzeHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","terraBismuthBronzeHammer",16373),TFCItems.BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Hammer").setMaxDamage(TFCItems.BismuthBronzeUses);
BlackBronzeHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","terraBlackBronzeHammer",16374),TFCItems.BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Hammer").setMaxDamage(TFCItems.BlackBronzeUses);
BlackSteelHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","terraBlackSteelHammer",16375),TFCItems.BlackSteelToolMaterial).setUnlocalizedName("Black Steel Hammer").setMaxDamage(TFCItems.BlackSteelUses);
BlueSteelHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","terraBlueSteelHammer",16376),TFCItems.BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Hammer").setMaxDamage(TFCItems.BlueSteelUses);
BronzeHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","terraBronzeHammer",16377),TFCItems.BronzeToolMaterial).setUnlocalizedName("Bronze Hammer").setMaxDamage(TFCItems.BronzeUses);
CopperHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","terraCopperHammer",16378),TFCItems.CopperToolMaterial).setUnlocalizedName("Copper Hammer").setMaxDamage(TFCItems.CopperUses);
WroughtIronHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","terraWroughtIronHammer",16379),TFCItems.IronToolMaterial).setUnlocalizedName("Wrought Iron Hammer").setMaxDamage(TFCItems.WroughtIronUses);
RedSteelHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","terraRedSteelHammer",16380),TFCItems.RedSteelToolMaterial).setUnlocalizedName("Red Steel Hammer").setMaxDamage(TFCItems.RedSteelUses);
RoseGoldHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","terraRoseGoldHammer",16381),TFCItems.RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Hammer").setMaxDamage(TFCItems.RoseGoldUses);
SteelHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","terraSteelHammer",16382),TFCItems.SteelToolMaterial).setUnlocalizedName("Steel Hammer").setMaxDamage(TFCItems.SteelUses);
TinHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","terraTinHammer",16383),TFCItems.TinToolMaterial).setUnlocalizedName("Tin Hammer").setMaxDamage(TFCItems.TinUses);
ZincHammer = new ItemHammer(TFC_Settings.getIntFor(config,"item","terraZincHammer",16384),TFCItems.ZincToolMaterial).setUnlocalizedName("Zinc Hammer").setMaxDamage(TFCItems.ZincUses);
Ink = new ItemTerra(TFC_Settings.getIntFor(config,"item","Ink",16391)).setUnlocalizedName("Ink");
BellowsItem = new ItemBellows(TFC_Settings.getIntFor(config,"item","terraBellowsItem",16406)).setUnlocalizedName("Bellows");
FireStarter = new ItemFirestarter(TFC_Settings.getIntFor(config,"item","terraFireStarter",16407)).setFolder("tools/").setUnlocalizedName("Firestarter");
ClayMold = new ItemTerra(TFC_Settings.getIntFor(config,"item","terraClayMold",16408)).setUnlocalizedName("Clay Mold");
CeramicMold = new ItemTerra(TFC_Settings.getIntFor(config,"item","terraFiredClayMold",16409)).setUnlocalizedName("Ceramic Mold");
//Tool heads
BismuthPickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthPickaxeHead",16500)).setUnlocalizedName("Bismuth Pick Head");
BismuthBronzePickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzePickaxeHead",16501)).setUnlocalizedName("Bismuth Bronze Pick Head");
BlackBronzePickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzePickaxeHead",16502)).setUnlocalizedName("Black Bronze Pick Head");
BlackSteelPickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelPickaxeHead",16503)).setUnlocalizedName("Black Steel Pick Head");
BlueSteelPickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelPickaxeHead",16504)).setUnlocalizedName("Blue Steel Pick Head");
BronzePickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzePickaxeHead",16505)).setUnlocalizedName("Bronze Pick Head");
CopperPickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperPickaxeHead",16506)).setUnlocalizedName("Copper Pick Head");
WroughtIronPickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronPickaxeHead",16507)).setUnlocalizedName("Wrought Iron Pick Head");
RedSteelPickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelPickaxeHead",16508)).setUnlocalizedName("Red Steel Pick Head");
RoseGoldPickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldPickaxeHead",16509)).setUnlocalizedName("Rose Gold Pick Head");
SteelPickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelPickaxeHead",16510)).setUnlocalizedName("Steel Pick Head");
TinPickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinPickaxeHead",16511)).setUnlocalizedName("Tin Pick Head");
ZincPickaxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincPickaxeHead",16512)).setUnlocalizedName("Zinc Pick Head");
BismuthShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthShovelHead",16513)).setUnlocalizedName("Bismuth Shovel Head");
BismuthBronzeShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeShovelHead",16514)).setUnlocalizedName("Bismuth Bronze Shovel Head");
BlackBronzeShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeShovelHead",16515)).setUnlocalizedName("Black Bronze Shovel Head");
BlackSteelShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelShovelHead",16516)).setUnlocalizedName("Black Steel Shovel Head");
BlueSteelShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelShovelHead",16517)).setUnlocalizedName("Blue Steel Shovel Head");
BronzeShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeShovelHead",16518)).setUnlocalizedName("Bronze Shovel Head");
CopperShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperShovelHead",16519)).setUnlocalizedName("Copper Shovel Head");
WroughtIronShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronShovelHead",16520)).setUnlocalizedName("Wrought Iron Shovel Head");
RedSteelShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelShovelHead",16521)).setUnlocalizedName("Red Steel Shovel Head");
RoseGoldShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldShovelHead",16522)).setUnlocalizedName("Rose Gold Shovel Head");
SteelShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelShovelHead",16523)).setUnlocalizedName("Steel Shovel Head");
TinShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinShovelHead",16524)).setUnlocalizedName("Tin Shovel Head");
ZincShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincShovelHead",16525)).setUnlocalizedName("Zinc Shovel Head");
BismuthHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthHoeHead",16526)).setUnlocalizedName("Bismuth Hoe Head");
BismuthBronzeHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeHoeHead",16527)).setUnlocalizedName("Bismuth Bronze Hoe Head");
BlackBronzeHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeHoeHead",16528)).setUnlocalizedName("Black Bronze Hoe Head");
BlackSteelHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelHoeHead",16529)).setUnlocalizedName("Black Steel Hoe Head");
BlueSteelHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelHoeHead",16530)).setUnlocalizedName("Blue Steel Hoe Head");
BronzeHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeHoeHead",16531)).setUnlocalizedName("Bronze Hoe Head");
CopperHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperHoeHead",16532)).setUnlocalizedName("Copper Hoe Head");
WroughtIronHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronHoeHead",16533)).setUnlocalizedName("Wrought Iron Hoe Head");
RedSteelHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelHoeHead",16534)).setUnlocalizedName("Red Steel Hoe Head");
RoseGoldHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldHoeHead",16535)).setUnlocalizedName("Rose Gold Hoe Head");
SteelHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelHoeHead",16536)).setUnlocalizedName("Steel Hoe Head");
TinHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinHoeHead",16537)).setUnlocalizedName("Tin Hoe Head");
ZincHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincHoeHead",16538)).setUnlocalizedName("Zinc Hoe Head");
BismuthAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthAxeHead",16539)).setUnlocalizedName("Bismuth Axe Head");
BismuthBronzeAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeAxeHead",16540)).setUnlocalizedName("Bismuth Bronze Axe Head");
BlackBronzeAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeAxeHead",16541)).setUnlocalizedName("Black Bronze Axe Head");
BlackSteelAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelAxeHead",16542)).setUnlocalizedName("Black Steel Axe Head");
BlueSteelAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelAxeHead",16543)).setUnlocalizedName("Blue Steel Axe Head");
BronzeAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeAxeHead",16544)).setUnlocalizedName("Bronze Axe Head");
CopperAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperAxeHead",16545)).setUnlocalizedName("Copper Axe Head");
WroughtIronAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronAxeHead",16546)).setUnlocalizedName("Wrought Iron Axe Head");
RedSteelAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelAxeHead",16547)).setUnlocalizedName("Red Steel Axe Head");
RoseGoldAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldAxeHead",16548)).setUnlocalizedName("Rose Gold Axe Head");
SteelAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelAxeHead",16549)).setUnlocalizedName("Steel Axe Head");
TinAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinAxeHead",16550)).setUnlocalizedName("Tin Axe Head");
ZincAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincAxeHead",16551)).setUnlocalizedName("Zinc Axe Head");
BismuthHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthHammerHead",16552)).setUnlocalizedName("Bismuth Hammer Head");
BismuthBronzeHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeHammerHead",16553)).setUnlocalizedName("Bismuth Bronze Hammer Head");
BlackBronzeHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeHammerHead",16554)).setUnlocalizedName("Black Bronze Hammer Head");
BlackSteelHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelHammerHead",16555)).setUnlocalizedName("Black Steel Hammer Head");
BlueSteelHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelHammerHead",16556)).setUnlocalizedName("Blue Steel Hammer Head");
BronzeHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeHammerHead",16557)).setUnlocalizedName("Bronze Hammer Head");
CopperHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperHammerHead",16558)).setUnlocalizedName("Copper Hammer Head");
WroughtIronHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronHammerHead",16559)).setUnlocalizedName("Wrought Iron Hammer Head");
RedSteelHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelHammerHead",16560)).setUnlocalizedName("Red Steel Hammer Head");
RoseGoldHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldHammerHead",16561)).setUnlocalizedName("Rose Gold Hammer Head");
SteelHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelHammerHead",16562)).setUnlocalizedName("Steel Hammer Head");
TinHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinHammerHead",16563)).setUnlocalizedName("Tin Hammer Head");
ZincHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincHammerHead",16564)).setUnlocalizedName("Zinc Hammer Head");
//chisel heads
BismuthChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthChiselHead",16565)).setUnlocalizedName("Bismuth Chisel Head");
BismuthBronzeChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeChiselHead",16566)).setUnlocalizedName("Bismuth Bronze Chisel Head");
BlackBronzeChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeChiselHead",16567)).setUnlocalizedName("Black Bronze Chisel Head");
BlackSteelChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelChiselHead",16568)).setUnlocalizedName("Black Steel Chisel Head");
BlueSteelChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelChiselHead",16569)).setUnlocalizedName("Blue Steel Chisel Head");
BronzeChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeChiselHead",16570)).setUnlocalizedName("Bronze Chisel Head");
CopperChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperChiselHead",16571)).setUnlocalizedName("Copper Chisel Head");
WroughtIronChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronChiselHead",16572)).setUnlocalizedName("Wrought Iron Chisel Head");
RedSteelChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelChiselHead",16573)).setUnlocalizedName("Red Steel Chisel Head");
RoseGoldChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldChiselHead",16574)).setUnlocalizedName("Rose Gold Chisel Head");
SteelChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelChiselHead",16575)).setUnlocalizedName("Steel Chisel Head");
TinChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinChiselHead",16576)).setUnlocalizedName("Tin Chisel Head");
ZincChiselHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincChiselHead",16577)).setUnlocalizedName("Zinc Chisel Head");
BismuthSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthSwordHead",16578)).setUnlocalizedName("Bismuth Sword Blade");
BismuthBronzeSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeSwordHead",16579)).setUnlocalizedName("Bismuth Bronze Sword Blade");
BlackBronzeSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeSwordHead",16580)).setUnlocalizedName("Black Bronze Sword Blade");
BlackSteelSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelSwordHead",16581)).setUnlocalizedName("Black Steel Sword Blade");
BlueSteelSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelSwordHead",16582)).setUnlocalizedName("Blue Steel Sword Blade");
BronzeSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeSwordHead",16583)).setUnlocalizedName("Bronze Sword Blade");
CopperSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperSwordHead",16584)).setUnlocalizedName("Copper Sword Blade");
WroughtIronSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronSwordHead",16585)).setUnlocalizedName("Wrought Iron Sword Blade");
RedSteelSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelSwordHead",16586)).setUnlocalizedName("Red Steel Sword Blade");
RoseGoldSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldSwordHead",16587)).setUnlocalizedName("Rose Gold Sword Blade");
SteelSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelSwordHead",16588)).setUnlocalizedName("Steel Sword Blade");
TinSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinSwordHead",16589)).setUnlocalizedName("Tin Sword Blade");
ZincSwordHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincSwordHead",16590)).setUnlocalizedName("Zinc Sword Blade");
BismuthMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthMaceHead",16591)).setUnlocalizedName("Bismuth Mace Head");
BismuthBronzeMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeMaceHead",16592)).setUnlocalizedName("Bismuth Bronze Mace Head");
BlackBronzeMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeMaceHead",16593)).setUnlocalizedName("Black Bronze Mace Head");
BlackSteelMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelMaceHead",16594)).setUnlocalizedName("Black Steel Mace Head");
BlueSteelMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelMaceHead",16595)).setUnlocalizedName("Blue Steel Mace Head");
BronzeMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeMaceHead",16596)).setUnlocalizedName("Bronze Mace Head");
CopperMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperMaceHead",16597)).setUnlocalizedName("Copper Mace Head");
WroughtIronMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronMaceHead",16598)).setUnlocalizedName("Wrought Iron Mace Head");
RedSteelMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelMaceHead",16599)).setUnlocalizedName("Red Steel Mace Head");
RoseGoldMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldMaceHead",16600)).setUnlocalizedName("Rose Gold Mace Head");
SteelMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelMaceHead",16601)).setUnlocalizedName("Steel Mace Head");
TinMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinMaceHead",16602)).setUnlocalizedName("Tin Mace Head");
ZincMaceHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincMaceHead",16603)).setUnlocalizedName("Zinc Mace Head");
BismuthSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthSawHead",16604)).setUnlocalizedName("Bismuth Saw Blade");
BismuthBronzeSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeSawHead",16605)).setUnlocalizedName("Bismuth Bronze Saw Blade");
BlackBronzeSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeSawHead",16606)).setUnlocalizedName("Black Bronze Saw Blade");
BlackSteelSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelSawHead",16607)).setUnlocalizedName("Black Steel Saw Blade");
BlueSteelSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelSawHead",16608)).setUnlocalizedName("Blue Steel Saw Blade");
BronzeSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeSawHead",16609)).setUnlocalizedName("Bronze Saw Blade");
CopperSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperSawHead",16610)).setUnlocalizedName("Copper Saw Blade");
WroughtIronSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronSawHead",16611)).setUnlocalizedName("Wrought Iron Saw Blade");
RedSteelSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelSawHead",16612)).setUnlocalizedName("Red Steel Saw Blade");
RoseGoldSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldSawHead",16613)).setUnlocalizedName("Rose Gold Saw Blade");
SteelSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelSawHead",16614)).setUnlocalizedName("Steel Saw Blade");
TinSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinSawHead",16615)).setUnlocalizedName("Tin Saw Blade");
ZincSawHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincSawHead",16616)).setUnlocalizedName("Zinc Saw Blade");
HCBlackSteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedHCBlackSteel",16617)).setUnlocalizedName("HC Black Steel Unshaped");
WeakBlueSteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedWeakBlueSteel",16618)).setUnlocalizedName("Weak Blue Steel Unshaped");
HCBlueSteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedHCBlueSteel",16619)).setUnlocalizedName("HC Blue Steel Unshaped");
WeakRedSteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedWeakRedSteel",16621)).setUnlocalizedName("Weak Red Steel Unshaped");
HCRedSteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedHCRedSteel",16622)).setUnlocalizedName("HC Red Steel Unshaped");
WeakSteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedWeakSteel",16623)).setUnlocalizedName("Weak Steel Unshaped");
HCSteelUnshaped = new ItemMeltedMetal(TFC_Settings.getIntFor(config,"item","UnshapedHCSteel",16624)).setUnlocalizedName("HC Steel Unshaped");
Coke = (new ItemTerra(TFC_Settings.getIntFor(config,"item","Coke",16625)).setUnlocalizedName("Coke"));
BismuthProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthProPickHead",16626)).setUnlocalizedName("Bismuth ProPick Head");
BismuthBronzeProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeProPickHead",16627)).setUnlocalizedName("Bismuth Bronze ProPick Head");
BlackBronzeProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeProPickHead",16628)).setUnlocalizedName("Black Bronze ProPick Head");
BlackSteelProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelProPickHead",16629)).setUnlocalizedName("Black Steel ProPick Head");
BlueSteelProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelProPickHead",16630)).setUnlocalizedName("Blue Steel ProPick Head");
BronzeProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeProPickHead",16631)).setUnlocalizedName("Bronze ProPick Head");
CopperProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperProPickHead",16632)).setUnlocalizedName("Copper ProPick Head");
WroughtIronProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronProPickHead",16633)).setUnlocalizedName("Wrought Iron ProPick Head");
RedSteelProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelProPickHead",16634)).setUnlocalizedName("Red Steel ProPick Head");
RoseGoldProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldProPickHead",16635)).setUnlocalizedName("Rose Gold ProPick Head");
SteelProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelProPickHead",16636)).setUnlocalizedName("Steel ProPick Head");
TinProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinProPickHead",16637)).setUnlocalizedName("Tin ProPick Head");
ZincProPickHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincProPickHead",16638)).setUnlocalizedName("Zinc ProPick Head");
Flux = (new ItemTerra(TFC_Settings.getIntFor(config,"item","Flux",16639)).setUnlocalizedName("Flux"));
/**
* Scythe
* */
int num = 16643;
BismuthScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","BismuthScythe",num),BismuthToolMaterial).setUnlocalizedName("Bismuth Scythe").setMaxDamage(BismuthUses);num++;
BismuthBronzeScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","BismuthBronzeScythe",num),BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Scythe").setMaxDamage(BismuthBronzeUses);num++;
BlackBronzeScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","BlackBronzeScythe",num),BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Scythe").setMaxDamage(BlackBronzeUses);num++;
BlackSteelScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","BlackSteelScythe",num),BlackSteelToolMaterial).setUnlocalizedName("Black Steel Scythe").setMaxDamage(BlackSteelUses);num++;
BlueSteelScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","BlueSteelScythe",num),BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Scythe").setMaxDamage(BlueSteelUses);num++;
BronzeScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","BronzeScythe",num),BronzeToolMaterial).setUnlocalizedName("Bronze Scythe").setMaxDamage(BronzeUses);num++;
CopperScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","CopperScythe",num),CopperToolMaterial).setUnlocalizedName("Copper Scythe").setMaxDamage(CopperUses);num++;
WroughtIronScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","WroughtIronScythe",num),IronToolMaterial).setUnlocalizedName("Wrought Iron Scythe").setMaxDamage(WroughtIronUses);num++;
RedSteelScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","RedSteelScythe",num),RedSteelToolMaterial).setUnlocalizedName("Red Steel Scythe").setMaxDamage(RedSteelUses);num++;
RoseGoldScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","RoseGoldScythe",num),RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Scythe").setMaxDamage(RoseGoldUses);num++;
SteelScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","SteelScythe",num),SteelToolMaterial).setUnlocalizedName("Steel Scythe").setMaxDamage(SteelUses);num++;
TinScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","TinScythe",num),TinToolMaterial).setUnlocalizedName("Tin Scythe").setMaxDamage(TinUses);num++;
ZincScythe = new ItemCustomScythe(TFC_Settings.getIntFor(config,"item","ZincScythe",num),ZincToolMaterial).setUnlocalizedName("Zinc Scythe").setMaxDamage(ZincUses);num++;
BismuthScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthScytheHead",num)).setUnlocalizedName("Bismuth Scythe Blade");num++;
BismuthBronzeScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeScytheHead",num)).setUnlocalizedName("Bismuth Bronze Scythe Blade");num++;
BlackBronzeScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeScytheHead",num)).setUnlocalizedName("Black Bronze Scythe Blade");num++;
BlackSteelScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelScytheHead",num)).setUnlocalizedName("Black Steel Scythe Blade");num++;
BlueSteelScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelScytheHead",num)).setUnlocalizedName("Blue Steel Scythe Blade");num++;
BronzeScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeScytheHead",num)).setUnlocalizedName("Bronze Scythe Blade");num++;
CopperScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperScytheHead",num)).setUnlocalizedName("Copper Scythe Blade");num++;
WroughtIronScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronScytheHead",num)).setUnlocalizedName("Wrought Iron Scythe Blade");num++;
RedSteelScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelScytheHead",num)).setUnlocalizedName("Red Steel Scythe Blade");num++;
RoseGoldScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldScytheHead",num)).setUnlocalizedName("Rose Gold Scythe Blade");num++;
SteelScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelScytheHead",num)).setUnlocalizedName("Steel Scythe Blade");num++;
TinScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinScytheHead",num)).setUnlocalizedName("Tin Scythe Blade");num++;
ZincScytheHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincScytheHead",num)).setUnlocalizedName("Zinc Scythe Blade");num++;
WoodenBucketEmpty = (new ItemCustomBucket(TFC_Settings.getIntFor(config,"item","WoodenBucketEmpty",num), 0)).setUnlocalizedName("Wooden Bucket Empty");num++;
WoodenBucketWater = (new ItemCustomBucket(TFC_Settings.getIntFor(config,"item","WoodenBucketWater",num), TFCBlocks.finiteWater.blockID)).setUnlocalizedName("Wooden Bucket Water").setContainerItem(WoodenBucketEmpty);num++;
WoodenBucketMilk = (new ItemCustomBucketMilk(TFC_Settings.getIntFor(config,"item","WoodenBucketMilk",num))).setUnlocalizedName("Wooden Bucket Milk").setContainerItem(WoodenBucketEmpty);num++;
BismuthKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthKnifeHead",num)).setUnlocalizedName("Bismuth Knife Blade");num++;
BismuthBronzeKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BismuthBronzeKnifeHead",num)).setUnlocalizedName("Bismuth Bronze Knife Blade");num++;
BlackBronzeKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackBronzeKnifeHead",num)).setUnlocalizedName("Black Bronze Knife Blade");num++;
BlackSteelKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlackSteelKnifeHead",num)).setUnlocalizedName("Black Steel Knife Blade");num++;
BlueSteelKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BlueSteelKnifeHead",num)).setUnlocalizedName("Blue Steel Knife Blade");num++;
BronzeKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","BronzeKnifeHead",num)).setUnlocalizedName("Bronze Knife Blade");num++;
CopperKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","CopperKnifeHead",num)).setUnlocalizedName("Copper Knife Blade");num++;
WroughtIronKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","WroughtIronKnifeHead",num)).setUnlocalizedName("Wrought Iron Knife Blade");num++;
RedSteelKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RedSteelKnifeHead",num)).setUnlocalizedName("Red Steel Knife Blade");num++;
RoseGoldKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","RoseGoldKnifeHead",num)).setUnlocalizedName("Rose Gold Knife Blade");num++;
SteelKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SteelKnifeHead",num)).setUnlocalizedName("Steel Knife Blade");num++;
TinKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","TinKnifeHead",num)).setUnlocalizedName("Tin Knife Blade");num++;
ZincKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","ZincKnifeHead",num)).setUnlocalizedName("Zinc Knife Blade");num++;
BismuthKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","BismuthKnife",num),BismuthToolMaterial).setUnlocalizedName("Bismuth Knife").setMaxDamage(BismuthUses);num++;
BismuthBronzeKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","BismuthBronzeKnife",num),BismuthBronzeToolMaterial).setUnlocalizedName("Bismuth Bronze Knife").setMaxDamage(BismuthBronzeUses);num++;
BlackBronzeKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","BlackBronzeKnife",num),BlackBronzeToolMaterial).setUnlocalizedName("Black Bronze Knife").setMaxDamage(BlackBronzeUses);num++;
BlackSteelKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","BlackSteelKnife",num),BlackSteelToolMaterial).setUnlocalizedName("Black Steel Knife").setMaxDamage(BlackSteelUses);num++;
BlueSteelKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","BlueSteelKnife",num),BlueSteelToolMaterial).setUnlocalizedName("Blue Steel Knife").setMaxDamage(BlueSteelUses);num++;
BronzeKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","BronzeKnife",num),BronzeToolMaterial).setUnlocalizedName("Bronze Knife").setMaxDamage(BronzeUses);num++;
CopperKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","CopperKnife",num),CopperToolMaterial).setUnlocalizedName("Copper Knife").setMaxDamage(CopperUses);num++;
WroughtIronKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","WroughtIronKnife",num),IronToolMaterial).setUnlocalizedName("Wrought Iron Knife").setMaxDamage(WroughtIronUses);num++;
RedSteelKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","RedSteelKnife",num),RedSteelToolMaterial).setUnlocalizedName("Red Steel Knife").setMaxDamage(RedSteelUses);num++;
RoseGoldKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","RoseGoldKnife",num),RoseGoldToolMaterial).setUnlocalizedName("Rose Gold Knife").setMaxDamage(RoseGoldUses);num++;
SteelKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","SteelKnife",num),SteelToolMaterial).setUnlocalizedName("Steel Knife").setMaxDamage(SteelUses);num++;
TinKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","TinKnife",num),TinToolMaterial).setUnlocalizedName("Tin Knife").setMaxDamage(TinUses);num++;
ZincKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","ZincKnife",num),ZincToolMaterial).setUnlocalizedName("Zinc Knife").setMaxDamage(ZincUses);num++;
LooseRock = (new ItemLooseRock(TFC_Settings.getIntFor(config,"item","LooseRock",num)).setUnlocalizedName("LooseRock"));num++;
FlatRock = (new ItemFlatRock(TFC_Settings.getIntFor(config,"item","FlatRock",num)).setUnlocalizedName("FlatRock"));num++;
IgInStoneShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","IgInStoneShovelHead",num)).setUnlocalizedName("Stone Shovel Head");num++;
SedStoneShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SedStoneShovelHead",num)).setUnlocalizedName("Stone Shovel Head");num++;
IgExStoneShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","IgExStoneShovelHead",num)).setUnlocalizedName("Stone Shovel Head");num++;
MMStoneShovelHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","MMStoneShovelHead",num)).setUnlocalizedName("Stone Shovel Head");num++;
IgInStoneAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","IgInStoneAxeHead",num)).setUnlocalizedName("Stone Axe Head");num++;
SedStoneAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SedStoneAxeHead",num)).setUnlocalizedName("Stone Axe Head");num++;
IgExStoneAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","IgExStoneAxeHead",num)).setUnlocalizedName("Stone Axe Head");num++;
MMStoneAxeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","MMStoneAxeHead",num)).setUnlocalizedName("Stone Axe Head");num++;
IgInStoneHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","IgInStoneHoeHead",num)).setUnlocalizedName("Stone Hoe Head");num++;
SedStoneHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","SedStoneHoeHead",num)).setUnlocalizedName("Stone Hoe Head");num++;
IgExStoneHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","IgExStoneHoeHead",num)).setUnlocalizedName("Stone Hoe Head");num++;
MMStoneHoeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","MMStoneHoeHead",num)).setUnlocalizedName("Stone Hoe Head");num++;
StoneKnifeHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","StoneKnifeHead",num)).setUnlocalizedName("Stone Knife Blade");num++;
StoneHammerHead = new ItemMiscToolHead(TFC_Settings.getIntFor(config,"item","StoneHammerHead",num)).setUnlocalizedName("Stone Hammer Head");num++;
StoneKnife = new ItemCustomKnife(TFC_Settings.getIntFor(config,"item","StoneKnife",num),IgExToolMaterial).setUnlocalizedName("Stone Knife").setMaxDamage(IgExStoneUses);num++;
SmallOreChunk = new ItemOreSmall(TFC_Settings.getIntFor(config,"item","SmallOreChunk",num++)).setUnlocalizedName("Small Ore");
SinglePlank = new ItemPlank(TFC_Settings.getIntFor(config,"item","SinglePlank",num++)).setUnlocalizedName("SinglePlank");
RedSteelBucketEmpty = (new ItemCustomRedSteelBucket(TFC_Settings.getIntFor(config,"item","RedSteelBucketEmpty",num++), 0)).setUnlocalizedName("Red Steel Bucket Empty");
RedSteelBucketWater = (new ItemCustomRedSteelBucket(TFC_Settings.getIntFor(config,"item","RedSteelBucketWater",num++), Block.waterMoving.blockID)).setUnlocalizedName("Red Steel Bucket Water").setContainerItem(RedSteelBucketEmpty);
BlueSteelBucketEmpty = (new ItemCustomBlueSteelBucket(TFC_Settings.getIntFor(config,"item","BlueSteelBucketEmpty",num++), 0)).setUnlocalizedName("Blue Steel Bucket Empty");
BlueSteelBucketLava = (new ItemCustomBlueSteelBucket(TFC_Settings.getIntFor(config,"item","BlueSteelBucketLava",num++), Block.lavaMoving.blockID)).setUnlocalizedName("Blue Steel Bucket Lava").setContainerItem(BlueSteelBucketEmpty);
Quern = new ItemTerra(TFC_Settings.getIntFor(config,"item","Quern",num++)).setUnlocalizedName("Quern").setMaxDamage(250);
FlintSteel = new ItemFlintSteel(TFC_Settings.getIntFor(config,"item","FlintSteel",num++)).setUnlocalizedName("flintAndSteel").setMaxDamage(200);
DoorOak = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorOak", num++), 0).setUnlocalizedName("Oak Door");
DoorAspen = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorAspen", num++), 1).setUnlocalizedName("Aspen Door");
DoorBirch = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorBirch", num++), 2).setUnlocalizedName("Birch Door");
DoorChestnut = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorChestnut", num++), 3).setUnlocalizedName("Chestnut Door");
DoorDouglasFir = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorDouglasFir", num++), 4).setUnlocalizedName("Douglas Fir Door");
DoorHickory = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorHickory", num++), 5).setUnlocalizedName("Hickory Door");
DoorMaple = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorMaple", num++), 6).setUnlocalizedName("Maple Door");
DoorAsh = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorAsh", num++), 7).setUnlocalizedName("Ash Door");
DoorPine = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorPine", num++), 8).setUnlocalizedName("Pine Door");
DoorSequoia = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorSequoia", num++), 9).setUnlocalizedName("Sequoia Door");
DoorSpruce = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorSpruce", num++), 10).setUnlocalizedName("Spruce Door");
DoorSycamore = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorSycamore", num++), 11).setUnlocalizedName("Sycamore Door");
DoorWhiteCedar = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorWhiteCedar", num++), 12).setUnlocalizedName("White Cedar Door");
DoorWhiteElm = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorWhiteElm", num++), 13).setUnlocalizedName("White Elm Door");
DoorWillow = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorWillow", num++), 14).setUnlocalizedName("Willow Door");
DoorKapok = new ItemWoodDoor(TFC_Settings.getIntFor(config,"item","DoorKapok", num++), 15).setUnlocalizedName("Kapok Door");
Blueprint = new ItemBlueprint(TFC_Settings.getIntFor(config,"item","Blueprint", num++));
writabeBookTFC = new ItemWritableBookTFC(TFC_Settings.getIntFor(config,"item","WritableBookTFC", num++),"Fix Me I'm Broken").setUnlocalizedName("book");
WoolYarn = new ItemTerra(TFC_Settings.getIntFor(config, "item", "WoolYarn", num++)).setUnlocalizedName("WoolYarn").setCreativeTab(TFCTabs.TFCMaterials);
Wool = new ItemTerra(TFC_Settings.getIntFor(config,"item","Wool",num++)).setUnlocalizedName("Wool").setCreativeTab(TFCTabs.TFCMaterials);
WoolCloth = new ItemTerra(TFC_Settings.getIntFor(config, "item", "WoolCloth", num++)).setUnlocalizedName("WoolCloth").setCreativeTab(TFCTabs.TFCMaterials);
Spindle = new ItemSpindle(TFC_Settings.getIntFor(config,"item","Spindle",num++),SedToolMaterial).setUnlocalizedName("Spindle").setCreativeTab(TFCTabs.TFCMaterials);
ClaySpindle = new ItemTerra(TFC_Settings.getIntFor(config, "item", "ClaySpindle", num++)).setFolder("tools/").setUnlocalizedName("Clay Spindle").setCreativeTab(TFCTabs.TFCMaterials);
SpindleHead = new ItemTerra(TFC_Settings.getIntFor(config, "item", "SpindleHead", num++)).setFolder("toolheads/").setUnlocalizedName("Spindle Head").setCreativeTab(TFCTabs.TFCMaterials);
StoneBrick = (new ItemStoneBrick(TFC_Settings.getIntFor(config,"item","ItemStoneBrick2",num++)).setFolder("tools/").setUnlocalizedName("ItemStoneBrick"));
Mortar = new ItemTerra(TFC_Settings.getIntFor(config,"item","Mortar",num++)).setFolder("tools/").setUnlocalizedName("Mortar").setCreativeTab(TFCTabs.TFCMaterials);
Limewater = new ItemCustomBucket(TFC_Settings.getIntFor(config,"item","Limewater",num++),0).setFolder("tools/").setUnlocalizedName("Lime Water").setContainerItem(WoodenBucketEmpty).setCreativeTab(TFCTabs.TFCMaterials);
Hide = new ItemTerra(TFC_Settings.getIntFor(config,"item","Hide",num++)).setFolder("tools/").setUnlocalizedName("Hide").setCreativeTab(TFCTabs.TFCMaterials);
SoakedHide = new ItemTerra(TFC_Settings.getIntFor(config,"item","SoakedHide",num++)).setFolder("tools/").setUnlocalizedName("Soaked Hide").setCreativeTab(TFCTabs.TFCMaterials);
ScrapedHide = new ItemTerra(TFC_Settings.getIntFor(config,"item","ScrapedHide",num++)).setFolder("tools/").setUnlocalizedName("Scraped Hide").setCreativeTab(TFCTabs.TFCMaterials);
PrepHide = new ItemTerra(TFC_Settings.getIntFor(config,"item","PrepHide",num++)).setFolder("tools/").setFolder("tools/").setUnlocalizedName("Prep Hide").setCreativeTab(TFCTabs.TFCMaterials);
TerraLeather = new ItemTerra(TFC_Settings.getIntFor(config,"item","TFCLeather",num++)).setFolder("tools/").setUnlocalizedName("TFC Leather").setCreativeTab(TFCTabs.TFCMaterials);
SheepSkin = new ItemTerra(TFC_Settings.getIntFor(config,"item","SheepSkin",num++)).setFolder("tools/").setUnlocalizedName("Sheep Skin").setCreativeTab(TFCTabs.TFCMaterials);
muttonRaw = new ItemTerra(TFC_Settings.getIntFor(config,"item","muttonRaw",num++)).setFolder("food/").setUnlocalizedName("Mutton Raw");
muttonCooked = new ItemTerraFood(TFC_Settings.getIntFor(config,"item","muttonCooked",num++), 40, 0.8F, true, 48).setUnlocalizedName("Mutton Cooked");
FlatLeather = (new ItemFlatLeather(TFC_Settings.getIntFor(config,"items","FlatLeather2",num++)).setFolder("tools/").setUnlocalizedName("Flat Leather"));
PotteryJug = new ItemPotteryJug(TFC_Settings.getIntFor(config,"items","PotteryJug",num++)).setUnlocalizedName("Jug");
PotterySmallVessel = new ItemPotteryBase(TFC_Settings.getIntFor(config,"items","PotterySmallVessel",num++)).setUnlocalizedName("Small Vessel");
PotteryLargeVessel = new ItemPotteryLargeVessel(TFC_Settings.getIntFor(config,"items","PotteryLargeVessel",num++)).setUnlocalizedName("Large Vessel");
PotteryPot = new ItemPotteryPot(TFC_Settings.getIntFor(config,"items","PotteryPot",num++)).setUnlocalizedName("Pot");
Straw = new ItemTerra(TFC_Settings.getIntFor(config,"items","Straw",num++)).setFolder("plants/").setUnlocalizedName("Straw");
/**Plans*/
num = 20000;
SetupPlans(num);
/**Food related items*/
num = 18000;
SetupFood(num);
/**Armor Crafting related items*/
num = 19000;
SetupArmor(num);
Recipes.Doors = new Item[]{DoorOak, DoorAspen, DoorBirch, DoorChestnut, DoorDouglasFir,
DoorHickory, DoorMaple, DoorAsh, DoorPine, DoorSequoia, DoorSpruce, DoorSycamore,
DoorWhiteCedar, DoorWhiteElm, DoorWillow, DoorKapok};
Recipes.Axes = new Item[]{SedAxe,IgInAxe,IgExAxe,MMAxe,
BismuthAxe,BismuthBronzeAxe,BlackBronzeAxe,
BlackSteelAxe,BlueSteelAxe,BronzeAxe,CopperAxe,
WroughtIronAxe,RedSteelAxe,RoseGoldAxe,SteelAxe,
TinAxe,ZincAxe};
Recipes.Chisels = new Item[]{BismuthChisel,BismuthBronzeChisel,BlackBronzeChisel,
BlackSteelChisel,BlueSteelChisel,BronzeChisel,CopperChisel,
WroughtIronChisel,RedSteelChisel,RoseGoldChisel,SteelChisel,
TinChisel,ZincChisel};
Recipes.Saws = new Item[]{BismuthSaw,BismuthBronzeSaw,BlackBronzeSaw,
BlackSteelSaw,BlueSteelSaw,BronzeSaw,CopperSaw,
WroughtIronSaw,RedSteelSaw,RoseGoldSaw,SteelSaw,
TinSaw,ZincSaw};
Recipes.Knives = new Item[]{StoneKnife,BismuthKnife,BismuthBronzeKnife,BlackBronzeKnife,
BlackSteelKnife,BlueSteelKnife,BronzeKnife,CopperKnife,
WroughtIronKnife,RedSteelKnife,RoseGoldKnife,SteelKnife,
TinKnife,ZincKnife};
Recipes.MeltedMetal = new Item[]{BismuthUnshaped, BismuthBronzeUnshaped,BlackBronzeUnshaped,
TFCItems.BlackSteelUnshaped,TFCItems.BlueSteelUnshaped,TFCItems.BrassUnshaped,TFCItems.BronzeUnshaped,
TFCItems.CopperUnshaped,TFCItems.GoldUnshaped,
TFCItems.WroughtIronUnshaped,TFCItems.LeadUnshaped,TFCItems.NickelUnshaped,TFCItems.PigIronUnshaped,
TFCItems.PlatinumUnshaped,TFCItems.RedSteelUnshaped,TFCItems.RoseGoldUnshaped,TFCItems.SilverUnshaped,
TFCItems.SteelUnshaped,TFCItems.SterlingSilverUnshaped,
TFCItems.TinUnshaped,TFCItems.ZincUnshaped, TFCItems.HCSteelUnshaped, TFCItems.WeakSteelUnshaped,
TFCItems.HCBlackSteelUnshaped, TFCItems.HCBlueSteelUnshaped, TFCItems.HCRedSteelUnshaped,
TFCItems.WeakBlueSteelUnshaped, TFCItems.WeakRedSteelUnshaped};
Recipes.Hammers = new Item[]{TFCItems.StoneHammer,TFCItems.BismuthHammer,TFCItems.BismuthBronzeHammer,TFCItems.BlackBronzeHammer,
TFCItems.BlackSteelHammer,TFCItems.BlueSteelHammer,TFCItems.BronzeHammer,TFCItems.CopperHammer,
TFCItems.WroughtIronHammer,TFCItems.RedSteelHammer,TFCItems.RoseGoldHammer,TFCItems.SteelHammer,
TFCItems.TinHammer,TFCItems.ZincHammer};
Recipes.Spindle = new Item[]{TFCItems.Spindle};
Recipes.Gems = new Item[]{TFCItems.GemAgate, TFCItems.GemAmethyst, TFCItems.GemBeryl, TFCItems.GemDiamond, TFCItems.GemEmerald, TFCItems.GemGarnet,
TFCItems.GemJade, TFCItems.GemJasper, TFCItems.GemOpal,TFCItems.GemRuby,TFCItems.GemSapphire,TFCItems.GemTopaz,TFCItems.GemTourmaline};
Meals = new Item[]{MealMoveSpeed, MealDigSpeed, MealDamageBoost, MealJump, MealDamageResist,
MealFireResist, MealWaterBreathing, MealNightVision};
((TFCTabs)TFCTabs.TFCTools).setTabIconItemIndex(TFCItems.RoseGoldHammer.itemID);
((TFCTabs)TFCTabs.TFCMaterials).setTabIconItemIndex(TFCItems.Spindle.itemID);
((TFCTabs)TFCTabs.TFCUnfinished).setTabIconItemIndex(TFCItems.RoseGoldHammerHead.itemID);
((TFCTabs)TFCTabs.TFCArmor).setTabIconItemIndex(TFCItems.SteelHelmet.itemID);
System.out.println(new StringBuilder().append("[TFC] Done Loading Items").toString());
if (config != null) {
config.save();
}
}
|
diff --git a/src/test/java/dk/frankbille/scoreboard/player/TestPlayerEditPage.java b/src/test/java/dk/frankbille/scoreboard/player/TestPlayerEditPage.java
index cfd91d6..a4d256e 100644
--- a/src/test/java/dk/frankbille/scoreboard/player/TestPlayerEditPage.java
+++ b/src/test/java/dk/frankbille/scoreboard/player/TestPlayerEditPage.java
@@ -1,66 +1,65 @@
package dk.frankbille.scoreboard.player;
import static org.junit.Assert.assertEquals;
import org.apache.wicket.model.Model;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.util.tester.FormTester;
import org.junit.Test;
import dk.frankbille.scoreboard.domain.Player;
import dk.frankbille.scoreboard.service.ScoreBoardService;
import dk.frankbille.scoreboard.test.WicketSpringTestCase;
public class TestPlayerEditPage extends WicketSpringTestCase {
@Test
public void testBasicRendering() {
PageParameters pageParameters = new PageParameters();
pageParameters.set(0, 2L);
tester.startPage(PlayerEditPage.class, pageParameters);
tester.assertRenderedPage(PlayerEditPage.class);
}
@Test
public void testRenderWithData() {
ScoreBoardService scoreBoardService = getScoreBoardService();
scoreBoardService.createNewPlayer("Player 1");
Player player2 = scoreBoardService.createNewPlayer("Player 2");
player2.setFullName("Player 2 Full Name");
player2.setGroupName("Player 2 Group");
scoreBoardService.savePlayer(player2);
scoreBoardService.createNewPlayer("Player 3");
scoreBoardService.createNewPlayer("Player 4");
PageParameters pageParameters = new PageParameters();
pageParameters.set(0, player2.getId());
tester.startPage(PlayerEditPage.class, pageParameters);
tester.assertRenderedPage(PlayerEditPage.class);
- tester.assertLabel("name", player2.getName());
FormTester formTester = tester.newFormTester("playerForm");
assertEquals(player2.getName(), formTester.getTextComponentValue("nameField"));
assertEquals(player2.getFullName(), formTester.getTextComponentValue("fullNameField"));
assertEquals(player2.getGroupName(), formTester.getTextComponentValue("groupField"));
formTester.setValue("nameField", "New Name");
formTester.setValue("fullNameField", "New Full Name");
formTester.setValue("groupField", "New Group");
formTester.submit();
tester.assertRenderedPage(PlayerListPage.class);
Player updatedPlayer = scoreBoardService.getPlayer(player2.getId());
assertEquals("New Name", updatedPlayer.getName());
assertEquals("New Full Name", updatedPlayer.getFullName());
assertEquals("New Group", updatedPlayer.getGroupName());
}
@Test
public void testRenderWithNewPlayer() {
tester.startPage(new PlayerEditPage(new Model<Player>(new Player())));
tester.assertRenderedPage(PlayerEditPage.class);
}
}
| true | true | public void testRenderWithData() {
ScoreBoardService scoreBoardService = getScoreBoardService();
scoreBoardService.createNewPlayer("Player 1");
Player player2 = scoreBoardService.createNewPlayer("Player 2");
player2.setFullName("Player 2 Full Name");
player2.setGroupName("Player 2 Group");
scoreBoardService.savePlayer(player2);
scoreBoardService.createNewPlayer("Player 3");
scoreBoardService.createNewPlayer("Player 4");
PageParameters pageParameters = new PageParameters();
pageParameters.set(0, player2.getId());
tester.startPage(PlayerEditPage.class, pageParameters);
tester.assertRenderedPage(PlayerEditPage.class);
tester.assertLabel("name", player2.getName());
FormTester formTester = tester.newFormTester("playerForm");
assertEquals(player2.getName(), formTester.getTextComponentValue("nameField"));
assertEquals(player2.getFullName(), formTester.getTextComponentValue("fullNameField"));
assertEquals(player2.getGroupName(), formTester.getTextComponentValue("groupField"));
formTester.setValue("nameField", "New Name");
formTester.setValue("fullNameField", "New Full Name");
formTester.setValue("groupField", "New Group");
formTester.submit();
tester.assertRenderedPage(PlayerListPage.class);
Player updatedPlayer = scoreBoardService.getPlayer(player2.getId());
assertEquals("New Name", updatedPlayer.getName());
assertEquals("New Full Name", updatedPlayer.getFullName());
assertEquals("New Group", updatedPlayer.getGroupName());
}
| public void testRenderWithData() {
ScoreBoardService scoreBoardService = getScoreBoardService();
scoreBoardService.createNewPlayer("Player 1");
Player player2 = scoreBoardService.createNewPlayer("Player 2");
player2.setFullName("Player 2 Full Name");
player2.setGroupName("Player 2 Group");
scoreBoardService.savePlayer(player2);
scoreBoardService.createNewPlayer("Player 3");
scoreBoardService.createNewPlayer("Player 4");
PageParameters pageParameters = new PageParameters();
pageParameters.set(0, player2.getId());
tester.startPage(PlayerEditPage.class, pageParameters);
tester.assertRenderedPage(PlayerEditPage.class);
FormTester formTester = tester.newFormTester("playerForm");
assertEquals(player2.getName(), formTester.getTextComponentValue("nameField"));
assertEquals(player2.getFullName(), formTester.getTextComponentValue("fullNameField"));
assertEquals(player2.getGroupName(), formTester.getTextComponentValue("groupField"));
formTester.setValue("nameField", "New Name");
formTester.setValue("fullNameField", "New Full Name");
formTester.setValue("groupField", "New Group");
formTester.submit();
tester.assertRenderedPage(PlayerListPage.class);
Player updatedPlayer = scoreBoardService.getPlayer(player2.getId());
assertEquals("New Name", updatedPlayer.getName());
assertEquals("New Full Name", updatedPlayer.getFullName());
assertEquals("New Group", updatedPlayer.getGroupName());
}
|
diff --git a/blocks/sublima-app/src/main/java/com/computas/sublima/app/controller/admin/ResourceController.java b/blocks/sublima-app/src/main/java/com/computas/sublima/app/controller/admin/ResourceController.java
index 22155fbf..26c94448 100644
--- a/blocks/sublima-app/src/main/java/com/computas/sublima/app/controller/admin/ResourceController.java
+++ b/blocks/sublima-app/src/main/java/com/computas/sublima/app/controller/admin/ResourceController.java
@@ -1,597 +1,596 @@
package com.computas.sublima.app.controller.admin;
import com.computas.sublima.app.service.AdminService;
import com.computas.sublima.app.service.Form2SparqlService;
import com.computas.sublima.query.SparqlDispatcher;
import com.computas.sublima.query.SparulDispatcher;
import static com.computas.sublima.query.service.SettingsService.getProperty;
import com.hp.hpl.jena.sparql.util.StringUtils;
import org.apache.cocoon.auth.ApplicationUtil;
import org.apache.cocoon.auth.User;
import org.apache.cocoon.auth.ApplicationManager;
import org.apache.cocoon.components.flow.apples.AppleRequest;
import org.apache.cocoon.components.flow.apples.AppleResponse;
import org.apache.cocoon.components.flow.apples.StatelessAppleController;
import org.apache.cocoon.environment.Request;
import org.apache.log4j.Logger;
import java.io.IOException;
import java.util.*;
import java.text.SimpleDateFormat;
import java.text.DateFormat;
/**
* @author: mha
* Date: 31.mar.2008
*/
public class ResourceController implements StatelessAppleController {
private SparqlDispatcher sparqlDispatcher;
private SparulDispatcher sparulDispatcher;
AdminService adminService = new AdminService();
private ApplicationManager appMan;
private ApplicationUtil appUtil = new ApplicationUtil();
private User user;
private String mode;
private String submode;
String[] completePrefixArray = {
"PREFIX dct: <http://purl.org/dc/terms/>",
"PREFIX foaf: <http://xmlns.com/foaf/0.1/>",
"PREFIX sub: <http://xmlns.computas.com/sublima#>",
"PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>",
"PREFIX wdr: <http://www.w3.org/2007/05/powder#>",
"PREFIX skos: <http://www.w3.org/2004/02/skos/core#>",
"PREFIX lingvoj: <http://www.lingvoj.org/ontology#>"};
String completePrefixes = StringUtils.join("\n", completePrefixArray);
String[] prefixArray = {
"dct: <http://purl.org/dc/terms/>",
"foaf: <http://xmlns.com/foaf/0.1/>",
"sub: <http://xmlns.computas.com/sublima#>",
"rdfs: <http://www.w3.org/2000/01/rdf-schema#>",
"wdr: <http://www.w3.org/2007/05/powder#>",
"skos: <http://www.w3.org/2004/02/skos/core#>",
"lingvoj: <http://www.lingvoj.org/ontology#>"};
String prefixes = StringUtils.join("\n", prefixArray);
private String userPrivileges = "<empty/>";
private static Logger logger = Logger.getLogger(AdminController.class);
@SuppressWarnings("unchecked")
public void process(AppleRequest req, AppleResponse res) throws Exception {
this.mode = req.getSitemapParameter("mode");
this.submode = req.getSitemapParameter("submode");
if (appUtil.getUser() != null) {
user = appUtil.getUser();
userPrivileges = adminService.getRolePrivilegesAsXML(user.getAttribute("role").toString());
}
if ("ressurser".equalsIgnoreCase(mode)) {
if ("".equalsIgnoreCase(submode) || submode == null) {
showResourcesIndex(res, req);
return;
} else if ("foreslaatte".equalsIgnoreCase(submode)) {
showSuggestedResources(res, req);
return;
} else if ("ny".equalsIgnoreCase(submode)) {
editResource(res, req, "ny", null);
return;
} else if ("edit".equalsIgnoreCase(submode)) {
editResource(res, req, "edit", null);
return;
}else if ("checkurl".equalsIgnoreCase(submode)) {
registerNewResourceURL(req, res);
return;
} else {
return;
}
} else {
res.sendStatus(404);
return;
}
}
/**
* Method to do the first step in the registration process for new resources.
* This method checks the given URL and forwards the user to the resource form if valid.
* Otherwise an error message is displayed.
*
* @param req
* @param res
*/
private void registerNewResourceURL(AppleRequest req, AppleResponse res) {
Map<String, Object> bizData = new HashMap<String, Object>();
StringBuffer messageBuffer = new StringBuffer();
messageBuffer.append("<c:messages xmlns:c=\"http://xmlns.computas.com/cocoon\" xmlns:i18n=\"http://apache.org/cocoon/i18n/2.1\">\n");
bizData.put("userprivileges", userPrivileges);
String tempPrefixes = "<c:tempvalues \n" +
"xmlns:topic=\"" + getProperty("sublima.base.url") + "topic/\"\n" +
"xmlns:skos=\"http://www.w3.org/2004/02/skos/core#\"\n" +
"xmlns:wdr=\"http://www.w3.org/2007/05/powder#\"\n" +
"xmlns:lingvoj=\"http://www.lingvoj.org/ontology#\"\n" +
"xmlns:sioc=\"http://rdfs.org/sioc/ns#\"\n" +
"xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n" +
"xmlns:foaf=\"http://xmlns.com/foaf/0.1/\"\n" +
"xmlns:owl=\"http://www.w3.org/2002/07/owl#\"\n" +
"xmlns:dct=\"http://purl.org/dc/terms/\"\n" +
"xmlns:xsd=\"http://www.w3.org/2001/XMLSchema#\"\n" +
"xmlns:dcmitype=\"http://purl.org/dc/dcmitype/\"\n" +
"xmlns:rdfs=\"http://www.w3.org/2000/01/rdf-schema#\"\n" +
"xmlns:c=\"http://xmlns.computas.com/cocoon\"\n" +
"xmlns:sub=\"http://xmlns.computas.com/sublima#\">\n";
if (req.getCocoonRequest().getMethod().equalsIgnoreCase("GET")) {
bizData.put("messages", "<empty/>");
bizData.put("tempvalues", "<empty/>");
res.sendPage("xml2/ressurs-prereg", bizData);
} else if (req.getCocoonRequest().getMethod().equalsIgnoreCase("POST")) {
String url = req.getCocoonRequest().getParameter("sub:url");
bizData.put("tempvalues", tempPrefixes + "<sub:url>" + req.getCocoonRequest().getParameter("sub:url") + "</sub:url></c:tempvalues>\n");
if (!"".equalsIgnoreCase(url)) {
if (adminService.validateURL(url)) {
if (adminService.checkForDuplicatesByURI(url)) {
messageBuffer.append("<c:message><i18n:text key=\"validation.urlexists\" xmlns:i18n=\"http://apache.org/cocoon/i18n/2.1\"/></c:message>\n");
messageBuffer.append("</c:messages>\n");
bizData.put("messages", messageBuffer.toString());
res.sendPage("xml2/ressurs-prereg", bizData);
} else { // The URL is okay
messageBuffer.append("<c:message><i18n:text key=\"validation.providedurlok\" xmlns:i18n=\"http://apache.org/cocoon/i18n/2.1\"/></c:message>");
messageBuffer.append("</c:messages>\n");
bizData.put("topics", adminService.getAllTopics());
bizData.put("languages", adminService.getAllLanguages());
bizData.put("mediatypes", adminService.getAllMediaTypes());
bizData.put("audience", adminService.getAllAudiences());
bizData.put("status", adminService.getAllStatuses());
bizData.put("publishers", adminService.getAllPublishers());
bizData.put("userprivileges", userPrivileges);
bizData.put("mode", "edit");
bizData.put("messages", messageBuffer.toString());
bizData.put("resource", "<rdf:RDF\n" +
" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n" +
" xmlns:sub=\"http://xmlns.computas.com/sublima#\">\n" +
" <sub:Resource>\n" +
" <sub:url rdf:resource=\"" + url + "\"/>\n" +
" </sub:Resource>\n" +
"</rdf:RDF>");
res.sendPage("xml2/ressurs", bizData);
}
} else {
messageBuffer.append("<c:message>Oppgitt URL gir en ugyldig statuskode. Vennligst kontroller URL i en nettleser.</c:message>\n");
messageBuffer.append("</c:messages>\n");
bizData.put("messages", messageBuffer.toString());
res.sendPage("xml2/ressurs-prereg", bizData);
}
} else {
messageBuffer.append("<c:message>URL kan ikke være blank.</c:message>\n");
messageBuffer.append("</c:messages>\n");
bizData.put("messages", messageBuffer.toString());
res.sendPage("xml2/ressurs-prereg", bizData);
}
}
}
/**
* Method to add new resources and edit existing ones
* Sparql queries for all topics, statuses, languages, media types and audience
* is done and the results forwarded to the JX Template and XSLT.
* <p/>
* A query for the resource is done when the action is "edit". In case of "new" a blank
* form is presented.
*
* @param res - AppleResponse
* @param req - AppleRequest
* @param type - String "new" or "edit"
* @param messages
*/
private void editResource
(AppleResponse
res, AppleRequest
req, String
type, String
messages) {
boolean validated = true;
boolean insertSuccess = false;
boolean updateDate = false;
String dctPublisher;
String dctIdentifier;
String dateAccepted;
String committer;
// Get all list values
String allTopics = adminService.getAllTopics();
String allLanguages = adminService.getAllLanguages();
String allMediatypes = adminService.getAllMediaTypes();
String allAudiences = adminService.getAllAudiences();
String allStatuses = adminService.getAllStatuses();
StringBuffer messageBuffer = new StringBuffer();
messageBuffer.append("<c:messages xmlns:c=\"http://xmlns.computas.com/cocoon\" xmlns:i18n=\"http://apache.org/cocoon/i18n/2.1\">\n");
messageBuffer.append(messages);
Map<String, Object> bizData = new HashMap<String, Object>();
bizData.put("topics", allTopics);
bizData.put("languages", allLanguages);
bizData.put("mediatypes", allMediatypes);
bizData.put("audience", allAudiences);
bizData.put("status", allStatuses);
bizData.put("userprivileges", userPrivileges);
// When GET present a blank form with listvalues or prefilled with resource
if (req.getCocoonRequest().getMethod().equalsIgnoreCase("GET")) {
bizData.put("tempvalues", "<empty></empty>");
if ("ny".equalsIgnoreCase(type)) {
registerNewResourceURL(req, res);
return;
} else {
bizData.put("resource", adminService.getResourceByURI(req.getCocoonRequest().getParameter("uri")));
bizData.put("publishers", adminService.getAllPublishers());
bizData.put("mode", "edit");
bizData.put("messages", "<empty></empty>");
res.sendPage("xml2/ressurs", bizData);
}
// When POST try to save the resource. Return error messages upon failure, and success message upon great success
} else if (req.getCocoonRequest().getMethod().equalsIgnoreCase("POST")) {
//todo This is not very robust, have to find another way to differentiate the different actions.
if ("Slett ressurs".equalsIgnoreCase(req.getCocoonRequest().getParameter("actionbutton")) || "Delete resource".equalsIgnoreCase(req.getCocoonRequest().getParameter("actionbutton"))) {
String deleteString = "DELETE {\n" +
"<" + req.getCocoonRequest().getParameter("uri") + "> ?a ?o.\n" +
"} WHERE {\n" +
"<" + req.getCocoonRequest().getParameter("uri") + "> ?a ?o. }";
boolean deleteResourceSuccess = sparulDispatcher.query(deleteString);
logger.trace("ResourceController.editResource --> DELETE RESOURCE QUERY:\n" + deleteString);
logger.trace("ResourceController.editResource --> DELETE RESOURCE QUERY RESULT: " + deleteResourceSuccess);
if (deleteResourceSuccess) {
messageBuffer.append("<c:message>Ressursen slettet!</c:message>\n");
bizData.put("resource", "<empty></empty>");
bizData.put("tempvalues", "<empty></empty>");
bizData.put("mode", "edit");
} else {
messageBuffer.append("<c:message>Feil ved sletting av ressurs</c:message>\n");
bizData.put("tempvalues", "<empty></empty>");
bizData.put("resource", adminService.getResourceByURI(req.getCocoonRequest().getParameter("sub:url")));
bizData.put("mode", "edit");
}
} else {
Map<String, String[]> parameterMap = new TreeMap<String, String[]>(createParametersMap(req.getCocoonRequest()));
//StringBuffer tempValues = getTempValues(req);
String tempPrefixes = "<c:tempvalues \n" +
"xmlns:topic=\"" + getProperty("sublima.base.url") + "topic/\"\n" +
"xmlns:skos=\"http://www.w3.org/2004/02/skos/core#\"\n" +
"xmlns:wdr=\"http://www.w3.org/2007/05/powder#\"\n" +
"xmlns:lingvoj=\"http://www.lingvoj.org/ontology#\"\n" +
"xmlns:sioc=\"http://rdfs.org/sioc/ns#\"\n" +
"xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n" +
"xmlns:foaf=\"http://xmlns.com/foaf/0.1/\"\n" +
"xmlns:owl=\"http://www.w3.org/2002/07/owl#\"\n" +
"xmlns:dct=\"http://purl.org/dc/terms/\"\n" +
"xmlns:xsd=\"http://www.w3.org/2001/XMLSchema#\"\n" +
"xmlns:dcmitype=\"http://purl.org/dc/dcmitype/\"\n" +
"xmlns:rdfs=\"http://www.w3.org/2000/01/rdf-schema#\"\n" +
"xmlns:c=\"http://xmlns.computas.com/cocoon\"\n" +
"xmlns:i18n=\"http://apache.org/cocoon/i18n/2.1\"\n" +
"xmlns:sub=\"http://xmlns.computas.com/sublima#\">\n";
// Check if all required fields are filled out, if not return error messages
/*
String validationMessages = validateRequest(req);
if (!"".equalsIgnoreCase(validationMessages)) {
messageBuffer.append(validationMessages + "\n");
bizData.put("resource", "<empty></empty>");
bizData.put("tempvalues", tempPrefixes + tempValues.toString() + "</c:tempvalues>");
bizData.put("mode", "temp");
}
*/
Date date = new Date();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
dateAccepted = dateFormat.format(date); //"2008-18-09T13:39:38";
// If the user checks that the resource should be marked as new, set updateDate to true
if (parameterMap.containsKey("markasnew")) {
updateDate = true;
parameterMap.remove("markasnew");
}
parameterMap.put("sub:committer", new String[]{user.getId()});
// Generate a dct:identifier if it's a new resource, and set the time and date for approval
if ("".equalsIgnoreCase(req.getCocoonRequest().getParameter("dct:identifier")) || req.getCocoonRequest().getParameter("dct:identifier") == null) {
updateDate = true;
dctIdentifier = req.getCocoonRequest().getParameter("dct:title-1").replace(" ", "_");
dctIdentifier = dctIdentifier.replace(",", "_");
dctIdentifier = dctIdentifier.replace(".", "_");
dctIdentifier = getProperty("sublima.base.url") + "resource/" + dctIdentifier + parameterMap.get("the-resource").hashCode();
} else {
dctIdentifier = req.getCocoonRequest().getParameter("dct:identifier");
}
if (updateDate) {
parameterMap.put("dct:dateAccepted", new String[]{dateAccepted});
}
Form2SparqlService form2SparqlService = new Form2SparqlService(parameterMap.get("prefix"));
parameterMap.put("sub:url", parameterMap.get("the-resource"));
parameterMap.remove("dct:identifier");
parameterMap.put("dct:identifier", new String[] {dctIdentifier});
parameterMap.remove("prefix"); // The prefixes are magic variables
parameterMap.remove("actionbutton"); // The name of the submit button
if (parameterMap.get("subjecturi-prefix") != null) {
parameterMap.put("subjecturi-prefix", new String[]{getProperty("sublima.base.url") +
parameterMap.get("subjecturi-prefix")[0]});
}
String sparqlQuery = null;
try {
sparqlQuery = form2SparqlService.convertForm2Sparul(parameterMap);
}
catch (IOException e) {
messageBuffer.append("<c:message>Feil ved lagring av emne</c:message>\n");
}
//String uri = form2SparqlService.getURI();
insertSuccess = sparulDispatcher.query(sparqlQuery);
//validated = sparulDispatcher.query(sparqlQuery);
logger.trace("AdminController.editResource --> INSERT QUERY RESULT: " + insertSuccess);
if (insertSuccess) {
messageBuffer.append("<c:message>Ny ressurs lagt til!</c:message>\n");
} else {
messageBuffer.append("<c:message>Feil ved lagring av ny ressurs</c:message>\n");
- bizData.put("resource", "<empty></empty>");
}
}
if (insertSuccess) {
bizData.put("resource", adminService.getResourceByURI(req.getCocoonRequest().getParameter("the-resource")));
bizData.put("tempvalues", "<empty></empty>");
bizData.put("mode", "edit");
} else {
bizData.put("resource", "<empty></empty>");
bizData.put("tempvalues", "<empty/>");//tempPrefixes + tempValues.toString() + "</c:tempvalues>");
- bizData.put("mode", "temp");
+ bizData.put("mode", "edit");
}
//}
//}
messageBuffer.append("</c:messages>\n");
bizData.put("messages", messageBuffer.toString());
bizData.put("userprivileges", userPrivileges);
bizData.put("publishers", adminService.getAllPublishers());
res.sendPage("xml2/ressurs", bizData);
}
}
/**
* Method to validate the request upon insert of new resource.
* Checks all parameters and gives error message if one or more required values are null
* Also chekcs for duplicates, and gives an error message when the resource URI is already registered.
*
* @param req
* @return
*/
private String validateRequest
(AppleRequest
req) {
StringBuffer validationMessages = new StringBuffer();
if ("".equalsIgnoreCase(req.getCocoonRequest().getParameter("dct:title")) || req.getCocoonRequest().getParameter("dct:title") == null) {
validationMessages.append("<c:message><i18n:text key=\"validation.topic.notitle\">uoversatt</i18n:text></c:message>\n");
}
if ("".equalsIgnoreCase(req.getCocoonRequest().getParameter("sub:url").trim()) || req.getCocoonRequest().getParameter("sub:url").trim() == null) {
validationMessages.append("<c:message>URL kan ikke være blank</c:message>\n");
}
if (req.getCocoonRequest().getParameter("uri") == null || "".equalsIgnoreCase(req.getCocoonRequest().getParameter("uri").trim())) {
// if the uri is empty, then it's a new resource and we do a already-exists check
if (adminService.checkForDuplicatesByURI(req.getCocoonRequest().getParameter("sub:url"))) {
validationMessages.append("<c:message>En ressurs med denne URI finnes fra før</c:message>\n");
}
}
if (!adminService.validateURL(req.getCocoonRequest().getParameter("sub:url").trim())) {
validationMessages.append("<c:message>Denne ressursens URI gir en statuskode som tilsier at den ikke er OK. Vennligst sjekk ressursens nettside og prøv igjen.</c:message>\n");
}
if ("".equalsIgnoreCase(req.getCocoonRequest().getParameter("dct:description")) || req.getCocoonRequest().getParameter("dct:description") == null) {
validationMessages.append("<c:message>Beskrivelsen kan ikke være blank</c:message>\n");
}
if (("".equalsIgnoreCase(req.getCocoonRequest().getParameter("dct:publisher")) || req.getCocoonRequest().getParameter("dct:publisher") == null)
&& ("".equalsIgnoreCase(req.getCocoonRequest().getParameter("dct:publisher/foaf:Agent/foaf:name")) || req.getCocoonRequest().getParameter("dct:publisher/foaf:Agent/foaf:name") == null)) {
validationMessages.append("<c:message>En utgiver må velges, eller et nytt utgivernavn angis</c:message>\n");
}
if (req.getCocoonRequest().getParameterValues("dct:language") == null) {
validationMessages.append("<c:message>Minst ett språk må være valgt</c:message>\n");
}
if (req.getCocoonRequest().getParameterValues("dct:format") == null) {
validationMessages.append("<c:message>Minst en mediatype må være valgt</c:message>\n");
}
/* Commented out due to the lack of dct:audience in SMIL test data
if (req.getCocoonRequest().getParameterValues("dct:audience") == null) {
validationMessages.append("<c:message>Minst en målgruppe må være valgt</c:message>\n");
}*/
if (req.getCocoonRequest().getParameterValues("dct:subject") == null) {
validationMessages.append("<c:message>Minst ett emne må være valgt</c:message>\n");
}
if ("".equalsIgnoreCase(req.getCocoonRequest().getParameter("wdr:describedBy")) || req.getCocoonRequest().getParameter("wdr:describedBy") == null) {
validationMessages.append("<c:message>En status må velges</c:message>\n");
} else if (!userPrivileges.contains(req.getCocoonRequest().getParameter("wdr:describedBy"))) {
validationMessages.append("<c:message>Rollen du har tillater ikke å lagre et emne med den valgte statusen.</c:message>\n");
}
return validationMessages.toString();
}
private StringBuffer getTempValues
(AppleRequest
req) {
//Keep all selected values in case of validation error
String temp_title = req.getCocoonRequest().getParameter("dct:title");
String temp_uri = req.getCocoonRequest().getParameter("sub:url");
String temp_description = req.getCocoonRequest().getParameter("dct:description");
String temp_publisher = req.getCocoonRequest().getParameter("dct:publisher");
String temp_added_publisher = req.getCocoonRequest().getParameter("dct:publisher/foaf:Agent/foaf:name");
String[] temp_languages = req.getCocoonRequest().getParameterValues("dct:language");
String[] temp_mediatypes = req.getCocoonRequest().getParameterValues("dct:format");
String[] temp_audiences = req.getCocoonRequest().getParameterValues("dct:audience");
String[] temp_subjects = req.getCocoonRequest().getParameterValues("dct:subject");
String temp_comment = req.getCocoonRequest().getParameter("rdfs:comment");
String temp_status = req.getCocoonRequest().getParameter("wdr:describedBy");
//Create an XML structure for the selected values, to use in the JX template
StringBuffer xmlStructureBuffer = new StringBuffer();
xmlStructureBuffer.append("<dct:title>" + temp_title + "</dct:title>\n");
xmlStructureBuffer.append("<sub:url>" + temp_uri + "</sub:url>\n");
xmlStructureBuffer.append("<dct:description>" + temp_description + "</dct:description>\n");
xmlStructureBuffer.append("<dct:publisher>" + temp_publisher + "</dct:publisher>\n");
xmlStructureBuffer.append("<foaf:Agent>" + temp_added_publisher + "</foaf:Agent>\n");
if (temp_languages != null) {
for (String s : temp_languages) {
//xmlStructureBuffer.append("<language>" + s + "</language>\n");
xmlStructureBuffer.append("<dct:language rdf:description=\"" + s + "\"/>\n");
}
}
if (temp_mediatypes != null) {
for (String s : temp_mediatypes) {
xmlStructureBuffer.append("<dct:format rdf:description=\"" + s + "\"/>\n");
}
}
if (temp_audiences != null) {
for (String s : temp_audiences) {
xmlStructureBuffer.append("<dct:audience rdf:description=\"" + s + "\"/>\n");
}
}
if (temp_subjects != null) {
for (String s : temp_subjects) {
xmlStructureBuffer.append("<dct:subject rdf:description=\"" + s + "\"/>\n");
}
}
xmlStructureBuffer.append("<rdfs:comment>" + temp_comment + "</rdfs:comment>\n");
xmlStructureBuffer.append("<wdr:describedBy>" + temp_status + "</wdr:describedBy>\n");
return xmlStructureBuffer;
}
/**
* Method to displaty a list of all resources suggested by users
*
* @param res - AppleResponse
* @param req - AppleRequest
*/
private void showSuggestedResources
(AppleResponse
res, AppleRequest
req) {
String queryString = StringUtils.join("\n", new String[]{
completePrefixes,
"CONSTRUCT {",
" ?resource dct:title ?title ;" +
//" dct:identifier ?identifier ;" +
" a sub:Resource . }",
" WHERE {",
" ?resource wdr:describedBy <" + getProperty("sublima.base.url") + "status/nytt_forslag> ;",
" dct:title ?title .",
//" dct:identifier ?identifier .",
"}"});
logger.trace("AdminController.showSuggestedResources() --> SPARQL query sent to dispatcher: \n" + queryString);
Object queryResult = sparqlDispatcher.query(queryString);
Map<String, Object> bizData = new HashMap<String, Object>();
if ("".equalsIgnoreCase((String) queryResult) || queryResult == null) {
bizData.put("suggestedresourceslist", "<empty></empty>");
} else {
bizData.put("suggestedresourceslist", queryResult);
}
res.sendPage("xml2/foreslaatte", bizData);
}
/**
* Method to display the initial page for administrating resources
*
* @param res - AppleResponse
* @param req - AppleRequest
*/
private void showResourcesIndex
(AppleResponse
res, AppleRequest
req) {
res.sendPage("xml2/ressurser", null);
}
public void setSparqlDispatcher
(SparqlDispatcher
sparqlDispatcher) {
this.sparqlDispatcher = sparqlDispatcher;
}
public void setSparulDispatcher
(SparulDispatcher
sparulDispatcher) {
this.sparulDispatcher = sparulDispatcher;
}
//todo Move to a Service-class
private Map<String, String[]> createParametersMap
(Request
request) {
Map<String, String[]> result = new HashMap<String, String[]>();
Enumeration parameterNames = request.getParameterNames();
while (parameterNames.hasMoreElements()) {
String paramName = (String) parameterNames.nextElement();
result.put(paramName, request.getParameterValues(paramName));
}
return result;
}
}
| false | true | private void editResource
(AppleResponse
res, AppleRequest
req, String
type, String
messages) {
boolean validated = true;
boolean insertSuccess = false;
boolean updateDate = false;
String dctPublisher;
String dctIdentifier;
String dateAccepted;
String committer;
// Get all list values
String allTopics = adminService.getAllTopics();
String allLanguages = adminService.getAllLanguages();
String allMediatypes = adminService.getAllMediaTypes();
String allAudiences = adminService.getAllAudiences();
String allStatuses = adminService.getAllStatuses();
StringBuffer messageBuffer = new StringBuffer();
messageBuffer.append("<c:messages xmlns:c=\"http://xmlns.computas.com/cocoon\" xmlns:i18n=\"http://apache.org/cocoon/i18n/2.1\">\n");
messageBuffer.append(messages);
Map<String, Object> bizData = new HashMap<String, Object>();
bizData.put("topics", allTopics);
bizData.put("languages", allLanguages);
bizData.put("mediatypes", allMediatypes);
bizData.put("audience", allAudiences);
bizData.put("status", allStatuses);
bizData.put("userprivileges", userPrivileges);
// When GET present a blank form with listvalues or prefilled with resource
if (req.getCocoonRequest().getMethod().equalsIgnoreCase("GET")) {
bizData.put("tempvalues", "<empty></empty>");
if ("ny".equalsIgnoreCase(type)) {
registerNewResourceURL(req, res);
return;
} else {
bizData.put("resource", adminService.getResourceByURI(req.getCocoonRequest().getParameter("uri")));
bizData.put("publishers", adminService.getAllPublishers());
bizData.put("mode", "edit");
bizData.put("messages", "<empty></empty>");
res.sendPage("xml2/ressurs", bizData);
}
// When POST try to save the resource. Return error messages upon failure, and success message upon great success
} else if (req.getCocoonRequest().getMethod().equalsIgnoreCase("POST")) {
//todo This is not very robust, have to find another way to differentiate the different actions.
if ("Slett ressurs".equalsIgnoreCase(req.getCocoonRequest().getParameter("actionbutton")) || "Delete resource".equalsIgnoreCase(req.getCocoonRequest().getParameter("actionbutton"))) {
String deleteString = "DELETE {\n" +
"<" + req.getCocoonRequest().getParameter("uri") + "> ?a ?o.\n" +
"} WHERE {\n" +
"<" + req.getCocoonRequest().getParameter("uri") + "> ?a ?o. }";
boolean deleteResourceSuccess = sparulDispatcher.query(deleteString);
logger.trace("ResourceController.editResource --> DELETE RESOURCE QUERY:\n" + deleteString);
logger.trace("ResourceController.editResource --> DELETE RESOURCE QUERY RESULT: " + deleteResourceSuccess);
if (deleteResourceSuccess) {
messageBuffer.append("<c:message>Ressursen slettet!</c:message>\n");
bizData.put("resource", "<empty></empty>");
bizData.put("tempvalues", "<empty></empty>");
bizData.put("mode", "edit");
} else {
messageBuffer.append("<c:message>Feil ved sletting av ressurs</c:message>\n");
bizData.put("tempvalues", "<empty></empty>");
bizData.put("resource", adminService.getResourceByURI(req.getCocoonRequest().getParameter("sub:url")));
bizData.put("mode", "edit");
}
} else {
Map<String, String[]> parameterMap = new TreeMap<String, String[]>(createParametersMap(req.getCocoonRequest()));
//StringBuffer tempValues = getTempValues(req);
String tempPrefixes = "<c:tempvalues \n" +
"xmlns:topic=\"" + getProperty("sublima.base.url") + "topic/\"\n" +
"xmlns:skos=\"http://www.w3.org/2004/02/skos/core#\"\n" +
"xmlns:wdr=\"http://www.w3.org/2007/05/powder#\"\n" +
"xmlns:lingvoj=\"http://www.lingvoj.org/ontology#\"\n" +
"xmlns:sioc=\"http://rdfs.org/sioc/ns#\"\n" +
"xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n" +
"xmlns:foaf=\"http://xmlns.com/foaf/0.1/\"\n" +
"xmlns:owl=\"http://www.w3.org/2002/07/owl#\"\n" +
"xmlns:dct=\"http://purl.org/dc/terms/\"\n" +
"xmlns:xsd=\"http://www.w3.org/2001/XMLSchema#\"\n" +
"xmlns:dcmitype=\"http://purl.org/dc/dcmitype/\"\n" +
"xmlns:rdfs=\"http://www.w3.org/2000/01/rdf-schema#\"\n" +
"xmlns:c=\"http://xmlns.computas.com/cocoon\"\n" +
"xmlns:i18n=\"http://apache.org/cocoon/i18n/2.1\"\n" +
"xmlns:sub=\"http://xmlns.computas.com/sublima#\">\n";
// Check if all required fields are filled out, if not return error messages
/*
String validationMessages = validateRequest(req);
if (!"".equalsIgnoreCase(validationMessages)) {
messageBuffer.append(validationMessages + "\n");
bizData.put("resource", "<empty></empty>");
bizData.put("tempvalues", tempPrefixes + tempValues.toString() + "</c:tempvalues>");
bizData.put("mode", "temp");
}
*/
Date date = new Date();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
dateAccepted = dateFormat.format(date); //"2008-18-09T13:39:38";
// If the user checks that the resource should be marked as new, set updateDate to true
if (parameterMap.containsKey("markasnew")) {
updateDate = true;
parameterMap.remove("markasnew");
}
parameterMap.put("sub:committer", new String[]{user.getId()});
// Generate a dct:identifier if it's a new resource, and set the time and date for approval
if ("".equalsIgnoreCase(req.getCocoonRequest().getParameter("dct:identifier")) || req.getCocoonRequest().getParameter("dct:identifier") == null) {
updateDate = true;
dctIdentifier = req.getCocoonRequest().getParameter("dct:title-1").replace(" ", "_");
dctIdentifier = dctIdentifier.replace(",", "_");
dctIdentifier = dctIdentifier.replace(".", "_");
dctIdentifier = getProperty("sublima.base.url") + "resource/" + dctIdentifier + parameterMap.get("the-resource").hashCode();
} else {
dctIdentifier = req.getCocoonRequest().getParameter("dct:identifier");
}
if (updateDate) {
parameterMap.put("dct:dateAccepted", new String[]{dateAccepted});
}
Form2SparqlService form2SparqlService = new Form2SparqlService(parameterMap.get("prefix"));
parameterMap.put("sub:url", parameterMap.get("the-resource"));
parameterMap.remove("dct:identifier");
parameterMap.put("dct:identifier", new String[] {dctIdentifier});
parameterMap.remove("prefix"); // The prefixes are magic variables
parameterMap.remove("actionbutton"); // The name of the submit button
if (parameterMap.get("subjecturi-prefix") != null) {
parameterMap.put("subjecturi-prefix", new String[]{getProperty("sublima.base.url") +
parameterMap.get("subjecturi-prefix")[0]});
}
String sparqlQuery = null;
try {
sparqlQuery = form2SparqlService.convertForm2Sparul(parameterMap);
}
catch (IOException e) {
messageBuffer.append("<c:message>Feil ved lagring av emne</c:message>\n");
}
//String uri = form2SparqlService.getURI();
insertSuccess = sparulDispatcher.query(sparqlQuery);
//validated = sparulDispatcher.query(sparqlQuery);
logger.trace("AdminController.editResource --> INSERT QUERY RESULT: " + insertSuccess);
if (insertSuccess) {
messageBuffer.append("<c:message>Ny ressurs lagt til!</c:message>\n");
} else {
messageBuffer.append("<c:message>Feil ved lagring av ny ressurs</c:message>\n");
bizData.put("resource", "<empty></empty>");
}
}
if (insertSuccess) {
bizData.put("resource", adminService.getResourceByURI(req.getCocoonRequest().getParameter("the-resource")));
bizData.put("tempvalues", "<empty></empty>");
bizData.put("mode", "edit");
} else {
bizData.put("resource", "<empty></empty>");
bizData.put("tempvalues", "<empty/>");//tempPrefixes + tempValues.toString() + "</c:tempvalues>");
bizData.put("mode", "temp");
}
//}
//}
messageBuffer.append("</c:messages>\n");
bizData.put("messages", messageBuffer.toString());
bizData.put("userprivileges", userPrivileges);
bizData.put("publishers", adminService.getAllPublishers());
res.sendPage("xml2/ressurs", bizData);
}
| private void editResource
(AppleResponse
res, AppleRequest
req, String
type, String
messages) {
boolean validated = true;
boolean insertSuccess = false;
boolean updateDate = false;
String dctPublisher;
String dctIdentifier;
String dateAccepted;
String committer;
// Get all list values
String allTopics = adminService.getAllTopics();
String allLanguages = adminService.getAllLanguages();
String allMediatypes = adminService.getAllMediaTypes();
String allAudiences = adminService.getAllAudiences();
String allStatuses = adminService.getAllStatuses();
StringBuffer messageBuffer = new StringBuffer();
messageBuffer.append("<c:messages xmlns:c=\"http://xmlns.computas.com/cocoon\" xmlns:i18n=\"http://apache.org/cocoon/i18n/2.1\">\n");
messageBuffer.append(messages);
Map<String, Object> bizData = new HashMap<String, Object>();
bizData.put("topics", allTopics);
bizData.put("languages", allLanguages);
bizData.put("mediatypes", allMediatypes);
bizData.put("audience", allAudiences);
bizData.put("status", allStatuses);
bizData.put("userprivileges", userPrivileges);
// When GET present a blank form with listvalues or prefilled with resource
if (req.getCocoonRequest().getMethod().equalsIgnoreCase("GET")) {
bizData.put("tempvalues", "<empty></empty>");
if ("ny".equalsIgnoreCase(type)) {
registerNewResourceURL(req, res);
return;
} else {
bizData.put("resource", adminService.getResourceByURI(req.getCocoonRequest().getParameter("uri")));
bizData.put("publishers", adminService.getAllPublishers());
bizData.put("mode", "edit");
bizData.put("messages", "<empty></empty>");
res.sendPage("xml2/ressurs", bizData);
}
// When POST try to save the resource. Return error messages upon failure, and success message upon great success
} else if (req.getCocoonRequest().getMethod().equalsIgnoreCase("POST")) {
//todo This is not very robust, have to find another way to differentiate the different actions.
if ("Slett ressurs".equalsIgnoreCase(req.getCocoonRequest().getParameter("actionbutton")) || "Delete resource".equalsIgnoreCase(req.getCocoonRequest().getParameter("actionbutton"))) {
String deleteString = "DELETE {\n" +
"<" + req.getCocoonRequest().getParameter("uri") + "> ?a ?o.\n" +
"} WHERE {\n" +
"<" + req.getCocoonRequest().getParameter("uri") + "> ?a ?o. }";
boolean deleteResourceSuccess = sparulDispatcher.query(deleteString);
logger.trace("ResourceController.editResource --> DELETE RESOURCE QUERY:\n" + deleteString);
logger.trace("ResourceController.editResource --> DELETE RESOURCE QUERY RESULT: " + deleteResourceSuccess);
if (deleteResourceSuccess) {
messageBuffer.append("<c:message>Ressursen slettet!</c:message>\n");
bizData.put("resource", "<empty></empty>");
bizData.put("tempvalues", "<empty></empty>");
bizData.put("mode", "edit");
} else {
messageBuffer.append("<c:message>Feil ved sletting av ressurs</c:message>\n");
bizData.put("tempvalues", "<empty></empty>");
bizData.put("resource", adminService.getResourceByURI(req.getCocoonRequest().getParameter("sub:url")));
bizData.put("mode", "edit");
}
} else {
Map<String, String[]> parameterMap = new TreeMap<String, String[]>(createParametersMap(req.getCocoonRequest()));
//StringBuffer tempValues = getTempValues(req);
String tempPrefixes = "<c:tempvalues \n" +
"xmlns:topic=\"" + getProperty("sublima.base.url") + "topic/\"\n" +
"xmlns:skos=\"http://www.w3.org/2004/02/skos/core#\"\n" +
"xmlns:wdr=\"http://www.w3.org/2007/05/powder#\"\n" +
"xmlns:lingvoj=\"http://www.lingvoj.org/ontology#\"\n" +
"xmlns:sioc=\"http://rdfs.org/sioc/ns#\"\n" +
"xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n" +
"xmlns:foaf=\"http://xmlns.com/foaf/0.1/\"\n" +
"xmlns:owl=\"http://www.w3.org/2002/07/owl#\"\n" +
"xmlns:dct=\"http://purl.org/dc/terms/\"\n" +
"xmlns:xsd=\"http://www.w3.org/2001/XMLSchema#\"\n" +
"xmlns:dcmitype=\"http://purl.org/dc/dcmitype/\"\n" +
"xmlns:rdfs=\"http://www.w3.org/2000/01/rdf-schema#\"\n" +
"xmlns:c=\"http://xmlns.computas.com/cocoon\"\n" +
"xmlns:i18n=\"http://apache.org/cocoon/i18n/2.1\"\n" +
"xmlns:sub=\"http://xmlns.computas.com/sublima#\">\n";
// Check if all required fields are filled out, if not return error messages
/*
String validationMessages = validateRequest(req);
if (!"".equalsIgnoreCase(validationMessages)) {
messageBuffer.append(validationMessages + "\n");
bizData.put("resource", "<empty></empty>");
bizData.put("tempvalues", tempPrefixes + tempValues.toString() + "</c:tempvalues>");
bizData.put("mode", "temp");
}
*/
Date date = new Date();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
dateAccepted = dateFormat.format(date); //"2008-18-09T13:39:38";
// If the user checks that the resource should be marked as new, set updateDate to true
if (parameterMap.containsKey("markasnew")) {
updateDate = true;
parameterMap.remove("markasnew");
}
parameterMap.put("sub:committer", new String[]{user.getId()});
// Generate a dct:identifier if it's a new resource, and set the time and date for approval
if ("".equalsIgnoreCase(req.getCocoonRequest().getParameter("dct:identifier")) || req.getCocoonRequest().getParameter("dct:identifier") == null) {
updateDate = true;
dctIdentifier = req.getCocoonRequest().getParameter("dct:title-1").replace(" ", "_");
dctIdentifier = dctIdentifier.replace(",", "_");
dctIdentifier = dctIdentifier.replace(".", "_");
dctIdentifier = getProperty("sublima.base.url") + "resource/" + dctIdentifier + parameterMap.get("the-resource").hashCode();
} else {
dctIdentifier = req.getCocoonRequest().getParameter("dct:identifier");
}
if (updateDate) {
parameterMap.put("dct:dateAccepted", new String[]{dateAccepted});
}
Form2SparqlService form2SparqlService = new Form2SparqlService(parameterMap.get("prefix"));
parameterMap.put("sub:url", parameterMap.get("the-resource"));
parameterMap.remove("dct:identifier");
parameterMap.put("dct:identifier", new String[] {dctIdentifier});
parameterMap.remove("prefix"); // The prefixes are magic variables
parameterMap.remove("actionbutton"); // The name of the submit button
if (parameterMap.get("subjecturi-prefix") != null) {
parameterMap.put("subjecturi-prefix", new String[]{getProperty("sublima.base.url") +
parameterMap.get("subjecturi-prefix")[0]});
}
String sparqlQuery = null;
try {
sparqlQuery = form2SparqlService.convertForm2Sparul(parameterMap);
}
catch (IOException e) {
messageBuffer.append("<c:message>Feil ved lagring av emne</c:message>\n");
}
//String uri = form2SparqlService.getURI();
insertSuccess = sparulDispatcher.query(sparqlQuery);
//validated = sparulDispatcher.query(sparqlQuery);
logger.trace("AdminController.editResource --> INSERT QUERY RESULT: " + insertSuccess);
if (insertSuccess) {
messageBuffer.append("<c:message>Ny ressurs lagt til!</c:message>\n");
} else {
messageBuffer.append("<c:message>Feil ved lagring av ny ressurs</c:message>\n");
}
}
if (insertSuccess) {
bizData.put("resource", adminService.getResourceByURI(req.getCocoonRequest().getParameter("the-resource")));
bizData.put("tempvalues", "<empty></empty>");
bizData.put("mode", "edit");
} else {
bizData.put("resource", "<empty></empty>");
bizData.put("tempvalues", "<empty/>");//tempPrefixes + tempValues.toString() + "</c:tempvalues>");
bizData.put("mode", "edit");
}
//}
//}
messageBuffer.append("</c:messages>\n");
bizData.put("messages", messageBuffer.toString());
bizData.put("userprivileges", userPrivileges);
bizData.put("publishers", adminService.getAllPublishers());
res.sendPage("xml2/ressurs", bizData);
}
|
diff --git a/src/commons/org/codehaus/groovy/grails/commons/spring/SpringConfig.java b/src/commons/org/codehaus/groovy/grails/commons/spring/SpringConfig.java
index 2126a71a3..1e65167e9 100644
--- a/src/commons/org/codehaus/groovy/grails/commons/spring/SpringConfig.java
+++ b/src/commons/org/codehaus/groovy/grails/commons/spring/SpringConfig.java
@@ -1,262 +1,262 @@
/*
* Copyright 2004-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.codehaus.groovy.grails.commons.spring;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.lang.WordUtils;
import org.codehaus.groovy.grails.commons.GrailsApplication;
import org.codehaus.groovy.grails.commons.GrailsControllerClass;
import org.codehaus.groovy.grails.commons.GrailsDataSource;
import org.codehaus.groovy.grails.commons.GrailsPageFlowClass;
import org.codehaus.groovy.grails.commons.GrailsServiceClass;
import org.codehaus.groovy.grails.orm.hibernate.ConfigurableLocalsSessionFactoryBean;
import org.codehaus.groovy.grails.orm.hibernate.cfg.GrailsDomainConfiguration;
import org.codehaus.groovy.grails.orm.hibernate.support.HibernateDialectDetectorFactoryBean;
import org.codehaus.groovy.grails.web.pageflow.GrailsFlowBuilder;
import org.codehaus.groovy.grails.web.pageflow.execution.servlet.GrailsServletFlowExecutionManager;
import org.codehaus.groovy.grails.web.servlet.mvc.SimpleGrailsController;
import org.hibernate.dialect.HSQLDialect;
import org.springframework.beans.factory.config.MethodInvokingFactoryBean;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate3.HibernateTransactionManager;
import org.springframework.transaction.interceptor.TransactionProxyFactoryBean;
import org.springframework.util.Assert;
import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.webflow.config.FlowFactoryBean;
import org.springframework.webflow.mvc.FlowController;
import org.springmodules.beans.factory.config.MapToPropertiesFactoryBean;
import org.springmodules.beans.factory.drivers.Bean;
import org.springmodules.db.hsqldb.ServerBean;
/**
* <p>Creates beans and bean references for a Grails application.
*
* @author Steven Devijver
* @since Jul 2, 2005
*/
public class SpringConfig {
private GrailsApplication application = null;
public SpringConfig(GrailsApplication application) {
super();
this.application = application;
}
public Collection getBeanReferences() {
Collection beanReferences = new ArrayList();
Map urlMappings = new HashMap();
Assert.notNull(application);
GrailsPageFlowClass[] pageFlows = application.getPageFlows();
for (int i = 0; i < pageFlows.length; i++) {
GrailsPageFlowClass pageFlow = pageFlows[i];
if (!pageFlow.getAvailable()) {
continue;
}
Bean pageFlowClass = SpringConfigUtils.createSingletonBean(MethodInvokingFactoryBean.class);
pageFlowClass.setProperty("targetObject", SpringConfigUtils.createBeanReference("grailsApplication"));
pageFlowClass.setProperty("targetMethod", SpringConfigUtils.createLiteralValue("getPageFlow"));
pageFlowClass.setProperty("arguments", SpringConfigUtils.createLiteralValue(pageFlow.getFullName()));
beanReferences.add(SpringConfigUtils.createBeanReference(pageFlow.getFullName() + "Class", pageFlowClass));
Bean pageFlowInstance = SpringConfigUtils.createSingletonBean();
pageFlowInstance.setFactoryBean(SpringConfigUtils.createBeanReference(pageFlow.getFullName() + "Class"));
pageFlowInstance.setFactoryMethod("newInstance");
if (pageFlow.byType()) {
pageFlowInstance.setAutowire("byType");
} else if (pageFlow.byName()) {
pageFlowInstance.setAutowire("byName");
}
beanReferences.add(SpringConfigUtils.createBeanReference(pageFlow.getFullName(), pageFlowInstance));
Bean flowBuilder = SpringConfigUtils.createSingletonBean(GrailsFlowBuilder.class);
flowBuilder.setProperty("pageFlowClass", SpringConfigUtils.createBeanReference(pageFlow.getFullName() + "Class"));
Bean flowFactoryBean = SpringConfigUtils.createSingletonBean(FlowFactoryBean.class);
flowFactoryBean.setProperty("flowBuilder", flowBuilder);
beanReferences.add(SpringConfigUtils.createBeanReference(pageFlow.getFlowId(), flowFactoryBean));
if (pageFlow.getAccessible()) {
Bean flowExecutionManager = SpringConfigUtils.createSingletonBean(GrailsServletFlowExecutionManager.class);
flowExecutionManager.setProperty("flow", SpringConfigUtils.createBeanReference(pageFlow.getFlowId()));
Bean flowController = SpringConfigUtils.createSingletonBean(FlowController.class);
flowController.setProperty("flowExecutionManager", flowExecutionManager);
beanReferences.add(SpringConfigUtils.createBeanReference(pageFlow.getFullName() + "Controller", flowController));
urlMappings.put(pageFlow.getUri(), pageFlow.getFullName() + "Controller");
}
}
Bean simpleGrailsController = SpringConfigUtils.createSingletonBean(SimpleGrailsController.class);
simpleGrailsController.setAutowire("byType");
beanReferences.add(SpringConfigUtils.createBeanReference("simpleGrailsController", simpleGrailsController));
Bean internalResourceViewResolver = SpringConfigUtils.createSingletonBean(InternalResourceViewResolver.class);
internalResourceViewResolver.setProperty("prefix", SpringConfigUtils.createLiteralValue("/WEB-INF/jsp/"));
internalResourceViewResolver.setProperty("suffix", SpringConfigUtils.createLiteralValue(".jsp"));
beanReferences.add(SpringConfigUtils.createBeanReference("jspViewResolver", internalResourceViewResolver));
Bean simpleUrlHandlerMapping = null;
if (application.getControllers().length > 0 || application.getPageFlows().length > 0) {
simpleUrlHandlerMapping = SpringConfigUtils.createSingletonBean(SimpleUrlHandlerMapping.class);
beanReferences.add(SpringConfigUtils.createBeanReference("handlerMapping", simpleUrlHandlerMapping));
}
GrailsControllerClass[] simpleControllers = application.getControllers();
for (int i = 0; i < simpleControllers.length; i++) {
GrailsControllerClass simpleController = simpleControllers[i];
if (!simpleController.getAvailable()) {
continue;
}
Bean controllerClass = SpringConfigUtils.createSingletonBean(MethodInvokingFactoryBean.class);
controllerClass.setProperty("targetObject", SpringConfigUtils.createBeanReference("grailsApplication"));
controllerClass.setProperty("targetMethod", SpringConfigUtils.createLiteralValue("getController"));
controllerClass.setProperty("arguments", SpringConfigUtils.createLiteralValue(simpleController.getFullName()));
beanReferences.add(SpringConfigUtils.createBeanReference(simpleController.getFullName() + "Class", controllerClass));
Bean controller = SpringConfigUtils.createSingletonBean();
controller.setFactoryBean(SpringConfigUtils.createBeanReference(simpleController.getFullName() + "Class"));
controller.setFactoryMethod("newInstance");
if (simpleController.byType()) {
controller.setAutowire("byType");
} else if (simpleController.byName()) {
controller.setAutowire("byName");
}
beanReferences.add(SpringConfigUtils.createBeanReference(simpleController.getFullName(), controller));
for (int x = 0; x < simpleController.getURIs().length; x++) {
urlMappings.put(simpleController.getURIs()[x], "simpleGrailsController");
}
}
if (simpleUrlHandlerMapping != null) {
simpleUrlHandlerMapping.setProperty("mappings", SpringConfigUtils.createProperties(urlMappings));
}
boolean dependsOnHsqldbServer = false;
if (application.getGrailsDataSource() != null) {
GrailsDataSource grailsDataSource = application.getGrailsDataSource();
Bean dataSource = null;
if (grailsDataSource.isPooled()) {
dataSource = SpringConfigUtils.createSingletonBean(BasicDataSource.class);
dataSource.setDestroyMethod("close");
} else {
dataSource = SpringConfigUtils.createSingletonBean(DriverManagerDataSource.class);
}
dataSource.setProperty("driverClassName", SpringConfigUtils.createLiteralValue(grailsDataSource.getDriverClassName()));
dataSource.setProperty("url", SpringConfigUtils.createLiteralValue(grailsDataSource.getUrl()));
dataSource.setProperty("username", SpringConfigUtils.createLiteralValue(grailsDataSource.getUsername()));
dataSource.setProperty("password", SpringConfigUtils.createLiteralValue(grailsDataSource.getPassword()));
beanReferences.add(SpringConfigUtils.createBeanReference("dataSource", dataSource));
} else {
Bean dataSource = SpringConfigUtils.createSingletonBean(BasicDataSource.class);
dataSource.setDestroyMethod("close");
dataSource.setProperty("driverClassName", SpringConfigUtils.createLiteralValue("org.hsqldb.jdbcDriver"));
dataSource.setProperty("url", SpringConfigUtils.createLiteralValue("jdbc:hsqldb:hsql://localhost:9101/"));
dataSource.setProperty("username", SpringConfigUtils.createLiteralValue("sa"));
dataSource.setProperty("password", SpringConfigUtils.createLiteralValue(""));
beanReferences.add(SpringConfigUtils.createBeanReference("dataSource", dataSource));
Bean hsqldbServer = SpringConfigUtils.createSingletonBean(ServerBean.class);
hsqldbServer.setProperty("dataSource", SpringConfigUtils.createBeanReference("dataSource"));
Map hsqldbProperties = new HashMap();
hsqldbProperties.put("server.port", "9101");
hsqldbProperties.put("server.database.0", "mem:temp");
hsqldbServer.setProperty("serverProperties", SpringConfigUtils.createProperties(hsqldbProperties));
beanReferences.add(SpringConfigUtils.createBeanReference("hsqldbServer", hsqldbServer));
dependsOnHsqldbServer = true;
}
Map vendorNameDialectMappings = new HashMap();
vendorNameDialectMappings.put("HSQL Database Engine", HSQLDialect.class.getName());
Bean dialectDetector = SpringConfigUtils.createSingletonBean(HibernateDialectDetectorFactoryBean.class);
dialectDetector.setProperty("dataSource", SpringConfigUtils.createBeanReference("dataSource"));
dialectDetector.setProperty("vendorNameDialectMappings", SpringConfigUtils.createProperties(vendorNameDialectMappings));
if (dependsOnHsqldbServer) {
Collection dependsOn = new ArrayList();
dependsOn.add(SpringConfigUtils.createBeanReference("hsqldbServer"));
dialectDetector.setDependsOn(dependsOn);
}
Map hibernatePropertiesMap = new HashMap();
hibernatePropertiesMap.put(SpringConfigUtils.createLiteralValue("hibernate.dialect"), dialectDetector);
hibernatePropertiesMap.put(SpringConfigUtils.createLiteralValue("hibernate.hbm2ddl.auto"), SpringConfigUtils.createLiteralValue("create-drop"));
Bean hibernateProperties = SpringConfigUtils.createSingletonBean(MapToPropertiesFactoryBean.class);
hibernateProperties.setProperty("map", SpringConfigUtils.createMap(hibernatePropertiesMap));
Bean grailsHibernateConfiguration = SpringConfigUtils.createSingletonBean(GrailsDomainConfiguration.class);
grailsHibernateConfiguration.setProperty("grailsApplication", SpringConfigUtils.createBeanReference("grailsApplication"));
Bean grailsClassLoader = SpringConfigUtils.createSingletonBean(MethodInvokingFactoryBean.class);
grailsClassLoader.setProperty("targetObject", SpringConfigUtils.createBeanReference("grailsApplication"));
grailsClassLoader.setProperty("targetMethod", SpringConfigUtils.createLiteralValue("getClassLoader"));
Bean localSessionFactoryBean = SpringConfigUtils.createSingletonBean(ConfigurableLocalsSessionFactoryBean.class);
localSessionFactoryBean.setProperty("dataSource", SpringConfigUtils.createBeanReference("dataSource"));
localSessionFactoryBean.setProperty("hibernateProperties", hibernateProperties);
localSessionFactoryBean.setProperty("configuration", grailsHibernateConfiguration);
localSessionFactoryBean.setProperty("classLoader", grailsClassLoader);
beanReferences.add(SpringConfigUtils.createBeanReference("sessionFactory", localSessionFactoryBean));
Bean transactionManager = SpringConfigUtils.createSingletonBean(HibernateTransactionManager.class);
transactionManager.setProperty("sessionFactory", SpringConfigUtils.createBeanReference("sessionFactory"));
beanReferences.add(SpringConfigUtils.createBeanReference("transactionManager", transactionManager));
GrailsServiceClass[] serviceClasses = application.getGrailsServiceClasses();
for (int i = 0; i <serviceClasses.length; i++) {
GrailsServiceClass grailsServiceClass = serviceClasses[i];
Bean serviceClass = SpringConfigUtils.createSingletonBean(MethodInvokingFactoryBean.class);
serviceClass.setProperty("targetObject", SpringConfigUtils.createBeanReference("grailsApplication"));
serviceClass.setProperty("targetMethod", SpringConfigUtils.createLiteralValue("getGrailsServiceClass"));
serviceClass.setProperty("arguments", SpringConfigUtils.createLiteralValue(grailsServiceClass.getFullName()));
beanReferences.add(SpringConfigUtils.createBeanReference(grailsServiceClass.getFullName() + "Class", serviceClass));
Bean serviceInstance = SpringConfigUtils.createSingletonBean();
serviceInstance.setFactoryBean(SpringConfigUtils.createBeanReference(grailsServiceClass.getFullName() + "Class"));
- serviceInstance.setFactoryMethod("getInstance");
+ serviceInstance.setFactoryMethod("newInstance");
if (grailsServiceClass.byName()) {
serviceInstance.setAutowire("byName");
} else if (grailsServiceClass.byType()) {
serviceInstance.setAutowire("byType");
}
if (grailsServiceClass.isTransactional()) {
Map transactionAttributes = new HashMap();
transactionAttributes.put("*", "PROPAGATION_REQUIRED");
Bean transactionalProxy = SpringConfigUtils.createSingletonBean(TransactionProxyFactoryBean.class);
transactionalProxy.setProperty("target", serviceInstance);
transactionalProxy.setProperty("transactionAttributes", SpringConfigUtils.createProperties(transactionAttributes));
transactionalProxy.setProperty("transactionManager", SpringConfigUtils.createBeanReference("transactionManager"));
beanReferences.add(SpringConfigUtils.createBeanReference(WordUtils.uncapitalize(grailsServiceClass.getName()) + "Service", transactionalProxy));
} else {
beanReferences.add(SpringConfigUtils.createBeanReference(WordUtils.uncapitalize(grailsServiceClass.getName()) + "Service", serviceInstance));
}
}
return beanReferences;
}
}
| true | true | public Collection getBeanReferences() {
Collection beanReferences = new ArrayList();
Map urlMappings = new HashMap();
Assert.notNull(application);
GrailsPageFlowClass[] pageFlows = application.getPageFlows();
for (int i = 0; i < pageFlows.length; i++) {
GrailsPageFlowClass pageFlow = pageFlows[i];
if (!pageFlow.getAvailable()) {
continue;
}
Bean pageFlowClass = SpringConfigUtils.createSingletonBean(MethodInvokingFactoryBean.class);
pageFlowClass.setProperty("targetObject", SpringConfigUtils.createBeanReference("grailsApplication"));
pageFlowClass.setProperty("targetMethod", SpringConfigUtils.createLiteralValue("getPageFlow"));
pageFlowClass.setProperty("arguments", SpringConfigUtils.createLiteralValue(pageFlow.getFullName()));
beanReferences.add(SpringConfigUtils.createBeanReference(pageFlow.getFullName() + "Class", pageFlowClass));
Bean pageFlowInstance = SpringConfigUtils.createSingletonBean();
pageFlowInstance.setFactoryBean(SpringConfigUtils.createBeanReference(pageFlow.getFullName() + "Class"));
pageFlowInstance.setFactoryMethod("newInstance");
if (pageFlow.byType()) {
pageFlowInstance.setAutowire("byType");
} else if (pageFlow.byName()) {
pageFlowInstance.setAutowire("byName");
}
beanReferences.add(SpringConfigUtils.createBeanReference(pageFlow.getFullName(), pageFlowInstance));
Bean flowBuilder = SpringConfigUtils.createSingletonBean(GrailsFlowBuilder.class);
flowBuilder.setProperty("pageFlowClass", SpringConfigUtils.createBeanReference(pageFlow.getFullName() + "Class"));
Bean flowFactoryBean = SpringConfigUtils.createSingletonBean(FlowFactoryBean.class);
flowFactoryBean.setProperty("flowBuilder", flowBuilder);
beanReferences.add(SpringConfigUtils.createBeanReference(pageFlow.getFlowId(), flowFactoryBean));
if (pageFlow.getAccessible()) {
Bean flowExecutionManager = SpringConfigUtils.createSingletonBean(GrailsServletFlowExecutionManager.class);
flowExecutionManager.setProperty("flow", SpringConfigUtils.createBeanReference(pageFlow.getFlowId()));
Bean flowController = SpringConfigUtils.createSingletonBean(FlowController.class);
flowController.setProperty("flowExecutionManager", flowExecutionManager);
beanReferences.add(SpringConfigUtils.createBeanReference(pageFlow.getFullName() + "Controller", flowController));
urlMappings.put(pageFlow.getUri(), pageFlow.getFullName() + "Controller");
}
}
Bean simpleGrailsController = SpringConfigUtils.createSingletonBean(SimpleGrailsController.class);
simpleGrailsController.setAutowire("byType");
beanReferences.add(SpringConfigUtils.createBeanReference("simpleGrailsController", simpleGrailsController));
Bean internalResourceViewResolver = SpringConfigUtils.createSingletonBean(InternalResourceViewResolver.class);
internalResourceViewResolver.setProperty("prefix", SpringConfigUtils.createLiteralValue("/WEB-INF/jsp/"));
internalResourceViewResolver.setProperty("suffix", SpringConfigUtils.createLiteralValue(".jsp"));
beanReferences.add(SpringConfigUtils.createBeanReference("jspViewResolver", internalResourceViewResolver));
Bean simpleUrlHandlerMapping = null;
if (application.getControllers().length > 0 || application.getPageFlows().length > 0) {
simpleUrlHandlerMapping = SpringConfigUtils.createSingletonBean(SimpleUrlHandlerMapping.class);
beanReferences.add(SpringConfigUtils.createBeanReference("handlerMapping", simpleUrlHandlerMapping));
}
GrailsControllerClass[] simpleControllers = application.getControllers();
for (int i = 0; i < simpleControllers.length; i++) {
GrailsControllerClass simpleController = simpleControllers[i];
if (!simpleController.getAvailable()) {
continue;
}
Bean controllerClass = SpringConfigUtils.createSingletonBean(MethodInvokingFactoryBean.class);
controllerClass.setProperty("targetObject", SpringConfigUtils.createBeanReference("grailsApplication"));
controllerClass.setProperty("targetMethod", SpringConfigUtils.createLiteralValue("getController"));
controllerClass.setProperty("arguments", SpringConfigUtils.createLiteralValue(simpleController.getFullName()));
beanReferences.add(SpringConfigUtils.createBeanReference(simpleController.getFullName() + "Class", controllerClass));
Bean controller = SpringConfigUtils.createSingletonBean();
controller.setFactoryBean(SpringConfigUtils.createBeanReference(simpleController.getFullName() + "Class"));
controller.setFactoryMethod("newInstance");
if (simpleController.byType()) {
controller.setAutowire("byType");
} else if (simpleController.byName()) {
controller.setAutowire("byName");
}
beanReferences.add(SpringConfigUtils.createBeanReference(simpleController.getFullName(), controller));
for (int x = 0; x < simpleController.getURIs().length; x++) {
urlMappings.put(simpleController.getURIs()[x], "simpleGrailsController");
}
}
if (simpleUrlHandlerMapping != null) {
simpleUrlHandlerMapping.setProperty("mappings", SpringConfigUtils.createProperties(urlMappings));
}
boolean dependsOnHsqldbServer = false;
if (application.getGrailsDataSource() != null) {
GrailsDataSource grailsDataSource = application.getGrailsDataSource();
Bean dataSource = null;
if (grailsDataSource.isPooled()) {
dataSource = SpringConfigUtils.createSingletonBean(BasicDataSource.class);
dataSource.setDestroyMethod("close");
} else {
dataSource = SpringConfigUtils.createSingletonBean(DriverManagerDataSource.class);
}
dataSource.setProperty("driverClassName", SpringConfigUtils.createLiteralValue(grailsDataSource.getDriverClassName()));
dataSource.setProperty("url", SpringConfigUtils.createLiteralValue(grailsDataSource.getUrl()));
dataSource.setProperty("username", SpringConfigUtils.createLiteralValue(grailsDataSource.getUsername()));
dataSource.setProperty("password", SpringConfigUtils.createLiteralValue(grailsDataSource.getPassword()));
beanReferences.add(SpringConfigUtils.createBeanReference("dataSource", dataSource));
} else {
Bean dataSource = SpringConfigUtils.createSingletonBean(BasicDataSource.class);
dataSource.setDestroyMethod("close");
dataSource.setProperty("driverClassName", SpringConfigUtils.createLiteralValue("org.hsqldb.jdbcDriver"));
dataSource.setProperty("url", SpringConfigUtils.createLiteralValue("jdbc:hsqldb:hsql://localhost:9101/"));
dataSource.setProperty("username", SpringConfigUtils.createLiteralValue("sa"));
dataSource.setProperty("password", SpringConfigUtils.createLiteralValue(""));
beanReferences.add(SpringConfigUtils.createBeanReference("dataSource", dataSource));
Bean hsqldbServer = SpringConfigUtils.createSingletonBean(ServerBean.class);
hsqldbServer.setProperty("dataSource", SpringConfigUtils.createBeanReference("dataSource"));
Map hsqldbProperties = new HashMap();
hsqldbProperties.put("server.port", "9101");
hsqldbProperties.put("server.database.0", "mem:temp");
hsqldbServer.setProperty("serverProperties", SpringConfigUtils.createProperties(hsqldbProperties));
beanReferences.add(SpringConfigUtils.createBeanReference("hsqldbServer", hsqldbServer));
dependsOnHsqldbServer = true;
}
Map vendorNameDialectMappings = new HashMap();
vendorNameDialectMappings.put("HSQL Database Engine", HSQLDialect.class.getName());
Bean dialectDetector = SpringConfigUtils.createSingletonBean(HibernateDialectDetectorFactoryBean.class);
dialectDetector.setProperty("dataSource", SpringConfigUtils.createBeanReference("dataSource"));
dialectDetector.setProperty("vendorNameDialectMappings", SpringConfigUtils.createProperties(vendorNameDialectMappings));
if (dependsOnHsqldbServer) {
Collection dependsOn = new ArrayList();
dependsOn.add(SpringConfigUtils.createBeanReference("hsqldbServer"));
dialectDetector.setDependsOn(dependsOn);
}
Map hibernatePropertiesMap = new HashMap();
hibernatePropertiesMap.put(SpringConfigUtils.createLiteralValue("hibernate.dialect"), dialectDetector);
hibernatePropertiesMap.put(SpringConfigUtils.createLiteralValue("hibernate.hbm2ddl.auto"), SpringConfigUtils.createLiteralValue("create-drop"));
Bean hibernateProperties = SpringConfigUtils.createSingletonBean(MapToPropertiesFactoryBean.class);
hibernateProperties.setProperty("map", SpringConfigUtils.createMap(hibernatePropertiesMap));
Bean grailsHibernateConfiguration = SpringConfigUtils.createSingletonBean(GrailsDomainConfiguration.class);
grailsHibernateConfiguration.setProperty("grailsApplication", SpringConfigUtils.createBeanReference("grailsApplication"));
Bean grailsClassLoader = SpringConfigUtils.createSingletonBean(MethodInvokingFactoryBean.class);
grailsClassLoader.setProperty("targetObject", SpringConfigUtils.createBeanReference("grailsApplication"));
grailsClassLoader.setProperty("targetMethod", SpringConfigUtils.createLiteralValue("getClassLoader"));
Bean localSessionFactoryBean = SpringConfigUtils.createSingletonBean(ConfigurableLocalsSessionFactoryBean.class);
localSessionFactoryBean.setProperty("dataSource", SpringConfigUtils.createBeanReference("dataSource"));
localSessionFactoryBean.setProperty("hibernateProperties", hibernateProperties);
localSessionFactoryBean.setProperty("configuration", grailsHibernateConfiguration);
localSessionFactoryBean.setProperty("classLoader", grailsClassLoader);
beanReferences.add(SpringConfigUtils.createBeanReference("sessionFactory", localSessionFactoryBean));
Bean transactionManager = SpringConfigUtils.createSingletonBean(HibernateTransactionManager.class);
transactionManager.setProperty("sessionFactory", SpringConfigUtils.createBeanReference("sessionFactory"));
beanReferences.add(SpringConfigUtils.createBeanReference("transactionManager", transactionManager));
GrailsServiceClass[] serviceClasses = application.getGrailsServiceClasses();
for (int i = 0; i <serviceClasses.length; i++) {
GrailsServiceClass grailsServiceClass = serviceClasses[i];
Bean serviceClass = SpringConfigUtils.createSingletonBean(MethodInvokingFactoryBean.class);
serviceClass.setProperty("targetObject", SpringConfigUtils.createBeanReference("grailsApplication"));
serviceClass.setProperty("targetMethod", SpringConfigUtils.createLiteralValue("getGrailsServiceClass"));
serviceClass.setProperty("arguments", SpringConfigUtils.createLiteralValue(grailsServiceClass.getFullName()));
beanReferences.add(SpringConfigUtils.createBeanReference(grailsServiceClass.getFullName() + "Class", serviceClass));
Bean serviceInstance = SpringConfigUtils.createSingletonBean();
serviceInstance.setFactoryBean(SpringConfigUtils.createBeanReference(grailsServiceClass.getFullName() + "Class"));
serviceInstance.setFactoryMethod("getInstance");
if (grailsServiceClass.byName()) {
serviceInstance.setAutowire("byName");
} else if (grailsServiceClass.byType()) {
serviceInstance.setAutowire("byType");
}
if (grailsServiceClass.isTransactional()) {
Map transactionAttributes = new HashMap();
transactionAttributes.put("*", "PROPAGATION_REQUIRED");
Bean transactionalProxy = SpringConfigUtils.createSingletonBean(TransactionProxyFactoryBean.class);
transactionalProxy.setProperty("target", serviceInstance);
transactionalProxy.setProperty("transactionAttributes", SpringConfigUtils.createProperties(transactionAttributes));
transactionalProxy.setProperty("transactionManager", SpringConfigUtils.createBeanReference("transactionManager"));
beanReferences.add(SpringConfigUtils.createBeanReference(WordUtils.uncapitalize(grailsServiceClass.getName()) + "Service", transactionalProxy));
} else {
beanReferences.add(SpringConfigUtils.createBeanReference(WordUtils.uncapitalize(grailsServiceClass.getName()) + "Service", serviceInstance));
}
}
return beanReferences;
}
| public Collection getBeanReferences() {
Collection beanReferences = new ArrayList();
Map urlMappings = new HashMap();
Assert.notNull(application);
GrailsPageFlowClass[] pageFlows = application.getPageFlows();
for (int i = 0; i < pageFlows.length; i++) {
GrailsPageFlowClass pageFlow = pageFlows[i];
if (!pageFlow.getAvailable()) {
continue;
}
Bean pageFlowClass = SpringConfigUtils.createSingletonBean(MethodInvokingFactoryBean.class);
pageFlowClass.setProperty("targetObject", SpringConfigUtils.createBeanReference("grailsApplication"));
pageFlowClass.setProperty("targetMethod", SpringConfigUtils.createLiteralValue("getPageFlow"));
pageFlowClass.setProperty("arguments", SpringConfigUtils.createLiteralValue(pageFlow.getFullName()));
beanReferences.add(SpringConfigUtils.createBeanReference(pageFlow.getFullName() + "Class", pageFlowClass));
Bean pageFlowInstance = SpringConfigUtils.createSingletonBean();
pageFlowInstance.setFactoryBean(SpringConfigUtils.createBeanReference(pageFlow.getFullName() + "Class"));
pageFlowInstance.setFactoryMethod("newInstance");
if (pageFlow.byType()) {
pageFlowInstance.setAutowire("byType");
} else if (pageFlow.byName()) {
pageFlowInstance.setAutowire("byName");
}
beanReferences.add(SpringConfigUtils.createBeanReference(pageFlow.getFullName(), pageFlowInstance));
Bean flowBuilder = SpringConfigUtils.createSingletonBean(GrailsFlowBuilder.class);
flowBuilder.setProperty("pageFlowClass", SpringConfigUtils.createBeanReference(pageFlow.getFullName() + "Class"));
Bean flowFactoryBean = SpringConfigUtils.createSingletonBean(FlowFactoryBean.class);
flowFactoryBean.setProperty("flowBuilder", flowBuilder);
beanReferences.add(SpringConfigUtils.createBeanReference(pageFlow.getFlowId(), flowFactoryBean));
if (pageFlow.getAccessible()) {
Bean flowExecutionManager = SpringConfigUtils.createSingletonBean(GrailsServletFlowExecutionManager.class);
flowExecutionManager.setProperty("flow", SpringConfigUtils.createBeanReference(pageFlow.getFlowId()));
Bean flowController = SpringConfigUtils.createSingletonBean(FlowController.class);
flowController.setProperty("flowExecutionManager", flowExecutionManager);
beanReferences.add(SpringConfigUtils.createBeanReference(pageFlow.getFullName() + "Controller", flowController));
urlMappings.put(pageFlow.getUri(), pageFlow.getFullName() + "Controller");
}
}
Bean simpleGrailsController = SpringConfigUtils.createSingletonBean(SimpleGrailsController.class);
simpleGrailsController.setAutowire("byType");
beanReferences.add(SpringConfigUtils.createBeanReference("simpleGrailsController", simpleGrailsController));
Bean internalResourceViewResolver = SpringConfigUtils.createSingletonBean(InternalResourceViewResolver.class);
internalResourceViewResolver.setProperty("prefix", SpringConfigUtils.createLiteralValue("/WEB-INF/jsp/"));
internalResourceViewResolver.setProperty("suffix", SpringConfigUtils.createLiteralValue(".jsp"));
beanReferences.add(SpringConfigUtils.createBeanReference("jspViewResolver", internalResourceViewResolver));
Bean simpleUrlHandlerMapping = null;
if (application.getControllers().length > 0 || application.getPageFlows().length > 0) {
simpleUrlHandlerMapping = SpringConfigUtils.createSingletonBean(SimpleUrlHandlerMapping.class);
beanReferences.add(SpringConfigUtils.createBeanReference("handlerMapping", simpleUrlHandlerMapping));
}
GrailsControllerClass[] simpleControllers = application.getControllers();
for (int i = 0; i < simpleControllers.length; i++) {
GrailsControllerClass simpleController = simpleControllers[i];
if (!simpleController.getAvailable()) {
continue;
}
Bean controllerClass = SpringConfigUtils.createSingletonBean(MethodInvokingFactoryBean.class);
controllerClass.setProperty("targetObject", SpringConfigUtils.createBeanReference("grailsApplication"));
controllerClass.setProperty("targetMethod", SpringConfigUtils.createLiteralValue("getController"));
controllerClass.setProperty("arguments", SpringConfigUtils.createLiteralValue(simpleController.getFullName()));
beanReferences.add(SpringConfigUtils.createBeanReference(simpleController.getFullName() + "Class", controllerClass));
Bean controller = SpringConfigUtils.createSingletonBean();
controller.setFactoryBean(SpringConfigUtils.createBeanReference(simpleController.getFullName() + "Class"));
controller.setFactoryMethod("newInstance");
if (simpleController.byType()) {
controller.setAutowire("byType");
} else if (simpleController.byName()) {
controller.setAutowire("byName");
}
beanReferences.add(SpringConfigUtils.createBeanReference(simpleController.getFullName(), controller));
for (int x = 0; x < simpleController.getURIs().length; x++) {
urlMappings.put(simpleController.getURIs()[x], "simpleGrailsController");
}
}
if (simpleUrlHandlerMapping != null) {
simpleUrlHandlerMapping.setProperty("mappings", SpringConfigUtils.createProperties(urlMappings));
}
boolean dependsOnHsqldbServer = false;
if (application.getGrailsDataSource() != null) {
GrailsDataSource grailsDataSource = application.getGrailsDataSource();
Bean dataSource = null;
if (grailsDataSource.isPooled()) {
dataSource = SpringConfigUtils.createSingletonBean(BasicDataSource.class);
dataSource.setDestroyMethod("close");
} else {
dataSource = SpringConfigUtils.createSingletonBean(DriverManagerDataSource.class);
}
dataSource.setProperty("driverClassName", SpringConfigUtils.createLiteralValue(grailsDataSource.getDriverClassName()));
dataSource.setProperty("url", SpringConfigUtils.createLiteralValue(grailsDataSource.getUrl()));
dataSource.setProperty("username", SpringConfigUtils.createLiteralValue(grailsDataSource.getUsername()));
dataSource.setProperty("password", SpringConfigUtils.createLiteralValue(grailsDataSource.getPassword()));
beanReferences.add(SpringConfigUtils.createBeanReference("dataSource", dataSource));
} else {
Bean dataSource = SpringConfigUtils.createSingletonBean(BasicDataSource.class);
dataSource.setDestroyMethod("close");
dataSource.setProperty("driverClassName", SpringConfigUtils.createLiteralValue("org.hsqldb.jdbcDriver"));
dataSource.setProperty("url", SpringConfigUtils.createLiteralValue("jdbc:hsqldb:hsql://localhost:9101/"));
dataSource.setProperty("username", SpringConfigUtils.createLiteralValue("sa"));
dataSource.setProperty("password", SpringConfigUtils.createLiteralValue(""));
beanReferences.add(SpringConfigUtils.createBeanReference("dataSource", dataSource));
Bean hsqldbServer = SpringConfigUtils.createSingletonBean(ServerBean.class);
hsqldbServer.setProperty("dataSource", SpringConfigUtils.createBeanReference("dataSource"));
Map hsqldbProperties = new HashMap();
hsqldbProperties.put("server.port", "9101");
hsqldbProperties.put("server.database.0", "mem:temp");
hsqldbServer.setProperty("serverProperties", SpringConfigUtils.createProperties(hsqldbProperties));
beanReferences.add(SpringConfigUtils.createBeanReference("hsqldbServer", hsqldbServer));
dependsOnHsqldbServer = true;
}
Map vendorNameDialectMappings = new HashMap();
vendorNameDialectMappings.put("HSQL Database Engine", HSQLDialect.class.getName());
Bean dialectDetector = SpringConfigUtils.createSingletonBean(HibernateDialectDetectorFactoryBean.class);
dialectDetector.setProperty("dataSource", SpringConfigUtils.createBeanReference("dataSource"));
dialectDetector.setProperty("vendorNameDialectMappings", SpringConfigUtils.createProperties(vendorNameDialectMappings));
if (dependsOnHsqldbServer) {
Collection dependsOn = new ArrayList();
dependsOn.add(SpringConfigUtils.createBeanReference("hsqldbServer"));
dialectDetector.setDependsOn(dependsOn);
}
Map hibernatePropertiesMap = new HashMap();
hibernatePropertiesMap.put(SpringConfigUtils.createLiteralValue("hibernate.dialect"), dialectDetector);
hibernatePropertiesMap.put(SpringConfigUtils.createLiteralValue("hibernate.hbm2ddl.auto"), SpringConfigUtils.createLiteralValue("create-drop"));
Bean hibernateProperties = SpringConfigUtils.createSingletonBean(MapToPropertiesFactoryBean.class);
hibernateProperties.setProperty("map", SpringConfigUtils.createMap(hibernatePropertiesMap));
Bean grailsHibernateConfiguration = SpringConfigUtils.createSingletonBean(GrailsDomainConfiguration.class);
grailsHibernateConfiguration.setProperty("grailsApplication", SpringConfigUtils.createBeanReference("grailsApplication"));
Bean grailsClassLoader = SpringConfigUtils.createSingletonBean(MethodInvokingFactoryBean.class);
grailsClassLoader.setProperty("targetObject", SpringConfigUtils.createBeanReference("grailsApplication"));
grailsClassLoader.setProperty("targetMethod", SpringConfigUtils.createLiteralValue("getClassLoader"));
Bean localSessionFactoryBean = SpringConfigUtils.createSingletonBean(ConfigurableLocalsSessionFactoryBean.class);
localSessionFactoryBean.setProperty("dataSource", SpringConfigUtils.createBeanReference("dataSource"));
localSessionFactoryBean.setProperty("hibernateProperties", hibernateProperties);
localSessionFactoryBean.setProperty("configuration", grailsHibernateConfiguration);
localSessionFactoryBean.setProperty("classLoader", grailsClassLoader);
beanReferences.add(SpringConfigUtils.createBeanReference("sessionFactory", localSessionFactoryBean));
Bean transactionManager = SpringConfigUtils.createSingletonBean(HibernateTransactionManager.class);
transactionManager.setProperty("sessionFactory", SpringConfigUtils.createBeanReference("sessionFactory"));
beanReferences.add(SpringConfigUtils.createBeanReference("transactionManager", transactionManager));
GrailsServiceClass[] serviceClasses = application.getGrailsServiceClasses();
for (int i = 0; i <serviceClasses.length; i++) {
GrailsServiceClass grailsServiceClass = serviceClasses[i];
Bean serviceClass = SpringConfigUtils.createSingletonBean(MethodInvokingFactoryBean.class);
serviceClass.setProperty("targetObject", SpringConfigUtils.createBeanReference("grailsApplication"));
serviceClass.setProperty("targetMethod", SpringConfigUtils.createLiteralValue("getGrailsServiceClass"));
serviceClass.setProperty("arguments", SpringConfigUtils.createLiteralValue(grailsServiceClass.getFullName()));
beanReferences.add(SpringConfigUtils.createBeanReference(grailsServiceClass.getFullName() + "Class", serviceClass));
Bean serviceInstance = SpringConfigUtils.createSingletonBean();
serviceInstance.setFactoryBean(SpringConfigUtils.createBeanReference(grailsServiceClass.getFullName() + "Class"));
serviceInstance.setFactoryMethod("newInstance");
if (grailsServiceClass.byName()) {
serviceInstance.setAutowire("byName");
} else if (grailsServiceClass.byType()) {
serviceInstance.setAutowire("byType");
}
if (grailsServiceClass.isTransactional()) {
Map transactionAttributes = new HashMap();
transactionAttributes.put("*", "PROPAGATION_REQUIRED");
Bean transactionalProxy = SpringConfigUtils.createSingletonBean(TransactionProxyFactoryBean.class);
transactionalProxy.setProperty("target", serviceInstance);
transactionalProxy.setProperty("transactionAttributes", SpringConfigUtils.createProperties(transactionAttributes));
transactionalProxy.setProperty("transactionManager", SpringConfigUtils.createBeanReference("transactionManager"));
beanReferences.add(SpringConfigUtils.createBeanReference(WordUtils.uncapitalize(grailsServiceClass.getName()) + "Service", transactionalProxy));
} else {
beanReferences.add(SpringConfigUtils.createBeanReference(WordUtils.uncapitalize(grailsServiceClass.getName()) + "Service", serviceInstance));
}
}
return beanReferences;
}
|
diff --git a/forscene-core/src/forscene/core/events/system/AnimationUpdateEvent.java b/forscene-core/src/forscene/core/events/system/AnimationUpdateEvent.java
index 8145141..b859b95 100644
--- a/forscene-core/src/forscene/core/events/system/AnimationUpdateEvent.java
+++ b/forscene-core/src/forscene/core/events/system/AnimationUpdateEvent.java
@@ -1,64 +1,64 @@
/*
*
*/
package forscene.core.events.system;
import forscene.core.entities.toTest.AbstractAnimation;
import forscene.system.managers.AbstractGameLoopManager;
// TODO: Auto-generated Javadoc
/**
* The Class EventAnimationUpdate.
*/
public class AnimationUpdateEvent extends AbstractEvent {
/** The animation. */
private AbstractAnimation animation;
/**
* Instantiates a new event animation update.
*
* @param anim
* the anim
*/
public AnimationUpdateEvent(AbstractAnimation anim) {
animation = anim;
setDone(false);
setPriority(-1);
}
/*
* (non-Javadoc)
*
* @see forscene.core.events.AbstractEvent#run()
*/
@Override
public void run() {
if (animation.isStarted()) {
long updateRate = animation.getUpdateRate();
/*
* PlayN.log().debug( " ticks " +
* GameLoopManager.getInstance().getTicks()); PlayN.log().debug(
* " ticksRAte " + GameLoopManager.getInstance().getTickRate());
* PlayN.log().debug( " second " +
* GameLoopManager.getInstance().getSeconds()); PlayN.log().debug(
* " updateRate " + updateRate );
*/
long scaledFps;
if (updateRate != 0) {
scaledFps = (AbstractGameLoopManager.getInstance().getTickRate() / updateRate);
} else {
scaledFps = 1;
}
if ((updateRate == 0)
|| ((((AbstractGameLoopManager.getInstance().getTicks())) % scaledFps) == 0)) {
animation.run();
animation.getTarget().setToUpdate(true);
- setDone(true);
+ setDone(false);
}
} /*
* else { setDone(true); }
*/
}
}
| true | true | public void run() {
if (animation.isStarted()) {
long updateRate = animation.getUpdateRate();
/*
* PlayN.log().debug( " ticks " +
* GameLoopManager.getInstance().getTicks()); PlayN.log().debug(
* " ticksRAte " + GameLoopManager.getInstance().getTickRate());
* PlayN.log().debug( " second " +
* GameLoopManager.getInstance().getSeconds()); PlayN.log().debug(
* " updateRate " + updateRate );
*/
long scaledFps;
if (updateRate != 0) {
scaledFps = (AbstractGameLoopManager.getInstance().getTickRate() / updateRate);
} else {
scaledFps = 1;
}
if ((updateRate == 0)
|| ((((AbstractGameLoopManager.getInstance().getTicks())) % scaledFps) == 0)) {
animation.run();
animation.getTarget().setToUpdate(true);
setDone(true);
}
} /*
* else { setDone(true); }
*/
}
| public void run() {
if (animation.isStarted()) {
long updateRate = animation.getUpdateRate();
/*
* PlayN.log().debug( " ticks " +
* GameLoopManager.getInstance().getTicks()); PlayN.log().debug(
* " ticksRAte " + GameLoopManager.getInstance().getTickRate());
* PlayN.log().debug( " second " +
* GameLoopManager.getInstance().getSeconds()); PlayN.log().debug(
* " updateRate " + updateRate );
*/
long scaledFps;
if (updateRate != 0) {
scaledFps = (AbstractGameLoopManager.getInstance().getTickRate() / updateRate);
} else {
scaledFps = 1;
}
if ((updateRate == 0)
|| ((((AbstractGameLoopManager.getInstance().getTicks())) % scaledFps) == 0)) {
animation.run();
animation.getTarget().setToUpdate(true);
setDone(false);
}
} /*
* else { setDone(true); }
*/
}
|
diff --git a/src/Core/org/objectweb/proactive/core/body/reply/ReplyImpl.java b/src/Core/org/objectweb/proactive/core/body/reply/ReplyImpl.java
index da7aecc10..7ac4d8e7d 100644
--- a/src/Core/org/objectweb/proactive/core/body/reply/ReplyImpl.java
+++ b/src/Core/org/objectweb/proactive/core/body/reply/ReplyImpl.java
@@ -1,178 +1,181 @@
/*
* ################################################################
*
* ProActive: The Java(TM) library for Parallel, Distributed,
* Concurrent computing with Security and Mobility
*
* Copyright (C) 1997-2007 INRIA/University of Nice-Sophia Antipolis
* Contact: [email protected]
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or any later version.
*
* This 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
* General Public License for more details.
*
* You should have received a copy of the GNU 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
*
* Initial developer(s): The ProActive Team
* http://proactive.inria.fr/team_members.htm
* Contributor(s):
*
* ################################################################
*/
package org.objectweb.proactive.core.body.reply;
import java.io.IOException;
import java.io.Serializable;
import org.objectweb.proactive.core.UniqueID;
import org.objectweb.proactive.core.body.LocalBodyStore;
import org.objectweb.proactive.core.body.UniversalBody;
import org.objectweb.proactive.core.body.future.MethodCallResult;
import org.objectweb.proactive.core.body.message.MessageImpl;
import org.objectweb.proactive.core.mop.Utils;
import org.objectweb.proactive.core.security.ProActiveSecurityManager;
import org.objectweb.proactive.core.security.crypto.Session;
import org.objectweb.proactive.core.security.crypto.Session.ActAs;
import org.objectweb.proactive.core.security.crypto.SessionException;
import org.objectweb.proactive.core.security.exceptions.CommunicationForbiddenException;
import org.objectweb.proactive.core.security.exceptions.RenegotiateSessionException;
import org.objectweb.proactive.core.security.exceptions.SecurityNotAvailableException;
import org.objectweb.proactive.core.util.converter.ByteToObjectConverter;
public class ReplyImpl extends MessageImpl implements Reply, Serializable {
/**
* The hypothetic result
*/
protected MethodCallResult result;
// security features
/**
* the encrypted result
*/
protected byte[][] encryptedResult;
protected boolean ciphered;
// true if this reply is sent by automatic continuation
private boolean isAC;
/*
* the session ID used to find the key and decrypt the reply
*/
protected long sessionID;
protected transient ProActiveSecurityManager psm = null;
public ReplyImpl(UniqueID senderID, long sequenceNumber, String methodName, MethodCallResult result,
ProActiveSecurityManager psm) {
this(senderID, sequenceNumber, methodName, result, psm, false);
}
public ReplyImpl(UniqueID senderID, long sequenceNumber, String methodName, MethodCallResult result,
ProActiveSecurityManager psm, boolean isAutomaticContinuation) {
super(senderID, sequenceNumber, true, methodName);
this.result = result;
this.psm = psm;
this.isAC = isAutomaticContinuation;
}
public MethodCallResult getResult() {
return result;
}
public int send(UniversalBody destinationBody) throws IOException {
// if destination body is on the same VM that the sender, we must
// perform
// a deep copy of result in order to preserve ProActive model.
UniqueID destinationID = destinationBody.getID();
+ // The following code ensures that if the destination body is located
+ // on the same VM, the result will only be serialized once.
+ // This also solves the bug PROACTIVE-81.
UniversalBody localRef = LocalBodyStore.getInstance().getLocalBody(destinationID);
if (localRef == null) {
// halfBody ?
localRef = LocalBodyStore.getInstance().getLocalHalfBody(destinationID);
}
if (localRef != null) {
destinationBody = localRef;
result = (MethodCallResult) Utils.makeDeepCopy(result);
}
// security
if (!ciphered && (psm != null)) {
try {
Session session = this.psm.getSessionTo(destinationBody.getCertificate());
if (!session.getSecurityContext().getSendReply().getCommunication()) {
throw new CommunicationForbiddenException();
}
this.sessionID = session.getDistantSessionID();
long id = psm.getSessionIDTo(destinationBody.getCertificate());
encryptedResult = psm.encrypt(id, result, ActAs.SERVER);
ciphered = true;
} catch (SecurityNotAvailableException e) {
// do nothing
} catch (CommunicationForbiddenException e) {
e.printStackTrace();
} catch (RenegotiateSessionException e) {
psm.terminateSession(sessionID);
try {
destinationBody.terminateSession(sessionID);
} catch (SecurityNotAvailableException e1) {
e.printStackTrace();
}
this.send(destinationBody);
} catch (SessionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// end security
// fault-tolerance returned value
return destinationBody.receiveReply(this);
}
// security issue
public boolean isCiphered() {
return ciphered;
}
public boolean decrypt(ProActiveSecurityManager psm) throws RenegotiateSessionException {
if ((sessionID != 0) && ciphered) {
byte[] decryptedMethodCall = psm.decrypt(sessionID, encryptedResult, ActAs.CLIENT);
try {
result = (MethodCallResult) ByteToObjectConverter.ObjectStream.convert(decryptedMethodCall);
return true;
} catch (Exception e) {
e.printStackTrace();
}
}
return false;
}
/*
* (non-Javadoc)
*
* @see org.objectweb.proactive.core.body.reply.Reply#getSessionId()
*/
public long getSessionId() {
return sessionID;
}
/**
* @see org.objectweb.proactive.core.body.reply.Reply#isAutomaticContinuation()
*/
public boolean isAutomaticContinuation() {
return this.isAC;
}
}
| true | true | public int send(UniversalBody destinationBody) throws IOException {
// if destination body is on the same VM that the sender, we must
// perform
// a deep copy of result in order to preserve ProActive model.
UniqueID destinationID = destinationBody.getID();
UniversalBody localRef = LocalBodyStore.getInstance().getLocalBody(destinationID);
if (localRef == null) {
// halfBody ?
localRef = LocalBodyStore.getInstance().getLocalHalfBody(destinationID);
}
if (localRef != null) {
destinationBody = localRef;
result = (MethodCallResult) Utils.makeDeepCopy(result);
}
// security
if (!ciphered && (psm != null)) {
try {
Session session = this.psm.getSessionTo(destinationBody.getCertificate());
if (!session.getSecurityContext().getSendReply().getCommunication()) {
throw new CommunicationForbiddenException();
}
this.sessionID = session.getDistantSessionID();
long id = psm.getSessionIDTo(destinationBody.getCertificate());
encryptedResult = psm.encrypt(id, result, ActAs.SERVER);
ciphered = true;
} catch (SecurityNotAvailableException e) {
// do nothing
} catch (CommunicationForbiddenException e) {
e.printStackTrace();
} catch (RenegotiateSessionException e) {
psm.terminateSession(sessionID);
try {
destinationBody.terminateSession(sessionID);
} catch (SecurityNotAvailableException e1) {
e.printStackTrace();
}
this.send(destinationBody);
} catch (SessionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// end security
// fault-tolerance returned value
return destinationBody.receiveReply(this);
}
| public int send(UniversalBody destinationBody) throws IOException {
// if destination body is on the same VM that the sender, we must
// perform
// a deep copy of result in order to preserve ProActive model.
UniqueID destinationID = destinationBody.getID();
// The following code ensures that if the destination body is located
// on the same VM, the result will only be serialized once.
// This also solves the bug PROACTIVE-81.
UniversalBody localRef = LocalBodyStore.getInstance().getLocalBody(destinationID);
if (localRef == null) {
// halfBody ?
localRef = LocalBodyStore.getInstance().getLocalHalfBody(destinationID);
}
if (localRef != null) {
destinationBody = localRef;
result = (MethodCallResult) Utils.makeDeepCopy(result);
}
// security
if (!ciphered && (psm != null)) {
try {
Session session = this.psm.getSessionTo(destinationBody.getCertificate());
if (!session.getSecurityContext().getSendReply().getCommunication()) {
throw new CommunicationForbiddenException();
}
this.sessionID = session.getDistantSessionID();
long id = psm.getSessionIDTo(destinationBody.getCertificate());
encryptedResult = psm.encrypt(id, result, ActAs.SERVER);
ciphered = true;
} catch (SecurityNotAvailableException e) {
// do nothing
} catch (CommunicationForbiddenException e) {
e.printStackTrace();
} catch (RenegotiateSessionException e) {
psm.terminateSession(sessionID);
try {
destinationBody.terminateSession(sessionID);
} catch (SecurityNotAvailableException e1) {
e.printStackTrace();
}
this.send(destinationBody);
} catch (SessionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// end security
// fault-tolerance returned value
return destinationBody.receiveReply(this);
}
|
diff --git a/src/java/com/threerings/presents/server/net/ConnectionManager.java b/src/java/com/threerings/presents/server/net/ConnectionManager.java
index 1c9616246..d0f5ce257 100644
--- a/src/java/com/threerings/presents/server/net/ConnectionManager.java
+++ b/src/java/com/threerings/presents/server/net/ConnectionManager.java
@@ -1,1137 +1,1137 @@
//
// $Id$
//
// Narya library - tools for developing networked games
// Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/narya/
//
// 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
// (at your option) 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. 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 com.threerings.presents.server.net;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.channels.spi.SelectorProvider;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.samskivert.util.IntMap;
import com.samskivert.util.IntMaps;
import com.samskivert.util.Invoker;
import com.samskivert.util.LoopingThread;
import com.samskivert.util.Queue;
import com.samskivert.util.ResultListener;
import com.samskivert.util.Tuple;
import com.threerings.io.FramingOutputStream;
import com.threerings.io.ObjectOutputStream;
import com.threerings.presents.annotation.AuthInvoker;
import com.threerings.presents.client.Client;
import com.threerings.presents.data.ConMgrStats;
import com.threerings.presents.net.AuthRequest;
import com.threerings.presents.net.AuthResponse;
import com.threerings.presents.net.DownstreamMessage;
import com.threerings.presents.server.Authenticator;
import com.threerings.presents.server.ChainedAuthenticator;
import com.threerings.presents.server.DummyAuthenticator;
import com.threerings.presents.server.PresentsDObjectMgr;
import com.threerings.presents.server.ReportManager;
import com.threerings.presents.server.ShutdownManager;
import com.threerings.presents.util.DatagramSequencer;
import static com.threerings.presents.Log.log;
/**
* The connection manager manages the socket on which connections are received. It creates
* connection objects to manage each individual connection, but those connection objects interact
* closely with the connection manager because network I/O is done via a poll()-like mechanism
* rather than via threads.
*/
@Singleton
public class ConnectionManager extends LoopingThread
implements ShutdownManager.Shutdowner, ReportManager.Reporter
{
/**
* Creates a connection manager instance. Don't call this, Guice will do it for you.
*/
@Inject public ConnectionManager (ShutdownManager shutmgr, ReportManager repmgr)
{
super("ConnectionManager");
shutmgr.registerShutdowner(this);
repmgr.registerReporter(this);
}
/**
* Constructs and initialized a connection manager (binding socket on which it will listen for
* client connections to each of the specified ports).
*/
public void init (int[] ports)
throws IOException
{
init(ports, new int[0]);
}
/**
* Constructs and initialized a connection manager (binding socket on which it will listen for
* client connections to each of the specified ports).
*/
public void init (int[] ports, int[] datagramPorts)
throws IOException
{
_ports = ports;
_datagramPorts = datagramPorts;
_selector = SelectorProvider.provider().openSelector();
// create our stats record
_stats = new ConMgrStats();
_lastStats = new ConMgrStats();
}
/**
* Configures the connection manager with an entity that will be informed of the success or
* failure of the connection manager initialization process. <em>Note:</em> the callback
* methods will be called on the connection manager thread, so be careful not to do anything on
* those methods that will conflict with activities on the dobjmgr thread, etc.
*/
public void setStartupListener (ResultListener<Object> rl)
{
_startlist = rl;
}
/**
* Adds an authenticator to the authentication chain. This authenticator will be offered a
* chance to authenticate incoming connections in lieu of the main autuenticator.
*/
public void addChainedAuthenticator (ChainedAuthenticator author)
{
author.setChainedAuthenticator(_author);
_author = author;
}
/**
* Instructs us to execute the specified runnable when the connection manager thread exits.
* <em>Note:</em> this will be executed on the connection manager thread, so don't do anything
* dangerous. Only one action may be specified and it may be cleared by calling this method
* with null.
*/
public void setShutdownAction (Runnable onExit)
{
_onExit = onExit;
}
/**
* Returns our current runtime statistics. <em>Note:</em> don't call this method <em>too</em>
* frequently as it is synchronized and will contend with the network I/O thread.
*/
public synchronized ConMgrStats getStats ()
{
// fill in our snapshot values
_stats.authQueueSize = _authq.size();
_stats.deathQueueSize = _deathq.size();
_stats.outQueueSize = _outq.size();
if (_oflowqs.size() > 0) {
_stats.overQueueSize = 0;
for (OverflowQueue oq : _oflowqs.values()) {
_stats.overQueueSize += oq.size();
}
}
return (ConMgrStats)_stats.clone();
}
/**
* Adds the specified connection observer to the observers list. Connection observers will be
* notified of connection-related events. An observer will not be added to the list twice.
*
* @see ConnectionObserver
*/
public void addConnectionObserver (ConnectionObserver observer)
{
synchronized (_observers) {
_observers.add(observer);
}
}
/**
* Removes the specified connection observer from the observers list.
*/
public void removeConnectionObserver (ConnectionObserver observer)
{
synchronized (_observers) {
_observers.remove(observer);
}
}
/**
* Queues a connection up to be closed on the conmgr thread.
*/
public void closeConnection (Connection conn)
{
_deathq.append(conn);
}
/**
* Performs the authentication process on the specified connection. This is called by {@link
* AuthingConnection} itself once it receives its auth request.
*/
public void authenticateConnection (AuthingConnection conn)
{
_author.authenticateConnection(_authInvoker, conn, new ResultListener<AuthingConnection>() {
public void requestCompleted (AuthingConnection conn) {
_authq.append(conn);
}
public void requestFailed (Exception cause) {
// this never happens
}
});
}
// documentation inherited from interface ReportManager.Reporter
public void appendReport (
StringBuilder report, long now, long sinceLast, boolean reset)
{
ConMgrStats stats = getStats();
int connects = stats.connects - _lastStats.connects;
int disconnects = stats.disconnects - _lastStats.disconnects;
long bytesIn = stats.bytesIn - _lastStats.bytesIn;
long bytesOut = stats.bytesOut - _lastStats.bytesOut;
long msgsIn = stats.msgsIn - _lastStats.msgsIn;
long msgsOut = stats.msgsOut - _lastStats.msgsOut;
if (reset) {
_lastStats = stats;
}
// make sure we don't div0 if this method somehow gets called twice in
// the same millisecond
sinceLast = Math.max(sinceLast, 1L);
report.append("* presents.net.ConnectionManager:\n");
report.append("- Network connections: ");
report.append(connects).append(" connects, ");
report.append(disconnects).append(" disconnects\n");
report.append("- Network input: ");
report.append(bytesIn).append(" bytes, ");
report.append(msgsIn).append(" msgs, ");
report.append(msgsIn*1000/sinceLast).append(" mps, ");
long avgIn = (msgsIn == 0) ? 0 : (bytesIn/msgsIn);
report.append(avgIn).append(" avg size, ");
report.append(bytesIn*1000/sinceLast).append(" bps\n");
report.append("- Network output: ");
report.append(bytesOut).append(" bytes, ");
report.append(msgsOut).append(" msgs, ");
report.append(msgsOut*1000/sinceLast).append(" mps, ");
long avgOut = (msgsOut == 0) ? 0 : (bytesOut/msgsOut);
report.append(avgOut).append(" avg size, ");
report.append(bytesOut*1000/sinceLast).append(" bps\n");
}
@Override // from LoopingThread
public boolean isRunning ()
{
// Prevent exiting our thread until the object manager is done.
return super.isRunning() || _omgr.isRunning();
}
/**
* Notifies the connection observers of a connection event. Used internally.
*/
protected void notifyObservers (
int code, Connection conn, Object arg1, Object arg2)
{
synchronized (_observers) {
for (ConnectionObserver obs : _observers) {
switch (code) {
case CONNECTION_ESTABLISHED:
obs.connectionEstablished(conn, (AuthRequest)arg1, (AuthResponse)arg2);
break;
case CONNECTION_FAILED:
obs.connectionFailed(conn, (IOException)arg1);
break;
case CONNECTION_CLOSED:
obs.connectionClosed(conn);
break;
default:
throw new RuntimeException("Invalid code supplied to notifyObservers: " + code);
}
}
}
}
@Override
protected void willStart ()
{
int successes = 0;
IOException failure = null;
for (int port : _ports) {
try {
// create a listening socket and add it to the select set
_ssocket = ServerSocketChannel.open();
_ssocket.configureBlocking(false);
InetSocketAddress isa = new InetSocketAddress(port);
_ssocket.socket().bind(isa);
registerChannel(_ssocket);
successes++;
log.info("Server listening on " + isa + ".");
} catch (IOException ioe) {
log.warning("Failure listening to socket on port '" + port + "'.", ioe);
failure = ioe;
}
}
// NOTE: this is not currently working; it works but for whatever inscrutable reason the
// inherited channel claims to be readable immediately every time through the select() loop
// which causes the server to consume 100% of the CPU repeatedly ignoring the inherited
// channel (except when an actual connection comes in in which case it does the right
// thing)
// // now look to see if we were passed a socket inetd style by a
// // privileged parent process
// try {
// Channel inherited = System.inheritedChannel();
// if (inherited instanceof ServerSocketChannel) {
// _ssocket = (ServerSocketChannel)inherited;
// _ssocket.configureBlocking(false);
// registerChannel(_ssocket);
// successes++;
// log.info("Server listening on " +
// _ssocket.socket().getInetAddress() + ":" +
// _ssocket.socket().getLocalPort() + ".");
// } else if (inherited != null) {
// log.warning("Inherited non-server-socket channel " + inherited + ".");
// }
// } catch (IOException ioe) {
// log.warning("Failed to check for inherited channel.");
// }
// if we failed to listen on at least one port, give up the ghost
if (successes == 0) {
if (_startlist != null) {
_startlist.requestFailed(failure);
}
return;
}
// open up the datagram ports as well
for (int port : _datagramPorts) {
try {
// create a channel and add it to the select set
_datagramChannel = DatagramChannel.open();
_datagramChannel.configureBlocking(false);
InetSocketAddress isa = new InetSocketAddress(port);
_datagramChannel.socket().bind(isa);
registerChannel(_datagramChannel);
log.info("Server accepting datagrams on " + isa + ".");
} catch (IOException ioe) {
log.warning("Failure opening datagram channel on port '" +
port + "'.", ioe);
}
}
// we'll use these for sending messages to clients
_framer = new FramingOutputStream();
_flattener = new ByteArrayOutputStream();
// notify our startup listener, if we have one
if (_startlist != null) {
_startlist.requestCompleted(null);
}
}
/** Helper function for {@link #willStart}. */
protected void registerChannel (final ServerSocketChannel listener)
throws IOException
{
// register this listening socket and map its select key to a net event handler that will
// accept new connections
SelectionKey sk = listener.register(_selector, SelectionKey.OP_ACCEPT);
_handlers.put(sk, new NetEventHandler() {
public int handleEvent (long when) {
acceptConnection(listener);
// there's no easy way to measure bytes read when accepting a connection, so we
// claim nothing
return 0;
}
public boolean checkIdle (long now) {
return false; // we're never idle
}
});
}
/** Helper function for {@link #willStart}. */
protected void registerChannel (final DatagramChannel listener)
throws IOException
{
SelectionKey sk = listener.register(_selector, SelectionKey.OP_READ);
_handlers.put(sk, new NetEventHandler() {
public int handleEvent (long when) {
return readDatagram(listener, when);
}
public boolean checkIdle (long now) {
return false; // we're never idle
}
});
}
/**
* Returns a reference to the output stream used to flatten messages into byte arrays. Should
* only be called by {@link Connection}.
*/
protected ByteArrayOutputStream getFlattener ()
{
return _flattener;
}
/**
* Performs the select loop. This is the body of the conmgr thread.
*/
@Override
protected void iterate ()
{
long iterStamp = System.currentTimeMillis();
// close any connections that have been queued up to die
Connection dconn;
while ((dconn = _deathq.getNonBlocking()) != null) {
// it's possible that we caught an EOF trying to read from this connection even after
// it was queued up for death, so let's avoid trying to close it twice
if (!dconn.isClosed()) {
dconn.close();
}
}
// close connections that have had no network traffic for too long
for (NetEventHandler handler : _handlers.values()) {
if (handler.checkIdle(iterStamp)) {
// this will queue the connection for closure on our next tick
closeConnection((Connection)handler);
}
}
// send any messages that are waiting on the outgoing overflow and message queues
sendOutgoingMessages(iterStamp);
- // if we have been shutdown, but we're stick around because the DObjectManager is still
+ // if we have been shutdown, but we're still around because the DObjectManager is still
// running (and we want to deliver any outgoing events queued up during shutdown), then we
// stop here, because we've delivered outgoing events on this tick and all that remains
// below is accepting new connections and receiving incoming messages, neither of which we
// want to do during the shutdown process
if (!super.isRunning()) {
return;
}
// check for connections that have completed authentication
AuthingConnection conn;
while ((conn = _authq.getNonBlocking()) != null) {
try {
// construct a new running connection to handle this connections network traffic
// from here on out
SelectionKey selkey = conn.getSelectionKey();
RunningConnection rconn = new RunningConnection(
this, selkey, conn.getChannel(), iterStamp);
// we need to keep using the same object input and output streams from the
// beginning of the session because they have context that needs to be preserved
rconn.inheritStreams(conn);
// replace the mapping in the handlers table from the old conn with the new one
_handlers.put(selkey, rconn);
// add a mapping for the connection id and set the datagram secret
_connections.put(rconn.getConnectionId(), rconn);
rconn.setDatagramSecret(
conn.getAuthRequest().getCredentials().getDatagramSecret());
// transfer any overflow queue for that connection
OverflowQueue oflowHandler = _oflowqs.remove(conn);
if (oflowHandler != null) {
_oflowqs.put(rconn, oflowHandler);
}
// and let our observers know about our new connection
notifyObservers(CONNECTION_ESTABLISHED, rconn,
conn.getAuthRequest(), conn.getAuthResponse());
} catch (IOException ioe) {
log.warning("Failure upgrading authing connection to running.", ioe);
}
}
Set<SelectionKey> ready = null;
try {
// check for incoming network events
// log.debug("Selecting from " + StringUtil.toString(_selector.keys()) + " (" +
// SELECT_LOOP_TIME + ").");
int ecount = _selector.select(SELECT_LOOP_TIME);
ready = _selector.selectedKeys();
if (ecount == 0) {
if (ready.size() == 0) {
return;
} else {
log.warning("select() returned no selected sockets, but there are " +
ready.size() + " in the ready set.");
}
}
} catch (IOException ioe) {
if ("Invalid argument".equals(ioe.getMessage())) {
// what is this, anyway?
log.warning("Failure select()ing.", ioe);
} else {
log.warning("Failure select()ing [ioe=" + ioe + "].");
}
return;
} catch (RuntimeException re) {
// this block of code deals with a bug in the _selector that we observed on 2005-05-02,
// instead of looping indefinitely after things go pear-shaped, shut us down in an
// orderly fashion
log.warning("Failure select()ing.", re);
if (_runtimeExceptionCount++ >= 20) {
log.warning("Too many errors, bailing.");
shutdown();
}
return;
}
// clear the runtime error count
_runtimeExceptionCount = 0;
// process those events
// log.info("Ready set " + StringUtil.toString(ready) + ".");
for (SelectionKey selkey : ready) {
NetEventHandler handler = null;
try {
handler = _handlers.get(selkey);
if (handler == null) {
log.warning("Received network event but have no registered handler " +
"[selkey=" + selkey + "].");
// request that this key be removed from our selection set, which normally
// happens automatically but for some reason didn't
selkey.cancel();
continue;
}
// log.info("Got event [selkey=" + selkey + ", handler=" + handler + "].");
int got = handler.handleEvent(iterStamp);
if (got != 0) {
synchronized (this) {
_bytesIn += got;
_stats.bytesIn += got;
// we know that the handlers only report having read bytes when they have a
// whole message, so we can count thusly
_msgsIn++;
_stats.msgsIn++;
}
}
} catch (Exception e) {
log.warning("Error processing network data: " + handler + ".", e);
// if you freak out here, you go straight in the can
if (handler != null && handler instanceof Connection) {
closeConnection((Connection)handler);
}
}
}
ready.clear();
}
/**
* Writes all queued overflow and normal messages to their respective sockets. Connections that
* already have established overflow queues will have their messages appended to their overflow
* queue instead so that they are delivered in the proper order.
*/
protected void sendOutgoingMessages (long iterStamp)
{
// first attempt to send any messages waiting on the overflow queues
if (_oflowqs.size() > 0) {
Iterator<OverflowQueue> oqiter = _oflowqs.values().iterator();
while (oqiter.hasNext()) {
OverflowQueue oq = oqiter.next();
try {
// try writing the messages in this overflow queue
if (oq.writeOverflowMessages(iterStamp)) {
// if they were all written, we can remove it
oqiter.remove();
}
} catch (IOException ioe) {
oq.conn.handleFailure(ioe);
}
}
}
// then send any new messages
Tuple<Connection, byte[]> tup;
while ((tup = _outq.getNonBlocking()) != null) {
Connection conn = tup.left;
// if an overflow queue exists for this client, go ahead and slap the message on there
// because we can't send it until all other messages in their queue have gone out
OverflowQueue oqueue = _oflowqs.get(conn);
if (oqueue != null) {
int size = oqueue.size();
if ((size > 500) && (size % 50 == 0)) {
log.warning("Aiya, big overflow queue for " + conn + " [size=" + size +
", adding=" + tup.right + "].");
}
oqueue.add(tup.right);
continue;
}
// otherwise write the message out to the client directly
writeMessage(conn, tup.right, _oflowHandler);
}
// send any datagrams
while ((tup = _dataq.getNonBlocking()) != null) {
writeDatagram(tup.left, tup.right);
}
}
/**
* Writes a message out to a connection, passing the buck to the partial write handler if the
* entire message could not be written.
*
* @return true if the message was fully written, false if it was partially written (in which
* case the partial message handler will have been invoked).
*/
protected boolean writeMessage (Connection conn, byte[] data, PartialWriteHandler pwh)
{
// if the connection to which this message is destined is closed, drop the message and move
// along quietly; this is perfectly legal, a user can logoff whenever they like, even if we
// still have things to tell them; such is life in a fully asynchronous distributed system
if (conn.isClosed()) {
return true;
}
// sanity check the message size
if (data.length > 1024 * 1024) {
log.warning("Refusing to write absurdly large message [conn=" + conn +
", size=" + data.length + "].");
return true;
}
// expand our output buffer if needed to accomodate this message
if (data.length > _outbuf.capacity()) {
// increase the buffer size in large increments
int ncapacity = Math.max(_outbuf.capacity() << 1, data.length);
log.info("Expanding output buffer size [nsize=" + ncapacity + "].");
_outbuf = ByteBuffer.allocateDirect(ncapacity);
}
boolean fully = true;
try {
// log.info("Writing " + data.length + " byte message to " + conn + ".");
// first copy the data into our "direct" output buffer
_outbuf.put(data);
_outbuf.flip();
// then write the data to the socket
int wrote = conn.getChannel().write(_outbuf);
noteWrite(1, wrote);
if (_outbuf.remaining() > 0) {
fully = false;
// log.info("Partial write [conn=" + conn +
// ", msg=" + StringUtil.shortClassName(outmsg) + ", wrote=" + wrote +
// ", size=" + buffer.limit() + "].");
pwh.handlePartialWrite(conn, _outbuf);
// } else if (wrote > 10000) {
// log.info("Big write [conn=" + conn +
// ", msg=" + StringUtil.shortClassName(outmsg) +
// ", wrote=" + wrote + "].");
}
} catch (IOException ioe) {
// instruct the connection to deal with its failure
conn.handleFailure(ioe);
} finally {
_outbuf.clear();
}
return fully;
}
/**
* Sends a datagram to the specified connection.
*
* @return true if the datagram was sent, false if we failed to send for any reason.
*/
protected boolean writeDatagram (Connection conn, byte[] data)
{
InetSocketAddress target = conn.getDatagramAddress();
if (target == null) {
log.warning("No address to send datagram [conn=" + conn + "].");
return false;
}
_databuf.clear();
_databuf.put(data).flip();
try {
return _datagramChannel.send(_databuf, target) > 0;
} catch (IOException ioe) {
log.warning("Failed to send datagram.", ioe);
return false;
}
}
/** Called by {@link #writeMessage} and friends when they write data over the network. */
protected final synchronized void noteWrite (int msgs, int bytes)
{
_msgsOut += msgs;
_bytesOut += bytes;
_stats.msgsOut += msgs;
_stats.bytesOut += bytes;
}
@Override
protected void handleIterateFailure (Exception e)
{
// log the exception
log.warning("ConnectionManager.iterate() uncaught exception.", e);
}
@Override
protected void didShutdown ()
{
// take one last crack at the outgoing message queue
sendOutgoingMessages(System.currentTimeMillis());
// unbind our listening socket
// Note: because we wait for the object manager to exit before we do, we will still be
// accepting connections as long as there are events pending.
// TODO: consider shutting down the listen socker earlier, like in the shutdown method
try {
_ssocket.socket().close();
} catch (IOException ioe) {
log.warning("Failed to close listening socket.", ioe);
}
// and the datagram socket, if any
if (_datagramChannel != null) {
_datagramChannel.socket().close();
}
// report if there's anything left on the outgoing message queue
if (_outq.size() > 0) {
log.warning("Connection Manager failed to deliver " + _outq.size() + " message(s).");
}
// run our on-exit handler if we have one
Runnable onExit = _onExit;
if (onExit != null) {
log.info("Connection Manager thread exited (running onExit).");
onExit.run();
} else {
log.info("Connection Manager thread exited.");
}
}
/**
* Called by our net event handler when a new connection is ready to be accepted on our
* listening socket.
*/
protected void acceptConnection (ServerSocketChannel listener)
{
SocketChannel channel = null;
try {
channel = listener.accept();
if (channel == null) {
// in theory this shouldn't happen because we got an ACCEPT_READY event, but better
// safe than sorry
log.info("Psych! Got ACCEPT_READY, but no connection.");
return;
}
// log.debug("Accepted connection " + channel + ".");
// create a new authing connection object to manage the authentication of this client
// connection and register it with our selection set
SelectableChannel selchan = channel;
selchan.configureBlocking(false);
SelectionKey selkey = selchan.register(_selector, SelectionKey.OP_READ);
_handlers.put(selkey, new AuthingConnection(this, selkey, channel));
synchronized (this) {
_stats.connects++;
}
return;
} catch (IOException ioe) {
// no need to complain this happens in the normal course of events
// log.warning("Failure accepting new connection.", ioe);
}
// make sure we don't leak a socket if something went awry
if (channel != null) {
try {
channel.socket().close();
} catch (IOException ioe) {
log.warning("Failed closing aborted connection: " + ioe);
}
}
}
/**
* Called by our net event handler when a datagram is ready to be read from the channel.
*
* @return the size of the datagram.
*/
protected int readDatagram (DatagramChannel listener, long when)
{
InetSocketAddress source;
_databuf.clear();
try {
source = (InetSocketAddress)listener.receive(_databuf);
} catch (IOException ioe) {
log.warning("Failure receiving datagram.", ioe);
return 0;
}
// make sure we actually read a packet
if (source == null) {
log.info("Psych! Got READ_READY, but no datagram.");
return 0;
}
// flip the buffer and record the size (which must be at least 14 to contain the connection
// id, authentication hash, and a class reference)
int size = _databuf.flip().remaining();
if (size < 14) {
log.warning("Received undersized datagram [source=" + source +
", size=" + size + "].");
return 0;
}
// the first four bytes are the connection id
int connectionId = _databuf.getInt();
Connection conn = _connections.get(connectionId);
if (conn != null) {
conn.handleDatagram(source, _databuf, when);
} else {
log.warning("Received datagram for unknown connection [id=" + connectionId +
", source=" + source + "].");
}
// return the size of the datagram
return size;
}
/**
* Called by a connection when it has a downstream message that needs to be delivered.
* <em>Note:</em> this method is called as a result of a call to {@link Connection#postMessage}
* which happens when forwarding an event to a client and at the completion of authentication,
* both of which <em>must</em> happen only on the distributed object thread.
*/
void postMessage (Connection conn, DownstreamMessage msg)
{
if (!isRunning()) {
log.warning("Posting message to inactive connection manager", new Exception());
}
// sanity check
if (conn == null || msg == null) {
log.warning("postMessage() bogosity", "conn", conn, "msg", msg, new Exception());
return;
}
// more sanity check; messages must only be posted from the dobjmgr thread
if (!_omgr.isDispatchThread()) {
log.warning("Message posted on non-distributed object thread", "conn", conn,
"msg", msg, "thread", Thread.currentThread(), new Exception());
// let it through though as we don't want to break things unnecessarily
}
try {
// send it as a datagram if hinted and possible
if (!msg.getTransport().isReliable() && conn.getDatagramAddress() != null) {
postDatagram(conn, msg);
return;
}
_framer.resetFrame();
// flatten this message using the connection's output stream
ObjectOutputStream oout = conn.getObjectOutputStream(_framer);
oout.writeObject(msg);
oout.flush();
// now extract that data into a byte array
ByteBuffer buffer = _framer.frameAndReturnBuffer();
byte[] data = new byte[buffer.limit()];
buffer.get(data);
// log.info("Flattened " + msg + " into " + data.length + " bytes.");
// and slap both on the queue
_outq.append(new Tuple<Connection, byte[]>(conn, data));
} catch (Exception e) {
log.warning("Failure flattening message [conn=" + conn +
", msg=" + msg + "].", e);
}
}
/**
* Helper function for {@link #postMessage}; handles posting the message as a datagram.
*/
void postDatagram (Connection conn, DownstreamMessage msg)
throws Exception
{
_flattener.reset();
// flatten the message using the connection's sequencer
DatagramSequencer sequencer = conn.getDatagramSequencer();
sequencer.writeDatagram(msg);
// extract as a byte array
byte[] data = _flattener.toByteArray();
// slap it on the queue
_dataq.append(new Tuple<Connection, byte[]>(conn, data));
}
/**
* Called by a connection if it experiences a network failure.
*/
void connectionFailed (Connection conn, IOException ioe)
{
// remove this connection from our mappings (it is automatically removed from the Selector
// when the socket is closed)
_handlers.remove(conn.getSelectionKey());
_connections.remove(conn.getConnectionId());
_oflowqs.remove(conn);
synchronized (this) {
_stats.disconnects++;
}
// let our observers know what's up
notifyObservers(CONNECTION_FAILED, conn, ioe, null);
}
/**
* Called by a connection when it discovers that it's closed.
*/
void connectionClosed (Connection conn)
{
// remove this connection from our mappings (it is automatically removed from the Selector
// when the socket is closed)
_handlers.remove(conn.getSelectionKey());
_connections.remove(conn.getConnectionId());
_oflowqs.remove(conn);
// let our observers know what's up
notifyObservers(CONNECTION_CLOSED, conn, null, null);
}
/** Used to handle partial writes in {@link ConnectionManager#writeMessage}. */
protected static interface PartialWriteHandler
{
void handlePartialWrite (Connection conn, ByteBuffer buffer);
}
/**
* Used to handle messages for a client whose network buffer has filled up because their
* outgoing network buffer has filled up. This can happen if the client receives many messages
* in rapid succession or if they receive very large messages or if they become unresponsive
* and stop acknowledging network packets sent by the server. We want to accomodate the first
* to circumstances and recognize the third as quickly as possible so that we can disconnect
* the client and propagate that information up to the higher levels so that further messages
* are not queued up for the unresponsive client.
*/
protected class OverflowQueue extends ArrayList<byte[]>
implements PartialWriteHandler
{
/** The connection for which we're managing overflow. */
public Connection conn;
/**
* Creates a new overflow queue for the supplied connection and with the supplied initial
* partial message.
*/
public OverflowQueue (Connection conn, ByteBuffer message)
{
this.conn = conn;
// set up our initial _partial buffer
handlePartialWrite(conn, message);
}
/**
* Called each time through the {@link ConnectionManager#iterate} loop, this attempts to
* send any remaining partial message and all subsequent messages in the overflow queue.
*
* @return true if all messages in this queue were successfully sent, false if there
* remains data to be sent on the next loop.
*
* @throws IOException if an error occurs writing data to the connection or if we have been
* unable to write any data to the connection for ten seconds.
*/
public boolean writeOverflowMessages (long iterStamp)
throws IOException
{
// write any partial message if we have one
if (_partial != null) {
// write all we can of our partial buffer
int wrote = conn.getChannel().write(_partial);
noteWrite(0, wrote);
if (_partial.remaining() == 0) {
_partial = null;
_partials++;
} else {
// log.info("Still going [conn=" + conn + ", wrote=" + wrote +
// ", remain=" + _partial.remaining() + "].");
return false;
}
}
while (size() > 0) {
byte[] data = remove(0);
// if any of these messages are partially written, we have to stop and wait for the
// next tick
_msgs++;
if (!writeMessage(conn, data, this)) {
return false;
}
}
return true;
}
// documentation inherited
public void handlePartialWrite (Connection wconn, ByteBuffer buffer)
{
// set up our _partial buffer
_partial = ByteBuffer.allocateDirect(buffer.remaining());
_partial.put(buffer);
_partial.flip();
}
@Override
public String toString ()
{
return "[conn=" + conn + ", partials=" + _partials + ", msgs=" + _msgs + "]";
}
/** The remains of a message that was only partially written on its first attempt. */
protected ByteBuffer _partial;
/** A couple of counters. */
protected int _msgs, _partials;
}
/** Used to create an overflow queue on the first partial write. */
protected PartialWriteHandler _oflowHandler = new PartialWriteHandler() {
public void handlePartialWrite (Connection conn, ByteBuffer msgbuf) {
// if we couldn't write all the data for this message, we'll need to establish an
// overflow queue
_oflowqs.put(conn, new OverflowQueue(conn, msgbuf));
}
};
/** Handles client authentication. The base authenticator is injected but optional services
* like the PeerManager may replace this authenticator with one that intercepts certain types
* of authentication and then passes normal authentications through. */
@Inject(optional=true) protected Authenticator _author = new DummyAuthenticator();
protected int[] _ports, _datagramPorts;
protected Selector _selector;
protected ServerSocketChannel _ssocket;
protected DatagramChannel _datagramChannel;
protected ResultListener<Object> _startlist;
/** Counts consecutive runtime errors in select(). */
protected int _runtimeExceptionCount;
/** Maps selection keys to network event handlers. */
protected Map<SelectionKey, NetEventHandler> _handlers = Maps.newHashMap();
/** Connections mapped by identifier. */
protected IntMap<Connection> _connections = IntMaps.newHashIntMap();
protected Queue<Connection> _deathq = new Queue<Connection>();
protected Queue<AuthingConnection> _authq = new Queue<AuthingConnection>();
protected Queue<Tuple<Connection, byte[]>> _outq = new Queue<Tuple<Connection, byte[]>>();
protected Queue<Tuple<Connection, byte[]>> _dataq = new Queue<Tuple<Connection, byte[]>>();
protected FramingOutputStream _framer;
protected ByteArrayOutputStream _flattener;
protected ByteBuffer _outbuf = ByteBuffer.allocateDirect(64 * 1024);
protected ByteBuffer _databuf = ByteBuffer.allocateDirect(Client.MAX_DATAGRAM_SIZE);
protected Map<Connection, OverflowQueue> _oflowqs = Maps.newHashMap();
protected List<ConnectionObserver> _observers = Lists.newArrayList();
/** Bytes in and out in the last reporting period. */
protected long _bytesIn, _bytesOut;
/** Messages read and written in the last reporting period. */
protected int _msgsIn, _msgsOut;
/** Our current runtime stats. */
protected ConMgrStats _stats;
/** A snapshot of our runtime stats as of our last report. */
protected ConMgrStats _lastStats;
/** A runnable to execute when the connection manager thread exits. */
protected volatile Runnable _onExit;
/** The invoker on which we do our authenticating. */
@Inject @AuthInvoker protected Invoker _authInvoker;
/** The distributed object manager with which we operate. */
@Inject protected PresentsDObjectMgr _omgr;
/** How long we wait for network events before checking our running flag to see if we should
* still be running. We don't want to loop too tightly, but we need to make sure we don't sit
* around listening for incoming network events too long when there are outgoing messages in
* the queue. */
protected static final int SELECT_LOOP_TIME = 100;
// codes for notifyObservers()
protected static final int CONNECTION_ESTABLISHED = 0;
protected static final int CONNECTION_FAILED = 1;
protected static final int CONNECTION_CLOSED = 2;
}
| true | true | protected void iterate ()
{
long iterStamp = System.currentTimeMillis();
// close any connections that have been queued up to die
Connection dconn;
while ((dconn = _deathq.getNonBlocking()) != null) {
// it's possible that we caught an EOF trying to read from this connection even after
// it was queued up for death, so let's avoid trying to close it twice
if (!dconn.isClosed()) {
dconn.close();
}
}
// close connections that have had no network traffic for too long
for (NetEventHandler handler : _handlers.values()) {
if (handler.checkIdle(iterStamp)) {
// this will queue the connection for closure on our next tick
closeConnection((Connection)handler);
}
}
// send any messages that are waiting on the outgoing overflow and message queues
sendOutgoingMessages(iterStamp);
// if we have been shutdown, but we're stick around because the DObjectManager is still
// running (and we want to deliver any outgoing events queued up during shutdown), then we
// stop here, because we've delivered outgoing events on this tick and all that remains
// below is accepting new connections and receiving incoming messages, neither of which we
// want to do during the shutdown process
if (!super.isRunning()) {
return;
}
// check for connections that have completed authentication
AuthingConnection conn;
while ((conn = _authq.getNonBlocking()) != null) {
try {
// construct a new running connection to handle this connections network traffic
// from here on out
SelectionKey selkey = conn.getSelectionKey();
RunningConnection rconn = new RunningConnection(
this, selkey, conn.getChannel(), iterStamp);
// we need to keep using the same object input and output streams from the
// beginning of the session because they have context that needs to be preserved
rconn.inheritStreams(conn);
// replace the mapping in the handlers table from the old conn with the new one
_handlers.put(selkey, rconn);
// add a mapping for the connection id and set the datagram secret
_connections.put(rconn.getConnectionId(), rconn);
rconn.setDatagramSecret(
conn.getAuthRequest().getCredentials().getDatagramSecret());
// transfer any overflow queue for that connection
OverflowQueue oflowHandler = _oflowqs.remove(conn);
if (oflowHandler != null) {
_oflowqs.put(rconn, oflowHandler);
}
// and let our observers know about our new connection
notifyObservers(CONNECTION_ESTABLISHED, rconn,
conn.getAuthRequest(), conn.getAuthResponse());
} catch (IOException ioe) {
log.warning("Failure upgrading authing connection to running.", ioe);
}
}
Set<SelectionKey> ready = null;
try {
// check for incoming network events
// log.debug("Selecting from " + StringUtil.toString(_selector.keys()) + " (" +
// SELECT_LOOP_TIME + ").");
int ecount = _selector.select(SELECT_LOOP_TIME);
ready = _selector.selectedKeys();
if (ecount == 0) {
if (ready.size() == 0) {
return;
} else {
log.warning("select() returned no selected sockets, but there are " +
ready.size() + " in the ready set.");
}
}
} catch (IOException ioe) {
if ("Invalid argument".equals(ioe.getMessage())) {
// what is this, anyway?
log.warning("Failure select()ing.", ioe);
} else {
log.warning("Failure select()ing [ioe=" + ioe + "].");
}
return;
} catch (RuntimeException re) {
// this block of code deals with a bug in the _selector that we observed on 2005-05-02,
// instead of looping indefinitely after things go pear-shaped, shut us down in an
// orderly fashion
log.warning("Failure select()ing.", re);
if (_runtimeExceptionCount++ >= 20) {
log.warning("Too many errors, bailing.");
shutdown();
}
return;
}
// clear the runtime error count
_runtimeExceptionCount = 0;
// process those events
// log.info("Ready set " + StringUtil.toString(ready) + ".");
for (SelectionKey selkey : ready) {
NetEventHandler handler = null;
try {
handler = _handlers.get(selkey);
if (handler == null) {
log.warning("Received network event but have no registered handler " +
"[selkey=" + selkey + "].");
// request that this key be removed from our selection set, which normally
// happens automatically but for some reason didn't
selkey.cancel();
continue;
}
// log.info("Got event [selkey=" + selkey + ", handler=" + handler + "].");
int got = handler.handleEvent(iterStamp);
if (got != 0) {
synchronized (this) {
_bytesIn += got;
_stats.bytesIn += got;
// we know that the handlers only report having read bytes when they have a
// whole message, so we can count thusly
_msgsIn++;
_stats.msgsIn++;
}
}
} catch (Exception e) {
log.warning("Error processing network data: " + handler + ".", e);
// if you freak out here, you go straight in the can
if (handler != null && handler instanceof Connection) {
closeConnection((Connection)handler);
}
}
}
ready.clear();
}
| protected void iterate ()
{
long iterStamp = System.currentTimeMillis();
// close any connections that have been queued up to die
Connection dconn;
while ((dconn = _deathq.getNonBlocking()) != null) {
// it's possible that we caught an EOF trying to read from this connection even after
// it was queued up for death, so let's avoid trying to close it twice
if (!dconn.isClosed()) {
dconn.close();
}
}
// close connections that have had no network traffic for too long
for (NetEventHandler handler : _handlers.values()) {
if (handler.checkIdle(iterStamp)) {
// this will queue the connection for closure on our next tick
closeConnection((Connection)handler);
}
}
// send any messages that are waiting on the outgoing overflow and message queues
sendOutgoingMessages(iterStamp);
// if we have been shutdown, but we're still around because the DObjectManager is still
// running (and we want to deliver any outgoing events queued up during shutdown), then we
// stop here, because we've delivered outgoing events on this tick and all that remains
// below is accepting new connections and receiving incoming messages, neither of which we
// want to do during the shutdown process
if (!super.isRunning()) {
return;
}
// check for connections that have completed authentication
AuthingConnection conn;
while ((conn = _authq.getNonBlocking()) != null) {
try {
// construct a new running connection to handle this connections network traffic
// from here on out
SelectionKey selkey = conn.getSelectionKey();
RunningConnection rconn = new RunningConnection(
this, selkey, conn.getChannel(), iterStamp);
// we need to keep using the same object input and output streams from the
// beginning of the session because they have context that needs to be preserved
rconn.inheritStreams(conn);
// replace the mapping in the handlers table from the old conn with the new one
_handlers.put(selkey, rconn);
// add a mapping for the connection id and set the datagram secret
_connections.put(rconn.getConnectionId(), rconn);
rconn.setDatagramSecret(
conn.getAuthRequest().getCredentials().getDatagramSecret());
// transfer any overflow queue for that connection
OverflowQueue oflowHandler = _oflowqs.remove(conn);
if (oflowHandler != null) {
_oflowqs.put(rconn, oflowHandler);
}
// and let our observers know about our new connection
notifyObservers(CONNECTION_ESTABLISHED, rconn,
conn.getAuthRequest(), conn.getAuthResponse());
} catch (IOException ioe) {
log.warning("Failure upgrading authing connection to running.", ioe);
}
}
Set<SelectionKey> ready = null;
try {
// check for incoming network events
// log.debug("Selecting from " + StringUtil.toString(_selector.keys()) + " (" +
// SELECT_LOOP_TIME + ").");
int ecount = _selector.select(SELECT_LOOP_TIME);
ready = _selector.selectedKeys();
if (ecount == 0) {
if (ready.size() == 0) {
return;
} else {
log.warning("select() returned no selected sockets, but there are " +
ready.size() + " in the ready set.");
}
}
} catch (IOException ioe) {
if ("Invalid argument".equals(ioe.getMessage())) {
// what is this, anyway?
log.warning("Failure select()ing.", ioe);
} else {
log.warning("Failure select()ing [ioe=" + ioe + "].");
}
return;
} catch (RuntimeException re) {
// this block of code deals with a bug in the _selector that we observed on 2005-05-02,
// instead of looping indefinitely after things go pear-shaped, shut us down in an
// orderly fashion
log.warning("Failure select()ing.", re);
if (_runtimeExceptionCount++ >= 20) {
log.warning("Too many errors, bailing.");
shutdown();
}
return;
}
// clear the runtime error count
_runtimeExceptionCount = 0;
// process those events
// log.info("Ready set " + StringUtil.toString(ready) + ".");
for (SelectionKey selkey : ready) {
NetEventHandler handler = null;
try {
handler = _handlers.get(selkey);
if (handler == null) {
log.warning("Received network event but have no registered handler " +
"[selkey=" + selkey + "].");
// request that this key be removed from our selection set, which normally
// happens automatically but for some reason didn't
selkey.cancel();
continue;
}
// log.info("Got event [selkey=" + selkey + ", handler=" + handler + "].");
int got = handler.handleEvent(iterStamp);
if (got != 0) {
synchronized (this) {
_bytesIn += got;
_stats.bytesIn += got;
// we know that the handlers only report having read bytes when they have a
// whole message, so we can count thusly
_msgsIn++;
_stats.msgsIn++;
}
}
} catch (Exception e) {
log.warning("Error processing network data: " + handler + ".", e);
// if you freak out here, you go straight in the can
if (handler != null && handler instanceof Connection) {
closeConnection((Connection)handler);
}
}
}
ready.clear();
}
|
diff --git a/java/src/eu/semaine/components/dialogue/interpreters/TurnTakingInterpreter.java b/java/src/eu/semaine/components/dialogue/interpreters/TurnTakingInterpreter.java
index 95bfa30c..c99ff0e8 100644
--- a/java/src/eu/semaine/components/dialogue/interpreters/TurnTakingInterpreter.java
+++ b/java/src/eu/semaine/components/dialogue/interpreters/TurnTakingInterpreter.java
@@ -1,506 +1,508 @@
/**
* Copyright (C) 2009 University of Twente. All rights reserved.
* Use is subject to license terms -- see license.txt.
*/
package eu.semaine.components.dialogue.interpreters;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import javax.jms.JMSException;
import eu.semaine.components.Component;
import eu.semaine.components.dialogue.datastructures.DMProperties;
import eu.semaine.components.dialogue.datastructures.EmotionEvent;
import eu.semaine.components.dialogue.test.DMLogger;
import eu.semaine.datatypes.stateinfo.AgentStateInfo;
import eu.semaine.datatypes.stateinfo.DialogStateInfo;
import eu.semaine.datatypes.stateinfo.StateInfo;
import eu.semaine.jms.message.SEMAINEMessage;
import eu.semaine.jms.message.SEMAINEStateMessage;
import eu.semaine.jms.receiver.StateReceiver;
import eu.semaine.jms.sender.StateSender;
import eu.semaine.system.CharacterConfigInfo;
/**
* The TurnTakingInterpreter looks at the behaviour of the user and has to decide when is
* a good moment to start speaking. When this moment is decided the decision is send forward.
*
* Input
* UserStateReceiver('semaine.data.state.user') --> user speaking state and detected emotions
* AgentStateReceiver('semaine.data.state.agent') --> current character
*
* Output
* AgentStateSender('semaine.data.state.agent') --> take/release turn messages
*
* @author MaatM
*
*/
public class TurnTakingInterpreter extends Component
{
/* The four characters */
public final static int POPPY = 1;
public final static int PRUDENCE = 2;
public final static int SPIKE = 3;
public final static int OBADIAH = 4;
/* Possible turn states */
private final static int WAITING = 0;
private final static int SILENT = 1;
private final static int SPEAKING = 2;
private HashMap<String,Integer> charNumbers = new HashMap<String,Integer>();
/* Take/release turn threshold */
private static int POPPY_TT_THRESHOLD; // = 60;
private static int PRUDENCE_TT_THRESHOLD; // = 80;
private static int SPIKE_TT_THRESHOLD; // = 30;
private static int OBADIAH_TT_THRESHOLD; // = 100;
private int curr_TT_Threshold = 100;
private static int EXPECTING_ANSWER_TIMEOUT = 8000;
private String convState = "listening";
/* Senders and Receivers */
private StateReceiver userStateReceiver;
private StateReceiver agentStateReceiver;
private StateReceiver dialogStateReceiver;
private StateReceiver contextReceiver;
private StateSender agentStateSender;
private StateSender dialogStateSender;
/* Turn state of speaker */
private int userSpeakingState = 0; // 0 = unknown, 1 = silence, 2 = speaking
private long userSpeakingStateTime = 0;
private long latestUtteranceLength = 0;
/* Turn state of Agent */
private int agentSpeakingState = 1; // 1 = silence, 2 = speaking
private long agentSpeakingStateTime = 0;
private int agentSpeakingIntention = 0; // 1 = silence, 2 = speaking
private long agentSpeakingIntentionTime = 0;
/* The current character*/
private static final String USER = "user";
private int character;
/* List of detected emotion events (generated by the EmotionInterpreter) */
private ArrayList<EmotionEvent> detectedEmotions = new ArrayList<EmotionEvent>();
private int recentEmotionCounter = 0;
private int index = 0;
/* If a backchannel was given this silence */
private boolean backchannel_given = false;
/* Most recent detected words */
private String currentDetectedKeywords = "";
private long previousMetaTime;
/**
* Constructor of TurnTakingInterpreter
* Initializes the senders and receivers, and sets the waitingtime for Act()
* @throws JMSException
*/
public TurnTakingInterpreter() throws JMSException
{
super("TurnTakingInterpreter");
charNumbers.put("poppy", POPPY);
charNumbers.put("prudence", PRUDENCE);
charNumbers.put("spike", SPIKE);
charNumbers.put("obadiah", OBADIAH);
waitingTime = 50;
previousMetaTime = meta.getTime();
userStateReceiver = new StateReceiver( "semaine.data.state.user.behaviour", StateInfo.Type.UserState);
receivers.add( userStateReceiver );
agentStateReceiver = new StateReceiver( "semaine.data.state.agent", StateInfo.Type.AgentState);
receivers.add( agentStateReceiver );
dialogStateReceiver = new StateReceiver( "semaine.data.state.dialog", StateInfo.Type.DialogState);
receivers.add( dialogStateReceiver );
contextReceiver = new StateReceiver("semaine.data.state.context", StateInfo.Type.ContextState);
receivers.add( contextReceiver );
agentStateSender = new StateSender( "semaine.data.state.agent", StateInfo.Type.AgentState, getName() );
senders.add( agentStateSender );
dialogStateSender = new StateSender("semaine.data.state.dialog", StateInfo.Type.DialogState, getName());
senders.add(dialogStateSender);
POPPY_TT_THRESHOLD = Integer.parseInt(CharacterConfigInfo.getInfo("Poppy").getSetting("TurnTakingThreshold"));
PRUDENCE_TT_THRESHOLD = Integer.parseInt(CharacterConfigInfo.getInfo("Prudence").getSetting("TurnTakingThreshold"));
SPIKE_TT_THRESHOLD = Integer.parseInt(CharacterConfigInfo.getInfo("Spike").getSetting("TurnTakingThreshold"));
OBADIAH_TT_THRESHOLD = Integer.parseInt(CharacterConfigInfo.getInfo("Obadiah").getSetting("TurnTakingThreshold"));
}
/**
* Reads the message, filters out the detected user speaking state and the detected emotions,
* and tries to determine if the agent should start speaking.
*/
public void react( SEMAINEMessage m ) throws JMSException
{
if (m instanceof SEMAINEStateMessage) {
SEMAINEStateMessage sm = (SEMAINEStateMessage) m;
StateInfo stateInfo = sm.getState();
StateInfo.Type stateInfoType = stateInfo.getType();
switch (stateInfoType) {
case UserState:
/* Update current detected words */
if( stateInfo.hasInfo("userUtterance") ) {
currentDetectedKeywords = stateInfo.getInfo("userUtterance");
}
/* Updates user speaking state (speaking or silent) */
setUserSpeakingState(stateInfo);
/* Updates detected emotions (valence, arousal, interest) */
addDetectedEmotions(stateInfo);
processHeadMovements( stateInfo );
/* called to determine the turn state of the agent */
determineAgentTurn();
break;
case DialogState:
/* Processes Dialog state updates */
/* updates agent speaking state */
setAgentSpeakingState(stateInfo);
if( stateInfo.hasInfo("agentTurnState") ) {
convState = stateInfo.getInfo("agentTurnState");
}
break;
case AgentState:
/* Processes Agent state changes */
/* processes an agent backchannel */
processBackchannel(stateInfo);
break;
case ContextState:
setCharacter( stateInfo );
break;
default:
// We could complain here if we were certain we don't expect other state infos, as in:
// throw new MessageFormatException("Unexpected state info type: "+stateInfo.getType().toString());
}
}
}
public void processHeadMovements( StateInfo stateInfo ) throws JMSException
{
if( stateInfo.hasInfo("headGesture") && stateInfo.hasInfo("headGestureStarted") && stateInfo.hasInfo("headGestureStopped") ) {
DMLogger.getLogger().log(meta.getTime(), "UserAction:HeadMovement type=" + stateInfo.getInfo("headGesture") );
if( stateInfo.getInfo("headGesture").equals("NOD") ) {
userSpeakingState = SILENT;
userSpeakingStateTime = meta.getTime();
} else if( stateInfo.getInfo("headGesture").equals("SHAKE") ) {
userSpeakingState = SILENT;
userSpeakingStateTime = meta.getTime();
}
}
}
public void updateCharacter( StateInfo stateInfo ) throws JMSException
{
if( stateInfo.hasInfo("character") ) {
character = charNumbers.get( stateInfo.getInfo("character") );
}
}
/**
* Called every 50ms, reevaluates the current situation and tries to determine if the agent
* should start talking.
*/
public void act() throws JMSException
{
determineAgentTurn();
// Determine if timeout of ExpectingAnswer is reached.
if( agentSpeakingState == WAITING && agentSpeakingStateTime + EXPECTING_ANSWER_TIMEOUT < meta.getTime() ) {
Map<String,String> info = new HashMap<String,String>();
info.put("agentTurnState","listening");
DialogStateInfo dsi = new DialogStateInfo(info, null);
dialogStateSender.sendStateInfo(dsi, meta.getTime());
}
}
/**
* Reads the received Message and tries to filter out the detected user speaking state.
* @param m - the received message
*/
public void setAgentSpeakingState(StateInfo dialogInfo)
{
if( dialogInfo.hasInfo("agentTurnState") ) {
if( dialogInfo.getInfo("agentTurnState").equals("speaking") ) {
backchannel_given = false;
agentSpeakingState = SPEAKING;
agentSpeakingStateTime = meta.getTime();
detectedEmotions.clear();
recentEmotionCounter = 0;
} else if( dialogInfo.getInfo("agentTurnState").equals("listening") ) {
backchannel_given = false;
agentSpeakingState = SILENT;
agentSpeakingStateTime = meta.getTime();
if( userSpeakingState == SILENT ) {
userSpeakingState = WAITING;
userSpeakingStateTime = meta.getTime();
} else if( userSpeakingState == WAITING ) {
userSpeakingStateTime = meta.getTime();
}
} else if( dialogInfo.getInfo("agentTurnState").equals("expectingAnswer") ) {
backchannel_given = false;
agentSpeakingState = WAITING;
agentSpeakingStateTime = meta.getTime();
if( userSpeakingState == SILENT ) {
userSpeakingState = WAITING;
userSpeakingStateTime = meta.getTime();
} else if( userSpeakingState == WAITING ) {
userSpeakingStateTime = meta.getTime();
}
}
}
}
/**
* Reads the received Message and tries to filter out the detected user speaking state.
* @param m - the received message
*/
public void setUserSpeakingState(StateInfo userInfo)
{
if( userInfo.hasInfo("speaking") ) {
if( userInfo.getInfo("speaking").equals("true") ) {
if( userSpeakingState != SPEAKING ) {
DMLogger.getLogger().log(meta.getTime(), "UserAction:UserStartedSpeaking" );
System.out.println("Detected user speaking");
backchannel_given = false;
userSpeakingState = SPEAKING;
userSpeakingStateTime = meta.getTime();
}
} else if( userInfo.getInfo("speaking").equals("false") ) {
if( userSpeakingState != SILENT ) {
DMLogger.getLogger().log(meta.getTime(), "UserAction:UserStoppedSpeaking words=" + currentDetectedKeywords );
System.out.println("Detected user silent");
latestUtteranceLength = meta.getTime() - userSpeakingStateTime;
userSpeakingState = SILENT;
userSpeakingStateTime = meta.getTime();
}
}
}
}
/**
* Reads the received Message and tries to filter out a change of character
* @param am - the received message
*/
public void setCharacter(StateInfo agentInfo)
{
Map<String,String> agentInfoMap = agentInfo.getInfos();
String newChar = agentInfoMap.get( "character" );
if( newChar != null ) {
newChar = newChar.toLowerCase();
if( newChar.equals("poppy") ) {
character = POPPY;
curr_TT_Threshold = POPPY_TT_THRESHOLD;
} else if( newChar.equals("prudence") ) {
character = PRUDENCE;
curr_TT_Threshold = PRUDENCE_TT_THRESHOLD;
} else if( newChar.equals("spike") ) {
character = SPIKE;
curr_TT_Threshold = SPIKE_TT_THRESHOLD;
} else if( newChar.equals("obadiah") ) {
character = OBADIAH;
curr_TT_Threshold = OBADIAH_TT_THRESHOLD;
} else {
}
} else {
}
}
public void processBackchannel(StateInfo agentInfo)
{
// TODO: To Fix
Map<String,String> agentInfoMap = agentInfo.getInfos();
String intention = agentInfoMap.get( "turnTakingIntention" );
if( intention != null && intention.equals("backchannel") ) {
backchannel_given = true;
}
}
/**
* Reads the received Message and tries to filter out the detected Emotion Events.
* @param m - the received message
*/
public void addDetectedEmotions(StateInfo userInfo)
{
if( userInfo.hasInfo("valence") ) {
float valence = Float.parseFloat( userInfo.getInfo("valence") );
EmotionEvent ee = new EmotionEvent( meta.getTime(), 0, EmotionEvent.VALENCE, valence );
if( detectedEmotions.size() == 0 || meta.getTime() - detectedEmotions.get(detectedEmotions.size()-1).getTime() > 500 ) {
recentEmotionCounter++;
}
detectedEmotions.add( ee );
}
if( userInfo.hasInfo("arousal") ) {
float arousal = Float.parseFloat( userInfo.getInfo("arousal") );
EmotionEvent ee = new EmotionEvent( meta.getTime(), 0, EmotionEvent.AROUSAL, arousal );
if( detectedEmotions.size() == 0 || meta.getTime() - detectedEmotions.get(detectedEmotions.size()-1).getTime() > 500 ) {
recentEmotionCounter++;
}
detectedEmotions.add( ee );
}
if( userInfo.hasInfo("interest") ) {
float interest = Float.parseFloat( userInfo.getInfo("interest") );
EmotionEvent ee = new EmotionEvent( meta.getTime(), 0, EmotionEvent.INTEREST, interest );
if( detectedEmotions.size() == 0 || meta.getTime() - detectedEmotions.get(detectedEmotions.size()-1).getTime() > 500 ) {
recentEmotionCounter++;
}
detectedEmotions.add( ee );
}
}
/**
* Determines if the agent should start speaking or not. It bases this decision
* on the speaking_intention, a value for how much the agent wants the turn.
*/
public void determineAgentTurn() throws JMSException
{
int speakingIntention = getSpeakingIntentionValue();
if( speakingIntention >= curr_TT_Threshold && agentSpeakingIntention != SPEAKING && (agentSpeakingState == SILENT || agentSpeakingState == WAITING) ) {
agentSpeakingIntention = SPEAKING;
agentSpeakingIntentionTime = meta.getTime();
sendAgentTurnState();
} else if( speakingIntention < curr_TT_Threshold && agentSpeakingIntention != SILENT ) {
agentSpeakingIntention = SILENT;
agentSpeakingIntentionTime = meta.getTime();
sendAgentTurnState();
}
}
/**
* Calculates the speaking intention value for the current moment.
* This is a value for how much the agent wants the turn.
* This is calculated based on detected emotion events, the user speaking state,
* the duration of this state, and the agent speaking state plus its duration.
* The higher the value, the higher the intention to speak.
*
* Currently, the speaking intention value is the sum of these values:
* user_silence_time_value: a value between 0 and 100 which is higher when the user is silent for a longer time (max is reached after 0.8 seconds).
* emotion_value: a value based on the number of detected emotion events. More detected events lead to a higher value.
* agent_silence_time_value: a value that's higher when the agent is silent (user is speaking) for a longer period (max is reached after 30 seconds).
* agent_end_wait_value: a value that starts at -100 when the agent finishes its utterance, and in the next 2 seconds slowly rises (linear) to 0;
* user_not_responding_value: a value that rises from 0 to 100 when the user does not start talking after an agent-turn. It starts after 2 seconds, and then rises to 100 in 4 seconds unless the user starts speaking.
* @return
*/
public int getSpeakingIntentionValue()
{
if( meta.getTime() < previousMetaTime ) {
/* System clock reset */
userSpeakingStateTime = meta.getTime();
agentSpeakingStateTime = meta.getTime();
}
previousMetaTime = meta.getTime();
int speakingIntention = 0;
/* The components of the speaking intention value */
int user_silence_time_value = 0;
int emotion_value = 0;
int agent_silence_time_value = 0;
int agent_end_wait_value = 0;
int user_not_responding_value = 0;
/* silence_time_value */
if( userSpeakingState == SILENT ) {
double time = ((double)meta.getTime() - (double)userSpeakingStateTime)/1000;
if( backchannel_given ) {
time = time - 1;
}
//double value = Math.max( Math.min( -(Math.sqrt(time))+1, 100 ), 0 );
double value;
if( time >= 0 ) {
+ //System.out.println("time: "+time);
double a = 100;
double b1 = 10;
double r;
if( convState.equals("listening") ) {
r = 2;
} else {
r = 0.7;
}
double b = (b1/r);
value = a /(1+Math.exp(-b*(time-(r/2))));
//value = Math.max( Math.min( Math.pow(time+0.3,2), 1 ), 0 );
} else {
value = 0;
}
- user_silence_time_value = (int)(value * 100);
+ user_silence_time_value = (int)(value);
+ //user_silence_time_value = (int)(value * 100);
}
/* emotion_value */
emotion_value = Math.min( recentEmotionCounter*10, 30 );
/* time_turn_value */
if( agentSpeakingState == SILENT || agentSpeakingState == WAITING ) {
double time = ((double)meta.getTime() - (double)agentSpeakingStateTime)/1000;
double value = Math.min( (4/3)*time, 30 );
agent_silence_time_value = (int)(value);
}
/* agent_end_wait_value */
long agentSpeakingTime = meta.getTime() - agentSpeakingStateTime;
long userSpeakingTime = meta.getTime() - userSpeakingStateTime;
if( (agentSpeakingState == SILENT || agentSpeakingState == WAITING) && agentSpeakingTime < 1000 ) {
agent_end_wait_value = ((int)(0.05*agentSpeakingTime - 100));
}
/* user_not_responding_value */
//System.out.println("Agent:" + agentSpeakingState + ", User:" + userSpeakingState + ", userSpeakingTime: " + userSpeakingTime + ", agentSpeakingTime: " + agentSpeakingTime );
if( (agentSpeakingState == SILENT || agentSpeakingState == WAITING ) && userSpeakingState == WAITING && Math.abs(agentSpeakingTime - userSpeakingTime) < 30 ) {
if( userSpeakingTime < 2000 ) {
// Do nothing
} else if( userSpeakingTime > 6000 ) {
user_not_responding_value = 100;
} else {
user_not_responding_value = ((int)(0.025*(agentSpeakingTime-2000)));
}
}
/* Calculating the speaking intention value */
speakingIntention = user_silence_time_value + emotion_value + agent_silence_time_value + agent_end_wait_value + user_not_responding_value;
//System.out.println( speakingIntention + " = " + user_silence_time_value + " + " + emotion_value + " + " + agent_silence_time_value + " + " + agent_end_wait_value + " + " + user_not_responding_value + " : currTime: " + meta.getTime() );
DMLogger.getLogger().log(meta.getTime(), speakingIntention + " = " + user_silence_time_value + " + " + emotion_value + " + " + agent_silence_time_value + " + " + agent_end_wait_value + " + " + user_not_responding_value);
return speakingIntention;
}
public void sendAgentTurnState() throws JMSException
{
Map<String,String> agentStateInfo = new HashMap<String,String>();
if( agentSpeakingIntention == SPEAKING ) {
agentStateInfo.put("turnTakingIntention", "startSpeaking");
DMLogger.getLogger().log(meta.getTime(), "TurnTakingIntention:StartSpeaking");
} else if( agentSpeakingIntention == SILENT ) {
agentStateInfo.put("turnTakingIntention", "stopSpeaking");
DMLogger.getLogger().log(meta.getTime(), "TurnTakingIntention:StartSpeaking");
} else {
return;
}
AgentStateInfo asi = new AgentStateInfo( agentStateInfo );
agentStateSender.sendStateInfo(asi, meta.getTime());
}
}
| false | true | public int getSpeakingIntentionValue()
{
if( meta.getTime() < previousMetaTime ) {
/* System clock reset */
userSpeakingStateTime = meta.getTime();
agentSpeakingStateTime = meta.getTime();
}
previousMetaTime = meta.getTime();
int speakingIntention = 0;
/* The components of the speaking intention value */
int user_silence_time_value = 0;
int emotion_value = 0;
int agent_silence_time_value = 0;
int agent_end_wait_value = 0;
int user_not_responding_value = 0;
/* silence_time_value */
if( userSpeakingState == SILENT ) {
double time = ((double)meta.getTime() - (double)userSpeakingStateTime)/1000;
if( backchannel_given ) {
time = time - 1;
}
//double value = Math.max( Math.min( -(Math.sqrt(time))+1, 100 ), 0 );
double value;
if( time >= 0 ) {
double a = 100;
double b1 = 10;
double r;
if( convState.equals("listening") ) {
r = 2;
} else {
r = 0.7;
}
double b = (b1/r);
value = a /(1+Math.exp(-b*(time-(r/2))));
//value = Math.max( Math.min( Math.pow(time+0.3,2), 1 ), 0 );
} else {
value = 0;
}
user_silence_time_value = (int)(value * 100);
}
/* emotion_value */
emotion_value = Math.min( recentEmotionCounter*10, 30 );
/* time_turn_value */
if( agentSpeakingState == SILENT || agentSpeakingState == WAITING ) {
double time = ((double)meta.getTime() - (double)agentSpeakingStateTime)/1000;
double value = Math.min( (4/3)*time, 30 );
agent_silence_time_value = (int)(value);
}
/* agent_end_wait_value */
long agentSpeakingTime = meta.getTime() - agentSpeakingStateTime;
long userSpeakingTime = meta.getTime() - userSpeakingStateTime;
if( (agentSpeakingState == SILENT || agentSpeakingState == WAITING) && agentSpeakingTime < 1000 ) {
agent_end_wait_value = ((int)(0.05*agentSpeakingTime - 100));
}
/* user_not_responding_value */
//System.out.println("Agent:" + agentSpeakingState + ", User:" + userSpeakingState + ", userSpeakingTime: " + userSpeakingTime + ", agentSpeakingTime: " + agentSpeakingTime );
if( (agentSpeakingState == SILENT || agentSpeakingState == WAITING ) && userSpeakingState == WAITING && Math.abs(agentSpeakingTime - userSpeakingTime) < 30 ) {
if( userSpeakingTime < 2000 ) {
// Do nothing
} else if( userSpeakingTime > 6000 ) {
user_not_responding_value = 100;
} else {
user_not_responding_value = ((int)(0.025*(agentSpeakingTime-2000)));
}
}
/* Calculating the speaking intention value */
speakingIntention = user_silence_time_value + emotion_value + agent_silence_time_value + agent_end_wait_value + user_not_responding_value;
//System.out.println( speakingIntention + " = " + user_silence_time_value + " + " + emotion_value + " + " + agent_silence_time_value + " + " + agent_end_wait_value + " + " + user_not_responding_value + " : currTime: " + meta.getTime() );
DMLogger.getLogger().log(meta.getTime(), speakingIntention + " = " + user_silence_time_value + " + " + emotion_value + " + " + agent_silence_time_value + " + " + agent_end_wait_value + " + " + user_not_responding_value);
return speakingIntention;
}
| public int getSpeakingIntentionValue()
{
if( meta.getTime() < previousMetaTime ) {
/* System clock reset */
userSpeakingStateTime = meta.getTime();
agentSpeakingStateTime = meta.getTime();
}
previousMetaTime = meta.getTime();
int speakingIntention = 0;
/* The components of the speaking intention value */
int user_silence_time_value = 0;
int emotion_value = 0;
int agent_silence_time_value = 0;
int agent_end_wait_value = 0;
int user_not_responding_value = 0;
/* silence_time_value */
if( userSpeakingState == SILENT ) {
double time = ((double)meta.getTime() - (double)userSpeakingStateTime)/1000;
if( backchannel_given ) {
time = time - 1;
}
//double value = Math.max( Math.min( -(Math.sqrt(time))+1, 100 ), 0 );
double value;
if( time >= 0 ) {
//System.out.println("time: "+time);
double a = 100;
double b1 = 10;
double r;
if( convState.equals("listening") ) {
r = 2;
} else {
r = 0.7;
}
double b = (b1/r);
value = a /(1+Math.exp(-b*(time-(r/2))));
//value = Math.max( Math.min( Math.pow(time+0.3,2), 1 ), 0 );
} else {
value = 0;
}
user_silence_time_value = (int)(value);
//user_silence_time_value = (int)(value * 100);
}
/* emotion_value */
emotion_value = Math.min( recentEmotionCounter*10, 30 );
/* time_turn_value */
if( agentSpeakingState == SILENT || agentSpeakingState == WAITING ) {
double time = ((double)meta.getTime() - (double)agentSpeakingStateTime)/1000;
double value = Math.min( (4/3)*time, 30 );
agent_silence_time_value = (int)(value);
}
/* agent_end_wait_value */
long agentSpeakingTime = meta.getTime() - agentSpeakingStateTime;
long userSpeakingTime = meta.getTime() - userSpeakingStateTime;
if( (agentSpeakingState == SILENT || agentSpeakingState == WAITING) && agentSpeakingTime < 1000 ) {
agent_end_wait_value = ((int)(0.05*agentSpeakingTime - 100));
}
/* user_not_responding_value */
//System.out.println("Agent:" + agentSpeakingState + ", User:" + userSpeakingState + ", userSpeakingTime: " + userSpeakingTime + ", agentSpeakingTime: " + agentSpeakingTime );
if( (agentSpeakingState == SILENT || agentSpeakingState == WAITING ) && userSpeakingState == WAITING && Math.abs(agentSpeakingTime - userSpeakingTime) < 30 ) {
if( userSpeakingTime < 2000 ) {
// Do nothing
} else if( userSpeakingTime > 6000 ) {
user_not_responding_value = 100;
} else {
user_not_responding_value = ((int)(0.025*(agentSpeakingTime-2000)));
}
}
/* Calculating the speaking intention value */
speakingIntention = user_silence_time_value + emotion_value + agent_silence_time_value + agent_end_wait_value + user_not_responding_value;
//System.out.println( speakingIntention + " = " + user_silence_time_value + " + " + emotion_value + " + " + agent_silence_time_value + " + " + agent_end_wait_value + " + " + user_not_responding_value + " : currTime: " + meta.getTime() );
DMLogger.getLogger().log(meta.getTime(), speakingIntention + " = " + user_silence_time_value + " + " + emotion_value + " + " + agent_silence_time_value + " + " + agent_end_wait_value + " + " + user_not_responding_value);
return speakingIntention;
}
|
diff --git a/src/main/java/com/github/kpacha/jkata/tennis/Tennis.java b/src/main/java/com/github/kpacha/jkata/tennis/Tennis.java
index 8162593..05ad6ed 100644
--- a/src/main/java/com/github/kpacha/jkata/tennis/Tennis.java
+++ b/src/main/java/com/github/kpacha/jkata/tennis/Tennis.java
@@ -1,27 +1,28 @@
package com.github.kpacha.jkata.tennis;
public class Tennis {
private int playerOneScored = 0;
private int playerTwoScored = 0;
public String getScore() {
- if (playerOneScored == 3 && playerTwoScored == 3)
+ if (playerOneScored == 3 && playerTwoScored == 3
+ || playerOneScored == 4 && playerTwoScored == 4)
return "Deuce";
if (playerOneScored == 4) {
if (playerTwoScored == 3)
return "Advantage Player 1";
else
return "Player 1 wins";
}
return (15 * playerOneScored) + " - " + (15 * playerTwoScored);
}
public void playerOneScores() {
playerOneScored++;
}
public void playerTwoScores() {
playerTwoScored++;
}
}
| true | true | public String getScore() {
if (playerOneScored == 3 && playerTwoScored == 3)
return "Deuce";
if (playerOneScored == 4) {
if (playerTwoScored == 3)
return "Advantage Player 1";
else
return "Player 1 wins";
}
return (15 * playerOneScored) + " - " + (15 * playerTwoScored);
}
| public String getScore() {
if (playerOneScored == 3 && playerTwoScored == 3
|| playerOneScored == 4 && playerTwoScored == 4)
return "Deuce";
if (playerOneScored == 4) {
if (playerTwoScored == 3)
return "Advantage Player 1";
else
return "Player 1 wins";
}
return (15 * playerOneScored) + " - " + (15 * playerTwoScored);
}
|
diff --git a/plugins/org.eclipse.dltk.ruby.debug.ui/src/org/eclipse/dltk/ruby/internal/debug/ui/launchConfigurations/RubyMainLaunchConfigurationTab.java b/plugins/org.eclipse.dltk.ruby.debug.ui/src/org/eclipse/dltk/ruby/internal/debug/ui/launchConfigurations/RubyMainLaunchConfigurationTab.java
index 534d9b1f..b66ea995 100644
--- a/plugins/org.eclipse.dltk.ruby.debug.ui/src/org/eclipse/dltk/ruby/internal/debug/ui/launchConfigurations/RubyMainLaunchConfigurationTab.java
+++ b/plugins/org.eclipse.dltk.ruby.debug.ui/src/org/eclipse/dltk/ruby/internal/debug/ui/launchConfigurations/RubyMainLaunchConfigurationTab.java
@@ -1,39 +1,39 @@
package org.eclipse.dltk.ruby.internal.debug.ui.launchConfigurations;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.dltk.core.DLTKLanguageManager;
import org.eclipse.dltk.core.IDLTKLanguageToolkit;
import org.eclipse.dltk.core.IDLTKProject;
import org.eclipse.dltk.debug.ui.launchConfigurations.MainLaunchConfigurationTab;
import org.eclipse.dltk.ruby.core.RubyLanguageToolkit;
import org.eclipse.dltk.ui.DLTKPluginImages;
import org.eclipse.swt.graphics.Image;
public class RubyMainLaunchConfigurationTab extends MainLaunchConfigurationTab {
protected boolean validateProject(IDLTKProject project) {
if (project == null)
return false;
// check project nature
try {
- IDLTKLanguageToolkit ltk = DLTKLanguageManager.getLangaugeToolkit(project);
+ IDLTKLanguageToolkit ltk = DLTKLanguageManager.getLanguageToolkit(project);
if (ltk instanceof RubyLanguageToolkit)
return true;
} catch (CoreException e) {
}
return false;
}
protected String getLanguageName () {
return "RUBY";
}
/* (non-Javadoc)
* @see org.eclipse.debug.ui.AbstractLaunchConfigurationTab#getImage()
*/
public Image getImage() {
return DLTKPluginImages.get(DLTKPluginImages.IMG_OBJS_CLASS);
}
}
| true | true | protected boolean validateProject(IDLTKProject project) {
if (project == null)
return false;
// check project nature
try {
IDLTKLanguageToolkit ltk = DLTKLanguageManager.getLangaugeToolkit(project);
if (ltk instanceof RubyLanguageToolkit)
return true;
} catch (CoreException e) {
}
return false;
}
| protected boolean validateProject(IDLTKProject project) {
if (project == null)
return false;
// check project nature
try {
IDLTKLanguageToolkit ltk = DLTKLanguageManager.getLanguageToolkit(project);
if (ltk instanceof RubyLanguageToolkit)
return true;
} catch (CoreException e) {
}
return false;
}
|
diff --git a/src/org/geometerplus/android/fbreader/DictionaryUtil.java b/src/org/geometerplus/android/fbreader/DictionaryUtil.java
index 365cf57..b670638 100644
--- a/src/org/geometerplus/android/fbreader/DictionaryUtil.java
+++ b/src/org/geometerplus/android/fbreader/DictionaryUtil.java
@@ -1,75 +1,74 @@
/*
* Copyright (C) 2010 Geometer Plus <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
package org.geometerplus.android.fbreader;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.SearchManager;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import org.geometerplus.zlibrary.core.resources.ZLResource;
import org.geometerplus.android.util.UIUtil;
import org.geometerplus.android.util.PackageUtil;
abstract class DictionaryUtil {
public static Intent getDictionaryIntent(String text) {
return new Intent(Intent.ACTION_SEARCH)
.setComponent(new ComponentName(
"com.socialnmobile.colordict",
"com.socialnmobile.colordict.activity.Main"
))
.putExtra(SearchManager.QUERY, text);
}
public static void installDictionaryIfNotInstalled(final Activity activity) {
if (PackageUtil.canBeStarted(activity, getDictionaryIntent("test"))) {
return;
}
final ZLResource dialogResource = ZLResource.resource("dialog");
final ZLResource buttonResource = dialogResource.getResource("button");
final ZLResource installResource = dialogResource.getResource("installDictionary");
new AlertDialog.Builder(activity)
.setTitle(installResource.getResource("title").getValue())
.setMessage(installResource.getResource("message").getValue().replace("%s", "ColorDict"))
.setIcon(0)
.setPositiveButton(
buttonResource.getResource("install").getValue(),
new DialogInterface.OnClickListener() {
- @Override
public void onClick(DialogInterface dialog, int which) {
installDictionary(activity);
}
}
)
.setNegativeButton(buttonResource.getResource("skip").getValue(), null)
.create().show();
}
private static void installDictionary(Activity activity) {
if (!PackageUtil.installFromMarket(activity, "com.socialnmobile.colordict")) {
UIUtil.showErrorMessage(activity, "cannotRunAndroidMarket", "ColorDict");
}
}
}
| true | true | public static void installDictionaryIfNotInstalled(final Activity activity) {
if (PackageUtil.canBeStarted(activity, getDictionaryIntent("test"))) {
return;
}
final ZLResource dialogResource = ZLResource.resource("dialog");
final ZLResource buttonResource = dialogResource.getResource("button");
final ZLResource installResource = dialogResource.getResource("installDictionary");
new AlertDialog.Builder(activity)
.setTitle(installResource.getResource("title").getValue())
.setMessage(installResource.getResource("message").getValue().replace("%s", "ColorDict"))
.setIcon(0)
.setPositiveButton(
buttonResource.getResource("install").getValue(),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
installDictionary(activity);
}
}
)
.setNegativeButton(buttonResource.getResource("skip").getValue(), null)
.create().show();
}
| public static void installDictionaryIfNotInstalled(final Activity activity) {
if (PackageUtil.canBeStarted(activity, getDictionaryIntent("test"))) {
return;
}
final ZLResource dialogResource = ZLResource.resource("dialog");
final ZLResource buttonResource = dialogResource.getResource("button");
final ZLResource installResource = dialogResource.getResource("installDictionary");
new AlertDialog.Builder(activity)
.setTitle(installResource.getResource("title").getValue())
.setMessage(installResource.getResource("message").getValue().replace("%s", "ColorDict"))
.setIcon(0)
.setPositiveButton(
buttonResource.getResource("install").getValue(),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
installDictionary(activity);
}
}
)
.setNegativeButton(buttonResource.getResource("skip").getValue(), null)
.create().show();
}
|
diff --git a/showcase-webdriver-ftest/src/test/java/org/richfaces/tests/showcase/ftest/webdriver/ftest/richTreeModelRecursiveAdaptor/TestRichTreeModelRecursiveAdaptorSimple.java b/showcase-webdriver-ftest/src/test/java/org/richfaces/tests/showcase/ftest/webdriver/ftest/richTreeModelRecursiveAdaptor/TestRichTreeModelRecursiveAdaptorSimple.java
index d6ae4e4f9..93909e548 100644
--- a/showcase-webdriver-ftest/src/test/java/org/richfaces/tests/showcase/ftest/webdriver/ftest/richTreeModelRecursiveAdaptor/TestRichTreeModelRecursiveAdaptorSimple.java
+++ b/showcase-webdriver-ftest/src/test/java/org/richfaces/tests/showcase/ftest/webdriver/ftest/richTreeModelRecursiveAdaptor/TestRichTreeModelRecursiveAdaptorSimple.java
@@ -1,53 +1,53 @@
/*******************************************************************************
* JBoss, Home of Professional Open Source
* Copyright 2010-2011, Red Hat, Inc. and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*******************************************************************************/
package org.richfaces.tests.showcase.ftest.webdriver.ftest.richTreeModelRecursiveAdaptor;
import static org.testng.Assert.assertEquals;
import org.richfaces.tests.showcase.ftest.webdriver.AbstractWebDriverTest;
import org.richfaces.tests.showcase.ftest.webdriver.page.richTreeModelRecursiveAdaptor.TreeModelRecursiveAdaptorPage;
import org.testng.annotations.Test;
/**
* @author <a href="mailto:[email protected]">Jan Papousek</a>
*/
public class TestRichTreeModelRecursiveAdaptorSimple extends AbstractWebDriverTest<TreeModelRecursiveAdaptorPage>{
@Test
public void testExpandFirstLevel() {
getPage().expandFirstLevelFirstNode();
- assertEquals(getPage().countSecondLevelVisible(), 15, "Number of visible second level nodes after expanding the fist level nodes doesn't match.");
+ assertEquals(getPage().countSecondLevelVisible(), 13, "Number of visible second level nodes after expanding the fist level nodes doesn't match.");
assertEquals(getPage().countThirdLevelVisible(), 0, "Number of visible third level nodes after expanding the fist level nodes doesn't match.");
}
@Test
public void testInit() {
assertEquals(getPage().countSecondLevelVisible(), 0, "Number of visible second level nodes doesn't match.");
assertEquals(getPage().countThirdLevelVisible(), 0, "Number of visible third level nodes doesn't match.");
}
@Override
protected TreeModelRecursiveAdaptorPage createPage() {
return new TreeModelRecursiveAdaptorPage(getWebDriver());
}
}
| true | true | public void testExpandFirstLevel() {
getPage().expandFirstLevelFirstNode();
assertEquals(getPage().countSecondLevelVisible(), 15, "Number of visible second level nodes after expanding the fist level nodes doesn't match.");
assertEquals(getPage().countThirdLevelVisible(), 0, "Number of visible third level nodes after expanding the fist level nodes doesn't match.");
}
| public void testExpandFirstLevel() {
getPage().expandFirstLevelFirstNode();
assertEquals(getPage().countSecondLevelVisible(), 13, "Number of visible second level nodes after expanding the fist level nodes doesn't match.");
assertEquals(getPage().countThirdLevelVisible(), 0, "Number of visible third level nodes after expanding the fist level nodes doesn't match.");
}
|
diff --git a/src/main/java/db/SubTaskDb.java b/src/main/java/db/SubTaskDb.java
index 7f9ff59..c53b8e4 100644
--- a/src/main/java/db/SubTaskDb.java
+++ b/src/main/java/db/SubTaskDb.java
@@ -1,408 +1,408 @@
package db;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import crowdtrust.Bee;
import crowdtrust.BinaryR;
import crowdtrust.MultiValueSubTask;
import crowdtrust.Response;
import crowdtrust.Estimate;
import crowdtrust.BinarySubTask;
import crowdtrust.SubTask;
import crowdtrust.Task;
public class SubTaskDb {
public static boolean close(int id) {
String sql = "UPDATE subtasks SET active = FALSE WHERE subtasks.id = ?";
try {
PreparedStatement preparedStatement = DbAdaptor.connect().prepareStatement(sql);
preparedStatement.setInt(1, id);
preparedStatement.execute();
}
catch (ClassNotFoundException e) {
System.err.println("Error connecting to DB on subtask close: PSQL driver not present");
e.printStackTrace();
return false;
} catch (SQLException e) {
System.err.println("SQL Error on subtask close");
e.printStackTrace();
return false;
}
return true;
}
public static Task getTask(int id) {
StringBuilder sql = new StringBuilder();
sql.append("SELECT * FROM tasks JOIN subtasks ON tasks.id = subtasks.task ");
sql.append("WHERE subtasks.id = ?");
try {
PreparedStatement preparedStatement = DbAdaptor.connect().prepareStatement(sql.toString());
preparedStatement.setInt(1, id);
ResultSet resultSet = preparedStatement.executeQuery();
if(!resultSet.next()) {
//task does not exist, grave error TODO log it
System.err.println("Subtask: " + id + " doesn't exist");
return null;
}
return TaskDb.map(resultSet);
} catch (ClassNotFoundException e) {
System.err.println("Error connecting to DB on get Subtask: PSQL driver not present");
e.printStackTrace();
return null;
} catch (SQLException e) {
System.err.println("SQL Error on get Subtask");
e.printStackTrace();
return null;
}
}
public static Map<Integer, Response> getBinaryResponses(int id, Bee[] annotators) {
HashMap<Integer,Response> responses = new HashMap <Integer,Response>();
StringBuilder sql = new StringBuilder();
sql.append("SELECT account, response");
sql.append("FROM responses");
sql.append("WHERE subtask = ?");
PreparedStatement preparedStatement;
try {
preparedStatement = DbAdaptor.connect().prepareStatement(sql.toString());
preparedStatement.setInt(1, id);
}
catch (ClassNotFoundException e) {
System.err.println("Error connecting to DB on check finished: PSQL driver not present");
e.printStackTrace();
return null;
} catch (SQLException e) {
System.err.println("SQL Error on check finished");
e.printStackTrace();
return null;
}
ResultSet resultSet;
try {
resultSet = preparedStatement.executeQuery();
while (resultSet.next()){
BinaryR br = new BinaryR(resultSet.getBytes("response"));
responses.put(resultSet.getInt("account"), br);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//FINISH THIS!
return null;
}
public static SubTask getRandomBinarySubTask(int task) {
String sql = "SELECT subtasks.id AS s, tasks.accuracy AS a, tasks.max_labels AS m, " +
"COUNT(responses.id) AS r FROM subtasks JOIN tasks ON subtasks.task = tasks.id " +
"LEFT JOIN responses ON responses.subtask = subtasks.id WHERE tasks.id = ? " +
"GROUP BY s,a,m ORDER BY random() LIMIT 1";
PreparedStatement preparedStatement;
try {
preparedStatement = DbAdaptor.connect().prepareStatement(sql);
preparedStatement.setInt(1, task);
}
catch (ClassNotFoundException e) {
System.err.println("Error connecting to DB on check finished: PSQL driver not present");
e.printStackTrace();
return null;
} catch (SQLException e) {
System.err.println("SQL Error on check finished");
e.printStackTrace();
return null;
}
try {
ResultSet rs = preparedStatement.executeQuery();
rs.next();
int taskAccuracy = rs.getInt("a");
int id = rs.getInt("s");
int responses = rs.getInt("r");
int maxLabels = rs.getInt("m");
return new BinarySubTask(id, taskAccuracy, responses, maxLabels);
}
catch(SQLException e) {
e.printStackTrace();
}
return null;
}
public static List<String> getImageSubtasks() {
StringBuilder sql = new StringBuilder();
sql.append("SELECT tasks.id, subtasks.file_name, tasks.date_created, tasks.submitter FROM tasks JOIN subtasks ON tasks.id = subtasks.task ");
- sql.append("WHERE tasks.media_type=1 ORDER BY DESC tasks.date_created");
+ sql.append("WHERE tasks.media_type=1 ORDER BY tasks.date_created DES");
List<String> list = new LinkedList<String>();
PreparedStatement preparedStatement;
try {
preparedStatement = DbAdaptor.connect().prepareStatement(sql.toString());
}
catch (ClassNotFoundException e) {
System.err.println("Error connecting to DB on get Subtask: PSQL driver not present");
e.printStackTrace();
return list;
} catch (SQLException e) {
System.err.println("SQL Error on connection during get image subtask");
e.printStackTrace();
return list;
}
try {
preparedStatement.execute();
} catch (SQLException e1) {
e1.printStackTrace();
}
ResultSet resultSet;
try{
resultSet = preparedStatement.getResultSet();
} catch (SQLException e) {
System.err.println("problem executing stement");
e.printStackTrace();
return list;
}
try{
for (int i = 0 ; resultSet.next() && i < 5 ; i++) {
String subtask = resultSet.getString(2);
int task = resultSet.getInt(1);
int submitter = resultSet.getInt(1); // may be useful to display uname of uploader
list.add(task + "/" + subtask);
resultSet.next();
}
} catch(SQLException e) {
System.err.println("problem with result set");
e.printStackTrace();
}
return list;
}
public static boolean addSubtask(String filename, int taskID) {
String insertQuery = "INSERT INTO subtasks VALUES (DEFAULT,?,?,?)";
PreparedStatement stmt;
try {
stmt = DbAdaptor.connect().prepareStatement(insertQuery);
stmt.setInt(1, taskID);
stmt.setString(2, filename);
stmt.setBoolean(3, true);
stmt.execute();
} catch (SQLException e1) {
System.err.println("some error with task fields: taskID not valid?");
System.err.println("taskID: " + taskID + ", filename: " + filename);
e1.printStackTrace();
return false;
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
return true;
}
public static Map<Integer, Response> getMultiValueResponses(int id,
Bee[] annotators) {
// TODO Auto-generated method stub
return null;
}
public static Map<Integer, Response> getContinuousResponses(int id,
Bee[] annotators) {
// TODO Auto-generated method stub
return null;
}
public static int getSubTaskId(String name){
StringBuilder sql = new StringBuilder();
sql.append("SELECT id FROM subtasks\n");
sql.append("WHERE file_name = ?");
PreparedStatement preparedStatement;
try {
preparedStatement = DbAdaptor.connect().prepareStatement(sql.toString());
} catch (ClassNotFoundException e) {
System.err.println("Error connecting to DB on get Task: PSQL driver not present");
e.printStackTrace();
return -1;
} catch (SQLException e) {
System.err.println("SQL Error on get Task");
e.printStackTrace();
return -1;
}
try {
preparedStatement.setString(1, name);
ResultSet resultSet = preparedStatement.executeQuery();
resultSet.next();
return resultSet.getInt(1);
} catch (SQLException e) {
System.err.println("SELECT task query invalid");
e.printStackTrace();
return -1;
}
}
public static BinarySubTask getBinarySubTask(int subTaskId) {
StringBuilder sql = new StringBuilder();
sql.append("SELECT subtasks.id AS s, tasks.accuracy AS a,");
sql.append("tasks.max_labels AS m, COUNT(responses.id) AS r ");
sql.append("FROM subtasks JOIN tasks ON subtasks.task = tasks.id ");
sql.append("LEFT JOIN responses ON responses.id ");
sql.append("WHERE subtasks.id = ? ");
sql.append("GROUP BY s,a,m ");
PreparedStatement preparedStatement;
try {
preparedStatement = DbAdaptor.connect().prepareStatement(sql.toString());
preparedStatement.setInt(1, subTaskId);
} catch (ClassNotFoundException e) {
System.err.println("Error connecting to DB on check finished: PSQL driver not present");
e.printStackTrace();
return null;
} catch (SQLException e) {
System.err.println("SQL Error on check finished");
e.printStackTrace();
return null;
}
try {
ResultSet rs = preparedStatement.executeQuery();
int taskAccuracy = rs.getInt("a");
int id = rs.getInt("s");
int responses = rs.getInt("r");
int maxLabels = rs.getInt("m");
return new BinarySubTask(id, taskAccuracy, responses, maxLabels);
}
catch(SQLException e) {
e.printStackTrace();
}
return null;
}
public static MultiValueSubTask getMultiValueSubtask(int subTaskId) {
StringBuilder sql = new StringBuilder();
sql.append("SELECT subtasks.id AS s, tasks.accuracy AS a,");
sql.append("tasks.max_labels AS m, ranged.finish AS o, COUNT(responses.id) AS r");
sql.append("FROM subtasks JOIN tasks ON subtasks.task = tasks.id");
sql.append("LEFT JOIN ranged ON subtasks.id = ranged.id");
sql.append("LEFT JOIN responses ON responses.id");
sql.append("WHERE subtasks.id = ?");
sql.append("GROUP BY s,a,m,o");
PreparedStatement preparedStatement;
try {
preparedStatement = DbAdaptor.connect().prepareStatement(sql.toString());
preparedStatement.setInt(1, subTaskId);
} catch (ClassNotFoundException e) {
System.err.println("Error connecting to DB on check finished: PSQL driver not present");
e.printStackTrace();
return null;
} catch (SQLException e) {
System.err.println("SQL Error on check finished");
e.printStackTrace();
return null;
}
try {
ResultSet rs = preparedStatement.executeQuery();
int taskAccuracy = rs.getInt("a");
int id = rs.getInt("s");
int responses = rs.getInt("r");
int maxLabels = rs.getInt("m");
int options = rs.getInt("o");
return new MultiValueSubTask(id, taskAccuracy, responses, maxLabels, options);
}
catch(SQLException e) {
e.printStackTrace();
}
return null;
}
public static Collection<Estimate> getBinaryEstimates(int id) {
String sql = "SELECT estimate, confidence " +
"FROM estimates " +
"WHERE subtask_id = ?";
PreparedStatement preparedStatement;
ArrayList<Estimate> state = new ArrayList<Estimate>();
try {
preparedStatement = DbAdaptor.connect().prepareStatement(sql);
preparedStatement.setInt(1, id);
} catch (ClassNotFoundException e) {
System.err.println("Error connecting to DB on check finished: PSQL driver not present");
e.printStackTrace();
return null;
} catch (SQLException e) {
System.err.println("SQL Error on check finished");
e.printStackTrace();
return null;
}
try {
ResultSet rs = preparedStatement.executeQuery();
while(rs.next()){
BinaryR r = new BinaryR(rs.getBytes("estimate"));
double c = rs.getFloat("confidence");
state.add(new Estimate(r,c));
}
}
catch(SQLException e) {
e.printStackTrace();
}
return state;
}
public static void updateBinaryEstimates(Collection<Estimate> state, int id) {
String query = "UPDATE estimates SET confidence = ? " +
"WHERE subtask_id = ? AND estimate = ?";
PreparedStatement preparedStatement;
try {
preparedStatement = DbAdaptor.connect().prepareStatement(query);
for (Estimate e : state){
preparedStatement.setFloat(1, (float) e.getConfidence());
preparedStatement.setInt(2, id);
preparedStatement.setString(3, e.getR().serialise());
preparedStatement.addBatch();
}
preparedStatement.executeBatch();
} catch (ClassNotFoundException e) {
System.err.println("Error connecting to DB on check finished: PSQL driver not present");
e.printStackTrace();
} catch (SQLException e) {
System.err.println("SQL Error on check finished");
e.printStackTrace();
System.out.println("-------------------");
e.getNextException().printStackTrace();
}
}
public static void addBinaryEstimate(Estimate est, int id) {
String query = "INSERT INTO estimates VALUES (DEFAULT,?,?,?)";
PreparedStatement preparedStatement;
try {
preparedStatement = DbAdaptor.connect().prepareStatement(query);
preparedStatement.setFloat(1, (float) est.getConfidence());
preparedStatement.setString(2, est.getR().serialise());
preparedStatement.setInt(3, id);
preparedStatement.execute();
} catch (ClassNotFoundException e) {
System.err.println("Error connecting to DB on check finished: PSQL driver not present");
e.printStackTrace();
} catch (SQLException e) {
System.err.println("SQL Error on check finished");
e.printStackTrace();
}
}
}
| true | true | public static List<String> getImageSubtasks() {
StringBuilder sql = new StringBuilder();
sql.append("SELECT tasks.id, subtasks.file_name, tasks.date_created, tasks.submitter FROM tasks JOIN subtasks ON tasks.id = subtasks.task ");
sql.append("WHERE tasks.media_type=1 ORDER BY DESC tasks.date_created");
List<String> list = new LinkedList<String>();
PreparedStatement preparedStatement;
try {
preparedStatement = DbAdaptor.connect().prepareStatement(sql.toString());
}
catch (ClassNotFoundException e) {
System.err.println("Error connecting to DB on get Subtask: PSQL driver not present");
e.printStackTrace();
return list;
} catch (SQLException e) {
System.err.println("SQL Error on connection during get image subtask");
e.printStackTrace();
return list;
}
try {
preparedStatement.execute();
} catch (SQLException e1) {
e1.printStackTrace();
}
ResultSet resultSet;
try{
resultSet = preparedStatement.getResultSet();
} catch (SQLException e) {
System.err.println("problem executing stement");
e.printStackTrace();
return list;
}
try{
for (int i = 0 ; resultSet.next() && i < 5 ; i++) {
String subtask = resultSet.getString(2);
int task = resultSet.getInt(1);
int submitter = resultSet.getInt(1); // may be useful to display uname of uploader
list.add(task + "/" + subtask);
resultSet.next();
}
} catch(SQLException e) {
System.err.println("problem with result set");
e.printStackTrace();
}
return list;
}
| public static List<String> getImageSubtasks() {
StringBuilder sql = new StringBuilder();
sql.append("SELECT tasks.id, subtasks.file_name, tasks.date_created, tasks.submitter FROM tasks JOIN subtasks ON tasks.id = subtasks.task ");
sql.append("WHERE tasks.media_type=1 ORDER BY tasks.date_created DES");
List<String> list = new LinkedList<String>();
PreparedStatement preparedStatement;
try {
preparedStatement = DbAdaptor.connect().prepareStatement(sql.toString());
}
catch (ClassNotFoundException e) {
System.err.println("Error connecting to DB on get Subtask: PSQL driver not present");
e.printStackTrace();
return list;
} catch (SQLException e) {
System.err.println("SQL Error on connection during get image subtask");
e.printStackTrace();
return list;
}
try {
preparedStatement.execute();
} catch (SQLException e1) {
e1.printStackTrace();
}
ResultSet resultSet;
try{
resultSet = preparedStatement.getResultSet();
} catch (SQLException e) {
System.err.println("problem executing stement");
e.printStackTrace();
return list;
}
try{
for (int i = 0 ; resultSet.next() && i < 5 ; i++) {
String subtask = resultSet.getString(2);
int task = resultSet.getInt(1);
int submitter = resultSet.getInt(1); // may be useful to display uname of uploader
list.add(task + "/" + subtask);
resultSet.next();
}
} catch(SQLException e) {
System.err.println("problem with result set");
e.printStackTrace();
}
return list;
}
|
diff --git a/Cindy3D/src/de/tum/in/cindy3dplugin/jogl/lighting/Light.java b/Cindy3D/src/de/tum/in/cindy3dplugin/jogl/lighting/Light.java
index 6b350a6..c9c257e 100644
--- a/Cindy3D/src/de/tum/in/cindy3dplugin/jogl/lighting/Light.java
+++ b/Cindy3D/src/de/tum/in/cindy3dplugin/jogl/lighting/Light.java
@@ -1,56 +1,56 @@
package de.tum.in.cindy3dplugin.jogl.lighting;
import java.awt.Color;
import javax.media.opengl.GL2;
import de.tum.in.cindy3dplugin.jogl.lighting.LightManager.LightType;
public abstract class Light {
private Color ambientColor = new Color(0.0f, 0.0f, 0.0f);
private Color diffuseColor = new Color(1.0f, 1.0f, 1.0f);
private Color specularColor = new Color(1.0f, 1.0f, 1.0f);
protected boolean enabled = false;
public void setGLState(GL2 gl, int light) {
if (enabled) {
- gl.glEnable(GL2.GL_LIGHT0 + light);
+ gl.glEnable(light);
}
else
- gl.glDisable(GL2.GL_LIGHT0 + light);
+ gl.glDisable(light);
gl.glLightfv(light, GL2.GL_AMBIENT,
ambientColor.getComponents(null), 0);
gl.glLightfv(light, GL2.GL_DIFFUSE,
diffuseColor.getComponents(null), 0);
gl.glLightfv(light, GL2.GL_SPECULAR,
specularColor.getComponents(null), 0);
}
public void setAmbientColor(Color ambient) {
ambientColor = ambient;
}
public void setDiffuseColor(Color diffuse) {
diffuseColor = diffuse;
}
public void setSpecularColor(Color specular) {
specularColor = specular;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public boolean isEnabled() {
return enabled;
}
public abstract String getShaderFillIn(int light);
public abstract LightType getType();
}
| false | true | public void setGLState(GL2 gl, int light) {
if (enabled) {
gl.glEnable(GL2.GL_LIGHT0 + light);
}
else
gl.glDisable(GL2.GL_LIGHT0 + light);
gl.glLightfv(light, GL2.GL_AMBIENT,
ambientColor.getComponents(null), 0);
gl.glLightfv(light, GL2.GL_DIFFUSE,
diffuseColor.getComponents(null), 0);
gl.glLightfv(light, GL2.GL_SPECULAR,
specularColor.getComponents(null), 0);
}
| public void setGLState(GL2 gl, int light) {
if (enabled) {
gl.glEnable(light);
}
else
gl.glDisable(light);
gl.glLightfv(light, GL2.GL_AMBIENT,
ambientColor.getComponents(null), 0);
gl.glLightfv(light, GL2.GL_DIFFUSE,
diffuseColor.getComponents(null), 0);
gl.glLightfv(light, GL2.GL_SPECULAR,
specularColor.getComponents(null), 0);
}
|
diff --git a/text/src/main/java/eu/interedition/text/xml/module/LineElementXMLParserModule.java b/text/src/main/java/eu/interedition/text/xml/module/LineElementXMLParserModule.java
index 25b36a7f..de1071eb 100644
--- a/text/src/main/java/eu/interedition/text/xml/module/LineElementXMLParserModule.java
+++ b/text/src/main/java/eu/interedition/text/xml/module/LineElementXMLParserModule.java
@@ -1,37 +1,37 @@
/*
* #%L
* Text: A text model with range-based markup via standoff annotations.
* %%
* Copyright (C) 2010 - 2011 The Interedition Development Group
* %%
* 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.
* #L%
*/
package eu.interedition.text.xml.module;
import eu.interedition.text.xml.XMLEntity;
import eu.interedition.text.xml.XMLParserState;
/**
* @author <a href="http://gregor.middell.net/" title="Homepage">Gregor Middell</a>
*/
public class LineElementXMLParserModule extends XMLParserModuleAdapter {
@Override
public void start(XMLEntity entity, XMLParserState state) {
final boolean lineElement = state.getConfiguration().isLineElement(entity);
- if (lineElement && state.getTextOffset() > 0) {
+ if (lineElement && state.getTextOffset() > 0 && state.getConfiguration().included(entity)) {
state.insert("\n", false);
}
}
}
| true | true | public void start(XMLEntity entity, XMLParserState state) {
final boolean lineElement = state.getConfiguration().isLineElement(entity);
if (lineElement && state.getTextOffset() > 0) {
state.insert("\n", false);
}
}
| public void start(XMLEntity entity, XMLParserState state) {
final boolean lineElement = state.getConfiguration().isLineElement(entity);
if (lineElement && state.getTextOffset() > 0 && state.getConfiguration().included(entity)) {
state.insert("\n", false);
}
}
|
diff --git a/gov.va.med.iss.debug.ui/src/gov/va/mumps/debug/ui/console/MDevConsole.java b/gov.va.med.iss.debug.ui/src/gov/va/mumps/debug/ui/console/MDevConsole.java
index d81ea99..6a7ab0c 100644
--- a/gov.va.med.iss.debug.ui/src/gov/va/mumps/debug/ui/console/MDevConsole.java
+++ b/gov.va.med.iss.debug.ui/src/gov/va/mumps/debug/ui/console/MDevConsole.java
@@ -1,87 +1,87 @@
package gov.va.mumps.debug.ui.console;
import gov.va.mumps.launching.ReadCommandListener;
import gov.va.mumps.launching.InputReadyListener;
import gov.va.mumps.launching.WriteCommandListener;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.console.AbstractConsole;
import org.eclipse.ui.console.IConsoleView;
import org.eclipse.ui.part.IPageBookViewPage;
public class MDevConsole extends AbstractConsole implements ReadCommandListener, WriteCommandListener {
private boolean readingUserInput;
private int maxCharInput;
private MDevConsolePage pageBookView;
private List<InputReadyListener> inputReadyListeners;
public MDevConsole(String name, String consoleType,
ImageDescriptor imageDescriptor, boolean autoLifecycle) {
super(name, consoleType, imageDescriptor, autoLifecycle);
inputReadyListeners = new LinkedList<InputReadyListener>();
}
@Override
public IPageBookViewPage createPage(IConsoleView view) {
pageBookView = new MDevConsolePage(this);
return pageBookView;
}
public boolean isReadingUserInput() {
return readingUserInput;
}
public void setReadingInput(boolean readingUserInput) {
this.readingUserInput = readingUserInput ;
}
public int getMaxCharInput() {
return maxCharInput;
}
@Override
public void handleWriteCommand(final String output) { //TODO: bug: write command could theoretically come in before the main gui thread creates the pageBookView causing a NPE
//TODO: bug? is this bein called twice? why? I'm not seeing double input but that may just becaues both async threads run so closely they grab append the same value to the same orig value
pageBookView.getSite().getShell().getDisplay().asyncExec(new Runnable() { //Only the async thread can access SWT controls
@Override
public void run() {
pageBookView.appendText(output);
//TODO: the classes for this need to be organized better? this seems kind of funny
}
});
}
@Override
public void handleReadCommand(int maxCharInput) {
this.maxCharInput = maxCharInput;
readingUserInput = true;
pageBookView.getSite().getShell().getDisplay().asyncExec(new Runnable() {
@Override
public void run() {
- pageBookView.setFocus();
+ pageBookView.setFocus(); //TODO: possibly have other indicator to the user that the console is ready for input
}
});
}
public void addInputReadyListener(InputReadyListener listener) {
inputReadyListeners.add(listener);
}
public void reemoveInputReadyListener(InputReadyListener listener) {
inputReadyListeners.remove(listener);
}
public Iterator<InputReadyListener> getInputReadyInputListeners() {
return inputReadyListeners.listIterator();
}
}
| true | true | public void handleReadCommand(int maxCharInput) {
this.maxCharInput = maxCharInput;
readingUserInput = true;
pageBookView.getSite().getShell().getDisplay().asyncExec(new Runnable() {
@Override
public void run() {
pageBookView.setFocus();
}
});
}
| public void handleReadCommand(int maxCharInput) {
this.maxCharInput = maxCharInput;
readingUserInput = true;
pageBookView.getSite().getShell().getDisplay().asyncExec(new Runnable() {
@Override
public void run() {
pageBookView.setFocus(); //TODO: possibly have other indicator to the user that the console is ready for input
}
});
}
|
diff --git a/src/com/android/gallery3d/ui/TileImageView.java b/src/com/android/gallery3d/ui/TileImageView.java
index eb5da89..7e811fc 100644
--- a/src/com/android/gallery3d/ui/TileImageView.java
+++ b/src/com/android/gallery3d/ui/TileImageView.java
@@ -1,757 +1,757 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.gallery3d.ui;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.FloatMath;
import android.util.LongSparseArray;
import com.android.gallery3d.app.GalleryContext;
import com.android.gallery3d.common.Utils;
import com.android.gallery3d.data.DecodeUtils;
import com.android.gallery3d.util.Future;
import com.android.gallery3d.util.ThreadPool;
import com.android.gallery3d.util.ThreadPool.CancelListener;
import com.android.gallery3d.util.ThreadPool.JobContext;
import java.util.concurrent.atomic.AtomicBoolean;
public class TileImageView extends GLView {
public static final int SIZE_UNKNOWN = -1;
@SuppressWarnings("unused")
private static final String TAG = "TileImageView";
// TILE_SIZE must be 2^N - 2. We put one pixel border in each side of the
// texture to avoid seams between tiles.
private static final int TILE_SIZE = 254;
private static final int TILE_BORDER = 1;
private static final int UPLOAD_LIMIT = 1;
/*
* This is the tile state in the CPU side.
* Life of a Tile:
* ACTIVATED (initial state)
* --> IN_QUEUE - by queueForDecode()
* --> RECYCLED - by recycleTile()
* IN_QUEUE --> DECODING - by decodeTile()
* --> RECYCLED - by recycleTile)
* DECODING --> RECYCLING - by recycleTile()
* --> DECODED - by decodeTile()
* --> DECODE_FAIL - by decodeTile()
* RECYCLING --> RECYCLED - by decodeTile()
* DECODED --> ACTIVATED - (after the decoded bitmap is uploaded)
* DECODED --> RECYCLED - by recycleTile()
* DECODE_FAIL -> RECYCLED - by recycleTile()
* RECYCLED --> ACTIVATED - by obtainTile()
*/
private static final int STATE_ACTIVATED = 0x01;
private static final int STATE_IN_QUEUE = 0x02;
private static final int STATE_DECODING = 0x04;
private static final int STATE_DECODED = 0x08;
private static final int STATE_DECODE_FAIL = 0x10;
private static final int STATE_RECYCLING = 0x20;
private static final int STATE_RECYCLED = 0x40;
private Model mModel;
private ScreenNail mScreenNail;
protected int mLevelCount; // cache the value of mScaledBitmaps.length
// The mLevel variable indicates which level of bitmap we should use.
// Level 0 means the original full-sized bitmap, and a larger value means
// a smaller scaled bitmap (The width and height of each scaled bitmap is
// half size of the previous one). If the value is in [0, mLevelCount), we
// use the bitmap in mScaledBitmaps[mLevel] for display, otherwise the value
// is mLevelCount, and that means we use mScreenNail for display.
private int mLevel = 0;
// The offsets of the (left, top) of the upper-left tile to the (left, top)
// of the view.
private int mOffsetX;
private int mOffsetY;
private int mUploadQuota;
private boolean mRenderComplete;
private final RectF mSourceRect = new RectF();
private final RectF mTargetRect = new RectF();
private final LongSparseArray<Tile> mActiveTiles = new LongSparseArray<Tile>();
// The following three queue is guarded by TileImageView.this
private TileQueue mRecycledQueue = new TileQueue();
private TileQueue mUploadQueue = new TileQueue();
private TileQueue mDecodeQueue = new TileQueue();
// The width and height of the full-sized bitmap
protected int mImageWidth = SIZE_UNKNOWN;
protected int mImageHeight = SIZE_UNKNOWN;
protected int mCenterX;
protected int mCenterY;
protected float mScale;
protected int mRotation;
protected float mAlpha = 1.0f;
// Temp variables to avoid memory allocation
private final Rect mTileRange = new Rect();
private final Rect mActiveRange[] = {new Rect(), new Rect()};
private final TileUploader mTileUploader = new TileUploader();
private boolean mIsTextureFreed;
private Future<Void> mTileDecoder;
private ThreadPool mThreadPool;
private boolean mBackgroundTileUploaded;
public static interface Model {
public int getLevelCount();
public ScreenNail getScreenNail();
public int getImageWidth();
public int getImageHeight();
// The tile returned by this method can be specified this way: Assuming
// the image size is (width, height), first take the intersection of (0,
// 0) - (width, height) and (x, y) - (x + tileSize, y + tileSize). Then
// extend this intersection region by borderSize pixels on each side. If
// in extending the region, we found some part of the region are outside
// the image, those pixels are filled with black.
//
// If level > 0, it does the same operation on a down-scaled version of
// the original image (down-scaled by a factor of 2^level), but (x, y)
// still refers to the coordinate on the original image.
//
// The method would be called in another thread.
public Bitmap getTile(int level, int x, int y, int tileSize,
int borderSize);
public boolean isFailedToLoad();
}
public TileImageView(GalleryContext context) {
mThreadPool = context.getThreadPool();
mTileDecoder = mThreadPool.submit(new TileDecoder());
}
public void setModel(Model model) {
mModel = model;
if (model != null) notifyModelInvalidated();
}
public void setScreenNail(ScreenNail s) {
mScreenNail = s;
}
public void notifyModelInvalidated() {
invalidateTiles();
if (mModel == null) {
mScreenNail = null;
mImageWidth = 0;
mImageHeight = 0;
mLevelCount = 0;
} else {
setScreenNail(mModel.getScreenNail());
mImageWidth = mModel.getImageWidth();
mImageHeight = mModel.getImageHeight();
mLevelCount = mModel.getLevelCount();
}
layoutTiles(mCenterX, mCenterY, mScale, mRotation);
invalidate();
}
@Override
protected void onLayout(
boolean changeSize, int left, int top, int right, int bottom) {
super.onLayout(changeSize, left, top, right, bottom);
if (changeSize) layoutTiles(mCenterX, mCenterY, mScale, mRotation);
}
// Prepare the tiles we want to use for display.
//
// 1. Decide the tile level we want to use for display.
// 2. Decide the tile levels we want to keep as texture (in addition to
// the one we use for display).
// 3. Recycle unused tiles.
// 4. Activate the tiles we want.
private void layoutTiles(int centerX, int centerY, float scale, int rotation) {
// The width and height of this view.
int width = getWidth();
int height = getHeight();
// The tile levels we want to keep as texture is in the range
// [fromLevel, endLevel).
int fromLevel;
int endLevel;
// We want to use a texture larger than or equal to the display size.
mLevel = Utils.clamp(Utils.floorLog2(1f / scale), 0, mLevelCount);
// We want to keep one more tile level as texture in addition to what
// we use for display. So it can be faster when the scale moves to the
// next level. We choose a level closer to the current scale.
if (mLevel != mLevelCount) {
Rect range = mTileRange;
getRange(range, centerX, centerY, mLevel, scale, rotation);
mOffsetX = Math.round(width / 2f + (range.left - centerX) * scale);
mOffsetY = Math.round(height / 2f + (range.top - centerY) * scale);
fromLevel = scale * (1 << mLevel) > 0.75f ? mLevel - 1 : mLevel;
} else {
// Activate the tiles of the smallest two levels.
fromLevel = mLevel - 2;
mOffsetX = Math.round(width / 2f - centerX * scale);
mOffsetY = Math.round(height / 2f - centerY * scale);
}
fromLevel = Math.max(0, Math.min(fromLevel, mLevelCount - 2));
endLevel = Math.min(fromLevel + 2, mLevelCount);
Rect range[] = mActiveRange;
for (int i = fromLevel; i < endLevel; ++i) {
getRange(range[i - fromLevel], centerX, centerY, i, rotation);
}
// If rotation is transient, don't update the tile.
if (rotation % 90 != 0) return;
synchronized (this) {
mDecodeQueue.clean();
mUploadQueue.clean();
mBackgroundTileUploaded = false;
- }
- // Recycle unused tiles: if the level of the active tile is outside the
- // range [fromLevel, endLevel) or not in the visible range.
- int n = mActiveTiles.size();
- for (int i = 0; i < n; i++) {
- Tile tile = mActiveTiles.valueAt(i);
- int level = tile.mTileLevel;
- if (level < fromLevel || level >= endLevel
- || !range[level - fromLevel].contains(tile.mX, tile.mY)) {
- mActiveTiles.removeAt(i);
- i--;
- n--;
- recycleTile(tile);
+ // Recycle unused tiles: if the level of the active tile is outside the
+ // range [fromLevel, endLevel) or not in the visible range.
+ int n = mActiveTiles.size();
+ for (int i = 0; i < n; i++) {
+ Tile tile = mActiveTiles.valueAt(i);
+ int level = tile.mTileLevel;
+ if (level < fromLevel || level >= endLevel
+ || !range[level - fromLevel].contains(tile.mX, tile.mY)) {
+ mActiveTiles.removeAt(i);
+ i--;
+ n--;
+ recycleTile(tile);
+ }
}
}
for (int i = fromLevel; i < endLevel; ++i) {
int size = TILE_SIZE << i;
Rect r = range[i - fromLevel];
for (int y = r.top, bottom = r.bottom; y < bottom; y += size) {
for (int x = r.left, right = r.right; x < right; x += size) {
activateTile(x, y, i);
}
}
}
invalidate();
}
protected synchronized void invalidateTiles() {
mDecodeQueue.clean();
mUploadQueue.clean();
// TODO disable decoder
int n = mActiveTiles.size();
for (int i = 0; i < n; i++) {
Tile tile = mActiveTiles.valueAt(i);
recycleTile(tile);
}
mActiveTiles.clear();
}
private void getRange(Rect out, int cX, int cY, int level, int rotation) {
getRange(out, cX, cY, level, 1f / (1 << (level + 1)), rotation);
}
// If the bitmap is scaled by the given factor "scale", return the
// rectangle containing visible range. The left-top coordinate returned is
// aligned to the tile boundary.
//
// (cX, cY) is the point on the original bitmap which will be put in the
// center of the ImageViewer.
private void getRange(Rect out,
int cX, int cY, int level, float scale, int rotation) {
double radians = Math.toRadians(-rotation);
double w = getWidth();
double h = getHeight();
double cos = Math.cos(radians);
double sin = Math.sin(radians);
int width = (int) Math.ceil(Math.max(
Math.abs(cos * w - sin * h), Math.abs(cos * w + sin * h)));
int height = (int) Math.ceil(Math.max(
Math.abs(sin * w + cos * h), Math.abs(sin * w - cos * h)));
int left = (int) FloatMath.floor(cX - width / (2f * scale));
int top = (int) FloatMath.floor(cY - height / (2f * scale));
int right = (int) FloatMath.ceil(left + width / scale);
int bottom = (int) FloatMath.ceil(top + height / scale);
// align the rectangle to tile boundary
int size = TILE_SIZE << level;
left = Math.max(0, size * (left / size));
top = Math.max(0, size * (top / size));
right = Math.min(mImageWidth, right);
bottom = Math.min(mImageHeight, bottom);
out.set(left, top, right, bottom);
}
// Calculate where the center of the image is, in the view coordinates.
public void getImageCenter(Point center) {
// The width and height of this view.
int viewW = getWidth();
int viewH = getHeight();
// The distance between the center of the view to the center of the
// bitmap, in bitmap units. (mCenterX and mCenterY are the bitmap
// coordinates correspond to the center of view)
int distW, distH;
if (mRotation % 180 == 0) {
distW = mImageWidth / 2 - mCenterX;
distH = mImageHeight / 2 - mCenterY;
} else {
distW = mImageHeight / 2 - mCenterY;
distH = mImageWidth / 2 - mCenterX;
}
// Convert to view coordinates. mScale translates from bitmap units to
// view units.
center.x = Math.round(viewW / 2f + distW * mScale);
center.y = Math.round(viewH / 2f + distH * mScale);
}
public boolean setPosition(int centerX, int centerY, float scale, int rotation) {
if (mCenterX == centerX && mCenterY == centerY
&& mScale == scale && mRotation == rotation) return false;
mCenterX = centerX;
mCenterY = centerY;
mScale = scale;
mRotation = rotation;
layoutTiles(centerX, centerY, scale, rotation);
invalidate();
return true;
}
public boolean setAlpha(float alpha) {
if (mAlpha == alpha) return false;
mAlpha = alpha;
invalidate();
return true;
}
public void freeTextures() {
mIsTextureFreed = true;
if (mTileDecoder != null) {
mTileDecoder.cancel();
mTileDecoder.get();
mTileDecoder = null;
}
int n = mActiveTiles.size();
for (int i = 0; i < n; i++) {
Tile texture = mActiveTiles.valueAt(i);
texture.recycle();
}
mActiveTiles.clear();
mTileRange.set(0, 0, 0, 0);
synchronized (this) {
mUploadQueue.clean();
mDecodeQueue.clean();
Tile tile = mRecycledQueue.pop();
while (tile != null) {
tile.recycle();
tile = mRecycledQueue.pop();
}
}
setScreenNail(null);
}
public void prepareTextures() {
if (mTileDecoder == null) {
mTileDecoder = mThreadPool.submit(new TileDecoder());
}
if (mIsTextureFreed) {
layoutTiles(mCenterX, mCenterY, mScale, mRotation);
mIsTextureFreed = false;
setScreenNail(mModel == null ? null : mModel.getScreenNail());
}
}
@Override
protected void render(GLCanvas canvas) {
mUploadQuota = UPLOAD_LIMIT;
mRenderComplete = true;
int level = mLevel;
int rotation = mRotation;
int flags = 0;
if (rotation != 0) flags |= GLCanvas.SAVE_FLAG_MATRIX;
if (mAlpha != 1.0f) flags |= GLCanvas.SAVE_FLAG_ALPHA;
if (flags != 0) {
canvas.save(flags);
if (rotation != 0) {
int centerX = getWidth() / 2, centerY = getHeight() / 2;
canvas.translate(centerX, centerY);
canvas.rotate(rotation, 0, 0, 1);
canvas.translate(-centerX, -centerY);
}
if (mAlpha != 1.0f) canvas.multiplyAlpha(mAlpha);
}
try {
if (level != mLevelCount) {
if (mScreenNail != null) {
mScreenNail.noDraw();
}
int size = (TILE_SIZE << level);
float length = size * mScale;
Rect r = mTileRange;
for (int ty = r.top, i = 0; ty < r.bottom; ty += size, i++) {
float y = mOffsetY + i * length;
for (int tx = r.left, j = 0; tx < r.right; tx += size, j++) {
float x = mOffsetX + j * length;
drawTile(canvas, tx, ty, level, x, y, length);
}
}
} else if (mScreenNail != null) {
mScreenNail.draw(canvas, mOffsetX, mOffsetY,
Math.round(mImageWidth * mScale),
Math.round(mImageHeight * mScale));
}
} finally {
if (flags != 0) canvas.restore();
}
if (mRenderComplete) {
if (!mBackgroundTileUploaded) uploadBackgroundTiles(canvas);
} else {
invalidate();
}
}
private void uploadBackgroundTiles(GLCanvas canvas) {
mBackgroundTileUploaded = true;
int n = mActiveTiles.size();
for (int i = 0; i < n; i++) {
Tile tile = mActiveTiles.valueAt(i);
if (!tile.isContentValid(canvas)) queueForDecode(tile);
}
}
void queueForUpload(Tile tile) {
synchronized (this) {
mUploadQueue.push(tile);
}
if (mTileUploader.mActive.compareAndSet(false, true)) {
getGLRoot().addOnGLIdleListener(mTileUploader);
}
}
synchronized void queueForDecode(Tile tile) {
if (tile.mTileState == STATE_ACTIVATED) {
tile.mTileState = STATE_IN_QUEUE;
if (mDecodeQueue.push(tile)) notifyAll();
}
}
boolean decodeTile(Tile tile) {
synchronized (this) {
if (tile.mTileState != STATE_IN_QUEUE) return false;
tile.mTileState = STATE_DECODING;
}
boolean decodeComplete = tile.decode();
synchronized (this) {
if (tile.mTileState == STATE_RECYCLING) {
tile.mTileState = STATE_RECYCLED;
tile.mDecodedTile = null;
mRecycledQueue.push(tile);
return false;
}
tile.mTileState = decodeComplete ? STATE_DECODED : STATE_DECODE_FAIL;
return decodeComplete;
}
}
private synchronized Tile obtainTile(int x, int y, int level) {
Tile tile = mRecycledQueue.pop();
if (tile != null) {
tile.mTileState = STATE_ACTIVATED;
tile.update(x, y, level);
return tile;
}
return new Tile(x, y, level);
}
synchronized void recycleTile(Tile tile) {
if (tile.mTileState == STATE_DECODING) {
tile.mTileState = STATE_RECYCLING;
return;
}
tile.mTileState = STATE_RECYCLED;
tile.mDecodedTile = null;
mRecycledQueue.push(tile);
}
private void activateTile(int x, int y, int level) {
long key = makeTileKey(x, y, level);
Tile tile = mActiveTiles.get(key);
if (tile != null) {
if (tile.mTileState == STATE_IN_QUEUE) {
tile.mTileState = STATE_ACTIVATED;
}
return;
}
tile = obtainTile(x, y, level);
mActiveTiles.put(key, tile);
}
private Tile getTile(int x, int y, int level) {
return mActiveTiles.get(makeTileKey(x, y, level));
}
private static long makeTileKey(int x, int y, int level) {
long result = x;
result = (result << 16) | y;
result = (result << 16) | level;
return result;
}
private class TileUploader implements GLRoot.OnGLIdleListener {
AtomicBoolean mActive = new AtomicBoolean(false);
@Override
public boolean onGLIdle(GLCanvas canvas, boolean renderRequested) {
if (renderRequested) return false;
int quota = UPLOAD_LIMIT;
Tile tile;
while (true) {
synchronized (TileImageView.this) {
tile = mUploadQueue.pop();
}
if (tile == null || quota <= 0) break;
if (!tile.isContentValid(canvas)) {
Utils.assertTrue(tile.mTileState == STATE_DECODED);
tile.updateContent(canvas);
--quota;
}
}
mActive.set(tile != null);
return tile != null;
}
}
// Draw the tile to a square at canvas that locates at (x, y) and
// has a side length of length.
public void drawTile(GLCanvas canvas,
int tx, int ty, int level, float x, float y, float length) {
RectF source = mSourceRect;
RectF target = mTargetRect;
target.set(x, y, x + length, y + length);
source.set(0, 0, TILE_SIZE, TILE_SIZE);
Tile tile = getTile(tx, ty, level);
if (tile != null) {
if (!tile.isContentValid(canvas)) {
if (tile.mTileState == STATE_DECODED) {
if (mUploadQuota > 0) {
--mUploadQuota;
tile.updateContent(canvas);
} else {
mRenderComplete = false;
}
} else if (tile.mTileState != STATE_DECODE_FAIL){
mRenderComplete = false;
queueForDecode(tile);
}
}
if (drawTile(tile, canvas, source, target)) return;
}
if (mScreenNail != null) {
int size = TILE_SIZE << level;
float scaleX = (float) mScreenNail.getWidth() / mImageWidth;
float scaleY = (float) mScreenNail.getHeight() / mImageHeight;
source.set(tx * scaleX, ty * scaleY, (tx + size) * scaleX,
(ty + size) * scaleY);
mScreenNail.draw(canvas, source, target);
}
}
// TODO: avoid drawing the unused part of the textures.
static boolean drawTile(
Tile tile, GLCanvas canvas, RectF source, RectF target) {
while (true) {
if (tile.isContentValid(canvas)) {
// offset source rectangle for the texture border.
source.offset(TILE_BORDER, TILE_BORDER);
canvas.drawTexture(tile, source, target);
return true;
}
// Parent can be divided to four quads and tile is one of the four.
Tile parent = tile.getParentTile();
if (parent == null) return false;
if (tile.mX == parent.mX) {
source.left /= 2f;
source.right /= 2f;
} else {
source.left = (TILE_SIZE + source.left) / 2f;
source.right = (TILE_SIZE + source.right) / 2f;
}
if (tile.mY == parent.mY) {
source.top /= 2f;
source.bottom /= 2f;
} else {
source.top = (TILE_SIZE + source.top) / 2f;
source.bottom = (TILE_SIZE + source.bottom) / 2f;
}
tile = parent;
}
}
private class Tile extends UploadedTexture {
int mX;
int mY;
int mTileLevel;
Tile mNext;
Bitmap mDecodedTile;
volatile int mTileState = STATE_ACTIVATED;
public Tile(int x, int y, int level) {
mX = x;
mY = y;
mTileLevel = level;
}
@Override
protected void onFreeBitmap(Bitmap bitmap) {
bitmap.recycle();
}
boolean decode() {
// Get a tile from the original image. The tile is down-scaled
// by (1 << mTilelevel) from a region in the original image.
try {
mDecodedTile = DecodeUtils.ensureGLCompatibleBitmap(mModel.getTile(
mTileLevel, mX, mY, TILE_SIZE, TILE_BORDER));
} catch (Throwable t) {
Log.w(TAG, "fail to decode tile", t);
}
return mDecodedTile != null;
}
@Override
protected Bitmap onGetBitmap() {
Utils.assertTrue(mTileState == STATE_DECODED);
Bitmap bitmap = mDecodedTile;
mDecodedTile = null;
mTileState = STATE_ACTIVATED;
return bitmap;
}
// We override getTextureWidth() and getTextureHeight() here, so the
// texture can be re-used for different tiles regardless of the actual
// size of the tile (which may be small because it is a tile at the
// boundary).
@Override
public int getTextureWidth() {
return TILE_SIZE + TILE_BORDER * 2;
}
@Override
public int getTextureHeight() {
return TILE_SIZE + TILE_BORDER * 2;
}
public void update(int x, int y, int level) {
mX = x;
mY = y;
mTileLevel = level;
invalidateContent();
}
public Tile getParentTile() {
if (mTileLevel + 1 == mLevelCount) return null;
int size = TILE_SIZE << (mTileLevel + 1);
int x = size * (mX / size);
int y = size * (mY / size);
return getTile(x, y, mTileLevel + 1);
}
@Override
public String toString() {
return String.format("tile(%s, %s, %s / %s)",
mX / TILE_SIZE, mY / TILE_SIZE, mLevel, mLevelCount);
}
}
private static class TileQueue {
private Tile mHead;
public Tile pop() {
Tile tile = mHead;
if (tile != null) mHead = tile.mNext;
return tile;
}
public boolean push(Tile tile) {
boolean wasEmpty = mHead == null;
tile.mNext = mHead;
mHead = tile;
return wasEmpty;
}
public void clean() {
mHead = null;
}
}
private class TileDecoder implements ThreadPool.Job<Void> {
private CancelListener mNotifier = new CancelListener() {
@Override
public void onCancel() {
synchronized (TileImageView.this) {
TileImageView.this.notifyAll();
}
}
};
@Override
public Void run(JobContext jc) {
jc.setMode(ThreadPool.MODE_NONE);
jc.setCancelListener(mNotifier);
while (!jc.isCancelled()) {
Tile tile = null;
synchronized(TileImageView.this) {
tile = mDecodeQueue.pop();
if (tile == null && !jc.isCancelled()) {
Utils.waitWithoutInterrupt(TileImageView.this);
}
}
if (tile == null) continue;
if (decodeTile(tile)) queueForUpload(tile);
}
return null;
}
}
}
| false | true | private void layoutTiles(int centerX, int centerY, float scale, int rotation) {
// The width and height of this view.
int width = getWidth();
int height = getHeight();
// The tile levels we want to keep as texture is in the range
// [fromLevel, endLevel).
int fromLevel;
int endLevel;
// We want to use a texture larger than or equal to the display size.
mLevel = Utils.clamp(Utils.floorLog2(1f / scale), 0, mLevelCount);
// We want to keep one more tile level as texture in addition to what
// we use for display. So it can be faster when the scale moves to the
// next level. We choose a level closer to the current scale.
if (mLevel != mLevelCount) {
Rect range = mTileRange;
getRange(range, centerX, centerY, mLevel, scale, rotation);
mOffsetX = Math.round(width / 2f + (range.left - centerX) * scale);
mOffsetY = Math.round(height / 2f + (range.top - centerY) * scale);
fromLevel = scale * (1 << mLevel) > 0.75f ? mLevel - 1 : mLevel;
} else {
// Activate the tiles of the smallest two levels.
fromLevel = mLevel - 2;
mOffsetX = Math.round(width / 2f - centerX * scale);
mOffsetY = Math.round(height / 2f - centerY * scale);
}
fromLevel = Math.max(0, Math.min(fromLevel, mLevelCount - 2));
endLevel = Math.min(fromLevel + 2, mLevelCount);
Rect range[] = mActiveRange;
for (int i = fromLevel; i < endLevel; ++i) {
getRange(range[i - fromLevel], centerX, centerY, i, rotation);
}
// If rotation is transient, don't update the tile.
if (rotation % 90 != 0) return;
synchronized (this) {
mDecodeQueue.clean();
mUploadQueue.clean();
mBackgroundTileUploaded = false;
}
// Recycle unused tiles: if the level of the active tile is outside the
// range [fromLevel, endLevel) or not in the visible range.
int n = mActiveTiles.size();
for (int i = 0; i < n; i++) {
Tile tile = mActiveTiles.valueAt(i);
int level = tile.mTileLevel;
if (level < fromLevel || level >= endLevel
|| !range[level - fromLevel].contains(tile.mX, tile.mY)) {
mActiveTiles.removeAt(i);
i--;
n--;
recycleTile(tile);
}
}
for (int i = fromLevel; i < endLevel; ++i) {
int size = TILE_SIZE << i;
Rect r = range[i - fromLevel];
for (int y = r.top, bottom = r.bottom; y < bottom; y += size) {
for (int x = r.left, right = r.right; x < right; x += size) {
activateTile(x, y, i);
}
}
}
invalidate();
}
| private void layoutTiles(int centerX, int centerY, float scale, int rotation) {
// The width and height of this view.
int width = getWidth();
int height = getHeight();
// The tile levels we want to keep as texture is in the range
// [fromLevel, endLevel).
int fromLevel;
int endLevel;
// We want to use a texture larger than or equal to the display size.
mLevel = Utils.clamp(Utils.floorLog2(1f / scale), 0, mLevelCount);
// We want to keep one more tile level as texture in addition to what
// we use for display. So it can be faster when the scale moves to the
// next level. We choose a level closer to the current scale.
if (mLevel != mLevelCount) {
Rect range = mTileRange;
getRange(range, centerX, centerY, mLevel, scale, rotation);
mOffsetX = Math.round(width / 2f + (range.left - centerX) * scale);
mOffsetY = Math.round(height / 2f + (range.top - centerY) * scale);
fromLevel = scale * (1 << mLevel) > 0.75f ? mLevel - 1 : mLevel;
} else {
// Activate the tiles of the smallest two levels.
fromLevel = mLevel - 2;
mOffsetX = Math.round(width / 2f - centerX * scale);
mOffsetY = Math.round(height / 2f - centerY * scale);
}
fromLevel = Math.max(0, Math.min(fromLevel, mLevelCount - 2));
endLevel = Math.min(fromLevel + 2, mLevelCount);
Rect range[] = mActiveRange;
for (int i = fromLevel; i < endLevel; ++i) {
getRange(range[i - fromLevel], centerX, centerY, i, rotation);
}
// If rotation is transient, don't update the tile.
if (rotation % 90 != 0) return;
synchronized (this) {
mDecodeQueue.clean();
mUploadQueue.clean();
mBackgroundTileUploaded = false;
// Recycle unused tiles: if the level of the active tile is outside the
// range [fromLevel, endLevel) or not in the visible range.
int n = mActiveTiles.size();
for (int i = 0; i < n; i++) {
Tile tile = mActiveTiles.valueAt(i);
int level = tile.mTileLevel;
if (level < fromLevel || level >= endLevel
|| !range[level - fromLevel].contains(tile.mX, tile.mY)) {
mActiveTiles.removeAt(i);
i--;
n--;
recycleTile(tile);
}
}
}
for (int i = fromLevel; i < endLevel; ++i) {
int size = TILE_SIZE << i;
Rect r = range[i - fromLevel];
for (int y = r.top, bottom = r.bottom; y < bottom; y += size) {
for (int x = r.left, right = r.right; x < right; x += size) {
activateTile(x, y, i);
}
}
}
invalidate();
}
|
diff --git a/org.amanzi.neo.loader/src/org/amanzi/neo/loader/TransmissionLoader.java b/org.amanzi.neo.loader/src/org/amanzi/neo/loader/TransmissionLoader.java
index 6953ea0de..18b867f3a 100644
--- a/org.amanzi.neo.loader/src/org/amanzi/neo/loader/TransmissionLoader.java
+++ b/org.amanzi.neo.loader/src/org/amanzi/neo/loader/TransmissionLoader.java
@@ -1,758 +1,759 @@
/* AWE - Amanzi Wireless Explorer
* http://awe.amanzi.org
* (C) 2008-2009, AmanziTel AB
*
* This library is provided under the terms of the Eclipse Public License
* as described at http://www.eclipse.org/legal/epl-v10.html. Any use,
* reproduction or distribution of the library constitutes recipient's
* acceptance of this agreement.
*
* This library is distributed WITHOUT ANY WARRANTY; without even the
* implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*/
package org.amanzi.neo.loader;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import org.amanzi.neo.core.INeoConstants;
import org.amanzi.neo.core.NeoCorePlugin;
import org.amanzi.neo.core.database.services.UpdateDatabaseEvent;
import org.amanzi.neo.core.database.services.UpdateDatabaseEventType;
import org.amanzi.neo.core.enums.GeoNeoRelationshipTypes;
import org.amanzi.neo.core.enums.NetworkRelationshipTypes;
import org.amanzi.neo.core.service.NeoServiceProvider;
import org.amanzi.neo.core.utils.CSVParser;
import org.amanzi.neo.core.utils.NeoUtils;
import org.amanzi.neo.core.utils.Pair;
import org.amanzi.neo.loader.internal.NeoLoaderPlugin;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.neo4j.api.core.Direction;
import org.neo4j.api.core.NeoService;
import org.neo4j.api.core.Node;
import org.neo4j.api.core.PropertyContainer;
import org.neo4j.api.core.Relationship;
import org.neo4j.api.core.ReturnableEvaluator;
import org.neo4j.api.core.StopEvaluator;
import org.neo4j.api.core.Transaction;
import org.neo4j.api.core.TraversalPosition;
import org.neo4j.api.core.Traverser.Order;
import org.neo4j.util.index.LuceneIndexService;
/**
* TODO extend from NeighbourLoader
* <p>
* Transmission data loader
* </p>
*
* @author Cinkel_A
* @since 1.0.0
*/
public class TransmissionLoader {
/** String ID3 field */
private static final String ID3 = "ITEM_Name";
/** String ID2 field */
private static final String ID1 = "Site ID";
/** String ID1 field */
private static final String ID2 = "Site No";
/** String STRING field */
// private static String directory = null;
private static final int COMMIT_MAX = 1000;
private Node network;
private String fileName;
private Header header;
private Node neighbour;
private String baseName;
private final NeoService neo;
/**
* Constructor
*
* @param networkNode network Node
* @param fileName Neighbour file Name
*/
public TransmissionLoader(Node networkNode, String fileName, NeoService neo) {
network = networkNode;
this.fileName = fileName;
this.neo = neo;
this.baseName = new File(fileName).getName();
}
/**
* gets directory
*
* @return
*/
public static String getDirectory() {
return NeoLoaderPlugin.getDefault().getPluginPreferences().getString(AbstractLoader.DEFAULT_DIRRECTORY_LOADER);
}
/**
* Sets Default Directory path for file dialogs in TEMSLoad and NetworkLoad
*
* @param newDirectory new default directory
* @author Lagutko_N
*/
public static void setDirectory(String newDirectory) {
NeoLoaderPlugin.getDefault().getPluginPreferences().setValue(AbstractLoader.DEFAULT_DIRRECTORY_LOADER, newDirectory);
}
/**
* Runs NeighbourLoader
*
* @param monitor monitor
* @throws IOException
*/
public void run(IProgressMonitor monitor) throws IOException {
CountingFileInputStream stream = null;
BufferedReader reader = null;
Transaction tx = neo.beginTx();
try {
if (monitor == null) {
monitor = new NullProgressMonitor();
}
monitor.beginTask("Importing " + baseName, 100);
stream = new CountingFileInputStream(new File(fileName));
String charSet = NeoLoaderPlugin.getDefault().getCharacterSet();
reader = new BufferedReader(new InputStreamReader(stream, charSet));
int perc = stream.percentage();
int prevPerc = 0;
String line = reader.readLine();
if (line == null) {
monitor.setCanceled(true);
return;
}
header = new Header(line, neo);
neighbour = getTransmission(network, baseName);
header.createSectorCache(network);
int commit = 0;
while ((line = reader.readLine()) != null) {
header.parseLine(line, network, baseName);
if (monitor.isCanceled())
break;
perc = stream.percentage();
if (perc > prevPerc) {
monitor.worked(perc - prevPerc);
prevPerc = perc;
}
if (++commit > COMMIT_MAX) {
tx.success();
tx.finish();
tx = neo.beginTx();
commit = 0;
}
}
header.saveStatistic(neighbour);
monitor.done();
tx.success();
} finally {
if (reader != null) {
reader.close();
}
NeoCorePlugin.getDefault().getUpdateDatabaseManager().fireUpdateDatabase(
new UpdateDatabaseEvent(UpdateDatabaseEventType.TRANSMISSION));
tx.finish();
header.finish();
NeoServiceProvider.getProvider().commit();
}
}
/**
* get transmission
*
* @param network network node
* @param fileName neighbour file name
* @return neighbour node
*/
private Node getTransmission(Node network, String fileName) {
Node result = NeoUtils.findTransmission(network, fileName, neo);
if (result != null) {
return result;
}
Transaction tx = neo.beginTx();
try {
result = neo.createNode();
result.setProperty(INeoConstants.PROPERTY_TYPE_NAME, INeoConstants.TRANSMISSION_TYPE_NAME);
result.setProperty(INeoConstants.PROPERTY_NAME_NAME, fileName);
network.createRelationshipTo(result, NetworkRelationshipTypes.TRANSMISSION_DATA);
tx.success();
return result;
} finally {
tx.finish();
}
}
/**
* <p>
* Header of Neighbour file
* </p>
*
* @author Cinkel_A
* @since 1.0.0
*/
public class Header {
private static final String STRING = "STRING";
/** String DOUBLE field */
private static final String DOUBLE = "DOUBLE";
/** String INTEGER field */
private static final String INTEGER = "INTEGER";
private static final int CACH_SIZE = 10000;
private static final String KEY_ID = "name";
private static final String KEY_ID2 = "name2";
private Map<Integer, Pair<String, String>> indexMap = new LinkedHashMap<Integer, Pair<String, String>>();
private NodeName serverNodeName;
private NodeName neighbourNodeName;
private String[] headers;
// private Map<String, Pair<Node, Integer>> cach = new HashMap<String, Pair<Node,
// Integer>>();
private LuceneIndexService index;
private final NeoService neo;
private char fieldSepRegex;
private char[] possibleFieldSepRegexes = new char[] {'\t', ',', ';'};
private CSVParser parser;
private Node lastNode = null;
/**
* Constructor
*
* @param line - header line
*/
public Header(String line, NeoService neo) {
this.neo = neo;
determineFieldSepRegex(line);
headers = splitLine(line);
serverNodeName = new NodeName(new String[] {ID1, "Near end Name"}, new String[] {ID2, "Near End Site No"},
new String[] {ID3});
neighbourNodeName = new NodeName(new String[] {ID1, "Far end Name"}, new String[] {ID2, "Far End Site No"},
new String[] {ID3});
for (int i = 0; i < headers.length; i++) {
String fieldHeader = headers[i];
if (serverNodeName.setFieldIndex(fieldHeader, i)) {
continue;
} else if (neighbourNodeName.setFieldIndex(fieldHeader, i)) {
continue;
} else {
indexMap.put(i, new Pair<String, String>(fieldHeader, null));
}
}
}
protected String[] splitLine(String line) {
return parser.parse(line).toArray(new String[0]);
}
private void determineFieldSepRegex(String line) {
int maxMatch = 0;
for (char regex : possibleFieldSepRegexes) {
String[] fields = line.split(String.valueOf(regex));
if (fields.length > maxMatch) {
maxMatch = fields.length;
fieldSepRegex = regex;
}
}
parser = new CSVParser(fieldSepRegex);
}
/**
* save statistic information in node
*
* @param neighbour
*/
public void saveStatistic(Node neighbour) {
saveNumericList(neighbour);
saveAllFields(neighbour);
}
/**
* finish work with header
*/
public void finish() {
if (index != null) {
index.shutdown();
}
}
/**
* create cache
*
* @param network - network node
*/
public void createSectorCache(Node network) {
Transaction tx = neo.beginTx();
try {
index = new LuceneIndexService(neo);
index.enableCache(KEY_ID, CACH_SIZE);
// it useful if neighbour file much bigger then network
indexesAllSectors(network, index);
tx.success();
} finally {
// if tx.finish() - finds work slow but memory do not using
tx.finish();
}
}
/**
* Indexes all sectors
*
* @param network network node
* @param index LuceneIndexService
*/
private void indexesAllSectors(Node network, LuceneIndexService index) {
long t1 = System.currentTimeMillis();
Iterator<Node> iterator = network.traverse(Order.DEPTH_FIRST, StopEvaluator.END_OF_GRAPH, new ReturnableEvaluator() {
@Override
public boolean isReturnableNode(TraversalPosition currentPos) {
return currentPos.currentNode().getProperty(INeoConstants.PROPERTY_TYPE_NAME, "").equals("site");
}
}, GeoNeoRelationshipTypes.NEXT, Direction.OUTGOING).iterator();
while (iterator.hasNext()) {
Node node = (Node)iterator.next();
String id1 = NodeName.getId1(node);
if (id1 != null) {
index.index(node, KEY_ID, id1);
}
String id2 = NodeName.getId2(node);
if (id2 != null) {
index.index(node, KEY_ID2, id2);
}
}
System.out.println("INDEXES=\t" + (System.currentTimeMillis() - t1));
}
/**
* Save list of Numeric properties in database
*
* @param neighbour neighbour node
*/
public void saveNumericList(Node neighbour) {
Transaction tx = neo.beginTx();
try {
Set<String> propertyes = new HashSet<String>();
for (Pair<String, String> pair : indexMap.values()) {
String clas = pair.getRight();
if (INTEGER.equals(clas) || DOUBLE.equals(clas)) {
propertyes.add(pair.getLeft());
}
}
neighbour.setProperty(INeoConstants.LIST_NUMERIC_PROPERTIES, propertyes.toArray(new String[0]));
tx.success();
} finally {
tx.finish();
}
}
/**
* Save list of All properties in database
*
* @param neighbour neighbour node
*/
public void saveAllFields(Node neighbour) {
Transaction tx = neo.beginTx();
try {
Set<String> integer = new HashSet<String>();
Set<String> doubl = new HashSet<String>();
Set<String> propertyes = new HashSet<String>();
for (Pair<String, String> pair : indexMap.values()) {
String clas = pair.getRight();
if (INTEGER.equals(clas)) {
integer.add(pair.getLeft());
} else if (DOUBLE.equals(clas)) {
doubl.add(pair.getLeft());
}
propertyes.add(pair.getLeft());
}
neighbour.setProperty(INeoConstants.LIST_ALL_PROPERTIES, propertyes.toArray(new String[0]));
neighbour.setProperty(INeoConstants.LIST_DOUBLE_PROPERTIES, doubl.toArray(new String[0]));
neighbour.setProperty(INeoConstants.LIST_INTEGER_PROPERTIES, integer.toArray(new String[0]));
tx.success();
} finally {
tx.finish();
}
}
/**
* Parse single line
*
* @param line - string line
* @param fileName - neighbour name
* @param network - network node
*/
public void parseLine(String line, Node network, String fileName) {
String fields[] = splitLine(line);// line.split("\\t");
Transaction tx = neo.beginTx();
try {
String servCounName = NeoUtils.getTransmissionPropertyName(fileName);
serverNodeName.setFieldValues(fields);
neighbourNodeName.setFieldValues(fields);
String servId = serverNodeName.getId1();
Node serverNode = null;
if (servId != null) {
serverNode = index.getSingleNode(KEY_ID, servId);
if (serverNode == null) {
servId = serverNodeName.getId2();
serverNode = index.getSingleNode(KEY_ID2, servId);
}
}
Node neighbourNode = null;
String neighbourId = neighbourNodeName.getId1();
if (neighbourId != null) {
neighbourNode = index.getSingleNode(KEY_ID, neighbourId);
if (neighbourNode == null) {
neighbourId = neighbourNodeName.getId2();
neighbourNode = index.getSingleNode(KEY_ID2, neighbourId);
}
}
if (serverNode == null) {
serverNode = createTransmissionSite(serverNodeName, fields);
NeoLoaderPlugin.error("Not found site: " + servId);
}
if (neighbourNode == null) {
+ neighbourNode = createTransmissionSite(neighbourNodeName, fields);
NeoLoaderPlugin.error("Not found site: " + neighbourId);
}
if (serverNode == null || neighbourNode == null) {
NeoLoaderPlugin.error("Not found sites for line:\n" + line);
return;
}
Relationship relation = serverNode.createRelationshipTo(neighbourNode, NetworkRelationshipTypes.TRANSMISSION);
relation.setProperty(INeoConstants.NEIGHBOUR_NAME, fileName);
for (Integer index : indexMap.keySet()) {
String value = fields[index];
if (value.length() > 0) {
saveValue(relation, index, value);
}
}
updateCount(serverNode, servCounName);
tx.success();
} catch (Exception e) {
NeoLoaderPlugin.error(line + "\n" + e.getLocalizedMessage());
} finally {
tx.finish();
}
}
/**
* Creates Transmission Sites if
*
* @param nodeName - Id of node
* @param fields - line fields
* @return Node
*/
private Node createTransmissionSite(NodeName nodeName, String[] fields) {
if (nodeName==null||(nodeName.getId1()==null&&nodeName.getId2()==null)){
return null;
}
//TODO create NetworkIndexes if necessary.
Transaction tx = neo.beginTx();
try {
if (lastNode == null) {
lastNode = findNetworkLastSite();
}
Node result = neo.createNode();
result.setProperty(INeoConstants.PROPERTY_TYPE_NAME, "site");
String id1 = nodeName.getId1();
if (id1 != null) {
result.setProperty(INeoConstants.PROPERTY_NAME_NAME, id1);
index.index(result, KEY_ID, id1);
}
String id2 = nodeName.getId2();
if (id2 != null) {
result.setProperty("site_no", id2);
index.index(result, KEY_ID2, id2);
}
lastNode.createRelationshipTo(result, GeoNeoRelationshipTypes.NEXT);
tx.success();
lastNode = result;
return result;
} finally {
tx.finish();
}
}
/**
* Finds last site in network
*
* @return last node;
*/
private Node findNetworkLastSite() {
return network.traverse(Order.DEPTH_FIRST, StopEvaluator.END_OF_GRAPH, new ReturnableEvaluator() {
@Override
public boolean isReturnableNode(TraversalPosition currentPos) {
Node node = currentPos.currentNode();
return !node.hasRelationship(GeoNeoRelationshipTypes.NEXT, Direction.OUTGOING);
}
}, GeoNeoRelationshipTypes.NEXT, Direction.OUTGOING).iterator().next();
}
/**
* Updates count of properties
*
* @param serverNode node
* @param name name of properties
*/
private void updateCount(Node serverNode, String name) {
serverNode.setProperty(name, (Integer)serverNode.getProperty(name, 0) + 1);
}
/**
* Save value in property container
*
* @param container property container
* @param index index of property
* @param value value of property
* @return true if save is successful
*/
private boolean saveValue(PropertyContainer container, Integer index, String value) {
Pair<String, String> pair = indexMap.get(index);
if (pair == null || pair.left() == null) {
return false;
}
String key = pair.left();
Object valueToSave;
String clas = pair.right();
try {
if (clas == null) {
try {
valueToSave = Integer.parseInt(value);
clas = INTEGER;
} catch (NumberFormatException e) {
valueToSave = Double.parseDouble(value);
clas = DOUBLE;
}
} else if (INTEGER.equals(clas)) {
try {
valueToSave = Integer.parseInt(value);
} catch (NumberFormatException e) {
valueToSave = Double.parseDouble(value);
clas = DOUBLE;
}
} else if (DOUBLE.equals(clas)) {
valueToSave = Double.parseDouble(value);
} else {
valueToSave = value;
clas = STRING;
}
} catch (NumberFormatException e) {
clas = STRING;
valueToSave = value;
}
if (!valueToSave.toString().equals(value)) {
valueToSave = value;
clas = STRING;
}
pair.setRight(clas);
// indexMap.put(index, pair.create(key, clas));
container.setProperty(key, valueToSave);
return true;
}
// /**
// * finds necessary sector in network
// *
// * @param nodeName sector name
// * @param network network node
// * @param fields array of values
// * @return necessary sector or null
// */
// private Node findSectors(final NodeName nodeName, Node network) {
// Iterator<Node> iterator = network.traverse(Order.DEPTH_FIRST, StopEvaluator.END_OF_GRAPH,
// new ReturnableEvaluator() {
//
// @Override
// public boolean isReturnableNode(TraversalPosition currentPos) {
// return nodeName.isNecessaryNode(currentPos.currentNode());
// }
// }, GeoNeoRelationshipTypes.NEXT, Direction.OUTGOING).iterator();
// return iterator.hasNext() ? iterator.next() : null;
// }
}
/**
* <p>
* Class that contains information about sectors name
* </p>
*
* @author Cinkel_A
* @since 1.0.0
*/
private static class NodeName {
/** String BTS_NAME field "Site No", "Site ID", "Item Name" */
private static final String SITE_NO = "site_no";
/** String LAC field */
private static final String SITE_ID = "site_id";
/** String CI field */
private static final String ITEM_NAME = "item_Name";
Map<String, String> nameMap = new HashMap<String, String>();
Map<String, Integer> indexMap = new HashMap<String, Integer>();
Map<String, String> valuesMap = new HashMap<String, String>();
private String[] id1;
private String[] id2;
private String[] id3;
/**
* Constructor
*
* @param ci name of "SITE_NO" properties
* @param lac name of "SITE_ID" properties
* @param btsName name of "ITEM_NAME" properties
*/
public NodeName(String[] siteId, String[] siteN, String[] ItemName) {
id1 = siteId;
id2 = siteN;
id3 = ItemName;
for (String id : siteId) {
nameMap.put(id, SITE_ID);
}
for (String id : siteN) {
nameMap.put(id, SITE_NO);
}
for (String id : ItemName) {
nameMap.put(id, ITEM_NAME);
}
}
/**
* get Id1 (SITE_ID)
*
* @return id
*/
public String getId1() {
String ci = valuesMap.get(SITE_ID);
if (ci == null || ci.isEmpty()) {
return null;
}
return ci;
}
/**
* get Id1 (SITE_ID)
*
* @return id
*/
public String getId2() {
String ci = valuesMap.get(SITE_NO);
if (ci == null || ci.isEmpty()) {
return null;
}
return ci;
}
/**
* get Id1 (CI+LAC) of node
*
* @param node node
* @return id
*/
public static String getId1(Node node) {
return (String)node.getProperty(INeoConstants.PROPERTY_NAME_NAME, null);
}
/**
* get Id1 (CI+LAC) of node
*
* @param node node
* @return id
*/
public static String getId2(Node node) {
Object property = node.getProperty("site_no", null);
return property == null ? null : property.toString();
}
/**
* Checks node
*
* @param checkNode - current node
* @return true if current node contains necessary name
*/
public boolean isNecessaryNode(Node checkNode) {
if (!NeoUtils.getNodeType(checkNode, "").equals("site")) {
return false;
}
String siteId = valuesMap.get(SITE_ID);
String siteId2 = valuesMap.get(SITE_NO);
if (checkNode.hasProperty(SITE_NO) && siteId2 != null) {
return siteId2.equals(checkNode.getProperty(SITE_NO).toString());
}
return checkNode.hasProperty(INeoConstants.PROPERTY_NAME_NAME) && siteId != null
&& siteId.equals(checkNode.getProperty(INeoConstants.PROPERTY_NAME_NAME));
}
/**
* Sets the properties of sector
*
* @param fields array of values
*/
public void setFieldValues(String[] fields) {
valuesMap.clear();
for (String index : indexMap.keySet()) {
valuesMap.put(index, fields[indexMap.get(index)]);
}
}
/**
* Sets field index
*
* @param fieldHeader field name
* @param i - index
* @return true if NodeName contains field
*/
public boolean setFieldIndex(String fieldHeader, int i) {
String key = nameMap.get(fieldHeader);
// TODO identify column
if (key == null && fieldHeader.length() > 1) {
String findSubstring = fieldHeader.toLowerCase();
for (String nameKey : nameMap.keySet()) {
if (nameKey.toLowerCase().equals(findSubstring)) {
key = nameMap.get(nameKey);
break;
}
}
}
if (key == null) {
return false;
}
// because site and child site header have equal name
if (indexMap.get(key) != null) {
return false;
}
indexMap.put(key, i);
return true;
}
/**
* Check field
*
* @param field - field name
* @return true if NodeName contains field
*/
public boolean containsField(String field) {
return nameMap.keySet().contains(field);
}
}
}
| true | true | public void parseLine(String line, Node network, String fileName) {
String fields[] = splitLine(line);// line.split("\\t");
Transaction tx = neo.beginTx();
try {
String servCounName = NeoUtils.getTransmissionPropertyName(fileName);
serverNodeName.setFieldValues(fields);
neighbourNodeName.setFieldValues(fields);
String servId = serverNodeName.getId1();
Node serverNode = null;
if (servId != null) {
serverNode = index.getSingleNode(KEY_ID, servId);
if (serverNode == null) {
servId = serverNodeName.getId2();
serverNode = index.getSingleNode(KEY_ID2, servId);
}
}
Node neighbourNode = null;
String neighbourId = neighbourNodeName.getId1();
if (neighbourId != null) {
neighbourNode = index.getSingleNode(KEY_ID, neighbourId);
if (neighbourNode == null) {
neighbourId = neighbourNodeName.getId2();
neighbourNode = index.getSingleNode(KEY_ID2, neighbourId);
}
}
if (serverNode == null) {
serverNode = createTransmissionSite(serverNodeName, fields);
NeoLoaderPlugin.error("Not found site: " + servId);
}
if (neighbourNode == null) {
NeoLoaderPlugin.error("Not found site: " + neighbourId);
}
if (serverNode == null || neighbourNode == null) {
NeoLoaderPlugin.error("Not found sites for line:\n" + line);
return;
}
Relationship relation = serverNode.createRelationshipTo(neighbourNode, NetworkRelationshipTypes.TRANSMISSION);
relation.setProperty(INeoConstants.NEIGHBOUR_NAME, fileName);
for (Integer index : indexMap.keySet()) {
String value = fields[index];
if (value.length() > 0) {
saveValue(relation, index, value);
}
}
updateCount(serverNode, servCounName);
tx.success();
} catch (Exception e) {
NeoLoaderPlugin.error(line + "\n" + e.getLocalizedMessage());
} finally {
tx.finish();
}
}
| public void parseLine(String line, Node network, String fileName) {
String fields[] = splitLine(line);// line.split("\\t");
Transaction tx = neo.beginTx();
try {
String servCounName = NeoUtils.getTransmissionPropertyName(fileName);
serverNodeName.setFieldValues(fields);
neighbourNodeName.setFieldValues(fields);
String servId = serverNodeName.getId1();
Node serverNode = null;
if (servId != null) {
serverNode = index.getSingleNode(KEY_ID, servId);
if (serverNode == null) {
servId = serverNodeName.getId2();
serverNode = index.getSingleNode(KEY_ID2, servId);
}
}
Node neighbourNode = null;
String neighbourId = neighbourNodeName.getId1();
if (neighbourId != null) {
neighbourNode = index.getSingleNode(KEY_ID, neighbourId);
if (neighbourNode == null) {
neighbourId = neighbourNodeName.getId2();
neighbourNode = index.getSingleNode(KEY_ID2, neighbourId);
}
}
if (serverNode == null) {
serverNode = createTransmissionSite(serverNodeName, fields);
NeoLoaderPlugin.error("Not found site: " + servId);
}
if (neighbourNode == null) {
neighbourNode = createTransmissionSite(neighbourNodeName, fields);
NeoLoaderPlugin.error("Not found site: " + neighbourId);
}
if (serverNode == null || neighbourNode == null) {
NeoLoaderPlugin.error("Not found sites for line:\n" + line);
return;
}
Relationship relation = serverNode.createRelationshipTo(neighbourNode, NetworkRelationshipTypes.TRANSMISSION);
relation.setProperty(INeoConstants.NEIGHBOUR_NAME, fileName);
for (Integer index : indexMap.keySet()) {
String value = fields[index];
if (value.length() > 0) {
saveValue(relation, index, value);
}
}
updateCount(serverNode, servCounName);
tx.success();
} catch (Exception e) {
NeoLoaderPlugin.error(line + "\n" + e.getLocalizedMessage());
} finally {
tx.finish();
}
}
|
diff --git a/src/org/flowvisor/message/FVFlowRemoved.java b/src/org/flowvisor/message/FVFlowRemoved.java
index 7a50d68..bc57e78 100644
--- a/src/org/flowvisor/message/FVFlowRemoved.java
+++ b/src/org/flowvisor/message/FVFlowRemoved.java
@@ -1,116 +1,116 @@
package org.flowvisor.message;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.flowvisor.classifier.CookiePair;
import org.flowvisor.classifier.CookieTranslator;
import org.flowvisor.classifier.FVClassifier;
import org.flowvisor.flows.FlowEntry;
import org.flowvisor.flows.FlowMap;
import org.flowvisor.flows.SliceAction;
import org.flowvisor.log.FVLog;
import org.flowvisor.log.LogLevel;
import org.flowvisor.openflow.protocol.FVMatch;
import org.flowvisor.slicer.FVSlicer;
import org.openflow.protocol.OFFlowRemoved;
import org.openflow.protocol.OFMatch;
import org.openflow.protocol.action.OFAction;
public class FVFlowRemoved extends OFFlowRemoved implements Classifiable,
Slicable {
/**
* Current algorithm: if flow tracking knows who sent this flow, then just
* send to them
*
* If flow tracking doesn't know (or is disabled) send to everyone who
* *could* have sent the flow
*
* FIXME: do the reference counting so that if a flow is expanded three
* ways, only send the flow_removed up to the controller if all three flows
* have expired
*/
@Override
public void classifyFromSwitch(FVClassifier fvClassifier) {
FlowMap flowSpace = fvClassifier.getSwitchFlowMap();
Set<String> slicesToUpdate = new HashSet<String>();
String sliceName = fvClassifier.getFlowDB().processFlowRemoved(this,
fvClassifier.getDPID());
FVLog.log(LogLevel.DEBUG, fvClassifier, "Starting flowremoved message processing");
String slicerFromCookie = untanslateCookie(fvClassifier);
- FVLog.log(LogLevel.DEBUG, fvClassifier, slicerFromCookie);
+ //FVLog.log(LogLevel.DEBUG, fvClassifier, slicerFromCookie);
if (sliceName != null)
slicesToUpdate.add(sliceName);
else if (slicerFromCookie != null)
slicesToUpdate.add(slicerFromCookie);
else {
// flow tracking either disabled or broken
// just fall back to everyone who *could* have inserted this flow
List<FlowEntry> flowEntries = flowSpace.matches(
fvClassifier.getDPID(), new FVMatch(getMatch()));
for (FlowEntry flowEntry : flowEntries) {
for (OFAction ofAction : flowEntry.getActionsList()) {
if (ofAction instanceof SliceAction) {
SliceAction sliceAction = (SliceAction) ofAction;
if ((sliceAction.getSlicePerms() & SliceAction.WRITE) != 0) {
slicesToUpdate.add(sliceAction.getSliceName());
}
}
}
}
}
// forward this msg to each of them
FVLog.log(LogLevel.DEBUG, fvClassifier, slicesToUpdate.toString());
for (String slice : slicesToUpdate) {
FVSlicer fvSlicer = fvClassifier.getSlicerByName(slice);
if (fvSlicer == null) {
FVLog.log(LogLevel.CRIT, fvClassifier,
"inconsistent state: missing fvSliver entry for: "
+ slice);
continue;
}
fvSlicer.decrementFlowRules();
fvSlicer.getFlowRewriteDB().processFlowRemoved(this);
fvSlicer.sendMsg(this, fvClassifier);
}
}
@Override
public void sliceFromController(FVClassifier fvClassifier, FVSlicer fvSlicer) {
FVMessageUtil.dropUnexpectedMesg(this, fvSlicer);
}
public FVFlowRemoved setMatch(FVMatch match) {
this.match = match;
return this;
}
private String untanslateCookie(FVClassifier fvClassifier) {
CookieTranslator cookieTrans = fvClassifier.getCookieTranslator();
CookiePair pair = cookieTrans.untranslate(this.cookie);
if (pair == null) {
FVLog.log(LogLevel.DEBUG, fvClassifier, "Returning null");
return null;
}
this.setCookie(pair.getCookie());
FVLog.log(LogLevel.DEBUG, fvClassifier, pair.getSliceName());
return pair.getSliceName();
}
@Override
public OFMatch getMatch() {
return this.match;
}
@Override
public String toString() {
return super.toString() + ";" + this.getMatch().toString();
}
}
| true | true | public void classifyFromSwitch(FVClassifier fvClassifier) {
FlowMap flowSpace = fvClassifier.getSwitchFlowMap();
Set<String> slicesToUpdate = new HashSet<String>();
String sliceName = fvClassifier.getFlowDB().processFlowRemoved(this,
fvClassifier.getDPID());
FVLog.log(LogLevel.DEBUG, fvClassifier, "Starting flowremoved message processing");
String slicerFromCookie = untanslateCookie(fvClassifier);
FVLog.log(LogLevel.DEBUG, fvClassifier, slicerFromCookie);
if (sliceName != null)
slicesToUpdate.add(sliceName);
else if (slicerFromCookie != null)
slicesToUpdate.add(slicerFromCookie);
else {
// flow tracking either disabled or broken
// just fall back to everyone who *could* have inserted this flow
List<FlowEntry> flowEntries = flowSpace.matches(
fvClassifier.getDPID(), new FVMatch(getMatch()));
for (FlowEntry flowEntry : flowEntries) {
for (OFAction ofAction : flowEntry.getActionsList()) {
if (ofAction instanceof SliceAction) {
SliceAction sliceAction = (SliceAction) ofAction;
if ((sliceAction.getSlicePerms() & SliceAction.WRITE) != 0) {
slicesToUpdate.add(sliceAction.getSliceName());
}
}
}
}
}
// forward this msg to each of them
FVLog.log(LogLevel.DEBUG, fvClassifier, slicesToUpdate.toString());
for (String slice : slicesToUpdate) {
FVSlicer fvSlicer = fvClassifier.getSlicerByName(slice);
if (fvSlicer == null) {
FVLog.log(LogLevel.CRIT, fvClassifier,
"inconsistent state: missing fvSliver entry for: "
+ slice);
continue;
}
fvSlicer.decrementFlowRules();
fvSlicer.getFlowRewriteDB().processFlowRemoved(this);
fvSlicer.sendMsg(this, fvClassifier);
}
}
| public void classifyFromSwitch(FVClassifier fvClassifier) {
FlowMap flowSpace = fvClassifier.getSwitchFlowMap();
Set<String> slicesToUpdate = new HashSet<String>();
String sliceName = fvClassifier.getFlowDB().processFlowRemoved(this,
fvClassifier.getDPID());
FVLog.log(LogLevel.DEBUG, fvClassifier, "Starting flowremoved message processing");
String slicerFromCookie = untanslateCookie(fvClassifier);
//FVLog.log(LogLevel.DEBUG, fvClassifier, slicerFromCookie);
if (sliceName != null)
slicesToUpdate.add(sliceName);
else if (slicerFromCookie != null)
slicesToUpdate.add(slicerFromCookie);
else {
// flow tracking either disabled or broken
// just fall back to everyone who *could* have inserted this flow
List<FlowEntry> flowEntries = flowSpace.matches(
fvClassifier.getDPID(), new FVMatch(getMatch()));
for (FlowEntry flowEntry : flowEntries) {
for (OFAction ofAction : flowEntry.getActionsList()) {
if (ofAction instanceof SliceAction) {
SliceAction sliceAction = (SliceAction) ofAction;
if ((sliceAction.getSlicePerms() & SliceAction.WRITE) != 0) {
slicesToUpdate.add(sliceAction.getSliceName());
}
}
}
}
}
// forward this msg to each of them
FVLog.log(LogLevel.DEBUG, fvClassifier, slicesToUpdate.toString());
for (String slice : slicesToUpdate) {
FVSlicer fvSlicer = fvClassifier.getSlicerByName(slice);
if (fvSlicer == null) {
FVLog.log(LogLevel.CRIT, fvClassifier,
"inconsistent state: missing fvSliver entry for: "
+ slice);
continue;
}
fvSlicer.decrementFlowRules();
fvSlicer.getFlowRewriteDB().processFlowRemoved(this);
fvSlicer.sendMsg(this, fvClassifier);
}
}
|
diff --git a/services/org/powertac/householdcustomer/HouseholdCustomerInitializationService.java b/services/org/powertac/householdcustomer/HouseholdCustomerInitializationService.java
index 9ede0b5..df46718 100644
--- a/services/org/powertac/householdcustomer/HouseholdCustomerInitializationService.java
+++ b/services/org/powertac/householdcustomer/HouseholdCustomerInitializationService.java
@@ -1,83 +1,83 @@
/*
* 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.powertac.householdcustomer;
import java.io.IOException;
import java.util.List;
import org.apache.log4j.Logger;
import org.powertac.common.Competition;
import org.powertac.common.PluginConfig;
import org.powertac.common.interfaces.InitializationService;
import org.powertac.common.repo.PluginConfigRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* Pre-game initialization for the Household Customers
* @author Antonios Chrysopoulos
*/
@Service
public class HouseholdCustomerInitializationService implements InitializationService
{
/**
* logger for trace logging -- use log.info(), log.warn(), and log.error() appropriately. Use
* log.debug() for output you want to see in testing or debugging.
*/
static private Logger log = Logger.getLogger(HouseholdCustomerInitializationService.class.getName());
@Autowired
private HouseholdCustomerService householdCustomerService;
@Autowired
private PluginConfigRepo pluginConfigRepo;
/**
* This method is called during pre-game to set defaults. In this example the default value of the
* parameter is hard-coded, but in general it would make sense to take it from a config file. The
* result is a PluginConfig instance that can be viewed and modified through the web interface
* before a game is started.
*/
public void setDefaults ()
{
pluginConfigRepo.makePluginConfig("HouseholdCustomer", "").addConfiguration("configFile", "src/org/powertac/common/configurations/Household.properties");
}
/**
* Called during game startup to set initial conditions for Generic Customer Service. In order to
* begin this Service the Default Broker must be initialized first.
*/
public String initialize (Competition competition, List<String> completedInits)
{
if (!completedInits.contains("DefaultBroker")) {
log.debug("waiting for DefaultBroker to initialize");
return null;
}
PluginConfig config = pluginConfigRepo.findByRoleName("HouseholdCustomer");
if (config == null) {
log.error("PluginConfig for HouseholdCustomer does not exist.");
return "fail";
}
try {
householdCustomerService.init(config);
} catch (IOException e) {
- log.info("Error with configuration file");
+ log.error("Error with configuration file");
}
return "HouseholdCustomer";
}
}
| true | true | public String initialize (Competition competition, List<String> completedInits)
{
if (!completedInits.contains("DefaultBroker")) {
log.debug("waiting for DefaultBroker to initialize");
return null;
}
PluginConfig config = pluginConfigRepo.findByRoleName("HouseholdCustomer");
if (config == null) {
log.error("PluginConfig for HouseholdCustomer does not exist.");
return "fail";
}
try {
householdCustomerService.init(config);
} catch (IOException e) {
log.info("Error with configuration file");
}
return "HouseholdCustomer";
}
| public String initialize (Competition competition, List<String> completedInits)
{
if (!completedInits.contains("DefaultBroker")) {
log.debug("waiting for DefaultBroker to initialize");
return null;
}
PluginConfig config = pluginConfigRepo.findByRoleName("HouseholdCustomer");
if (config == null) {
log.error("PluginConfig for HouseholdCustomer does not exist.");
return "fail";
}
try {
householdCustomerService.init(config);
} catch (IOException e) {
log.error("Error with configuration file");
}
return "HouseholdCustomer";
}
|
diff --git a/Exercise1/src/main/java/at/ac/tuwien/complang/carfactory/application/FactoryFacade.java b/Exercise1/src/main/java/at/ac/tuwien/complang/carfactory/application/FactoryFacade.java
index 8df1b35..aa6a5d5 100644
--- a/Exercise1/src/main/java/at/ac/tuwien/complang/carfactory/application/FactoryFacade.java
+++ b/Exercise1/src/main/java/at/ac/tuwien/complang/carfactory/application/FactoryFacade.java
@@ -1,96 +1,96 @@
package at.ac.tuwien.complang.carfactory.application;
import java.util.Hashtable;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import org.mozartspaces.core.Capi;
import org.mozartspaces.core.ContainerReference;
public class FactoryFacade {
//Static Fields
private static Map<ProducerType, FactoryFacade> factories;
static {
factories = new Hashtable<ProducerType, FactoryFacade>();
}
//Fields
private int count;
private boolean running = false;
private Thread thread;
private IProducer producer;
private FactoryFacade(ProducerType type, Capi capi, ContainerReference cref) {
switch(type) {
case BODY: producer = new BodyFactory(capi, cref); break;
case WHEEL: producer = new WheelFactory(capi, cref); break;
case MOTOR: producer = new MotorFactory(capi, cref); break;
default: throw new IllegalArgumentException("Specificed ProducerType is not implemented");
}
}
public static FactoryFacade getInstance(ProducerType type, Capi capi, ContainerReference cref) {
if(factories.get(type) == null) {
synchronized(FactoryFacade.class) {
if(factories.get(type) == null) {
FactoryFacade.factories.put(type, new FactoryFacade(type, capi, cref));
}
}
}
return factories.get(type);
}
public void start() {
this.running = true;
//start the timer task and produce bodies
this.thread.start();
}
public void stop() {
this.count = 0;
this.thread.interrupt();
this.running = false;
}
public void init(int count) throws IllegalStateException {
if(running) {
throw new IllegalStateException("Factory must be stopped first");
}
this.count = count;
//Prepare TimerTask
thread = new Thread(new Producer());
}
class Producer implements Runnable {
public void run() {
int originalCount = count;
int delay = 0;
int total = 0;
while(count > 0) {
//The producer sleeps for a random period between 1 and 3 seconds
delay = (int) (Math.random() * 3) + 1;
total += delay;
int millisecondsPerSecond = 1000;
try {
Thread.sleep(delay * millisecondsPerSecond);
} catch (InterruptedException e) {
System.err.println("Producer was interrupted.");
}
//TODO: Produce a Body...
count--;
producer.produce();
System.out.println("Time to produce was " + delay + " seconds. Parts remaining: " + count);
}
- System.out.println("All done. Average time to produce: " + total / (double) originalCount);
+ System.out.println("All done. Average time to produce: " + total / (double) originalCount + " seconds.");
}
}
}
| true | true | public void run() {
int originalCount = count;
int delay = 0;
int total = 0;
while(count > 0) {
//The producer sleeps for a random period between 1 and 3 seconds
delay = (int) (Math.random() * 3) + 1;
total += delay;
int millisecondsPerSecond = 1000;
try {
Thread.sleep(delay * millisecondsPerSecond);
} catch (InterruptedException e) {
System.err.println("Producer was interrupted.");
}
//TODO: Produce a Body...
count--;
producer.produce();
System.out.println("Time to produce was " + delay + " seconds. Parts remaining: " + count);
}
System.out.println("All done. Average time to produce: " + total / (double) originalCount);
}
| public void run() {
int originalCount = count;
int delay = 0;
int total = 0;
while(count > 0) {
//The producer sleeps for a random period between 1 and 3 seconds
delay = (int) (Math.random() * 3) + 1;
total += delay;
int millisecondsPerSecond = 1000;
try {
Thread.sleep(delay * millisecondsPerSecond);
} catch (InterruptedException e) {
System.err.println("Producer was interrupted.");
}
//TODO: Produce a Body...
count--;
producer.produce();
System.out.println("Time to produce was " + delay + " seconds. Parts remaining: " + count);
}
System.out.println("All done. Average time to produce: " + total / (double) originalCount + " seconds.");
}
|
diff --git a/cerberus_core/src/cerberus/view/opengl/canvas/heatmap/GLCanvasHeatmap2DColumn.java b/cerberus_core/src/cerberus/view/opengl/canvas/heatmap/GLCanvasHeatmap2DColumn.java
index a140dd9ca..32ae1452f 100644
--- a/cerberus_core/src/cerberus/view/opengl/canvas/heatmap/GLCanvasHeatmap2DColumn.java
+++ b/cerberus_core/src/cerberus/view/opengl/canvas/heatmap/GLCanvasHeatmap2DColumn.java
@@ -1,1763 +1,1763 @@
/**
*
*/
package cerberus.view.opengl.canvas.heatmap;
import gleem.linalg.Vec2f;
import java.awt.Point;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import javax.media.opengl.GL;
import org.geneview.graph.EGraphItemHierarchy;
import org.geneview.graph.EGraphItemProperty;
import org.geneview.graph.IGraph;
import org.geneview.graph.IGraphItem;
import cerberus.data.collection.IVirtualArray;
import cerberus.data.collection.ISet;
import cerberus.data.collection.IStorage;
import cerberus.data.collection.set.selection.SetSelection;
import cerberus.data.collection.storage.FlatThreadStorageSimple;
import cerberus.data.collection.virtualarray.iterator.IVirtualArrayIterator;
import cerberus.data.graph.core.PathwayGraph;
import cerberus.data.graph.item.vertex.PathwayVertexGraphItem;
//import cerberus.data.graph.item.vertex.PathwayVertexGraphItemRep;
//import cerberus.data.mapping.GenomeMappingType;
import cerberus.manager.IGeneralManager;
import cerberus.manager.ILoggerManager.LoggerType;
//import cerberus.manager.data.IGenomeIdManager;
import cerberus.manager.event.EventPublisher;
import cerberus.manager.event.mediator.IMediatorReceiver;
import cerberus.manager.event.mediator.IMediatorSender;
//import cerberus.math.statistics.minmax.MinMaxDataInteger;
//import cerberus.view.jogl.mouse.PickingJoglMouseListener; //import cerberus.view.opengl.canvas.heatmap.AGLCanvasHeatmap2D;
import cerberus.view.opengl.canvas.heatmap.GLCanvasHeatmap2D;
import cerberus.view.opengl.canvas.pathway.GLPathwayManager;
import cerberus.view.opengl.util.GLInfoAreaRenderer;
/**
* @author Michael Kalkusch
*
* @see cerberus.view.opengl.IGLCanvasUser
*/
public class GLCanvasHeatmap2DColumn
//extends AGLCanvasHeatmap2D
extends GLCanvasHeatmap2D
implements IMediatorReceiver, IMediatorSender, IGLCanvasHeatmap2D {
public static final int OFFSET = AGLCanvasHeatmap2D.OFFSET;
public static final int X = AGLCanvasHeatmap2D.X;
public static final int MIN = AGLCanvasHeatmap2D.MIN;
public static final int Y = AGLCanvasHeatmap2D.Y;
public static final int Z = AGLCanvasHeatmap2D.Z;
public static final int MAX = AGLCanvasHeatmap2D.MAX;
private float fSelectionPixel = 0.1f;
private float fSelectionLineWidth = 2.0f;
private boolean bRenderingStyleFlat = false;
private int iSelectedMode_identifyier = 0;
private float fIncX_forSelection;
/**
* If this limit is exceeded no lines between the data values will be shown
*/
private final int iRenderIndexLength_UpperLimit = 1000;
private boolean bRenderEnableDelimiterPerExperiment = true;
//private int[] iIndexPickedCoored = {-1,-1};
/**
* used to store index, that shall not be rendered.
*/
private HashMap <Integer,Boolean> hashHighlightSelectionIndex;
/**
*
*/
private ArrayList < ArrayList <Integer>> alHighlightSelectionIndex_sortByDepth;
//private HashMap<Integer, Integer> hashNCBI_GENE2index;
private int[] selectedIndex;
private int[] selectedIndexMode;
private HashMap<Integer, Integer> hashExternalId_2_HeatmapIndex;
private HashMap<Integer, Integer> hashExternalId_2_HeatmapIndex_reverse;
private int iRenderIndexStart = 0;
private int iRenderIndexStop = 80;
private static final int iInitialSizeArrayList_Selection = 10;
private ArrayList<ISet> alTargetSet;
private PathwayVertexGraphItem pickedGeneVertex;
private GLInfoAreaRenderer infoAreaRenderer;
/**
* @param setGeneralManager
*/
public GLCanvasHeatmap2DColumn(final IGeneralManager setGeneralManager,
int iViewId,
int iParentContainerId,
String sLabel) {
super(setGeneralManager, iViewId, iParentContainerId, sLabel);
//hashNCBI_GENE2index = new HashMap<Integer, Integer>();
System.err.println(" GLCanvasHeatmap2DColumn()");
selectedIndex = new int[0];
selectedIndexMode = new int[0];
//hashExternalId_2_HeatmapIndex = new HashMap<Integer, Integer>(100);
alTargetSet = new ArrayList<ISet>(10);
hashHighlightSelectionIndex = new HashMap <Integer,Boolean> ();
// int[] selIndex =
// { 3, 5, 10, 15 };
// int[] selIndexMode =
// { 0, 1, 2, 3 };
// this.setSelectedIndex(selIndex, selIndexMode);
alHighlightSelectionIndex_sortByDepth = new ArrayList < ArrayList <Integer>> (5);
alHighlightSelectionIndex_sortByDepth.add( new ArrayList <Integer> (
GLCanvasHeatmap2DColumn.iInitialSizeArrayList_Selection));
infoAreaRenderer = new GLInfoAreaRenderer(refGeneralManager,
new GLPathwayManager(setGeneralManager));
}
private int addhighlightSelectionIndex_addItem( ArrayList < ArrayList <Integer>> container,
final Integer value,
final int mode,
final int containerSize) {
if ( mode < containerSize ) {
/* allocate new */
int iDifference = mode - containerSize;
/* insert missing empty ArrayList <Integer> objects .. */
for (int i=0; i<iDifference; i++) {
container.add( new ArrayList<Integer> (
GLCanvasHeatmap2DColumn.iInitialSizeArrayList_Selection));
}
container.get(mode).add( new Integer(value));
return mode;
}
container.get(mode).add( new Integer(value));
return containerSize;
}
private void removehighlightSelectionIndex_Item( ArrayList < ArrayList <Integer>> container,
final Integer value ) {
Iterator <ArrayList <Integer>> iter = container.iterator();
while ( iter.hasNext()) {
if ( iter.next().remove( value ) ) {
/* found value, exit immediately */
return;
}
} //while ( iter.hasNext()) {
assert false : "value could not be removed!";
}
protected void assignHighlightSelectionIndex( final ArrayList <Integer> indexList,
final ArrayList <Integer> indexListMode ) {
Iterator<Integer> iterIndex = indexList.iterator();
Iterator<Integer> iterIndexMode = indexListMode.iterator();
int iSizeContainer = alHighlightSelectionIndex_sortByDepth.size();
while (iterIndex.hasNext()) {
Integer buffer = iterIndex.next();
int bufferMode = iterIndexMode.next().intValue();
if ( bufferMode > 0 ) {
iSizeContainer = addhighlightSelectionIndex_addItem(
this.alHighlightSelectionIndex_sortByDepth,
buffer,
bufferMode,
iSizeContainer);
hashHighlightSelectionIndex.put(buffer, new Boolean(true));
} else {
removehighlightSelectionIndex_Item(alHighlightSelectionIndex_sortByDepth, buffer);
hashHighlightSelectionIndex.remove(buffer);
} //if ( bufferMode > 0 ) {..}else{..
} //alHighlightSelectionIndex_sortByDepth
}
public void setSelectedIndex_asArrayList(
final ArrayList<Integer> updateIndex,
final ArrayList<Integer> updateIndexMode) {
/* integrity check.. */
if (updateIndex.size() != updateIndexMode.size())
{
assert false : "setSelectedIndex() int [] updateIndex != int [] updateIndexMode !";
return;
}
/* write local hashExternalId_2_HeatmapIndex to global variables int[] selectedIndex and int[] selectedIndexMode .. */
/* does size of arrays fit? */
if (selectedIndex.length != updateIndex.size())
{
selectedIndex = new int[updateIndex.size()];
selectedIndexMode = new int[updateIndex.size()];
}
for ( int index=0; index< updateIndex.size(); index++ ) {
selectedIndex[index] = updateIndex.get(index);
selectedIndexMode[index] = updateIndexMode.get(index).intValue();
}
}
public void setSelectedIndex(final int[] updateIndex,
final int[] updateIndexMode) {
/* integrity check.. */
if (updateIndex.length != updateIndexMode.length)
{
assert false : "setSelectedIndex() int [] updateIndex != int [] updateIndexMode !";
return;
}
boolean bUpdate = false;
for (int i = 0; i < updateIndex.length; i++)
{
if (hashExternalId_2_HeatmapIndex.containsKey(updateIndex[i]))
{
if (hashExternalId_2_HeatmapIndex.get(updateIndex[i]).intValue() != updateIndexMode[i])
{
hashExternalId_2_HeatmapIndex.put(updateIndex[i], updateIndexMode[i]);
bUpdate = true;
}
/* else .. data is identical to data in HashMap! */
} else
{
hashExternalId_2_HeatmapIndex.put(updateIndex[i], updateIndexMode[i]);
bUpdate = true;
}
}
if (bUpdate)
{
/* does size of arrays fit? */
if (selectedIndex.length != hashExternalId_2_HeatmapIndex.size())
{
selectedIndex = new int[hashExternalId_2_HeatmapIndex.size()];
selectedIndexMode = new int[hashExternalId_2_HeatmapIndex.size()];
}
Iterator<Integer> keys = hashExternalId_2_HeatmapIndex.keySet().iterator();
Iterator<Integer> values = hashExternalId_2_HeatmapIndex.values().iterator();
for (int index = 0; keys.hasNext(); index++)
{
selectedIndex[index] = keys.next().intValue();
selectedIndexMode[index] = values.next().intValue();
}
} //if ( bUpdate ) {
}
// private void renderGL_Selection(GL gl) {
//
// if (selectedIndex.length < 1)
// {
// /* nothing to render.. */
// return;
// }
//
// /* public void render_displayListHeatmap(GL gl) { */
//
// gl.glNormal3f(0.0f, 0.0f, 1.0f);
//
// /**
// * force update ...
// */
//
// float fIncX = (viewingFrame[X][MAX] - viewingFrame[X][MIN])
// / (float) (iValuesInRow);
//
//// float fIncY = (viewingFrame[Y][MAX] - viewingFrame[X][MIN])
//// / (float) (iValuesInColum);
//
// /* Y_min .. Y_max*/
// for (int index = 0; index < selectedIndex.length; index++)
// {
// float fNowY = viewingFrame[Y][MIN];
// float fNextY = viewingFrame[Y][MAX];
//
// float fNowX = viewingFrame[X][MIN] + fIncX * selectedIndex[index];
// float fNextX = fNowX + fIncX;
//
// gl.glBegin(GL.GL_TRIANGLE_FAN);
//
// gl.glVertex3f(fNowX, fNowY, viewingFrame[Z][MIN]);
// gl.glVertex3f(fNextX, fNowY, viewingFrame[Z][MIN]);
// gl.glVertex3f(fNextX, fNextY, viewingFrame[Z][MIN]);
// gl.glVertex3f(fNowX, fNextY, viewingFrame[Z][MIN]);
//
// gl.glEnd();
// gl.glPopName();
//
// } //for (int yCoord_name=0; yCoord_name<iValuesInRow; yCoord_name++)
//
// }
/**
* init after IGenomeIdManager has load all its data from file.
*/
//protected void init(final IGenomeIdManager readFromIGenomeIdManager) {
protected void init_External2InternalHashMap() {
HashMap <Integer,Integer> hashNCBI_GENEID_2_internalGraphVertexId =
refGeneralManager.getSingelton().getPathwayItemManager().getHashNCBIGeneIdToPathwayVertexGraphItemId();
// IGenomeIdManager refIGenomeIdManager = refGeneralManager.getSingelton()
// .getGenomeIdManager();
//
// hashNCBI_GENE2index = refIGenomeIdManager
// .getAllValuesByGenomeIdTypeHashMap(GenomeMappingType.NCBI_GENEID_2_NCBI_GENEID_CODE);
//
// if ( hashNCBI_GENE2index == null ) {
// refGeneralManager.getSingelton().logMsg("Can not load NCBI_GENEID mapping!", LoggerType.MINOR_ERROR_XML);
//
// return;
// }
//
//
// /* create HashMap now.. */
// hashExternalId_2_HeatmapIndex_reverse = new HashMap<Integer, Integer>();
// Iterator<Integer> iter = hashNCBI_GENE2index.keySet().iterator();
//
// for (int index=0; iter.hasNext(); index++) {
// hashExternalId_2_HeatmapIndex_reverse.put(new Integer(index), iter.next());
// }
hashExternalId_2_HeatmapIndex = new HashMap<Integer, Integer>(hashNCBI_GENEID_2_internalGraphVertexId.size());
hashExternalId_2_HeatmapIndex_reverse = new HashMap<Integer, Integer>(hashNCBI_GENEID_2_internalGraphVertexId.size());
Iterator<Integer> iter_InternalGraphVertexId =
hashNCBI_GENEID_2_internalGraphVertexId.values().iterator();
for ( int index = 0; iter_InternalGraphVertexId.hasNext(); index++ ) {
Integer buffer = iter_InternalGraphVertexId.next();
hashExternalId_2_HeatmapIndex.put(buffer, new Integer(index));
hashExternalId_2_HeatmapIndex_reverse.put(new Integer(index),buffer);
}
}
public void setKeysForHeatmap(int[] keys) {
}
public void selectKeys(int[] keys) {
}
/* --------------------------- */
/* ----- BEGEN: PICKING ----- */
protected final boolean processHits(final GL gl, int iHitCount,
int iArPickingBuffer[], final Point pickPoint,
ArrayList<Vec2f> fIndexPickedCoored) {
// System.out.println("Number of hits: " +iHitCount);
float fDepthSort = Float.MAX_VALUE;
int iResultPickCoordIndex = 0;
int[] resultPickPointCoord =
{ -1, -1 };
int iPtr = 0;
int i = 0;
//int iPickedObjectId = 0;
System.out.println("GLCanvasHeatmap2DColumn PICK: ----- ");
// Only pick object that is nearest
for (i = 0; i < iHitCount; i++)
{
int iNumbersPerHit = iArPickingBuffer[iPtr];
System.out.print(" #name for this hit=" + iArPickingBuffer[iPtr]);
iPtr++;
// // Check if object is nearer than previous objects
// if (iArPickingBuffer[iPtr] < iMinimumZValue)
// {
// System.out.print(" nearer than previous hit! ");
// }
/* ist doch ein float! */
//iMinimumZValue = iArPickingBuffer[iPtr];
float fZmin = (float) iArPickingBuffer[iPtr];
System.out.print(" minZ=" + fZmin);
iPtr++;
System.out.print(" maxZ=" + (float) iArPickingBuffer[iPtr]);
iPtr++;
System.out.print(" Pick-> [");
int iName = -1;
for (int j = 0; j < iNumbersPerHit; j++)
{
iName = iArPickingBuffer[iPtr];
if (fZmin < fDepthSort)
{
fDepthSort = fZmin - AGLCanvasHeatmap2D.fPickingBias;
if (iResultPickCoordIndex < 2)
{
resultPickPointCoord[iResultPickCoordIndex] = iName;
iResultPickCoordIndex++;
}
}
System.out.print(" #" + i + " name=" + iName + ",");
iPtr++;
}
System.out.println("]");
}
if (iHitCount < 1)
{
// Remove pathway pool fisheye
return false;
}
System.out
.println("GLCanvasHeatmap2DColumn PICKED index=["
+ resultPickPointCoord[0] + ","
+ resultPickPointCoord[1] + "]");
// Reset pick point
//source of problems??
infoAreaRenderer.convertWindowCoordinatesToWorldCoordinates(gl,
pickPoint.x, pickPoint.y);
// // Check if real picking is performed
// if (bIsMousePickingEvent)
// {
int[] selectedIndexArray = addPickedPoint(fIndexPickedCoored,
(float) resultPickPointCoord[0],
(float) resultPickPointCoord[1] );
if ( selectedIndexArray != null ) {
/** notify other listeners .. */
notifyReceiver_PickedObject_singleSelection(selectedIndexArray, iSelectedMode_identifyier);
// Integer iNCBIGeneID = hashExternalId_2_HeatmapIndex_reverse.get(resultPickPointCoord[0]);
// if ( iNCBIGeneID != null)
// {
// PathwayVertexGraphItem pickedGeneVertex;
// pickedGeneVertex = (PathwayVertexGraphItem) refGeneralManager.getSingelton(
// ).getPathwayItemManager().getItem(iNCBIGeneID.intValue());
//
// infoAreaRenderer.renderInfoArea(gl, pickedGeneVertex);
// }
}
/* hack, check if external hashmap was already created */
//TODO: clean up this call, init from outside as soon as data is available!
if ( hashExternalId_2_HeatmapIndex==null ) {
this.init_External2InternalHashMap();
}
Integer iNCBIGeneID = hashExternalId_2_HeatmapIndex_reverse.get(resultPickPointCoord[0]);
if ( iNCBIGeneID != null)
{
//PathwayVertexGraphItem pickedGeneVertex;
pickedGeneVertex = (PathwayVertexGraphItem) refGeneralManager.getSingelton(
).getPathwayItemManager().getItem(iNCBIGeneID.intValue());
assert pickedGeneVertex != null : "should not get null-pointer!";
infoAreaRenderer.renderInfoArea(gl, pickedGeneVertex);
}
//source of problems??
//infoAreaRenderer.resetPoint();
// }
return true;
}
/* ----- END: PICKING ----- */
/* --------------------------- */
/* ----- END: PICKING ----- */
/* --------------------------- */
private void notifyReceiver_PickedObject_singleSelection( final int [] resultPickPointCoord, final int iModeValue) {
if ( resultPickPointCoord.length < 1) {
return;
}
int [] resultSelectedIndex = new int [resultPickPointCoord.length];
int [] resultSelectedIndexMode = new int [resultPickPointCoord.length];
/* copy new indices to end of existing array.. */
for ( int iIndex=0; iIndex<resultPickPointCoord.length; iIndex++) {
resultSelectedIndex[iIndex] = resultPickPointCoord[iIndex];
resultSelectedIndexMode[iIndex] = iModeValue;
}
/* swap .. */
selectedIndex = resultSelectedIndex;
selectedIndexMode = resultSelectedIndexMode;
/* hack, check if external hashmap was already created */
//TODO: clean up this call, init from outside as soon as data is available!
if ( hashExternalId_2_HeatmapIndex==null ) {
this.init_External2InternalHashMap();
}
/* notify external objects via eventMediator.. */
if ( hashExternalId_2_HeatmapIndex_reverse != null ) {
/* data for SetSelection.. */
SetSelection selectionSet = new SetSelection(-5, refGeneralManager);
ArrayList <Integer> alSelectionId = new ArrayList <Integer> (resultPickPointCoord.length);
ArrayList <Integer> alSelectionId_PathwayId = new ArrayList <Integer> (resultPickPointCoord.length);
for ( int i=0; i< resultPickPointCoord.length; i++ ) {
/* convert internal index to external id.. */
Integer lookupValue = hashExternalId_2_HeatmapIndex_reverse.get(resultPickPointCoord[i]);
if ( lookupValue == null ) {
return;
}
PathwayVertexGraphItem vertexItemBuffer = (PathwayVertexGraphItem) refGeneralManager.getSingelton()
.getPathwayItemManager().getItem(lookupValue.intValue());
Iterator <IGraphItem> iterList =
vertexItemBuffer.getAllItemsByProp(EGraphItemProperty.ALIAS_CHILD).iterator();
while (iterList.hasNext()) {
IGraphItem bufferItem = iterList.next();
alSelectionId.add( bufferItem.getId() );
//alSelectionId.add( iterList.next().getId() );
// get pathway id from graph
List<IGraph> list = bufferItem.getAllGraphByType(EGraphItemHierarchy.GRAPH_PARENT);
PathwayGraph buffer = (PathwayGraph) list.get(0);
alSelectionId_PathwayId.add( buffer.getKeggId() );
}
}
int[] iArSelectionId = new int[alSelectionId.size()];
int[] iArSelectionDepthData = new int[alSelectionId.size()];
int[] iArSelectionOptionalData = new int[alSelectionId.size()];
for ( int i=0; i < alSelectionId.size(); i++) {
iArSelectionId[i] = alSelectionId.get(i).intValue();
iArSelectionDepthData[i] = iModeValue;
iArSelectionOptionalData[i] = alSelectionId_PathwayId.get(i);
}
IStorage [] storageArray = new IStorage [3];
for ( int i=0; i< 3 ; i++ ) {
storageArray[i] = new FlatThreadStorageSimple( selectionSet.getId(), refGeneralManager, null);
selectionSet.setStorageByDim(storageArray, 0);
}
selectionSet.setAllSelectionDataArrays(iArSelectionId, iArSelectionDepthData, iArSelectionOptionalData );
// Calls update with the ID of the PathwayViewRep
((EventPublisher)refGeneralManager.getSingelton().
getEventPublisher()).updateReceiver(this, selectionSet);
refGeneralManager.getSingelton().logMsg(this.getClass().getSimpleName()+
".broadcast selection event! " + selectionSet.toString(),
LoggerType.STATUS);
}
}
private void notifyReceiver_PickedObject_multipleSelection( final int [] resultPickPointCoord, final int iModeValue) {
if ( resultPickPointCoord.length < 1) {
return;
}
int [] resultSelectedIndex = new int [selectedIndex.length + resultPickPointCoord.length];
int [] resultSelectedIndexMode = new int [selectedIndex.length + resultPickPointCoord.length];
/* copy existing array.. */
for ( int i=0; i< selectedIndex.length; i++ ) {
resultSelectedIndex[i]= selectedIndex[i];
resultSelectedIndexMode[i]=selectedIndexMode[i];
}
/* copy new indices to end of existing array.. */
int iIndex = selectedIndex.length;
for ( int i=0; i<resultPickPointCoord.length; i++) {
resultSelectedIndex[iIndex] = resultPickPointCoord[i];
resultSelectedIndexMode[iIndex] = iModeValue;
iIndex++;
}
/* swap .. */
selectedIndex = resultSelectedIndex;
selectedIndexMode = resultSelectedIndexMode;
if ( hashExternalId_2_HeatmapIndex==null ) {
this.init_External2InternalHashMap();
}
/* notify external objects via eventMediator.. */
if ( hashExternalId_2_HeatmapIndex_reverse != null ) {
/* data for SetSelection.. */
SetSelection selectionSet = new SetSelection(-5, refGeneralManager);
ArrayList <Integer> alSelectionId = new ArrayList <Integer> (resultPickPointCoord.length);
ArrayList <Integer> alSelectionId_PathwayId = new ArrayList <Integer> (resultPickPointCoord.length);
for ( int i=0; i< resultPickPointCoord.length; i++ ) {
/* convert internal index to external id.. */
Integer lookupValue = hashExternalId_2_HeatmapIndex_reverse.get(resultPickPointCoord[i]);
if ( lookupValue == null ) {
return;
}
PathwayVertexGraphItem vertexItemBuffer = (PathwayVertexGraphItem) refGeneralManager.getSingelton()
.getPathwayItemManager().getItem(lookupValue.intValue());
Iterator <IGraphItem> iterList =
vertexItemBuffer.getAllItemsByProp(EGraphItemProperty.ALIAS_CHILD).iterator();
while (iterList.hasNext()) {
IGraphItem bufferItem = iterList.next();
alSelectionId.add( bufferItem.getId() );
//alSelectionId.add( iterList.next().getId() );
// get pathway id from graph
List<IGraph> list = bufferItem.getAllGraphByType(EGraphItemHierarchy.GRAPH_PARENT);
PathwayGraph buffer = (PathwayGraph) list.get(0);
alSelectionId_PathwayId.add( buffer.getKeggId() );
}
}
int[] iArSelectionId = new int[alSelectionId.size()];
int[] iArSelectionDepthData = new int[alSelectionId.size()];
int[] iArSelectionOptionalData = new int[alSelectionId.size()];
for ( int i=0; i < alSelectionId.size(); i++) {
iArSelectionId[i] = alSelectionId.get(i).intValue();
iArSelectionDepthData[i] = iModeValue;
iArSelectionOptionalData[i] = alSelectionId_PathwayId.get(i);
}
IStorage [] storageArray = new IStorage [3];
for ( int i=0; i< 3 ; i++ ) {
storageArray[i] = new FlatThreadStorageSimple( selectionSet.getId(), refGeneralManager, null);
selectionSet.setStorageByDim(storageArray, 0);
}
selectionSet.setAllSelectionDataArrays(iArSelectionId, iArSelectionDepthData, iArSelectionOptionalData );
// Calls update with the ID of the PathwayViewRep
((EventPublisher)refGeneralManager.getSingelton().
getEventPublisher()).updateReceiver(this, selectionSet);
refGeneralManager.getSingelton().logMsg("broadcast selection event! " + selectionSet.toString(),
LoggerType.STATUS);
}
}
@Override
public void renderPart(GL gl) {
gl.glPushMatrix();
if ( bEnablePicking ) {
handlePicking(gl);
}
gl.glTranslatef(0, 0, 0.01f);
if (alTargetSet.isEmpty())
{
refGeneralManager
.getSingelton()
.logMsg(
"createHistogram() can not create Heatmap, because targetSet=null",
LoggerType.STATUS);
return;
}
if (iValuesInRow < 1)
{
refGeneralManager
.getSingelton()
.logMsg(
"createHistogram() can not create Heatmap, because histogramLevels are outside range [1..max]",
LoggerType.FULL);
return;
}
ISet primaryTargetSet = alTargetSet.get(0);
if ((primaryTargetSet.hasCacheChanged(iSetCacheId))
|| (iHeatmapDisplayListId == -1))
{
iSetCacheId = primaryTargetSet.getCacheId();
// System.out.print("H:");
// for ( int i=0;i<iHistogramIntervalls.length; i++) {
// System.out.print(";" +
// Integer.toString(iHistogramIntervalls[i]) );
// }
System.out.println("GLCanvasHeatmap2DColumn - UPDATED!");
render_createDisplayLists(gl);
refGeneralManager.getSingelton().logMsg(
"createHistogram() use ISet(" + primaryTargetSet.getId()
+ ":" + primaryTargetSet.getLabel() + ")",
LoggerType.FULL);
}
if (bUseGLWireframe)
{
gl.glPolygonMode(GL.GL_FRONT_AND_BACK, GL.GL_LINE);
}
// else
// {
// gl.glPolygonMode(GL.GL_FRONT_AND_BACK, GL.GL_FILL);
// }
//renderGLSingleQuad(gl,this.fIndexPickedCoored,0);
gl.glDisable(GL.GL_LIGHTING);
gl.glCallList(iHeatmapDisplayListId);
if ( pickedGeneVertex!= null)
{
infoAreaRenderer.renderInfoArea(gl, pickedGeneVertex);
}
renderSelection_ownArea(gl);
gl.glTranslatef(0, 0, -AGLCanvasHeatmap2D.fPickingBias);
// gl.glColor3f(1, 1, 0);
// renderGLAllQuadRectangle(gl, this.fIndexPickedCoored);
//
// gl.glColor3f(0.8f, 0.8f, 0);
// renderGLAllQuadDots(gl, this.fIndexPickedCoored);
// gl.glColor3f(0, 0, 0.8f);
// renderGL_Selection(gl);
if ( bEnablePicking ) {
gl.glTranslatef(0, 0, AGLCanvasHeatmap2D.fPickingBias);
render_picketPoints(gl);
}
// if (pickedGeneVertex != null && infoAreaRenderer.isPositionValid())
// {
// infoAreaRenderer.renderInfoArea(gl, pickedGeneVertex);
// }
gl.glEnable(GL.GL_LIGHTING);
//System.err.println(" Heatmap2D ! .render(GLCanvas canvas)");
gl.glPopMatrix();
}
/**
* Render picked points in own area.
*
* @param gl
*/
private void render_picketPoints(GL gl) {
if ((selectedIndex.length > 0) || (!fIndexPickedCoored.isEmpty()))
{
int iRenderIndexRangeX = iRenderIndexStop - iRenderIndexStart;
float fIncY = (viewingFrame[Y][MAX] - viewingFrame[Y][MIN])
/ (float) (alTargetSet.size());
float fIncY_halfSize = fIncY * 0.5f;
float fNowY = viewingFrame[Y][MIN];
float fNextY = fNowY + fIncY;
float fIncX = (viewingFrame[X][MAX] - viewingFrame[X][MIN])
/ (float) (iRenderIndexRangeX + 1);
float fIncX_halfSize = fIncX * 0.5f;
float fNowX = viewingFrame[X][MIN];
float fNextX = fNowX + fIncX;
float fZ = viewingFrame[Z][MIN] + fPickingBias;
if (!fIndexPickedCoored.isEmpty())
{
/* -------------------------- */
/* show picked points .. */
Iterator<Vec2f> iterPickedPoints = fIndexPickedCoored
.iterator();
gl.glColor3f(1.0f, 1.0f, 0);
for (int i = 0; iterPickedPoints.hasNext(); i++)
{
/**
* Render a triangle on each selected item in the heatmap.
*/
Vec2f pickedIndex = iterPickedPoints.next();
/* TOP */
fNowX = viewingFrame[X][MIN] + fIncX * pickedIndex.x();
fNextX = viewingFrame[X][MIN] + fIncX
* (pickedIndex.x() + 1);
fNowY = viewingFrame[Y][MIN] + fIncY * pickedIndex.y();
fNextY = viewingFrame[Y][MIN] + fIncY
* (pickedIndex.y() + 1);
gl.glBegin(GL.GL_TRIANGLE_FAN);
gl.glVertex3f(fNowX, fNowY, fZ);
gl.glVertex3f(fNextX, fNowY, fZ);
gl.glVertex3f(fNextX, fNowY + fIncY_halfSize, fZ);
//gl.glVertex3f(fNowX, fNextY, viewingFrame[Z][MIN]);
gl.glEnd();
}
/* end: show picked points .. */
/* -------------------------- */
}
if (selectedIndex.length > 0)
{
/* ------------------- */
/* highlight selection */
/* Y_min .. Y_max */
for (int index_X_H = 0; index_X_H < selectedIndex.length; index_X_H++)
{
gl.glLineWidth(fSelectionLineWidth);
gl.glColor3f(0, 0, 1);
if ((selectedIndex[index_X_H] >= iRenderIndexStart)
&& (selectedIndex[index_X_H] < iRenderIndexStop))
{
/**
* Render one BOX on top, one Box below and connect them with 2 lines
* of each selected heatmap segment [X , Y_min..Y_max]
* */
fNowX = viewingFrame[X][MIN] + fIncX
* selectedIndex[index_X_H];
fNextX = fNowX + fIncX;
/* LINES */
fNowY = viewingFrame[Y][MIN];
fNextY = viewingFrame[Y][MAX];
gl.glBegin(GL.GL_LINES);
gl.glVertex3f(fNowX, fNowY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNowX, fNextY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNextX, fNowY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNextX, fNextY, viewingFrame[Z][MIN]);
gl.glEnd();
/* BOTTOM */
render_Selection_Detail(gl,
fNowX,
fNextX,
viewingFrame[Y][MIN],
fIncY,
viewingFrame[Z][MIN],
selectedIndexMode,
index_X_H,
-1.0f );
/* TOP */
fNowY = viewingFrame[Y][MAX];
fNextY = viewingFrame[Y][MAX] + fSelectionPixel
* fIncY;
gl.glColor3f(0,0,1);
gl.glBegin(GL.GL_TRIANGLE_FAN);
gl.glVertex3f(fNowX, fNowY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNextX, fNowY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNextX, fNextY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNowX, fNextY, viewingFrame[Z][MIN]);
gl.glEnd();
} // if (( selectedIndex[index_X_H] >= iRenderIndexStart
// )&&( selectedIndex[index_X_H] < iRenderIndexStop)) {
} // for (int index_X_H=0; index_X_H<selectedIndex.length;
// index_X_H++)
/* end highlight selection */
}
}
}
// public int[] createHistogram(final int iHistogramLevels) {
public void renderHeatmap(final int iHistogramLevels) {
refGeneralManager.getSingelton().logMsg("HEATMAP: set ",
LoggerType.FULL);
}
public int getHeatmapValuesInRow() {
return iValuesInRow;
}
/**
*
* @param fColorMappingShiftFromMean 1.0f indicates no shift
*/
private void initColorMapping(final float fColorMappingShiftFromMean) {
if (refMinMaxDataInteger.isValid())
{
fColorMappingLowValue = (float) refMinMaxDataInteger.getMin(0);
fColorMappingHighValue = (float) refMinMaxDataInteger.getMax(0);
fColorMappingMiddleValue = (float) refMinMaxDataInteger.getMean(0)
* fColorMappingShiftFromMean;
fColorMappingLowRange = fColorMappingMiddleValue
- fColorMappingLowValue;
fColorMappingHighRangeDivisor = 1.0f / (fColorMappingHighValue - fColorMappingMiddleValue);
fColorMappingLowRangeDivisor = 1.0f / (fColorMappingLowRange * (1.0f + fColorMappingPercentageStretch));
float fValuesInColum = (float) refMinMaxDataInteger.getItems(0)
/ (float) iValuesInRow;
iValuesInColum = (int) (fValuesInColum);
} else
{
System.err.println("Error while init color mapping for Heatmap!");
}
}
protected void colorMapping(final GL gl, final int iValue) {
float fValue = fColorMappingMiddleValue - (float) iValue;
if (fValue < 0.0f)
{
// range [fColorMappingLowValue..fColorMappingMiddleValue[
float fScale = (fColorMappingLowRange + fValue)
* fColorMappingLowRangeDivisor;
gl.glColor3f(0, 1.0f - fScale, 0);
return;
}
//else
//range [fColorMappingMiddleValue..fColorMappingHighValue]
float fScale = (fValue) * fColorMappingHighRangeDivisor;
gl.glColor3f(fScale, 0, 0);
}
public final void setRednerIndexStartStop(final int iSetRenderIndexStart,
final int iSetRenderIndexStop) {
if (iSetRenderIndexStart < iSetRenderIndexStop)
{
this.iRenderIndexStart = iSetRenderIndexStart;
this.iRenderIndexStop = iSetRenderIndexStop;
} else
{
refGeneralManager
.getSingelton()
.logMsg(
"Ignore render start/stop=["
+ iSetRenderIndexStart
+ "/"
+ iSetRenderIndexStop
+ "] , because start index is smaller than stop index!",
LoggerType.MINOR_ERROR_XML);
}
if ( (iSetRenderIndexStop - iSetRenderIndexStart) > iRenderIndexLength_UpperLimit ) {
bRenderEnableDelimiterPerExperiment = false;
}
}
/* (non-Javadoc)
* @see cerberus.view.opengl.canvas.heatmap.IGLCanvasHeatmap2D#setTargetSetId(int)
*/
public final void setTargetSetId(final int iTargetCollectionSetId) {
boolean bUpdateColorMapping = alTargetSet.isEmpty();
ISet addTargetSet = refGeneralManager.getSingelton().getSetManager()
.getItemSet(iTargetCollectionSetId);
if (addTargetSet == null)
{
refGeneralManager.getSingelton().logMsg(
"GLCanvasScatterPlot2D.setTargetSetId("
+ iTargetCollectionSetId
+ ") failed, because Set is not registered!",
LoggerType.FULL);
}
alTargetSet.add(addTargetSet);
refGeneralManager.getSingelton().logMsg(
"GLCanvasScatterPlot2D.setTargetSetId("
+ iTargetCollectionSetId + ") done!", LoggerType.FULL);
if (bUpdateColorMapping)
{
refMinMaxDataInteger.useSet(addTargetSet);
initColorMapping(fColorMappingShiftFromMean);
}
}
public void render_displayListHeatmap(GL gl) {
if ( alTargetSet.isEmpty())
{
return;
}
if ( bRenderingStyleFlat ) {
render_displaylistHeatmap_FlatStyle(gl);
} else {
render_displaylistHeatmap_SortedStyle(gl);
}
/* Sourrounding box */
float fBias_Z = viewingFrame[Z][MIN] + fPickingBias;
float fIncY = (viewingFrame[Y][MAX] - viewingFrame[Y][MIN])
/ (float) (alTargetSet.size());
gl.glColor3f(1.0f, 1.0f, 0.1f);
gl.glBegin(GL.GL_LINE_LOOP);
gl.glVertex3f(viewingFrame[X][MIN], viewingFrame[Y][MIN], fBias_Z);
gl.glVertex3f(viewingFrame[X][MAX], viewingFrame[Y][MIN], fBias_Z);
gl.glVertex3f(viewingFrame[X][MAX], viewingFrame[Y][MAX], fBias_Z);
gl.glVertex3f(viewingFrame[X][MIN], viewingFrame[Y][MAX], fBias_Z);
gl.glEnd();
/**
* Render each experiment in a row ..
*/
if ( bRenderEnableDelimiterPerExperiment ) {
if (alTargetSet.size() > 1)
{
/**
* Render lines between each row of experiments
*/
float fZ_2 = fBias_Z + fPickingBias;
gl.glBegin(GL.GL_LINES);
/* start with index=1 and goto alTargetSet.size() */
for (int i = 1; i < alTargetSet.size(); i++)
{
gl.glVertex3f(viewingFrame[X][MIN], viewingFrame[Y][MIN]
+ fIncY * i, fZ_2);
gl.glVertex3f(viewingFrame[X][MAX], viewingFrame[Y][MIN]
+ fIncY * i, fZ_2);
}
gl.glEnd();
}
}
}
private void render_displaylistHeatmap_SortedStyle(GL gl) {
/**
* Get data from Set...
*/
Iterator<ISet> iterTargetSet = alTargetSet.iterator();
int iRenderIndexRangeX = iRenderIndexStop - iRenderIndexStart;
float fIncY = (viewingFrame[Y][MAX] - viewingFrame[Y][MIN])
/ (float) (alTargetSet.size());
float fNowY = viewingFrame[Y][MIN];
float fNextY = fNowY + fIncY;
float fIncX = (viewingFrame[X][MAX] - viewingFrame[X][MIN])
/ (float) (iRenderIndexRangeX + 1);
this.fIncX_forSelection = fIncX;
float fNowX = viewingFrame[X][MIN];
float fNextX = fNowX + fIncX;
gl.glNormal3f(0.0f, 0.0f, 1.0f);
while (iterTargetSet.hasNext())
{
ISet currentTargetSet = iterTargetSet.next();
IStorage refStorage = currentTargetSet.getStorageByDimAndIndex(
0, 0);
int[] dataArrayInt = refStorage.getArrayInt();
IVirtualArray refVArray = currentTargetSet
.getVirtualArrayByDimAndIndex(0, 0);
IVirtualArrayIterator iter = refVArray.iterator();
//int[] i_dataValues = refStorage.getArrayInt();
if (dataArrayInt != null)
{
/**
* force update ...
*/
for (int iIndex_X = 0; iter.hasNext(); iIndex_X++)
{
if (iIndex_X >= iRenderIndexStart)
{
if (iIndex_X >= iRenderIndexStop)
{
iter.setToEnd();
break;
}
gl.glBegin(GL.GL_TRIANGLE_FAN);
// gl.glBegin( GL.GL_LINE_LOOP );
colorMapping(gl, dataArrayInt[iter.next()]);
gl.glVertex3f(fNowX, fNowY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNextX, fNowY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNextX, fNextY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNowX, fNextY, viewingFrame[Z][MIN]);
gl.glEnd();
fNowX = fNextX;
fNextX += fIncX;
} else
{
iter.next();
}
} //for (int iIndex_X = 0;iter.hasNext(); iIndex_X++ )
} // if (i_dataValues != null)
/* reset X .. */
fNowX = viewingFrame[X][MIN];
fNextX = fNowX + fIncX;
/* increment Y .. */
fNowY = fNextY;
fNextY += fIncY;
} //while ( iter.hasNext() )
}
private void render_Selection_Detail(GL gl,
final float fX,
final float fX_next,
final float fY,
final float fIncY,
final float fZ,
final int [] selectedIndexModeArray,
final int selectedIndexMode_Index,
final float fSign ) {
//if (selectedIndexModeArray[selectedIndexMode_Index] > 0 ) {
gl.glColor3f(0, 0, 1);
gl.glBegin(GL.GL_TRIANGLE_FAN);
float fY_a = fY + (selectedIndexModeArray[selectedIndexMode_Index])
* fIncY * fSelectionPixel * fSign;
gl.glVertex3f(fX, fY, fZ);
gl.glVertex3f(fX_next, fY, fZ);
gl.glVertex3f(fX_next, fY_a, fZ);
gl.glVertex3f(fX, fY_a, fZ);
gl.glEnd();
/**
* Render a line between the selected area and the top of the heatmap
*/
/**
* Render a line to indicate depth of selection; from neighborhood
*/
gl.glColor3f(1, 1, 1);
float fZb = fZ + fPickingBias;
for ( int j=1; j < selectedIndexModeArray[selectedIndexMode_Index]; j++ ) {
fY_a = fY + j * fIncY * fSelectionPixel * fSign;
gl.glBegin(GL.GL_LINES);
gl.glVertex3f(fX, fY_a, fZb);
gl.glVertex3f(fX_next, fY_a, fZb);
gl.glEnd();
} //for ( int j=1; j < selectedIndexMode[i]; j++ ) {
//} //if (selectedIndexMode[i] > 0 ) {
}
private void renderSelection_ownArea(GL gl) {
/* ----------------------------------- */
/* --- Render selected once more --- */
// Iterator < ArrayList <Integer>> iter_sortByDepth =
// alHighlightSelectionIndex_sortByDepth.iterator();
//
// int iSumItems = 0;
// while ( iter_sortByDepth.hasNext() ) {
// iSumItems += iter_sortByDepth.next().size();
// }
//
// if ( iSumItems < 1) {
// /* no selection to render.. */
// return;
// }
if ( selectedIndex.length < 1 ) {
return;
}
/* reset rendering parameters.. */
float fOffsetY= 2.0f; //(viewingFrame[X][MAX] - viewingFrame[X][MIN]);
float fIncY = (viewingFrame[Y][MAX] - viewingFrame[Y][MIN])
/ (float) (alTargetSet.size());
float fNowY = viewingFrame[Y][MIN] + fOffsetY;
float fNextY = fNowY + fIncY;
/* use global variable.. */
float fIncX = fIncX_forSelection;
float fIncX_halfSize = fIncX_forSelection * 0.5f;
float fXOffset = ((viewingFrame[X][MAX] - viewingFrame[X][MIN])
- (selectedIndex.length + 1) * fIncX) * 0.5f;
float fNowX = viewingFrame[X][MIN] + fXOffset;
float fNextX = fNowX + fIncX;
/* copy references to raw data int[] .. */
ArrayList <int[]> bufferValueArrays = new ArrayList <int[]> ();
ArrayList <Integer> bufferValueArrays_Offset = new ArrayList <Integer> ();
Iterator <ISet> iterTargetSet = alTargetSet.iterator();
while (iterTargetSet.hasNext()) {
ISet currentTargetSet = iterTargetSet.next();
IVirtualArray refVArray = currentTargetSet.getVirtualArrayByDimAndIndex(0, 0);
IVirtualArrayIterator iter = refVArray.iterator();
IStorage refStorage = currentTargetSet.getStorageByDimAndIndex(0, 0);
int[] dataArrayInt = refStorage.getArrayInt();
if (dataArrayInt != null)
{
bufferValueArrays.add(dataArrayInt);
bufferValueArrays_Offset.add(iter.next());
}
} //while (iterTargetSet.hasNext()) {
/* end: copy references to raw data int[] .. */
boolean bEnableGroupHighlighting = false;
if (selectedIndexMode.length > 0 ) {
bEnableGroupHighlighting = true;
}
for ( int i=0; i < selectedIndex.length; i++) {
int iCurrentIndex = selectedIndex[i];
Iterator<int[]> iterRawDataArrays = bufferValueArrays.iterator();
Iterator<Integer> iterRawDataArrays_Offset = bufferValueArrays_Offset.iterator();
while (iterRawDataArrays.hasNext()) {
int [] currentArrayBuffer = iterRawDataArrays.next();
int iCurrentIndex_InArray =
iterRawDataArrays_Offset.next().intValue()
+ iCurrentIndex;
gl.glBegin(GL.GL_TRIANGLE_FAN);
try {
colorMapping(gl, currentArrayBuffer[iCurrentIndex_InArray] );
} catch (ArrayIndexOutOfBoundsException aie) {
System.err.println("ERROR! ");
}
gl.glVertex3f(fNowX, fNowY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNextX, fNowY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNextX, fNextY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNowX, fNextY, viewingFrame[Z][MIN]);
gl.glEnd();
fNowY = fNextY;
fNextY += fIncY;
}
if (bEnableGroupHighlighting) {
if (selectedIndexMode[i] > 0 ) {
render_Selection_Detail(gl,
fNowX,
fNextX,
fNowY,
fIncY,
viewingFrame[Z][MIN],
selectedIndexMode,
i,
1.0f );
} //if (selectedIndexMode[i] > 0 ) {
}
/** render connection line to target in heatmap */
int iRenderTargetLine_Index =
iCurrentIndex - this.iRenderIndexStart;
float fLineX = viewingFrame[X][MIN] +
fIncX * iRenderTargetLine_Index +
fIncX_halfSize;
/**
* Render lines connecting Selected area and heatmap
*/
gl.glColor3f(0.2f, 0.2f, 1);
gl.glBegin(GL.GL_LINES);
gl.glVertex3f(fNowX + fIncX_halfSize,
viewingFrame[Y][MIN] + fOffsetY,
viewingFrame[Z][MIN]);
gl.glVertex3f(fLineX,
viewingFrame[Y][MAX] + fSelectionPixel * fIncY,
viewingFrame[Z][MIN]);
gl.glEnd();
/** end: render connection line to target in heatmap */
// /** render separation line in selection */
// gl.glBegin(GL.GL_LINES);
//
// gl.glVertex3f(fNowX, viewingFrame[Y][MIN] + fOffsetY, viewingFrame[Z][MIN]);
// gl.glVertex3f(fNowX, fNowY, viewingFrame[Z][MIN]);
//
// gl.glEnd();
// /** end: render separation line in selection */
fNowX = fNextX;
fNextX += fIncX;
/* reset Y.. */
fNowY = viewingFrame[Y][MIN] + fOffsetY;
fNextY = fNowY + fIncY;
/* search for data values now.. */
} //for ( int i=0; i < selectedIndex.length; i++) {
/* Sourrounding box */
gl.glColor3f(1.0f, 1.0f, 0.1f);
gl.glBegin(GL.GL_LINE_LOOP);
gl.glVertex3f(viewingFrame[X][MIN] + fXOffset, viewingFrame[Y][MIN]+ fOffsetY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNowX, viewingFrame[Y][MIN]+ fOffsetY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNowX, viewingFrame[Y][MAX]+ fOffsetY, viewingFrame[Z][MIN]);
gl.glVertex3f(viewingFrame[X][MIN] + fXOffset, viewingFrame[Y][MAX]+ fOffsetY, viewingFrame[Z][MIN]);
gl.glEnd();
/* --- Render selected once more --- */
/* ----------------------------------- */
}
private void render_displaylistHeatmap_FlatStyle(GL gl) {
/**
* Get data from Set...
*/
Iterator<ISet> iterTargetSet = alTargetSet.iterator();
int iRenderIndexRangeX = iRenderIndexStop - iRenderIndexStart;
float fIncY = (viewingFrame[Y][MAX] - viewingFrame[Y][MIN])
/ (float) (alTargetSet.size());
float fNowY = viewingFrame[Y][MIN];
float fNextY = fNowY + fIncY;
float fIncX = (viewingFrame[X][MAX] - viewingFrame[X][MIN])
/ (float) (iRenderIndexRangeX + 1);
this.fIncX_forSelection = fIncX;
float fNowX = viewingFrame[X][MIN];
float fNextX = fNowX + fIncX;
gl.glNormal3f(0.0f, 0.0f, 1.0f);
while (iterTargetSet.hasNext())
{
ISet currentTargetSet = iterTargetSet.next();
IStorage refStorage = currentTargetSet.getStorageByDimAndIndex(
0, 0);
int[] dataArrayInt = refStorage.getArrayInt();
IVirtualArray refVArray = currentTargetSet
.getVirtualArrayByDimAndIndex(0, 0);
IVirtualArrayIterator iter = refVArray.iterator();
int[] i_dataValues = refStorage.getArrayInt();
if (i_dataValues != null)
{
// if (currentTargetSet.hasCacheChanged(iSetCacheId))
// {
//
// iSetCacheId = currentTargetSet.getCacheId();
//
// // System.out.print("H:");
// // for ( int i=0;i<iHistogramIntervalls.length; i++) {
// // System.out.print(";" +
// // Integer.toString(iHistogramIntervalls[i]) );
// // }
// System.err.println(" UPDATED inside DispalyList!");
// }
//System.out.print("-");
/**
* force update ...
*/
for (int iIndex_X = 0; iter.hasNext(); iIndex_X++)
{
if (iIndex_X >= iRenderIndexStart)
{
if (iIndex_X >= iRenderIndexStop)
{
iter.setToEnd();
break;
}
gl.glBegin(GL.GL_TRIANGLE_FAN);
// gl.glBegin( GL.GL_LINE_LOOP );
colorMapping(gl, dataArrayInt[iter.next()]);
gl.glVertex3f(fNowX, fNowY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNextX, fNowY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNextX, fNextY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNowX, fNextY, viewingFrame[Z][MIN]);
gl.glEnd();
fNowX = fNextX;
fNextX += fIncX;
} else
{
iter.next();
}
} //for (int iIndex_X = 0;iter.hasNext(); iIndex_X++ )
} // if (i_dataValues != null)
/* reset X .. */
fNowX = viewingFrame[X][MIN];
fNextX = fNowX + fIncX;
/* increment Y .. */
fNowY = fNextY;
fNextY += fIncY;
} //while ( iter.hasNext() )
}
/* --------------------------- */
/* ----- BEGEN: PICKING ----- */
// private void setPickingBegin(GL gl,int id) {
// gl.glPushMatrix();
// gl.glPushName( id );
// }
//
// private void setPickingEnd(GL gl) {
// gl.glPopName();
// gl.glPopMatrix();
// }
//
// private void setPickingrowAndColum(GL gl,int id) {
// gl.glLoadName(id);
// }
protected final void renderPart4pickingX(GL gl) {
/* public void render_displayListHeatmap(GL gl) { */
gl.glNormal3f(0.0f, 0.0f, 1.0f);
/**
* force update ...
*/
int iRenderIndexRangeX = iRenderIndexStop - iRenderIndexStart;
float fIncX = (viewingFrame[X][MAX] - viewingFrame[X][MIN])
/ (float) (iRenderIndexRangeX);
float fNowY = viewingFrame[Y][MIN];
float fNextY = viewingFrame[Y][MAX];
float fNowX = viewingFrame[X][MIN];
float fNextX = fNowX + fIncX;
/* Y_min .. Y_max*/
for (int yCoord_name = 0; yCoord_name < iRenderIndexRangeX; yCoord_name++)
{
//this.setPickingBegin(gl, yCoord_name);
gl.glLoadName(yCoord_name);
gl.glPushName(yCoord_name);
gl.glBegin(GL.GL_TRIANGLE_FAN);
gl.glVertex3f(fNowX, fNowY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNextX, fNowY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNextX, fNextY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNowX, fNextY, viewingFrame[Z][MIN]);
gl.glEnd();
gl.glPopName();
fNowX = fNextX;
fNextX += fIncX;
} //for (int yCoord_name=0; yCoord_name<iValuesInRow; yCoord_name++)
}
protected final void renderPart4pickingY(GL gl) {
/* public void render_displayListHeatmap(GL gl) { */
gl.glNormal3f(0.0f, 0.0f, 1.0f);
int ycoord_name = 0;
/**
* force update ...
*/
float fIncY = (viewingFrame[Y][MAX] - viewingFrame[Y][MIN])
/ (float) (this.alTargetSet.size());
float fNowX = viewingFrame[X][MIN];
float fNextX = viewingFrame[X][MAX];
float fNowY = viewingFrame[Y][MIN];
float fNextY = fNowY + fIncY;
/* Y_min .. Y_max */
for (int i = 0; i < this.alTargetSet.size(); i++)
{
gl.glLoadName(ycoord_name);
gl.glPushName(ycoord_name);
gl.glBegin(GL.GL_TRIANGLE_FAN);
gl.glVertex3f(fNowX, fNowY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNextX, fNowY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNextX, fNextY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNowX, fNextY, viewingFrame[Z][MIN]);
gl.glEnd();
gl.glPopName();
fNowY = fNextY;
fNextY += fIncY;
ycoord_name++;
} // while (iter.hasNext())
}
/* (non-Javadoc)
* @see cerberus.view.opengl.canvas.heatmap.IGLCanvasHeatmap2D#setSelectionItems(int[], int[], int[], int[])
*/
public void setSelectionItems(int[] selectionStartAtIndexX,
int[] selectionLengthX, int[] selectionStartAtIndexY,
int[] selectionLengthY) {
super.setSelectionItems(selectionStartAtIndexX, selectionLengthX,
selectionStartAtIndexY, selectionLengthY);
}
public void updateReceiver(Object eventTrigger) {
refGeneralManager.getSingelton().logMsg(
this.getClass().getSimpleName()+
": updateReceiver( (" +
eventTrigger.getClass().getSimpleName() + ") " +
eventTrigger.toString() + ")",
LoggerType.STATUS );
}
public void updateReceiver(Object eventTrigger, ISet updatedSet) {
refGeneralManager.getSingelton().logMsg(
this.getClass().getSimpleName()+
": updateReceiver( (" +
eventTrigger.getClass().getSimpleName() + ") " +
eventTrigger.toString() + ")",
LoggerType.STATUS );
refGeneralManager.getSingelton().logMsg(
this.getClass().getSimpleName()+
": updateReceiver() udateSet: " + updatedSet.toString(),
LoggerType.STATUS );
if ( this.hashExternalId_2_HeatmapIndex == null ) {
init_External2InternalHashMap();
}
IStorage[] storage = updatedSet.getStorageByDim(0);
//TODO: Fix this after CHI
//IVirtualArray[] virtualArray = updatedSet.getVirtualArrayByDim(0);
ArrayList<Integer> resultBuffer = new ArrayList<Integer>(10);
ArrayList<Integer> resultBufferMode = new ArrayList<Integer>(10);
- for (int i = 0; i < storage.length; i++)
- {
+// for (int i = 0; i < storage.length; i++)
+// {
//IVirtualArray vaBuffer = virtualArray[i];
int[] intBuffer = storage[0].getArrayInt();
int[] intBufferMode = storage[1].getArrayInt();
//int[] intBufferPathway = storage[2].getArrayInt();
for (int j = 0; j < intBuffer.length; j++)
{
/* lookup id..*/
Iterator <IGraphItem> iterGraphItemRep =
((IGraphItem) refGeneralManager.getSingelton().getPathwayItemManager()
.getItem(intBuffer[j])).getAllItemsByProp(EGraphItemProperty.ALIAS_PARENT).iterator();
while (iterGraphItemRep.hasNext()) {
/* convert external id to internal.. */
Integer indexInt = hashExternalId_2_HeatmapIndex.get(
iterGraphItemRep.next().getId());
if (indexInt != null)
{
System.err.print("GLCanvasHeatmap2DColumn receiveUpdate [" + intBuffer[j] + "=>" + indexInt
+ "], ");
resultBuffer.add(indexInt);
if ( intBufferMode.length != 0 ) {
resultBufferMode.add(intBufferMode[j]);
} else {
resultBufferMode.add( iSelectedMode_identifyier );
}
} else
{
System.err.print("[" + intBuffer[j] + "=> ?? ], ");
}
}
}
- }
+// }
if (!resultBuffer.isEmpty())
{
System.err.print("GLCanvasHeatmap2DColumn receiveUpdate [] COPY to Heatmap-Selection.. ");
/* copy selection into local data structure .. */
setSelectedIndex_asArrayList(resultBuffer, resultBufferMode);
}
}
}
| false | true | private void removehighlightSelectionIndex_Item( ArrayList < ArrayList <Integer>> container,
final Integer value ) {
Iterator <ArrayList <Integer>> iter = container.iterator();
while ( iter.hasNext()) {
if ( iter.next().remove( value ) ) {
/* found value, exit immediately */
return;
}
} //while ( iter.hasNext()) {
assert false : "value could not be removed!";
}
protected void assignHighlightSelectionIndex( final ArrayList <Integer> indexList,
final ArrayList <Integer> indexListMode ) {
Iterator<Integer> iterIndex = indexList.iterator();
Iterator<Integer> iterIndexMode = indexListMode.iterator();
int iSizeContainer = alHighlightSelectionIndex_sortByDepth.size();
while (iterIndex.hasNext()) {
Integer buffer = iterIndex.next();
int bufferMode = iterIndexMode.next().intValue();
if ( bufferMode > 0 ) {
iSizeContainer = addhighlightSelectionIndex_addItem(
this.alHighlightSelectionIndex_sortByDepth,
buffer,
bufferMode,
iSizeContainer);
hashHighlightSelectionIndex.put(buffer, new Boolean(true));
} else {
removehighlightSelectionIndex_Item(alHighlightSelectionIndex_sortByDepth, buffer);
hashHighlightSelectionIndex.remove(buffer);
} //if ( bufferMode > 0 ) {..}else{..
} //alHighlightSelectionIndex_sortByDepth
}
public void setSelectedIndex_asArrayList(
final ArrayList<Integer> updateIndex,
final ArrayList<Integer> updateIndexMode) {
/* integrity check.. */
if (updateIndex.size() != updateIndexMode.size())
{
assert false : "setSelectedIndex() int [] updateIndex != int [] updateIndexMode !";
return;
}
/* write local hashExternalId_2_HeatmapIndex to global variables int[] selectedIndex and int[] selectedIndexMode .. */
/* does size of arrays fit? */
if (selectedIndex.length != updateIndex.size())
{
selectedIndex = new int[updateIndex.size()];
selectedIndexMode = new int[updateIndex.size()];
}
for ( int index=0; index< updateIndex.size(); index++ ) {
selectedIndex[index] = updateIndex.get(index);
selectedIndexMode[index] = updateIndexMode.get(index).intValue();
}
}
public void setSelectedIndex(final int[] updateIndex,
final int[] updateIndexMode) {
/* integrity check.. */
if (updateIndex.length != updateIndexMode.length)
{
assert false : "setSelectedIndex() int [] updateIndex != int [] updateIndexMode !";
return;
}
boolean bUpdate = false;
for (int i = 0; i < updateIndex.length; i++)
{
if (hashExternalId_2_HeatmapIndex.containsKey(updateIndex[i]))
{
if (hashExternalId_2_HeatmapIndex.get(updateIndex[i]).intValue() != updateIndexMode[i])
{
hashExternalId_2_HeatmapIndex.put(updateIndex[i], updateIndexMode[i]);
bUpdate = true;
}
/* else .. data is identical to data in HashMap! */
} else
{
hashExternalId_2_HeatmapIndex.put(updateIndex[i], updateIndexMode[i]);
bUpdate = true;
}
}
if (bUpdate)
{
/* does size of arrays fit? */
if (selectedIndex.length != hashExternalId_2_HeatmapIndex.size())
{
selectedIndex = new int[hashExternalId_2_HeatmapIndex.size()];
selectedIndexMode = new int[hashExternalId_2_HeatmapIndex.size()];
}
Iterator<Integer> keys = hashExternalId_2_HeatmapIndex.keySet().iterator();
Iterator<Integer> values = hashExternalId_2_HeatmapIndex.values().iterator();
for (int index = 0; keys.hasNext(); index++)
{
selectedIndex[index] = keys.next().intValue();
selectedIndexMode[index] = values.next().intValue();
}
} //if ( bUpdate ) {
}
// private void renderGL_Selection(GL gl) {
//
// if (selectedIndex.length < 1)
// {
// /* nothing to render.. */
// return;
// }
//
// /* public void render_displayListHeatmap(GL gl) { */
//
// gl.glNormal3f(0.0f, 0.0f, 1.0f);
//
// /**
// * force update ...
// */
//
// float fIncX = (viewingFrame[X][MAX] - viewingFrame[X][MIN])
// / (float) (iValuesInRow);
//
//// float fIncY = (viewingFrame[Y][MAX] - viewingFrame[X][MIN])
//// / (float) (iValuesInColum);
//
// /* Y_min .. Y_max*/
// for (int index = 0; index < selectedIndex.length; index++)
// {
// float fNowY = viewingFrame[Y][MIN];
// float fNextY = viewingFrame[Y][MAX];
//
// float fNowX = viewingFrame[X][MIN] + fIncX * selectedIndex[index];
// float fNextX = fNowX + fIncX;
//
// gl.glBegin(GL.GL_TRIANGLE_FAN);
//
// gl.glVertex3f(fNowX, fNowY, viewingFrame[Z][MIN]);
// gl.glVertex3f(fNextX, fNowY, viewingFrame[Z][MIN]);
// gl.glVertex3f(fNextX, fNextY, viewingFrame[Z][MIN]);
// gl.glVertex3f(fNowX, fNextY, viewingFrame[Z][MIN]);
//
// gl.glEnd();
// gl.glPopName();
//
// } //for (int yCoord_name=0; yCoord_name<iValuesInRow; yCoord_name++)
//
// }
/**
* init after IGenomeIdManager has load all its data from file.
*/
//protected void init(final IGenomeIdManager readFromIGenomeIdManager) {
protected void init_External2InternalHashMap() {
HashMap <Integer,Integer> hashNCBI_GENEID_2_internalGraphVertexId =
refGeneralManager.getSingelton().getPathwayItemManager().getHashNCBIGeneIdToPathwayVertexGraphItemId();
// IGenomeIdManager refIGenomeIdManager = refGeneralManager.getSingelton()
// .getGenomeIdManager();
//
// hashNCBI_GENE2index = refIGenomeIdManager
// .getAllValuesByGenomeIdTypeHashMap(GenomeMappingType.NCBI_GENEID_2_NCBI_GENEID_CODE);
//
// if ( hashNCBI_GENE2index == null ) {
// refGeneralManager.getSingelton().logMsg("Can not load NCBI_GENEID mapping!", LoggerType.MINOR_ERROR_XML);
//
// return;
// }
//
//
// /* create HashMap now.. */
// hashExternalId_2_HeatmapIndex_reverse = new HashMap<Integer, Integer>();
// Iterator<Integer> iter = hashNCBI_GENE2index.keySet().iterator();
//
// for (int index=0; iter.hasNext(); index++) {
// hashExternalId_2_HeatmapIndex_reverse.put(new Integer(index), iter.next());
// }
hashExternalId_2_HeatmapIndex = new HashMap<Integer, Integer>(hashNCBI_GENEID_2_internalGraphVertexId.size());
hashExternalId_2_HeatmapIndex_reverse = new HashMap<Integer, Integer>(hashNCBI_GENEID_2_internalGraphVertexId.size());
Iterator<Integer> iter_InternalGraphVertexId =
hashNCBI_GENEID_2_internalGraphVertexId.values().iterator();
for ( int index = 0; iter_InternalGraphVertexId.hasNext(); index++ ) {
Integer buffer = iter_InternalGraphVertexId.next();
hashExternalId_2_HeatmapIndex.put(buffer, new Integer(index));
hashExternalId_2_HeatmapIndex_reverse.put(new Integer(index),buffer);
}
}
public void setKeysForHeatmap(int[] keys) {
}
public void selectKeys(int[] keys) {
}
/* --------------------------- */
/* ----- BEGEN: PICKING ----- */
protected final boolean processHits(final GL gl, int iHitCount,
int iArPickingBuffer[], final Point pickPoint,
ArrayList<Vec2f> fIndexPickedCoored) {
// System.out.println("Number of hits: " +iHitCount);
float fDepthSort = Float.MAX_VALUE;
int iResultPickCoordIndex = 0;
int[] resultPickPointCoord =
{ -1, -1 };
int iPtr = 0;
int i = 0;
//int iPickedObjectId = 0;
System.out.println("GLCanvasHeatmap2DColumn PICK: ----- ");
// Only pick object that is nearest
for (i = 0; i < iHitCount; i++)
{
int iNumbersPerHit = iArPickingBuffer[iPtr];
System.out.print(" #name for this hit=" + iArPickingBuffer[iPtr]);
iPtr++;
// // Check if object is nearer than previous objects
// if (iArPickingBuffer[iPtr] < iMinimumZValue)
// {
// System.out.print(" nearer than previous hit! ");
// }
/* ist doch ein float! */
//iMinimumZValue = iArPickingBuffer[iPtr];
float fZmin = (float) iArPickingBuffer[iPtr];
System.out.print(" minZ=" + fZmin);
iPtr++;
System.out.print(" maxZ=" + (float) iArPickingBuffer[iPtr]);
iPtr++;
System.out.print(" Pick-> [");
int iName = -1;
for (int j = 0; j < iNumbersPerHit; j++)
{
iName = iArPickingBuffer[iPtr];
if (fZmin < fDepthSort)
{
fDepthSort = fZmin - AGLCanvasHeatmap2D.fPickingBias;
if (iResultPickCoordIndex < 2)
{
resultPickPointCoord[iResultPickCoordIndex] = iName;
iResultPickCoordIndex++;
}
}
System.out.print(" #" + i + " name=" + iName + ",");
iPtr++;
}
System.out.println("]");
}
if (iHitCount < 1)
{
// Remove pathway pool fisheye
return false;
}
System.out
.println("GLCanvasHeatmap2DColumn PICKED index=["
+ resultPickPointCoord[0] + ","
+ resultPickPointCoord[1] + "]");
// Reset pick point
//source of problems??
infoAreaRenderer.convertWindowCoordinatesToWorldCoordinates(gl,
pickPoint.x, pickPoint.y);
// // Check if real picking is performed
// if (bIsMousePickingEvent)
// {
int[] selectedIndexArray = addPickedPoint(fIndexPickedCoored,
(float) resultPickPointCoord[0],
(float) resultPickPointCoord[1] );
if ( selectedIndexArray != null ) {
/** notify other listeners .. */
notifyReceiver_PickedObject_singleSelection(selectedIndexArray, iSelectedMode_identifyier);
// Integer iNCBIGeneID = hashExternalId_2_HeatmapIndex_reverse.get(resultPickPointCoord[0]);
// if ( iNCBIGeneID != null)
// {
// PathwayVertexGraphItem pickedGeneVertex;
// pickedGeneVertex = (PathwayVertexGraphItem) refGeneralManager.getSingelton(
// ).getPathwayItemManager().getItem(iNCBIGeneID.intValue());
//
// infoAreaRenderer.renderInfoArea(gl, pickedGeneVertex);
// }
}
/* hack, check if external hashmap was already created */
//TODO: clean up this call, init from outside as soon as data is available!
if ( hashExternalId_2_HeatmapIndex==null ) {
this.init_External2InternalHashMap();
}
Integer iNCBIGeneID = hashExternalId_2_HeatmapIndex_reverse.get(resultPickPointCoord[0]);
if ( iNCBIGeneID != null)
{
//PathwayVertexGraphItem pickedGeneVertex;
pickedGeneVertex = (PathwayVertexGraphItem) refGeneralManager.getSingelton(
).getPathwayItemManager().getItem(iNCBIGeneID.intValue());
assert pickedGeneVertex != null : "should not get null-pointer!";
infoAreaRenderer.renderInfoArea(gl, pickedGeneVertex);
}
//source of problems??
//infoAreaRenderer.resetPoint();
// }
return true;
}
/* ----- END: PICKING ----- */
/* --------------------------- */
/* ----- END: PICKING ----- */
/* --------------------------- */
private void notifyReceiver_PickedObject_singleSelection( final int [] resultPickPointCoord, final int iModeValue) {
if ( resultPickPointCoord.length < 1) {
return;
}
int [] resultSelectedIndex = new int [resultPickPointCoord.length];
int [] resultSelectedIndexMode = new int [resultPickPointCoord.length];
/* copy new indices to end of existing array.. */
for ( int iIndex=0; iIndex<resultPickPointCoord.length; iIndex++) {
resultSelectedIndex[iIndex] = resultPickPointCoord[iIndex];
resultSelectedIndexMode[iIndex] = iModeValue;
}
/* swap .. */
selectedIndex = resultSelectedIndex;
selectedIndexMode = resultSelectedIndexMode;
/* hack, check if external hashmap was already created */
//TODO: clean up this call, init from outside as soon as data is available!
if ( hashExternalId_2_HeatmapIndex==null ) {
this.init_External2InternalHashMap();
}
/* notify external objects via eventMediator.. */
if ( hashExternalId_2_HeatmapIndex_reverse != null ) {
/* data for SetSelection.. */
SetSelection selectionSet = new SetSelection(-5, refGeneralManager);
ArrayList <Integer> alSelectionId = new ArrayList <Integer> (resultPickPointCoord.length);
ArrayList <Integer> alSelectionId_PathwayId = new ArrayList <Integer> (resultPickPointCoord.length);
for ( int i=0; i< resultPickPointCoord.length; i++ ) {
/* convert internal index to external id.. */
Integer lookupValue = hashExternalId_2_HeatmapIndex_reverse.get(resultPickPointCoord[i]);
if ( lookupValue == null ) {
return;
}
PathwayVertexGraphItem vertexItemBuffer = (PathwayVertexGraphItem) refGeneralManager.getSingelton()
.getPathwayItemManager().getItem(lookupValue.intValue());
Iterator <IGraphItem> iterList =
vertexItemBuffer.getAllItemsByProp(EGraphItemProperty.ALIAS_CHILD).iterator();
while (iterList.hasNext()) {
IGraphItem bufferItem = iterList.next();
alSelectionId.add( bufferItem.getId() );
//alSelectionId.add( iterList.next().getId() );
// get pathway id from graph
List<IGraph> list = bufferItem.getAllGraphByType(EGraphItemHierarchy.GRAPH_PARENT);
PathwayGraph buffer = (PathwayGraph) list.get(0);
alSelectionId_PathwayId.add( buffer.getKeggId() );
}
}
int[] iArSelectionId = new int[alSelectionId.size()];
int[] iArSelectionDepthData = new int[alSelectionId.size()];
int[] iArSelectionOptionalData = new int[alSelectionId.size()];
for ( int i=0; i < alSelectionId.size(); i++) {
iArSelectionId[i] = alSelectionId.get(i).intValue();
iArSelectionDepthData[i] = iModeValue;
iArSelectionOptionalData[i] = alSelectionId_PathwayId.get(i);
}
IStorage [] storageArray = new IStorage [3];
for ( int i=0; i< 3 ; i++ ) {
storageArray[i] = new FlatThreadStorageSimple( selectionSet.getId(), refGeneralManager, null);
selectionSet.setStorageByDim(storageArray, 0);
}
selectionSet.setAllSelectionDataArrays(iArSelectionId, iArSelectionDepthData, iArSelectionOptionalData );
// Calls update with the ID of the PathwayViewRep
((EventPublisher)refGeneralManager.getSingelton().
getEventPublisher()).updateReceiver(this, selectionSet);
refGeneralManager.getSingelton().logMsg(this.getClass().getSimpleName()+
".broadcast selection event! " + selectionSet.toString(),
LoggerType.STATUS);
}
}
private void notifyReceiver_PickedObject_multipleSelection( final int [] resultPickPointCoord, final int iModeValue) {
if ( resultPickPointCoord.length < 1) {
return;
}
int [] resultSelectedIndex = new int [selectedIndex.length + resultPickPointCoord.length];
int [] resultSelectedIndexMode = new int [selectedIndex.length + resultPickPointCoord.length];
/* copy existing array.. */
for ( int i=0; i< selectedIndex.length; i++ ) {
resultSelectedIndex[i]= selectedIndex[i];
resultSelectedIndexMode[i]=selectedIndexMode[i];
}
/* copy new indices to end of existing array.. */
int iIndex = selectedIndex.length;
for ( int i=0; i<resultPickPointCoord.length; i++) {
resultSelectedIndex[iIndex] = resultPickPointCoord[i];
resultSelectedIndexMode[iIndex] = iModeValue;
iIndex++;
}
/* swap .. */
selectedIndex = resultSelectedIndex;
selectedIndexMode = resultSelectedIndexMode;
if ( hashExternalId_2_HeatmapIndex==null ) {
this.init_External2InternalHashMap();
}
/* notify external objects via eventMediator.. */
if ( hashExternalId_2_HeatmapIndex_reverse != null ) {
/* data for SetSelection.. */
SetSelection selectionSet = new SetSelection(-5, refGeneralManager);
ArrayList <Integer> alSelectionId = new ArrayList <Integer> (resultPickPointCoord.length);
ArrayList <Integer> alSelectionId_PathwayId = new ArrayList <Integer> (resultPickPointCoord.length);
for ( int i=0; i< resultPickPointCoord.length; i++ ) {
/* convert internal index to external id.. */
Integer lookupValue = hashExternalId_2_HeatmapIndex_reverse.get(resultPickPointCoord[i]);
if ( lookupValue == null ) {
return;
}
PathwayVertexGraphItem vertexItemBuffer = (PathwayVertexGraphItem) refGeneralManager.getSingelton()
.getPathwayItemManager().getItem(lookupValue.intValue());
Iterator <IGraphItem> iterList =
vertexItemBuffer.getAllItemsByProp(EGraphItemProperty.ALIAS_CHILD).iterator();
while (iterList.hasNext()) {
IGraphItem bufferItem = iterList.next();
alSelectionId.add( bufferItem.getId() );
//alSelectionId.add( iterList.next().getId() );
// get pathway id from graph
List<IGraph> list = bufferItem.getAllGraphByType(EGraphItemHierarchy.GRAPH_PARENT);
PathwayGraph buffer = (PathwayGraph) list.get(0);
alSelectionId_PathwayId.add( buffer.getKeggId() );
}
}
int[] iArSelectionId = new int[alSelectionId.size()];
int[] iArSelectionDepthData = new int[alSelectionId.size()];
int[] iArSelectionOptionalData = new int[alSelectionId.size()];
for ( int i=0; i < alSelectionId.size(); i++) {
iArSelectionId[i] = alSelectionId.get(i).intValue();
iArSelectionDepthData[i] = iModeValue;
iArSelectionOptionalData[i] = alSelectionId_PathwayId.get(i);
}
IStorage [] storageArray = new IStorage [3];
for ( int i=0; i< 3 ; i++ ) {
storageArray[i] = new FlatThreadStorageSimple( selectionSet.getId(), refGeneralManager, null);
selectionSet.setStorageByDim(storageArray, 0);
}
selectionSet.setAllSelectionDataArrays(iArSelectionId, iArSelectionDepthData, iArSelectionOptionalData );
// Calls update with the ID of the PathwayViewRep
((EventPublisher)refGeneralManager.getSingelton().
getEventPublisher()).updateReceiver(this, selectionSet);
refGeneralManager.getSingelton().logMsg("broadcast selection event! " + selectionSet.toString(),
LoggerType.STATUS);
}
}
@Override
public void renderPart(GL gl) {
gl.glPushMatrix();
if ( bEnablePicking ) {
handlePicking(gl);
}
gl.glTranslatef(0, 0, 0.01f);
if (alTargetSet.isEmpty())
{
refGeneralManager
.getSingelton()
.logMsg(
"createHistogram() can not create Heatmap, because targetSet=null",
LoggerType.STATUS);
return;
}
if (iValuesInRow < 1)
{
refGeneralManager
.getSingelton()
.logMsg(
"createHistogram() can not create Heatmap, because histogramLevels are outside range [1..max]",
LoggerType.FULL);
return;
}
ISet primaryTargetSet = alTargetSet.get(0);
if ((primaryTargetSet.hasCacheChanged(iSetCacheId))
|| (iHeatmapDisplayListId == -1))
{
iSetCacheId = primaryTargetSet.getCacheId();
// System.out.print("H:");
// for ( int i=0;i<iHistogramIntervalls.length; i++) {
// System.out.print(";" +
// Integer.toString(iHistogramIntervalls[i]) );
// }
System.out.println("GLCanvasHeatmap2DColumn - UPDATED!");
render_createDisplayLists(gl);
refGeneralManager.getSingelton().logMsg(
"createHistogram() use ISet(" + primaryTargetSet.getId()
+ ":" + primaryTargetSet.getLabel() + ")",
LoggerType.FULL);
}
if (bUseGLWireframe)
{
gl.glPolygonMode(GL.GL_FRONT_AND_BACK, GL.GL_LINE);
}
// else
// {
// gl.glPolygonMode(GL.GL_FRONT_AND_BACK, GL.GL_FILL);
// }
//renderGLSingleQuad(gl,this.fIndexPickedCoored,0);
gl.glDisable(GL.GL_LIGHTING);
gl.glCallList(iHeatmapDisplayListId);
if ( pickedGeneVertex!= null)
{
infoAreaRenderer.renderInfoArea(gl, pickedGeneVertex);
}
renderSelection_ownArea(gl);
gl.glTranslatef(0, 0, -AGLCanvasHeatmap2D.fPickingBias);
// gl.glColor3f(1, 1, 0);
// renderGLAllQuadRectangle(gl, this.fIndexPickedCoored);
//
// gl.glColor3f(0.8f, 0.8f, 0);
// renderGLAllQuadDots(gl, this.fIndexPickedCoored);
// gl.glColor3f(0, 0, 0.8f);
// renderGL_Selection(gl);
if ( bEnablePicking ) {
gl.glTranslatef(0, 0, AGLCanvasHeatmap2D.fPickingBias);
render_picketPoints(gl);
}
// if (pickedGeneVertex != null && infoAreaRenderer.isPositionValid())
// {
// infoAreaRenderer.renderInfoArea(gl, pickedGeneVertex);
// }
gl.glEnable(GL.GL_LIGHTING);
//System.err.println(" Heatmap2D ! .render(GLCanvas canvas)");
gl.glPopMatrix();
}
/**
* Render picked points in own area.
*
* @param gl
*/
private void render_picketPoints(GL gl) {
if ((selectedIndex.length > 0) || (!fIndexPickedCoored.isEmpty()))
{
int iRenderIndexRangeX = iRenderIndexStop - iRenderIndexStart;
float fIncY = (viewingFrame[Y][MAX] - viewingFrame[Y][MIN])
/ (float) (alTargetSet.size());
float fIncY_halfSize = fIncY * 0.5f;
float fNowY = viewingFrame[Y][MIN];
float fNextY = fNowY + fIncY;
float fIncX = (viewingFrame[X][MAX] - viewingFrame[X][MIN])
/ (float) (iRenderIndexRangeX + 1);
float fIncX_halfSize = fIncX * 0.5f;
float fNowX = viewingFrame[X][MIN];
float fNextX = fNowX + fIncX;
float fZ = viewingFrame[Z][MIN] + fPickingBias;
if (!fIndexPickedCoored.isEmpty())
{
/* -------------------------- */
/* show picked points .. */
Iterator<Vec2f> iterPickedPoints = fIndexPickedCoored
.iterator();
gl.glColor3f(1.0f, 1.0f, 0);
for (int i = 0; iterPickedPoints.hasNext(); i++)
{
/**
* Render a triangle on each selected item in the heatmap.
*/
Vec2f pickedIndex = iterPickedPoints.next();
/* TOP */
fNowX = viewingFrame[X][MIN] + fIncX * pickedIndex.x();
fNextX = viewingFrame[X][MIN] + fIncX
* (pickedIndex.x() + 1);
fNowY = viewingFrame[Y][MIN] + fIncY * pickedIndex.y();
fNextY = viewingFrame[Y][MIN] + fIncY
* (pickedIndex.y() + 1);
gl.glBegin(GL.GL_TRIANGLE_FAN);
gl.glVertex3f(fNowX, fNowY, fZ);
gl.glVertex3f(fNextX, fNowY, fZ);
gl.glVertex3f(fNextX, fNowY + fIncY_halfSize, fZ);
//gl.glVertex3f(fNowX, fNextY, viewingFrame[Z][MIN]);
gl.glEnd();
}
/* end: show picked points .. */
/* -------------------------- */
}
if (selectedIndex.length > 0)
{
/* ------------------- */
/* highlight selection */
/* Y_min .. Y_max */
for (int index_X_H = 0; index_X_H < selectedIndex.length; index_X_H++)
{
gl.glLineWidth(fSelectionLineWidth);
gl.glColor3f(0, 0, 1);
if ((selectedIndex[index_X_H] >= iRenderIndexStart)
&& (selectedIndex[index_X_H] < iRenderIndexStop))
{
/**
* Render one BOX on top, one Box below and connect them with 2 lines
* of each selected heatmap segment [X , Y_min..Y_max]
* */
fNowX = viewingFrame[X][MIN] + fIncX
* selectedIndex[index_X_H];
fNextX = fNowX + fIncX;
/* LINES */
fNowY = viewingFrame[Y][MIN];
fNextY = viewingFrame[Y][MAX];
gl.glBegin(GL.GL_LINES);
gl.glVertex3f(fNowX, fNowY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNowX, fNextY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNextX, fNowY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNextX, fNextY, viewingFrame[Z][MIN]);
gl.glEnd();
/* BOTTOM */
render_Selection_Detail(gl,
fNowX,
fNextX,
viewingFrame[Y][MIN],
fIncY,
viewingFrame[Z][MIN],
selectedIndexMode,
index_X_H,
-1.0f );
/* TOP */
fNowY = viewingFrame[Y][MAX];
fNextY = viewingFrame[Y][MAX] + fSelectionPixel
* fIncY;
gl.glColor3f(0,0,1);
gl.glBegin(GL.GL_TRIANGLE_FAN);
gl.glVertex3f(fNowX, fNowY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNextX, fNowY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNextX, fNextY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNowX, fNextY, viewingFrame[Z][MIN]);
gl.glEnd();
} // if (( selectedIndex[index_X_H] >= iRenderIndexStart
// )&&( selectedIndex[index_X_H] < iRenderIndexStop)) {
} // for (int index_X_H=0; index_X_H<selectedIndex.length;
// index_X_H++)
/* end highlight selection */
}
}
}
// public int[] createHistogram(final int iHistogramLevels) {
public void renderHeatmap(final int iHistogramLevels) {
refGeneralManager.getSingelton().logMsg("HEATMAP: set ",
LoggerType.FULL);
}
public int getHeatmapValuesInRow() {
return iValuesInRow;
}
/**
*
* @param fColorMappingShiftFromMean 1.0f indicates no shift
*/
private void initColorMapping(final float fColorMappingShiftFromMean) {
if (refMinMaxDataInteger.isValid())
{
fColorMappingLowValue = (float) refMinMaxDataInteger.getMin(0);
fColorMappingHighValue = (float) refMinMaxDataInteger.getMax(0);
fColorMappingMiddleValue = (float) refMinMaxDataInteger.getMean(0)
* fColorMappingShiftFromMean;
fColorMappingLowRange = fColorMappingMiddleValue
- fColorMappingLowValue;
fColorMappingHighRangeDivisor = 1.0f / (fColorMappingHighValue - fColorMappingMiddleValue);
fColorMappingLowRangeDivisor = 1.0f / (fColorMappingLowRange * (1.0f + fColorMappingPercentageStretch));
float fValuesInColum = (float) refMinMaxDataInteger.getItems(0)
/ (float) iValuesInRow;
iValuesInColum = (int) (fValuesInColum);
} else
{
System.err.println("Error while init color mapping for Heatmap!");
}
}
protected void colorMapping(final GL gl, final int iValue) {
float fValue = fColorMappingMiddleValue - (float) iValue;
if (fValue < 0.0f)
{
// range [fColorMappingLowValue..fColorMappingMiddleValue[
float fScale = (fColorMappingLowRange + fValue)
* fColorMappingLowRangeDivisor;
gl.glColor3f(0, 1.0f - fScale, 0);
return;
}
//else
//range [fColorMappingMiddleValue..fColorMappingHighValue]
float fScale = (fValue) * fColorMappingHighRangeDivisor;
gl.glColor3f(fScale, 0, 0);
}
public final void setRednerIndexStartStop(final int iSetRenderIndexStart,
final int iSetRenderIndexStop) {
if (iSetRenderIndexStart < iSetRenderIndexStop)
{
this.iRenderIndexStart = iSetRenderIndexStart;
this.iRenderIndexStop = iSetRenderIndexStop;
} else
{
refGeneralManager
.getSingelton()
.logMsg(
"Ignore render start/stop=["
+ iSetRenderIndexStart
+ "/"
+ iSetRenderIndexStop
+ "] , because start index is smaller than stop index!",
LoggerType.MINOR_ERROR_XML);
}
if ( (iSetRenderIndexStop - iSetRenderIndexStart) > iRenderIndexLength_UpperLimit ) {
bRenderEnableDelimiterPerExperiment = false;
}
}
/* (non-Javadoc)
* @see cerberus.view.opengl.canvas.heatmap.IGLCanvasHeatmap2D#setTargetSetId(int)
*/
public final void setTargetSetId(final int iTargetCollectionSetId) {
boolean bUpdateColorMapping = alTargetSet.isEmpty();
ISet addTargetSet = refGeneralManager.getSingelton().getSetManager()
.getItemSet(iTargetCollectionSetId);
if (addTargetSet == null)
{
refGeneralManager.getSingelton().logMsg(
"GLCanvasScatterPlot2D.setTargetSetId("
+ iTargetCollectionSetId
+ ") failed, because Set is not registered!",
LoggerType.FULL);
}
alTargetSet.add(addTargetSet);
refGeneralManager.getSingelton().logMsg(
"GLCanvasScatterPlot2D.setTargetSetId("
+ iTargetCollectionSetId + ") done!", LoggerType.FULL);
if (bUpdateColorMapping)
{
refMinMaxDataInteger.useSet(addTargetSet);
initColorMapping(fColorMappingShiftFromMean);
}
}
public void render_displayListHeatmap(GL gl) {
if ( alTargetSet.isEmpty())
{
return;
}
if ( bRenderingStyleFlat ) {
render_displaylistHeatmap_FlatStyle(gl);
} else {
render_displaylistHeatmap_SortedStyle(gl);
}
/* Sourrounding box */
float fBias_Z = viewingFrame[Z][MIN] + fPickingBias;
float fIncY = (viewingFrame[Y][MAX] - viewingFrame[Y][MIN])
/ (float) (alTargetSet.size());
gl.glColor3f(1.0f, 1.0f, 0.1f);
gl.glBegin(GL.GL_LINE_LOOP);
gl.glVertex3f(viewingFrame[X][MIN], viewingFrame[Y][MIN], fBias_Z);
gl.glVertex3f(viewingFrame[X][MAX], viewingFrame[Y][MIN], fBias_Z);
gl.glVertex3f(viewingFrame[X][MAX], viewingFrame[Y][MAX], fBias_Z);
gl.glVertex3f(viewingFrame[X][MIN], viewingFrame[Y][MAX], fBias_Z);
gl.glEnd();
/**
* Render each experiment in a row ..
*/
if ( bRenderEnableDelimiterPerExperiment ) {
if (alTargetSet.size() > 1)
{
/**
* Render lines between each row of experiments
*/
float fZ_2 = fBias_Z + fPickingBias;
gl.glBegin(GL.GL_LINES);
/* start with index=1 and goto alTargetSet.size() */
for (int i = 1; i < alTargetSet.size(); i++)
{
gl.glVertex3f(viewingFrame[X][MIN], viewingFrame[Y][MIN]
+ fIncY * i, fZ_2);
gl.glVertex3f(viewingFrame[X][MAX], viewingFrame[Y][MIN]
+ fIncY * i, fZ_2);
}
gl.glEnd();
}
}
}
private void render_displaylistHeatmap_SortedStyle(GL gl) {
/**
* Get data from Set...
*/
Iterator<ISet> iterTargetSet = alTargetSet.iterator();
int iRenderIndexRangeX = iRenderIndexStop - iRenderIndexStart;
float fIncY = (viewingFrame[Y][MAX] - viewingFrame[Y][MIN])
/ (float) (alTargetSet.size());
float fNowY = viewingFrame[Y][MIN];
float fNextY = fNowY + fIncY;
float fIncX = (viewingFrame[X][MAX] - viewingFrame[X][MIN])
/ (float) (iRenderIndexRangeX + 1);
this.fIncX_forSelection = fIncX;
float fNowX = viewingFrame[X][MIN];
float fNextX = fNowX + fIncX;
gl.glNormal3f(0.0f, 0.0f, 1.0f);
while (iterTargetSet.hasNext())
{
ISet currentTargetSet = iterTargetSet.next();
IStorage refStorage = currentTargetSet.getStorageByDimAndIndex(
0, 0);
int[] dataArrayInt = refStorage.getArrayInt();
IVirtualArray refVArray = currentTargetSet
.getVirtualArrayByDimAndIndex(0, 0);
IVirtualArrayIterator iter = refVArray.iterator();
//int[] i_dataValues = refStorage.getArrayInt();
if (dataArrayInt != null)
{
/**
* force update ...
*/
for (int iIndex_X = 0; iter.hasNext(); iIndex_X++)
{
if (iIndex_X >= iRenderIndexStart)
{
if (iIndex_X >= iRenderIndexStop)
{
iter.setToEnd();
break;
}
gl.glBegin(GL.GL_TRIANGLE_FAN);
// gl.glBegin( GL.GL_LINE_LOOP );
colorMapping(gl, dataArrayInt[iter.next()]);
gl.glVertex3f(fNowX, fNowY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNextX, fNowY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNextX, fNextY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNowX, fNextY, viewingFrame[Z][MIN]);
gl.glEnd();
fNowX = fNextX;
fNextX += fIncX;
} else
{
iter.next();
}
} //for (int iIndex_X = 0;iter.hasNext(); iIndex_X++ )
} // if (i_dataValues != null)
/* reset X .. */
fNowX = viewingFrame[X][MIN];
fNextX = fNowX + fIncX;
/* increment Y .. */
fNowY = fNextY;
fNextY += fIncY;
} //while ( iter.hasNext() )
}
private void render_Selection_Detail(GL gl,
final float fX,
final float fX_next,
final float fY,
final float fIncY,
final float fZ,
final int [] selectedIndexModeArray,
final int selectedIndexMode_Index,
final float fSign ) {
//if (selectedIndexModeArray[selectedIndexMode_Index] > 0 ) {
gl.glColor3f(0, 0, 1);
gl.glBegin(GL.GL_TRIANGLE_FAN);
float fY_a = fY + (selectedIndexModeArray[selectedIndexMode_Index])
* fIncY * fSelectionPixel * fSign;
gl.glVertex3f(fX, fY, fZ);
gl.glVertex3f(fX_next, fY, fZ);
gl.glVertex3f(fX_next, fY_a, fZ);
gl.glVertex3f(fX, fY_a, fZ);
gl.glEnd();
/**
* Render a line between the selected area and the top of the heatmap
*/
/**
* Render a line to indicate depth of selection; from neighborhood
*/
gl.glColor3f(1, 1, 1);
float fZb = fZ + fPickingBias;
for ( int j=1; j < selectedIndexModeArray[selectedIndexMode_Index]; j++ ) {
fY_a = fY + j * fIncY * fSelectionPixel * fSign;
gl.glBegin(GL.GL_LINES);
gl.glVertex3f(fX, fY_a, fZb);
gl.glVertex3f(fX_next, fY_a, fZb);
gl.glEnd();
} //for ( int j=1; j < selectedIndexMode[i]; j++ ) {
//} //if (selectedIndexMode[i] > 0 ) {
}
private void renderSelection_ownArea(GL gl) {
/* ----------------------------------- */
/* --- Render selected once more --- */
// Iterator < ArrayList <Integer>> iter_sortByDepth =
// alHighlightSelectionIndex_sortByDepth.iterator();
//
// int iSumItems = 0;
// while ( iter_sortByDepth.hasNext() ) {
// iSumItems += iter_sortByDepth.next().size();
// }
//
// if ( iSumItems < 1) {
// /* no selection to render.. */
// return;
// }
if ( selectedIndex.length < 1 ) {
return;
}
/* reset rendering parameters.. */
float fOffsetY= 2.0f; //(viewingFrame[X][MAX] - viewingFrame[X][MIN]);
float fIncY = (viewingFrame[Y][MAX] - viewingFrame[Y][MIN])
/ (float) (alTargetSet.size());
float fNowY = viewingFrame[Y][MIN] + fOffsetY;
float fNextY = fNowY + fIncY;
/* use global variable.. */
float fIncX = fIncX_forSelection;
float fIncX_halfSize = fIncX_forSelection * 0.5f;
float fXOffset = ((viewingFrame[X][MAX] - viewingFrame[X][MIN])
- (selectedIndex.length + 1) * fIncX) * 0.5f;
float fNowX = viewingFrame[X][MIN] + fXOffset;
float fNextX = fNowX + fIncX;
/* copy references to raw data int[] .. */
ArrayList <int[]> bufferValueArrays = new ArrayList <int[]> ();
ArrayList <Integer> bufferValueArrays_Offset = new ArrayList <Integer> ();
Iterator <ISet> iterTargetSet = alTargetSet.iterator();
while (iterTargetSet.hasNext()) {
ISet currentTargetSet = iterTargetSet.next();
IVirtualArray refVArray = currentTargetSet.getVirtualArrayByDimAndIndex(0, 0);
IVirtualArrayIterator iter = refVArray.iterator();
IStorage refStorage = currentTargetSet.getStorageByDimAndIndex(0, 0);
int[] dataArrayInt = refStorage.getArrayInt();
if (dataArrayInt != null)
{
bufferValueArrays.add(dataArrayInt);
bufferValueArrays_Offset.add(iter.next());
}
} //while (iterTargetSet.hasNext()) {
/* end: copy references to raw data int[] .. */
boolean bEnableGroupHighlighting = false;
if (selectedIndexMode.length > 0 ) {
bEnableGroupHighlighting = true;
}
for ( int i=0; i < selectedIndex.length; i++) {
int iCurrentIndex = selectedIndex[i];
Iterator<int[]> iterRawDataArrays = bufferValueArrays.iterator();
Iterator<Integer> iterRawDataArrays_Offset = bufferValueArrays_Offset.iterator();
while (iterRawDataArrays.hasNext()) {
int [] currentArrayBuffer = iterRawDataArrays.next();
int iCurrentIndex_InArray =
iterRawDataArrays_Offset.next().intValue()
+ iCurrentIndex;
gl.glBegin(GL.GL_TRIANGLE_FAN);
try {
colorMapping(gl, currentArrayBuffer[iCurrentIndex_InArray] );
} catch (ArrayIndexOutOfBoundsException aie) {
System.err.println("ERROR! ");
}
gl.glVertex3f(fNowX, fNowY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNextX, fNowY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNextX, fNextY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNowX, fNextY, viewingFrame[Z][MIN]);
gl.glEnd();
fNowY = fNextY;
fNextY += fIncY;
}
if (bEnableGroupHighlighting) {
if (selectedIndexMode[i] > 0 ) {
render_Selection_Detail(gl,
fNowX,
fNextX,
fNowY,
fIncY,
viewingFrame[Z][MIN],
selectedIndexMode,
i,
1.0f );
} //if (selectedIndexMode[i] > 0 ) {
}
/** render connection line to target in heatmap */
int iRenderTargetLine_Index =
iCurrentIndex - this.iRenderIndexStart;
float fLineX = viewingFrame[X][MIN] +
fIncX * iRenderTargetLine_Index +
fIncX_halfSize;
/**
* Render lines connecting Selected area and heatmap
*/
gl.glColor3f(0.2f, 0.2f, 1);
gl.glBegin(GL.GL_LINES);
gl.glVertex3f(fNowX + fIncX_halfSize,
viewingFrame[Y][MIN] + fOffsetY,
viewingFrame[Z][MIN]);
gl.glVertex3f(fLineX,
viewingFrame[Y][MAX] + fSelectionPixel * fIncY,
viewingFrame[Z][MIN]);
gl.glEnd();
/** end: render connection line to target in heatmap */
// /** render separation line in selection */
// gl.glBegin(GL.GL_LINES);
//
// gl.glVertex3f(fNowX, viewingFrame[Y][MIN] + fOffsetY, viewingFrame[Z][MIN]);
// gl.glVertex3f(fNowX, fNowY, viewingFrame[Z][MIN]);
//
// gl.glEnd();
// /** end: render separation line in selection */
fNowX = fNextX;
fNextX += fIncX;
/* reset Y.. */
fNowY = viewingFrame[Y][MIN] + fOffsetY;
fNextY = fNowY + fIncY;
/* search for data values now.. */
} //for ( int i=0; i < selectedIndex.length; i++) {
/* Sourrounding box */
gl.glColor3f(1.0f, 1.0f, 0.1f);
gl.glBegin(GL.GL_LINE_LOOP);
gl.glVertex3f(viewingFrame[X][MIN] + fXOffset, viewingFrame[Y][MIN]+ fOffsetY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNowX, viewingFrame[Y][MIN]+ fOffsetY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNowX, viewingFrame[Y][MAX]+ fOffsetY, viewingFrame[Z][MIN]);
gl.glVertex3f(viewingFrame[X][MIN] + fXOffset, viewingFrame[Y][MAX]+ fOffsetY, viewingFrame[Z][MIN]);
gl.glEnd();
/* --- Render selected once more --- */
/* ----------------------------------- */
}
private void render_displaylistHeatmap_FlatStyle(GL gl) {
/**
* Get data from Set...
*/
Iterator<ISet> iterTargetSet = alTargetSet.iterator();
int iRenderIndexRangeX = iRenderIndexStop - iRenderIndexStart;
float fIncY = (viewingFrame[Y][MAX] - viewingFrame[Y][MIN])
/ (float) (alTargetSet.size());
float fNowY = viewingFrame[Y][MIN];
float fNextY = fNowY + fIncY;
float fIncX = (viewingFrame[X][MAX] - viewingFrame[X][MIN])
/ (float) (iRenderIndexRangeX + 1);
this.fIncX_forSelection = fIncX;
float fNowX = viewingFrame[X][MIN];
float fNextX = fNowX + fIncX;
gl.glNormal3f(0.0f, 0.0f, 1.0f);
while (iterTargetSet.hasNext())
{
ISet currentTargetSet = iterTargetSet.next();
IStorage refStorage = currentTargetSet.getStorageByDimAndIndex(
0, 0);
int[] dataArrayInt = refStorage.getArrayInt();
IVirtualArray refVArray = currentTargetSet
.getVirtualArrayByDimAndIndex(0, 0);
IVirtualArrayIterator iter = refVArray.iterator();
int[] i_dataValues = refStorage.getArrayInt();
if (i_dataValues != null)
{
// if (currentTargetSet.hasCacheChanged(iSetCacheId))
// {
//
// iSetCacheId = currentTargetSet.getCacheId();
//
// // System.out.print("H:");
// // for ( int i=0;i<iHistogramIntervalls.length; i++) {
// // System.out.print(";" +
// // Integer.toString(iHistogramIntervalls[i]) );
// // }
// System.err.println(" UPDATED inside DispalyList!");
// }
//System.out.print("-");
/**
* force update ...
*/
for (int iIndex_X = 0; iter.hasNext(); iIndex_X++)
{
if (iIndex_X >= iRenderIndexStart)
{
if (iIndex_X >= iRenderIndexStop)
{
iter.setToEnd();
break;
}
gl.glBegin(GL.GL_TRIANGLE_FAN);
// gl.glBegin( GL.GL_LINE_LOOP );
colorMapping(gl, dataArrayInt[iter.next()]);
gl.glVertex3f(fNowX, fNowY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNextX, fNowY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNextX, fNextY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNowX, fNextY, viewingFrame[Z][MIN]);
gl.glEnd();
fNowX = fNextX;
fNextX += fIncX;
} else
{
iter.next();
}
} //for (int iIndex_X = 0;iter.hasNext(); iIndex_X++ )
} // if (i_dataValues != null)
/* reset X .. */
fNowX = viewingFrame[X][MIN];
fNextX = fNowX + fIncX;
/* increment Y .. */
fNowY = fNextY;
fNextY += fIncY;
} //while ( iter.hasNext() )
}
/* --------------------------- */
/* ----- BEGEN: PICKING ----- */
// private void setPickingBegin(GL gl,int id) {
// gl.glPushMatrix();
// gl.glPushName( id );
// }
//
// private void setPickingEnd(GL gl) {
// gl.glPopName();
// gl.glPopMatrix();
// }
//
// private void setPickingrowAndColum(GL gl,int id) {
// gl.glLoadName(id);
// }
protected final void renderPart4pickingX(GL gl) {
/* public void render_displayListHeatmap(GL gl) { */
gl.glNormal3f(0.0f, 0.0f, 1.0f);
/**
* force update ...
*/
int iRenderIndexRangeX = iRenderIndexStop - iRenderIndexStart;
float fIncX = (viewingFrame[X][MAX] - viewingFrame[X][MIN])
/ (float) (iRenderIndexRangeX);
float fNowY = viewingFrame[Y][MIN];
float fNextY = viewingFrame[Y][MAX];
float fNowX = viewingFrame[X][MIN];
float fNextX = fNowX + fIncX;
/* Y_min .. Y_max*/
for (int yCoord_name = 0; yCoord_name < iRenderIndexRangeX; yCoord_name++)
{
//this.setPickingBegin(gl, yCoord_name);
gl.glLoadName(yCoord_name);
gl.glPushName(yCoord_name);
gl.glBegin(GL.GL_TRIANGLE_FAN);
gl.glVertex3f(fNowX, fNowY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNextX, fNowY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNextX, fNextY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNowX, fNextY, viewingFrame[Z][MIN]);
gl.glEnd();
gl.glPopName();
fNowX = fNextX;
fNextX += fIncX;
} //for (int yCoord_name=0; yCoord_name<iValuesInRow; yCoord_name++)
}
protected final void renderPart4pickingY(GL gl) {
/* public void render_displayListHeatmap(GL gl) { */
gl.glNormal3f(0.0f, 0.0f, 1.0f);
int ycoord_name = 0;
/**
* force update ...
*/
float fIncY = (viewingFrame[Y][MAX] - viewingFrame[Y][MIN])
/ (float) (this.alTargetSet.size());
float fNowX = viewingFrame[X][MIN];
float fNextX = viewingFrame[X][MAX];
float fNowY = viewingFrame[Y][MIN];
float fNextY = fNowY + fIncY;
/* Y_min .. Y_max */
for (int i = 0; i < this.alTargetSet.size(); i++)
{
gl.glLoadName(ycoord_name);
gl.glPushName(ycoord_name);
gl.glBegin(GL.GL_TRIANGLE_FAN);
gl.glVertex3f(fNowX, fNowY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNextX, fNowY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNextX, fNextY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNowX, fNextY, viewingFrame[Z][MIN]);
gl.glEnd();
gl.glPopName();
fNowY = fNextY;
fNextY += fIncY;
ycoord_name++;
} // while (iter.hasNext())
}
/* (non-Javadoc)
* @see cerberus.view.opengl.canvas.heatmap.IGLCanvasHeatmap2D#setSelectionItems(int[], int[], int[], int[])
*/
public void setSelectionItems(int[] selectionStartAtIndexX,
int[] selectionLengthX, int[] selectionStartAtIndexY,
int[] selectionLengthY) {
super.setSelectionItems(selectionStartAtIndexX, selectionLengthX,
selectionStartAtIndexY, selectionLengthY);
}
public void updateReceiver(Object eventTrigger) {
refGeneralManager.getSingelton().logMsg(
this.getClass().getSimpleName()+
": updateReceiver( (" +
eventTrigger.getClass().getSimpleName() + ") " +
eventTrigger.toString() + ")",
LoggerType.STATUS );
}
public void updateReceiver(Object eventTrigger, ISet updatedSet) {
refGeneralManager.getSingelton().logMsg(
this.getClass().getSimpleName()+
": updateReceiver( (" +
eventTrigger.getClass().getSimpleName() + ") " +
eventTrigger.toString() + ")",
LoggerType.STATUS );
refGeneralManager.getSingelton().logMsg(
this.getClass().getSimpleName()+
": updateReceiver() udateSet: " + updatedSet.toString(),
LoggerType.STATUS );
if ( this.hashExternalId_2_HeatmapIndex == null ) {
init_External2InternalHashMap();
}
IStorage[] storage = updatedSet.getStorageByDim(0);
//TODO: Fix this after CHI
//IVirtualArray[] virtualArray = updatedSet.getVirtualArrayByDim(0);
ArrayList<Integer> resultBuffer = new ArrayList<Integer>(10);
ArrayList<Integer> resultBufferMode = new ArrayList<Integer>(10);
for (int i = 0; i < storage.length; i++)
{
//IVirtualArray vaBuffer = virtualArray[i];
int[] intBuffer = storage[0].getArrayInt();
int[] intBufferMode = storage[1].getArrayInt();
//int[] intBufferPathway = storage[2].getArrayInt();
for (int j = 0; j < intBuffer.length; j++)
{
/* lookup id..*/
Iterator <IGraphItem> iterGraphItemRep =
((IGraphItem) refGeneralManager.getSingelton().getPathwayItemManager()
.getItem(intBuffer[j])).getAllItemsByProp(EGraphItemProperty.ALIAS_PARENT).iterator();
while (iterGraphItemRep.hasNext()) {
/* convert external id to internal.. */
Integer indexInt = hashExternalId_2_HeatmapIndex.get(
iterGraphItemRep.next().getId());
if (indexInt != null)
{
System.err.print("GLCanvasHeatmap2DColumn receiveUpdate [" + intBuffer[j] + "=>" + indexInt
+ "], ");
resultBuffer.add(indexInt);
if ( intBufferMode.length != 0 ) {
resultBufferMode.add(intBufferMode[j]);
} else {
resultBufferMode.add( iSelectedMode_identifyier );
}
} else
{
System.err.print("[" + intBuffer[j] + "=> ?? ], ");
}
}
}
}
if (!resultBuffer.isEmpty())
{
System.err.print("GLCanvasHeatmap2DColumn receiveUpdate [] COPY to Heatmap-Selection.. ");
/* copy selection into local data structure .. */
setSelectedIndex_asArrayList(resultBuffer, resultBufferMode);
}
}
}
| private void removehighlightSelectionIndex_Item( ArrayList < ArrayList <Integer>> container,
final Integer value ) {
Iterator <ArrayList <Integer>> iter = container.iterator();
while ( iter.hasNext()) {
if ( iter.next().remove( value ) ) {
/* found value, exit immediately */
return;
}
} //while ( iter.hasNext()) {
assert false : "value could not be removed!";
}
protected void assignHighlightSelectionIndex( final ArrayList <Integer> indexList,
final ArrayList <Integer> indexListMode ) {
Iterator<Integer> iterIndex = indexList.iterator();
Iterator<Integer> iterIndexMode = indexListMode.iterator();
int iSizeContainer = alHighlightSelectionIndex_sortByDepth.size();
while (iterIndex.hasNext()) {
Integer buffer = iterIndex.next();
int bufferMode = iterIndexMode.next().intValue();
if ( bufferMode > 0 ) {
iSizeContainer = addhighlightSelectionIndex_addItem(
this.alHighlightSelectionIndex_sortByDepth,
buffer,
bufferMode,
iSizeContainer);
hashHighlightSelectionIndex.put(buffer, new Boolean(true));
} else {
removehighlightSelectionIndex_Item(alHighlightSelectionIndex_sortByDepth, buffer);
hashHighlightSelectionIndex.remove(buffer);
} //if ( bufferMode > 0 ) {..}else{..
} //alHighlightSelectionIndex_sortByDepth
}
public void setSelectedIndex_asArrayList(
final ArrayList<Integer> updateIndex,
final ArrayList<Integer> updateIndexMode) {
/* integrity check.. */
if (updateIndex.size() != updateIndexMode.size())
{
assert false : "setSelectedIndex() int [] updateIndex != int [] updateIndexMode !";
return;
}
/* write local hashExternalId_2_HeatmapIndex to global variables int[] selectedIndex and int[] selectedIndexMode .. */
/* does size of arrays fit? */
if (selectedIndex.length != updateIndex.size())
{
selectedIndex = new int[updateIndex.size()];
selectedIndexMode = new int[updateIndex.size()];
}
for ( int index=0; index< updateIndex.size(); index++ ) {
selectedIndex[index] = updateIndex.get(index);
selectedIndexMode[index] = updateIndexMode.get(index).intValue();
}
}
public void setSelectedIndex(final int[] updateIndex,
final int[] updateIndexMode) {
/* integrity check.. */
if (updateIndex.length != updateIndexMode.length)
{
assert false : "setSelectedIndex() int [] updateIndex != int [] updateIndexMode !";
return;
}
boolean bUpdate = false;
for (int i = 0; i < updateIndex.length; i++)
{
if (hashExternalId_2_HeatmapIndex.containsKey(updateIndex[i]))
{
if (hashExternalId_2_HeatmapIndex.get(updateIndex[i]).intValue() != updateIndexMode[i])
{
hashExternalId_2_HeatmapIndex.put(updateIndex[i], updateIndexMode[i]);
bUpdate = true;
}
/* else .. data is identical to data in HashMap! */
} else
{
hashExternalId_2_HeatmapIndex.put(updateIndex[i], updateIndexMode[i]);
bUpdate = true;
}
}
if (bUpdate)
{
/* does size of arrays fit? */
if (selectedIndex.length != hashExternalId_2_HeatmapIndex.size())
{
selectedIndex = new int[hashExternalId_2_HeatmapIndex.size()];
selectedIndexMode = new int[hashExternalId_2_HeatmapIndex.size()];
}
Iterator<Integer> keys = hashExternalId_2_HeatmapIndex.keySet().iterator();
Iterator<Integer> values = hashExternalId_2_HeatmapIndex.values().iterator();
for (int index = 0; keys.hasNext(); index++)
{
selectedIndex[index] = keys.next().intValue();
selectedIndexMode[index] = values.next().intValue();
}
} //if ( bUpdate ) {
}
// private void renderGL_Selection(GL gl) {
//
// if (selectedIndex.length < 1)
// {
// /* nothing to render.. */
// return;
// }
//
// /* public void render_displayListHeatmap(GL gl) { */
//
// gl.glNormal3f(0.0f, 0.0f, 1.0f);
//
// /**
// * force update ...
// */
//
// float fIncX = (viewingFrame[X][MAX] - viewingFrame[X][MIN])
// / (float) (iValuesInRow);
//
//// float fIncY = (viewingFrame[Y][MAX] - viewingFrame[X][MIN])
//// / (float) (iValuesInColum);
//
// /* Y_min .. Y_max*/
// for (int index = 0; index < selectedIndex.length; index++)
// {
// float fNowY = viewingFrame[Y][MIN];
// float fNextY = viewingFrame[Y][MAX];
//
// float fNowX = viewingFrame[X][MIN] + fIncX * selectedIndex[index];
// float fNextX = fNowX + fIncX;
//
// gl.glBegin(GL.GL_TRIANGLE_FAN);
//
// gl.glVertex3f(fNowX, fNowY, viewingFrame[Z][MIN]);
// gl.glVertex3f(fNextX, fNowY, viewingFrame[Z][MIN]);
// gl.glVertex3f(fNextX, fNextY, viewingFrame[Z][MIN]);
// gl.glVertex3f(fNowX, fNextY, viewingFrame[Z][MIN]);
//
// gl.glEnd();
// gl.glPopName();
//
// } //for (int yCoord_name=0; yCoord_name<iValuesInRow; yCoord_name++)
//
// }
/**
* init after IGenomeIdManager has load all its data from file.
*/
//protected void init(final IGenomeIdManager readFromIGenomeIdManager) {
protected void init_External2InternalHashMap() {
HashMap <Integer,Integer> hashNCBI_GENEID_2_internalGraphVertexId =
refGeneralManager.getSingelton().getPathwayItemManager().getHashNCBIGeneIdToPathwayVertexGraphItemId();
// IGenomeIdManager refIGenomeIdManager = refGeneralManager.getSingelton()
// .getGenomeIdManager();
//
// hashNCBI_GENE2index = refIGenomeIdManager
// .getAllValuesByGenomeIdTypeHashMap(GenomeMappingType.NCBI_GENEID_2_NCBI_GENEID_CODE);
//
// if ( hashNCBI_GENE2index == null ) {
// refGeneralManager.getSingelton().logMsg("Can not load NCBI_GENEID mapping!", LoggerType.MINOR_ERROR_XML);
//
// return;
// }
//
//
// /* create HashMap now.. */
// hashExternalId_2_HeatmapIndex_reverse = new HashMap<Integer, Integer>();
// Iterator<Integer> iter = hashNCBI_GENE2index.keySet().iterator();
//
// for (int index=0; iter.hasNext(); index++) {
// hashExternalId_2_HeatmapIndex_reverse.put(new Integer(index), iter.next());
// }
hashExternalId_2_HeatmapIndex = new HashMap<Integer, Integer>(hashNCBI_GENEID_2_internalGraphVertexId.size());
hashExternalId_2_HeatmapIndex_reverse = new HashMap<Integer, Integer>(hashNCBI_GENEID_2_internalGraphVertexId.size());
Iterator<Integer> iter_InternalGraphVertexId =
hashNCBI_GENEID_2_internalGraphVertexId.values().iterator();
for ( int index = 0; iter_InternalGraphVertexId.hasNext(); index++ ) {
Integer buffer = iter_InternalGraphVertexId.next();
hashExternalId_2_HeatmapIndex.put(buffer, new Integer(index));
hashExternalId_2_HeatmapIndex_reverse.put(new Integer(index),buffer);
}
}
public void setKeysForHeatmap(int[] keys) {
}
public void selectKeys(int[] keys) {
}
/* --------------------------- */
/* ----- BEGEN: PICKING ----- */
protected final boolean processHits(final GL gl, int iHitCount,
int iArPickingBuffer[], final Point pickPoint,
ArrayList<Vec2f> fIndexPickedCoored) {
// System.out.println("Number of hits: " +iHitCount);
float fDepthSort = Float.MAX_VALUE;
int iResultPickCoordIndex = 0;
int[] resultPickPointCoord =
{ -1, -1 };
int iPtr = 0;
int i = 0;
//int iPickedObjectId = 0;
System.out.println("GLCanvasHeatmap2DColumn PICK: ----- ");
// Only pick object that is nearest
for (i = 0; i < iHitCount; i++)
{
int iNumbersPerHit = iArPickingBuffer[iPtr];
System.out.print(" #name for this hit=" + iArPickingBuffer[iPtr]);
iPtr++;
// // Check if object is nearer than previous objects
// if (iArPickingBuffer[iPtr] < iMinimumZValue)
// {
// System.out.print(" nearer than previous hit! ");
// }
/* ist doch ein float! */
//iMinimumZValue = iArPickingBuffer[iPtr];
float fZmin = (float) iArPickingBuffer[iPtr];
System.out.print(" minZ=" + fZmin);
iPtr++;
System.out.print(" maxZ=" + (float) iArPickingBuffer[iPtr]);
iPtr++;
System.out.print(" Pick-> [");
int iName = -1;
for (int j = 0; j < iNumbersPerHit; j++)
{
iName = iArPickingBuffer[iPtr];
if (fZmin < fDepthSort)
{
fDepthSort = fZmin - AGLCanvasHeatmap2D.fPickingBias;
if (iResultPickCoordIndex < 2)
{
resultPickPointCoord[iResultPickCoordIndex] = iName;
iResultPickCoordIndex++;
}
}
System.out.print(" #" + i + " name=" + iName + ",");
iPtr++;
}
System.out.println("]");
}
if (iHitCount < 1)
{
// Remove pathway pool fisheye
return false;
}
System.out
.println("GLCanvasHeatmap2DColumn PICKED index=["
+ resultPickPointCoord[0] + ","
+ resultPickPointCoord[1] + "]");
// Reset pick point
//source of problems??
infoAreaRenderer.convertWindowCoordinatesToWorldCoordinates(gl,
pickPoint.x, pickPoint.y);
// // Check if real picking is performed
// if (bIsMousePickingEvent)
// {
int[] selectedIndexArray = addPickedPoint(fIndexPickedCoored,
(float) resultPickPointCoord[0],
(float) resultPickPointCoord[1] );
if ( selectedIndexArray != null ) {
/** notify other listeners .. */
notifyReceiver_PickedObject_singleSelection(selectedIndexArray, iSelectedMode_identifyier);
// Integer iNCBIGeneID = hashExternalId_2_HeatmapIndex_reverse.get(resultPickPointCoord[0]);
// if ( iNCBIGeneID != null)
// {
// PathwayVertexGraphItem pickedGeneVertex;
// pickedGeneVertex = (PathwayVertexGraphItem) refGeneralManager.getSingelton(
// ).getPathwayItemManager().getItem(iNCBIGeneID.intValue());
//
// infoAreaRenderer.renderInfoArea(gl, pickedGeneVertex);
// }
}
/* hack, check if external hashmap was already created */
//TODO: clean up this call, init from outside as soon as data is available!
if ( hashExternalId_2_HeatmapIndex==null ) {
this.init_External2InternalHashMap();
}
Integer iNCBIGeneID = hashExternalId_2_HeatmapIndex_reverse.get(resultPickPointCoord[0]);
if ( iNCBIGeneID != null)
{
//PathwayVertexGraphItem pickedGeneVertex;
pickedGeneVertex = (PathwayVertexGraphItem) refGeneralManager.getSingelton(
).getPathwayItemManager().getItem(iNCBIGeneID.intValue());
assert pickedGeneVertex != null : "should not get null-pointer!";
infoAreaRenderer.renderInfoArea(gl, pickedGeneVertex);
}
//source of problems??
//infoAreaRenderer.resetPoint();
// }
return true;
}
/* ----- END: PICKING ----- */
/* --------------------------- */
/* ----- END: PICKING ----- */
/* --------------------------- */
private void notifyReceiver_PickedObject_singleSelection( final int [] resultPickPointCoord, final int iModeValue) {
if ( resultPickPointCoord.length < 1) {
return;
}
int [] resultSelectedIndex = new int [resultPickPointCoord.length];
int [] resultSelectedIndexMode = new int [resultPickPointCoord.length];
/* copy new indices to end of existing array.. */
for ( int iIndex=0; iIndex<resultPickPointCoord.length; iIndex++) {
resultSelectedIndex[iIndex] = resultPickPointCoord[iIndex];
resultSelectedIndexMode[iIndex] = iModeValue;
}
/* swap .. */
selectedIndex = resultSelectedIndex;
selectedIndexMode = resultSelectedIndexMode;
/* hack, check if external hashmap was already created */
//TODO: clean up this call, init from outside as soon as data is available!
if ( hashExternalId_2_HeatmapIndex==null ) {
this.init_External2InternalHashMap();
}
/* notify external objects via eventMediator.. */
if ( hashExternalId_2_HeatmapIndex_reverse != null ) {
/* data for SetSelection.. */
SetSelection selectionSet = new SetSelection(-5, refGeneralManager);
ArrayList <Integer> alSelectionId = new ArrayList <Integer> (resultPickPointCoord.length);
ArrayList <Integer> alSelectionId_PathwayId = new ArrayList <Integer> (resultPickPointCoord.length);
for ( int i=0; i< resultPickPointCoord.length; i++ ) {
/* convert internal index to external id.. */
Integer lookupValue = hashExternalId_2_HeatmapIndex_reverse.get(resultPickPointCoord[i]);
if ( lookupValue == null ) {
return;
}
PathwayVertexGraphItem vertexItemBuffer = (PathwayVertexGraphItem) refGeneralManager.getSingelton()
.getPathwayItemManager().getItem(lookupValue.intValue());
Iterator <IGraphItem> iterList =
vertexItemBuffer.getAllItemsByProp(EGraphItemProperty.ALIAS_CHILD).iterator();
while (iterList.hasNext()) {
IGraphItem bufferItem = iterList.next();
alSelectionId.add( bufferItem.getId() );
//alSelectionId.add( iterList.next().getId() );
// get pathway id from graph
List<IGraph> list = bufferItem.getAllGraphByType(EGraphItemHierarchy.GRAPH_PARENT);
PathwayGraph buffer = (PathwayGraph) list.get(0);
alSelectionId_PathwayId.add( buffer.getKeggId() );
}
}
int[] iArSelectionId = new int[alSelectionId.size()];
int[] iArSelectionDepthData = new int[alSelectionId.size()];
int[] iArSelectionOptionalData = new int[alSelectionId.size()];
for ( int i=0; i < alSelectionId.size(); i++) {
iArSelectionId[i] = alSelectionId.get(i).intValue();
iArSelectionDepthData[i] = iModeValue;
iArSelectionOptionalData[i] = alSelectionId_PathwayId.get(i);
}
IStorage [] storageArray = new IStorage [3];
for ( int i=0; i< 3 ; i++ ) {
storageArray[i] = new FlatThreadStorageSimple( selectionSet.getId(), refGeneralManager, null);
selectionSet.setStorageByDim(storageArray, 0);
}
selectionSet.setAllSelectionDataArrays(iArSelectionId, iArSelectionDepthData, iArSelectionOptionalData );
// Calls update with the ID of the PathwayViewRep
((EventPublisher)refGeneralManager.getSingelton().
getEventPublisher()).updateReceiver(this, selectionSet);
refGeneralManager.getSingelton().logMsg(this.getClass().getSimpleName()+
".broadcast selection event! " + selectionSet.toString(),
LoggerType.STATUS);
}
}
private void notifyReceiver_PickedObject_multipleSelection( final int [] resultPickPointCoord, final int iModeValue) {
if ( resultPickPointCoord.length < 1) {
return;
}
int [] resultSelectedIndex = new int [selectedIndex.length + resultPickPointCoord.length];
int [] resultSelectedIndexMode = new int [selectedIndex.length + resultPickPointCoord.length];
/* copy existing array.. */
for ( int i=0; i< selectedIndex.length; i++ ) {
resultSelectedIndex[i]= selectedIndex[i];
resultSelectedIndexMode[i]=selectedIndexMode[i];
}
/* copy new indices to end of existing array.. */
int iIndex = selectedIndex.length;
for ( int i=0; i<resultPickPointCoord.length; i++) {
resultSelectedIndex[iIndex] = resultPickPointCoord[i];
resultSelectedIndexMode[iIndex] = iModeValue;
iIndex++;
}
/* swap .. */
selectedIndex = resultSelectedIndex;
selectedIndexMode = resultSelectedIndexMode;
if ( hashExternalId_2_HeatmapIndex==null ) {
this.init_External2InternalHashMap();
}
/* notify external objects via eventMediator.. */
if ( hashExternalId_2_HeatmapIndex_reverse != null ) {
/* data for SetSelection.. */
SetSelection selectionSet = new SetSelection(-5, refGeneralManager);
ArrayList <Integer> alSelectionId = new ArrayList <Integer> (resultPickPointCoord.length);
ArrayList <Integer> alSelectionId_PathwayId = new ArrayList <Integer> (resultPickPointCoord.length);
for ( int i=0; i< resultPickPointCoord.length; i++ ) {
/* convert internal index to external id.. */
Integer lookupValue = hashExternalId_2_HeatmapIndex_reverse.get(resultPickPointCoord[i]);
if ( lookupValue == null ) {
return;
}
PathwayVertexGraphItem vertexItemBuffer = (PathwayVertexGraphItem) refGeneralManager.getSingelton()
.getPathwayItemManager().getItem(lookupValue.intValue());
Iterator <IGraphItem> iterList =
vertexItemBuffer.getAllItemsByProp(EGraphItemProperty.ALIAS_CHILD).iterator();
while (iterList.hasNext()) {
IGraphItem bufferItem = iterList.next();
alSelectionId.add( bufferItem.getId() );
//alSelectionId.add( iterList.next().getId() );
// get pathway id from graph
List<IGraph> list = bufferItem.getAllGraphByType(EGraphItemHierarchy.GRAPH_PARENT);
PathwayGraph buffer = (PathwayGraph) list.get(0);
alSelectionId_PathwayId.add( buffer.getKeggId() );
}
}
int[] iArSelectionId = new int[alSelectionId.size()];
int[] iArSelectionDepthData = new int[alSelectionId.size()];
int[] iArSelectionOptionalData = new int[alSelectionId.size()];
for ( int i=0; i < alSelectionId.size(); i++) {
iArSelectionId[i] = alSelectionId.get(i).intValue();
iArSelectionDepthData[i] = iModeValue;
iArSelectionOptionalData[i] = alSelectionId_PathwayId.get(i);
}
IStorage [] storageArray = new IStorage [3];
for ( int i=0; i< 3 ; i++ ) {
storageArray[i] = new FlatThreadStorageSimple( selectionSet.getId(), refGeneralManager, null);
selectionSet.setStorageByDim(storageArray, 0);
}
selectionSet.setAllSelectionDataArrays(iArSelectionId, iArSelectionDepthData, iArSelectionOptionalData );
// Calls update with the ID of the PathwayViewRep
((EventPublisher)refGeneralManager.getSingelton().
getEventPublisher()).updateReceiver(this, selectionSet);
refGeneralManager.getSingelton().logMsg("broadcast selection event! " + selectionSet.toString(),
LoggerType.STATUS);
}
}
@Override
public void renderPart(GL gl) {
gl.glPushMatrix();
if ( bEnablePicking ) {
handlePicking(gl);
}
gl.glTranslatef(0, 0, 0.01f);
if (alTargetSet.isEmpty())
{
refGeneralManager
.getSingelton()
.logMsg(
"createHistogram() can not create Heatmap, because targetSet=null",
LoggerType.STATUS);
return;
}
if (iValuesInRow < 1)
{
refGeneralManager
.getSingelton()
.logMsg(
"createHistogram() can not create Heatmap, because histogramLevels are outside range [1..max]",
LoggerType.FULL);
return;
}
ISet primaryTargetSet = alTargetSet.get(0);
if ((primaryTargetSet.hasCacheChanged(iSetCacheId))
|| (iHeatmapDisplayListId == -1))
{
iSetCacheId = primaryTargetSet.getCacheId();
// System.out.print("H:");
// for ( int i=0;i<iHistogramIntervalls.length; i++) {
// System.out.print(";" +
// Integer.toString(iHistogramIntervalls[i]) );
// }
System.out.println("GLCanvasHeatmap2DColumn - UPDATED!");
render_createDisplayLists(gl);
refGeneralManager.getSingelton().logMsg(
"createHistogram() use ISet(" + primaryTargetSet.getId()
+ ":" + primaryTargetSet.getLabel() + ")",
LoggerType.FULL);
}
if (bUseGLWireframe)
{
gl.glPolygonMode(GL.GL_FRONT_AND_BACK, GL.GL_LINE);
}
// else
// {
// gl.glPolygonMode(GL.GL_FRONT_AND_BACK, GL.GL_FILL);
// }
//renderGLSingleQuad(gl,this.fIndexPickedCoored,0);
gl.glDisable(GL.GL_LIGHTING);
gl.glCallList(iHeatmapDisplayListId);
if ( pickedGeneVertex!= null)
{
infoAreaRenderer.renderInfoArea(gl, pickedGeneVertex);
}
renderSelection_ownArea(gl);
gl.glTranslatef(0, 0, -AGLCanvasHeatmap2D.fPickingBias);
// gl.glColor3f(1, 1, 0);
// renderGLAllQuadRectangle(gl, this.fIndexPickedCoored);
//
// gl.glColor3f(0.8f, 0.8f, 0);
// renderGLAllQuadDots(gl, this.fIndexPickedCoored);
// gl.glColor3f(0, 0, 0.8f);
// renderGL_Selection(gl);
if ( bEnablePicking ) {
gl.glTranslatef(0, 0, AGLCanvasHeatmap2D.fPickingBias);
render_picketPoints(gl);
}
// if (pickedGeneVertex != null && infoAreaRenderer.isPositionValid())
// {
// infoAreaRenderer.renderInfoArea(gl, pickedGeneVertex);
// }
gl.glEnable(GL.GL_LIGHTING);
//System.err.println(" Heatmap2D ! .render(GLCanvas canvas)");
gl.glPopMatrix();
}
/**
* Render picked points in own area.
*
* @param gl
*/
private void render_picketPoints(GL gl) {
if ((selectedIndex.length > 0) || (!fIndexPickedCoored.isEmpty()))
{
int iRenderIndexRangeX = iRenderIndexStop - iRenderIndexStart;
float fIncY = (viewingFrame[Y][MAX] - viewingFrame[Y][MIN])
/ (float) (alTargetSet.size());
float fIncY_halfSize = fIncY * 0.5f;
float fNowY = viewingFrame[Y][MIN];
float fNextY = fNowY + fIncY;
float fIncX = (viewingFrame[X][MAX] - viewingFrame[X][MIN])
/ (float) (iRenderIndexRangeX + 1);
float fIncX_halfSize = fIncX * 0.5f;
float fNowX = viewingFrame[X][MIN];
float fNextX = fNowX + fIncX;
float fZ = viewingFrame[Z][MIN] + fPickingBias;
if (!fIndexPickedCoored.isEmpty())
{
/* -------------------------- */
/* show picked points .. */
Iterator<Vec2f> iterPickedPoints = fIndexPickedCoored
.iterator();
gl.glColor3f(1.0f, 1.0f, 0);
for (int i = 0; iterPickedPoints.hasNext(); i++)
{
/**
* Render a triangle on each selected item in the heatmap.
*/
Vec2f pickedIndex = iterPickedPoints.next();
/* TOP */
fNowX = viewingFrame[X][MIN] + fIncX * pickedIndex.x();
fNextX = viewingFrame[X][MIN] + fIncX
* (pickedIndex.x() + 1);
fNowY = viewingFrame[Y][MIN] + fIncY * pickedIndex.y();
fNextY = viewingFrame[Y][MIN] + fIncY
* (pickedIndex.y() + 1);
gl.glBegin(GL.GL_TRIANGLE_FAN);
gl.glVertex3f(fNowX, fNowY, fZ);
gl.glVertex3f(fNextX, fNowY, fZ);
gl.glVertex3f(fNextX, fNowY + fIncY_halfSize, fZ);
//gl.glVertex3f(fNowX, fNextY, viewingFrame[Z][MIN]);
gl.glEnd();
}
/* end: show picked points .. */
/* -------------------------- */
}
if (selectedIndex.length > 0)
{
/* ------------------- */
/* highlight selection */
/* Y_min .. Y_max */
for (int index_X_H = 0; index_X_H < selectedIndex.length; index_X_H++)
{
gl.glLineWidth(fSelectionLineWidth);
gl.glColor3f(0, 0, 1);
if ((selectedIndex[index_X_H] >= iRenderIndexStart)
&& (selectedIndex[index_X_H] < iRenderIndexStop))
{
/**
* Render one BOX on top, one Box below and connect them with 2 lines
* of each selected heatmap segment [X , Y_min..Y_max]
* */
fNowX = viewingFrame[X][MIN] + fIncX
* selectedIndex[index_X_H];
fNextX = fNowX + fIncX;
/* LINES */
fNowY = viewingFrame[Y][MIN];
fNextY = viewingFrame[Y][MAX];
gl.glBegin(GL.GL_LINES);
gl.glVertex3f(fNowX, fNowY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNowX, fNextY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNextX, fNowY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNextX, fNextY, viewingFrame[Z][MIN]);
gl.glEnd();
/* BOTTOM */
render_Selection_Detail(gl,
fNowX,
fNextX,
viewingFrame[Y][MIN],
fIncY,
viewingFrame[Z][MIN],
selectedIndexMode,
index_X_H,
-1.0f );
/* TOP */
fNowY = viewingFrame[Y][MAX];
fNextY = viewingFrame[Y][MAX] + fSelectionPixel
* fIncY;
gl.glColor3f(0,0,1);
gl.glBegin(GL.GL_TRIANGLE_FAN);
gl.glVertex3f(fNowX, fNowY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNextX, fNowY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNextX, fNextY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNowX, fNextY, viewingFrame[Z][MIN]);
gl.glEnd();
} // if (( selectedIndex[index_X_H] >= iRenderIndexStart
// )&&( selectedIndex[index_X_H] < iRenderIndexStop)) {
} // for (int index_X_H=0; index_X_H<selectedIndex.length;
// index_X_H++)
/* end highlight selection */
}
}
}
// public int[] createHistogram(final int iHistogramLevels) {
public void renderHeatmap(final int iHistogramLevels) {
refGeneralManager.getSingelton().logMsg("HEATMAP: set ",
LoggerType.FULL);
}
public int getHeatmapValuesInRow() {
return iValuesInRow;
}
/**
*
* @param fColorMappingShiftFromMean 1.0f indicates no shift
*/
private void initColorMapping(final float fColorMappingShiftFromMean) {
if (refMinMaxDataInteger.isValid())
{
fColorMappingLowValue = (float) refMinMaxDataInteger.getMin(0);
fColorMappingHighValue = (float) refMinMaxDataInteger.getMax(0);
fColorMappingMiddleValue = (float) refMinMaxDataInteger.getMean(0)
* fColorMappingShiftFromMean;
fColorMappingLowRange = fColorMappingMiddleValue
- fColorMappingLowValue;
fColorMappingHighRangeDivisor = 1.0f / (fColorMappingHighValue - fColorMappingMiddleValue);
fColorMappingLowRangeDivisor = 1.0f / (fColorMappingLowRange * (1.0f + fColorMappingPercentageStretch));
float fValuesInColum = (float) refMinMaxDataInteger.getItems(0)
/ (float) iValuesInRow;
iValuesInColum = (int) (fValuesInColum);
} else
{
System.err.println("Error while init color mapping for Heatmap!");
}
}
protected void colorMapping(final GL gl, final int iValue) {
float fValue = fColorMappingMiddleValue - (float) iValue;
if (fValue < 0.0f)
{
// range [fColorMappingLowValue..fColorMappingMiddleValue[
float fScale = (fColorMappingLowRange + fValue)
* fColorMappingLowRangeDivisor;
gl.glColor3f(0, 1.0f - fScale, 0);
return;
}
//else
//range [fColorMappingMiddleValue..fColorMappingHighValue]
float fScale = (fValue) * fColorMappingHighRangeDivisor;
gl.glColor3f(fScale, 0, 0);
}
public final void setRednerIndexStartStop(final int iSetRenderIndexStart,
final int iSetRenderIndexStop) {
if (iSetRenderIndexStart < iSetRenderIndexStop)
{
this.iRenderIndexStart = iSetRenderIndexStart;
this.iRenderIndexStop = iSetRenderIndexStop;
} else
{
refGeneralManager
.getSingelton()
.logMsg(
"Ignore render start/stop=["
+ iSetRenderIndexStart
+ "/"
+ iSetRenderIndexStop
+ "] , because start index is smaller than stop index!",
LoggerType.MINOR_ERROR_XML);
}
if ( (iSetRenderIndexStop - iSetRenderIndexStart) > iRenderIndexLength_UpperLimit ) {
bRenderEnableDelimiterPerExperiment = false;
}
}
/* (non-Javadoc)
* @see cerberus.view.opengl.canvas.heatmap.IGLCanvasHeatmap2D#setTargetSetId(int)
*/
public final void setTargetSetId(final int iTargetCollectionSetId) {
boolean bUpdateColorMapping = alTargetSet.isEmpty();
ISet addTargetSet = refGeneralManager.getSingelton().getSetManager()
.getItemSet(iTargetCollectionSetId);
if (addTargetSet == null)
{
refGeneralManager.getSingelton().logMsg(
"GLCanvasScatterPlot2D.setTargetSetId("
+ iTargetCollectionSetId
+ ") failed, because Set is not registered!",
LoggerType.FULL);
}
alTargetSet.add(addTargetSet);
refGeneralManager.getSingelton().logMsg(
"GLCanvasScatterPlot2D.setTargetSetId("
+ iTargetCollectionSetId + ") done!", LoggerType.FULL);
if (bUpdateColorMapping)
{
refMinMaxDataInteger.useSet(addTargetSet);
initColorMapping(fColorMappingShiftFromMean);
}
}
public void render_displayListHeatmap(GL gl) {
if ( alTargetSet.isEmpty())
{
return;
}
if ( bRenderingStyleFlat ) {
render_displaylistHeatmap_FlatStyle(gl);
} else {
render_displaylistHeatmap_SortedStyle(gl);
}
/* Sourrounding box */
float fBias_Z = viewingFrame[Z][MIN] + fPickingBias;
float fIncY = (viewingFrame[Y][MAX] - viewingFrame[Y][MIN])
/ (float) (alTargetSet.size());
gl.glColor3f(1.0f, 1.0f, 0.1f);
gl.glBegin(GL.GL_LINE_LOOP);
gl.glVertex3f(viewingFrame[X][MIN], viewingFrame[Y][MIN], fBias_Z);
gl.glVertex3f(viewingFrame[X][MAX], viewingFrame[Y][MIN], fBias_Z);
gl.glVertex3f(viewingFrame[X][MAX], viewingFrame[Y][MAX], fBias_Z);
gl.glVertex3f(viewingFrame[X][MIN], viewingFrame[Y][MAX], fBias_Z);
gl.glEnd();
/**
* Render each experiment in a row ..
*/
if ( bRenderEnableDelimiterPerExperiment ) {
if (alTargetSet.size() > 1)
{
/**
* Render lines between each row of experiments
*/
float fZ_2 = fBias_Z + fPickingBias;
gl.glBegin(GL.GL_LINES);
/* start with index=1 and goto alTargetSet.size() */
for (int i = 1; i < alTargetSet.size(); i++)
{
gl.glVertex3f(viewingFrame[X][MIN], viewingFrame[Y][MIN]
+ fIncY * i, fZ_2);
gl.glVertex3f(viewingFrame[X][MAX], viewingFrame[Y][MIN]
+ fIncY * i, fZ_2);
}
gl.glEnd();
}
}
}
private void render_displaylistHeatmap_SortedStyle(GL gl) {
/**
* Get data from Set...
*/
Iterator<ISet> iterTargetSet = alTargetSet.iterator();
int iRenderIndexRangeX = iRenderIndexStop - iRenderIndexStart;
float fIncY = (viewingFrame[Y][MAX] - viewingFrame[Y][MIN])
/ (float) (alTargetSet.size());
float fNowY = viewingFrame[Y][MIN];
float fNextY = fNowY + fIncY;
float fIncX = (viewingFrame[X][MAX] - viewingFrame[X][MIN])
/ (float) (iRenderIndexRangeX + 1);
this.fIncX_forSelection = fIncX;
float fNowX = viewingFrame[X][MIN];
float fNextX = fNowX + fIncX;
gl.glNormal3f(0.0f, 0.0f, 1.0f);
while (iterTargetSet.hasNext())
{
ISet currentTargetSet = iterTargetSet.next();
IStorage refStorage = currentTargetSet.getStorageByDimAndIndex(
0, 0);
int[] dataArrayInt = refStorage.getArrayInt();
IVirtualArray refVArray = currentTargetSet
.getVirtualArrayByDimAndIndex(0, 0);
IVirtualArrayIterator iter = refVArray.iterator();
//int[] i_dataValues = refStorage.getArrayInt();
if (dataArrayInt != null)
{
/**
* force update ...
*/
for (int iIndex_X = 0; iter.hasNext(); iIndex_X++)
{
if (iIndex_X >= iRenderIndexStart)
{
if (iIndex_X >= iRenderIndexStop)
{
iter.setToEnd();
break;
}
gl.glBegin(GL.GL_TRIANGLE_FAN);
// gl.glBegin( GL.GL_LINE_LOOP );
colorMapping(gl, dataArrayInt[iter.next()]);
gl.glVertex3f(fNowX, fNowY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNextX, fNowY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNextX, fNextY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNowX, fNextY, viewingFrame[Z][MIN]);
gl.glEnd();
fNowX = fNextX;
fNextX += fIncX;
} else
{
iter.next();
}
} //for (int iIndex_X = 0;iter.hasNext(); iIndex_X++ )
} // if (i_dataValues != null)
/* reset X .. */
fNowX = viewingFrame[X][MIN];
fNextX = fNowX + fIncX;
/* increment Y .. */
fNowY = fNextY;
fNextY += fIncY;
} //while ( iter.hasNext() )
}
private void render_Selection_Detail(GL gl,
final float fX,
final float fX_next,
final float fY,
final float fIncY,
final float fZ,
final int [] selectedIndexModeArray,
final int selectedIndexMode_Index,
final float fSign ) {
//if (selectedIndexModeArray[selectedIndexMode_Index] > 0 ) {
gl.glColor3f(0, 0, 1);
gl.glBegin(GL.GL_TRIANGLE_FAN);
float fY_a = fY + (selectedIndexModeArray[selectedIndexMode_Index])
* fIncY * fSelectionPixel * fSign;
gl.glVertex3f(fX, fY, fZ);
gl.glVertex3f(fX_next, fY, fZ);
gl.glVertex3f(fX_next, fY_a, fZ);
gl.glVertex3f(fX, fY_a, fZ);
gl.glEnd();
/**
* Render a line between the selected area and the top of the heatmap
*/
/**
* Render a line to indicate depth of selection; from neighborhood
*/
gl.glColor3f(1, 1, 1);
float fZb = fZ + fPickingBias;
for ( int j=1; j < selectedIndexModeArray[selectedIndexMode_Index]; j++ ) {
fY_a = fY + j * fIncY * fSelectionPixel * fSign;
gl.glBegin(GL.GL_LINES);
gl.glVertex3f(fX, fY_a, fZb);
gl.glVertex3f(fX_next, fY_a, fZb);
gl.glEnd();
} //for ( int j=1; j < selectedIndexMode[i]; j++ ) {
//} //if (selectedIndexMode[i] > 0 ) {
}
private void renderSelection_ownArea(GL gl) {
/* ----------------------------------- */
/* --- Render selected once more --- */
// Iterator < ArrayList <Integer>> iter_sortByDepth =
// alHighlightSelectionIndex_sortByDepth.iterator();
//
// int iSumItems = 0;
// while ( iter_sortByDepth.hasNext() ) {
// iSumItems += iter_sortByDepth.next().size();
// }
//
// if ( iSumItems < 1) {
// /* no selection to render.. */
// return;
// }
if ( selectedIndex.length < 1 ) {
return;
}
/* reset rendering parameters.. */
float fOffsetY= 2.0f; //(viewingFrame[X][MAX] - viewingFrame[X][MIN]);
float fIncY = (viewingFrame[Y][MAX] - viewingFrame[Y][MIN])
/ (float) (alTargetSet.size());
float fNowY = viewingFrame[Y][MIN] + fOffsetY;
float fNextY = fNowY + fIncY;
/* use global variable.. */
float fIncX = fIncX_forSelection;
float fIncX_halfSize = fIncX_forSelection * 0.5f;
float fXOffset = ((viewingFrame[X][MAX] - viewingFrame[X][MIN])
- (selectedIndex.length + 1) * fIncX) * 0.5f;
float fNowX = viewingFrame[X][MIN] + fXOffset;
float fNextX = fNowX + fIncX;
/* copy references to raw data int[] .. */
ArrayList <int[]> bufferValueArrays = new ArrayList <int[]> ();
ArrayList <Integer> bufferValueArrays_Offset = new ArrayList <Integer> ();
Iterator <ISet> iterTargetSet = alTargetSet.iterator();
while (iterTargetSet.hasNext()) {
ISet currentTargetSet = iterTargetSet.next();
IVirtualArray refVArray = currentTargetSet.getVirtualArrayByDimAndIndex(0, 0);
IVirtualArrayIterator iter = refVArray.iterator();
IStorage refStorage = currentTargetSet.getStorageByDimAndIndex(0, 0);
int[] dataArrayInt = refStorage.getArrayInt();
if (dataArrayInt != null)
{
bufferValueArrays.add(dataArrayInt);
bufferValueArrays_Offset.add(iter.next());
}
} //while (iterTargetSet.hasNext()) {
/* end: copy references to raw data int[] .. */
boolean bEnableGroupHighlighting = false;
if (selectedIndexMode.length > 0 ) {
bEnableGroupHighlighting = true;
}
for ( int i=0; i < selectedIndex.length; i++) {
int iCurrentIndex = selectedIndex[i];
Iterator<int[]> iterRawDataArrays = bufferValueArrays.iterator();
Iterator<Integer> iterRawDataArrays_Offset = bufferValueArrays_Offset.iterator();
while (iterRawDataArrays.hasNext()) {
int [] currentArrayBuffer = iterRawDataArrays.next();
int iCurrentIndex_InArray =
iterRawDataArrays_Offset.next().intValue()
+ iCurrentIndex;
gl.glBegin(GL.GL_TRIANGLE_FAN);
try {
colorMapping(gl, currentArrayBuffer[iCurrentIndex_InArray] );
} catch (ArrayIndexOutOfBoundsException aie) {
System.err.println("ERROR! ");
}
gl.glVertex3f(fNowX, fNowY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNextX, fNowY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNextX, fNextY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNowX, fNextY, viewingFrame[Z][MIN]);
gl.glEnd();
fNowY = fNextY;
fNextY += fIncY;
}
if (bEnableGroupHighlighting) {
if (selectedIndexMode[i] > 0 ) {
render_Selection_Detail(gl,
fNowX,
fNextX,
fNowY,
fIncY,
viewingFrame[Z][MIN],
selectedIndexMode,
i,
1.0f );
} //if (selectedIndexMode[i] > 0 ) {
}
/** render connection line to target in heatmap */
int iRenderTargetLine_Index =
iCurrentIndex - this.iRenderIndexStart;
float fLineX = viewingFrame[X][MIN] +
fIncX * iRenderTargetLine_Index +
fIncX_halfSize;
/**
* Render lines connecting Selected area and heatmap
*/
gl.glColor3f(0.2f, 0.2f, 1);
gl.glBegin(GL.GL_LINES);
gl.glVertex3f(fNowX + fIncX_halfSize,
viewingFrame[Y][MIN] + fOffsetY,
viewingFrame[Z][MIN]);
gl.glVertex3f(fLineX,
viewingFrame[Y][MAX] + fSelectionPixel * fIncY,
viewingFrame[Z][MIN]);
gl.glEnd();
/** end: render connection line to target in heatmap */
// /** render separation line in selection */
// gl.glBegin(GL.GL_LINES);
//
// gl.glVertex3f(fNowX, viewingFrame[Y][MIN] + fOffsetY, viewingFrame[Z][MIN]);
// gl.glVertex3f(fNowX, fNowY, viewingFrame[Z][MIN]);
//
// gl.glEnd();
// /** end: render separation line in selection */
fNowX = fNextX;
fNextX += fIncX;
/* reset Y.. */
fNowY = viewingFrame[Y][MIN] + fOffsetY;
fNextY = fNowY + fIncY;
/* search for data values now.. */
} //for ( int i=0; i < selectedIndex.length; i++) {
/* Sourrounding box */
gl.glColor3f(1.0f, 1.0f, 0.1f);
gl.glBegin(GL.GL_LINE_LOOP);
gl.glVertex3f(viewingFrame[X][MIN] + fXOffset, viewingFrame[Y][MIN]+ fOffsetY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNowX, viewingFrame[Y][MIN]+ fOffsetY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNowX, viewingFrame[Y][MAX]+ fOffsetY, viewingFrame[Z][MIN]);
gl.glVertex3f(viewingFrame[X][MIN] + fXOffset, viewingFrame[Y][MAX]+ fOffsetY, viewingFrame[Z][MIN]);
gl.glEnd();
/* --- Render selected once more --- */
/* ----------------------------------- */
}
private void render_displaylistHeatmap_FlatStyle(GL gl) {
/**
* Get data from Set...
*/
Iterator<ISet> iterTargetSet = alTargetSet.iterator();
int iRenderIndexRangeX = iRenderIndexStop - iRenderIndexStart;
float fIncY = (viewingFrame[Y][MAX] - viewingFrame[Y][MIN])
/ (float) (alTargetSet.size());
float fNowY = viewingFrame[Y][MIN];
float fNextY = fNowY + fIncY;
float fIncX = (viewingFrame[X][MAX] - viewingFrame[X][MIN])
/ (float) (iRenderIndexRangeX + 1);
this.fIncX_forSelection = fIncX;
float fNowX = viewingFrame[X][MIN];
float fNextX = fNowX + fIncX;
gl.glNormal3f(0.0f, 0.0f, 1.0f);
while (iterTargetSet.hasNext())
{
ISet currentTargetSet = iterTargetSet.next();
IStorage refStorage = currentTargetSet.getStorageByDimAndIndex(
0, 0);
int[] dataArrayInt = refStorage.getArrayInt();
IVirtualArray refVArray = currentTargetSet
.getVirtualArrayByDimAndIndex(0, 0);
IVirtualArrayIterator iter = refVArray.iterator();
int[] i_dataValues = refStorage.getArrayInt();
if (i_dataValues != null)
{
// if (currentTargetSet.hasCacheChanged(iSetCacheId))
// {
//
// iSetCacheId = currentTargetSet.getCacheId();
//
// // System.out.print("H:");
// // for ( int i=0;i<iHistogramIntervalls.length; i++) {
// // System.out.print(";" +
// // Integer.toString(iHistogramIntervalls[i]) );
// // }
// System.err.println(" UPDATED inside DispalyList!");
// }
//System.out.print("-");
/**
* force update ...
*/
for (int iIndex_X = 0; iter.hasNext(); iIndex_X++)
{
if (iIndex_X >= iRenderIndexStart)
{
if (iIndex_X >= iRenderIndexStop)
{
iter.setToEnd();
break;
}
gl.glBegin(GL.GL_TRIANGLE_FAN);
// gl.glBegin( GL.GL_LINE_LOOP );
colorMapping(gl, dataArrayInt[iter.next()]);
gl.glVertex3f(fNowX, fNowY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNextX, fNowY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNextX, fNextY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNowX, fNextY, viewingFrame[Z][MIN]);
gl.glEnd();
fNowX = fNextX;
fNextX += fIncX;
} else
{
iter.next();
}
} //for (int iIndex_X = 0;iter.hasNext(); iIndex_X++ )
} // if (i_dataValues != null)
/* reset X .. */
fNowX = viewingFrame[X][MIN];
fNextX = fNowX + fIncX;
/* increment Y .. */
fNowY = fNextY;
fNextY += fIncY;
} //while ( iter.hasNext() )
}
/* --------------------------- */
/* ----- BEGEN: PICKING ----- */
// private void setPickingBegin(GL gl,int id) {
// gl.glPushMatrix();
// gl.glPushName( id );
// }
//
// private void setPickingEnd(GL gl) {
// gl.glPopName();
// gl.glPopMatrix();
// }
//
// private void setPickingrowAndColum(GL gl,int id) {
// gl.glLoadName(id);
// }
protected final void renderPart4pickingX(GL gl) {
/* public void render_displayListHeatmap(GL gl) { */
gl.glNormal3f(0.0f, 0.0f, 1.0f);
/**
* force update ...
*/
int iRenderIndexRangeX = iRenderIndexStop - iRenderIndexStart;
float fIncX = (viewingFrame[X][MAX] - viewingFrame[X][MIN])
/ (float) (iRenderIndexRangeX);
float fNowY = viewingFrame[Y][MIN];
float fNextY = viewingFrame[Y][MAX];
float fNowX = viewingFrame[X][MIN];
float fNextX = fNowX + fIncX;
/* Y_min .. Y_max*/
for (int yCoord_name = 0; yCoord_name < iRenderIndexRangeX; yCoord_name++)
{
//this.setPickingBegin(gl, yCoord_name);
gl.glLoadName(yCoord_name);
gl.glPushName(yCoord_name);
gl.glBegin(GL.GL_TRIANGLE_FAN);
gl.glVertex3f(fNowX, fNowY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNextX, fNowY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNextX, fNextY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNowX, fNextY, viewingFrame[Z][MIN]);
gl.glEnd();
gl.glPopName();
fNowX = fNextX;
fNextX += fIncX;
} //for (int yCoord_name=0; yCoord_name<iValuesInRow; yCoord_name++)
}
protected final void renderPart4pickingY(GL gl) {
/* public void render_displayListHeatmap(GL gl) { */
gl.glNormal3f(0.0f, 0.0f, 1.0f);
int ycoord_name = 0;
/**
* force update ...
*/
float fIncY = (viewingFrame[Y][MAX] - viewingFrame[Y][MIN])
/ (float) (this.alTargetSet.size());
float fNowX = viewingFrame[X][MIN];
float fNextX = viewingFrame[X][MAX];
float fNowY = viewingFrame[Y][MIN];
float fNextY = fNowY + fIncY;
/* Y_min .. Y_max */
for (int i = 0; i < this.alTargetSet.size(); i++)
{
gl.glLoadName(ycoord_name);
gl.glPushName(ycoord_name);
gl.glBegin(GL.GL_TRIANGLE_FAN);
gl.glVertex3f(fNowX, fNowY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNextX, fNowY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNextX, fNextY, viewingFrame[Z][MIN]);
gl.glVertex3f(fNowX, fNextY, viewingFrame[Z][MIN]);
gl.glEnd();
gl.glPopName();
fNowY = fNextY;
fNextY += fIncY;
ycoord_name++;
} // while (iter.hasNext())
}
/* (non-Javadoc)
* @see cerberus.view.opengl.canvas.heatmap.IGLCanvasHeatmap2D#setSelectionItems(int[], int[], int[], int[])
*/
public void setSelectionItems(int[] selectionStartAtIndexX,
int[] selectionLengthX, int[] selectionStartAtIndexY,
int[] selectionLengthY) {
super.setSelectionItems(selectionStartAtIndexX, selectionLengthX,
selectionStartAtIndexY, selectionLengthY);
}
public void updateReceiver(Object eventTrigger) {
refGeneralManager.getSingelton().logMsg(
this.getClass().getSimpleName()+
": updateReceiver( (" +
eventTrigger.getClass().getSimpleName() + ") " +
eventTrigger.toString() + ")",
LoggerType.STATUS );
}
public void updateReceiver(Object eventTrigger, ISet updatedSet) {
refGeneralManager.getSingelton().logMsg(
this.getClass().getSimpleName()+
": updateReceiver( (" +
eventTrigger.getClass().getSimpleName() + ") " +
eventTrigger.toString() + ")",
LoggerType.STATUS );
refGeneralManager.getSingelton().logMsg(
this.getClass().getSimpleName()+
": updateReceiver() udateSet: " + updatedSet.toString(),
LoggerType.STATUS );
if ( this.hashExternalId_2_HeatmapIndex == null ) {
init_External2InternalHashMap();
}
IStorage[] storage = updatedSet.getStorageByDim(0);
//TODO: Fix this after CHI
//IVirtualArray[] virtualArray = updatedSet.getVirtualArrayByDim(0);
ArrayList<Integer> resultBuffer = new ArrayList<Integer>(10);
ArrayList<Integer> resultBufferMode = new ArrayList<Integer>(10);
// for (int i = 0; i < storage.length; i++)
// {
//IVirtualArray vaBuffer = virtualArray[i];
int[] intBuffer = storage[0].getArrayInt();
int[] intBufferMode = storage[1].getArrayInt();
//int[] intBufferPathway = storage[2].getArrayInt();
for (int j = 0; j < intBuffer.length; j++)
{
/* lookup id..*/
Iterator <IGraphItem> iterGraphItemRep =
((IGraphItem) refGeneralManager.getSingelton().getPathwayItemManager()
.getItem(intBuffer[j])).getAllItemsByProp(EGraphItemProperty.ALIAS_PARENT).iterator();
while (iterGraphItemRep.hasNext()) {
/* convert external id to internal.. */
Integer indexInt = hashExternalId_2_HeatmapIndex.get(
iterGraphItemRep.next().getId());
if (indexInt != null)
{
System.err.print("GLCanvasHeatmap2DColumn receiveUpdate [" + intBuffer[j] + "=>" + indexInt
+ "], ");
resultBuffer.add(indexInt);
if ( intBufferMode.length != 0 ) {
resultBufferMode.add(intBufferMode[j]);
} else {
resultBufferMode.add( iSelectedMode_identifyier );
}
} else
{
System.err.print("[" + intBuffer[j] + "=> ?? ], ");
}
}
}
// }
if (!resultBuffer.isEmpty())
{
System.err.print("GLCanvasHeatmap2DColumn receiveUpdate [] COPY to Heatmap-Selection.. ");
/* copy selection into local data structure .. */
setSelectedIndex_asArrayList(resultBuffer, resultBufferMode);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.