Merge branch 'android_branch' into send_in_background

Conflicts:
	xwords4/android/XWords4/src/org/eehouse/android/xw4/NetUtils.java
	xwords4/android/XWords4/src/org/eehouse/android/xw4/XWApp.java
This commit is contained in:
Andy2 2011-12-01 21:18:37 -08:00
commit 08063d9444
48 changed files with 640 additions and 386 deletions

View file

@ -4,3 +4,4 @@ local.properties
bin bin
gen gen
libs libs
proguard.cfg

View file

@ -34,7 +34,7 @@
<!-- <uses-permission android:name="android.permission.RECEIVE_SMS" /> --> <!-- <uses-permission android:name="android.permission.RECEIVE_SMS" /> -->
<!-- <uses-permission android:name="android.permission.SEND_SMS" /> --> <!-- <uses-permission android:name="android.permission.SEND_SMS" /> -->
<uses-sdk android:minSdkVersion="3" android:targetSdkVersion="4" /> <uses-sdk android:minSdkVersion="3" android:targetSdkVersion="5" />
<application android:icon="@drawable/icon48x48" <application android:icon="@drawable/icon48x48"
android:label="@string/app_name" android:label="@string/app_name"

View file

@ -10,4 +10,4 @@
# Indicates whether an apk should be generated for each density. # Indicates whether an apk should be generated for each density.
split.density=false split.density=false
# Project target. # Project target.
target=android-4 target=android-5

View file

@ -652,7 +652,7 @@ public class BoardActivity extends XWActivity
break; break;
default: default:
Utils.logf( "menuitem %d not handled", id ); DbgUtils.logf( "menuitem %d not handled", id );
handled = false; handled = false;
} }
@ -978,8 +978,8 @@ public class BoardActivity extends XWActivity
DeviceRole newRole = isServer? DeviceRole.SERVER_ISSERVER DeviceRole newRole = isServer? DeviceRole.SERVER_ISSERVER
: DeviceRole.SERVER_ISCLIENT; : DeviceRole.SERVER_ISCLIENT;
if ( newRole != m_gi.serverRole ) { if ( newRole != m_gi.serverRole ) {
Utils.logf( "new role: %s; old role: %s", DbgUtils.logf( "new role: %s; old role: %s",
newRole.toString(), m_gi.serverRole.toString() ); newRole.toString(), m_gi.serverRole.toString() );
m_gi.serverRole = newRole; m_gi.serverRole = newRole;
if ( !isServer ) { if ( !isServer ) {
m_jniThread.handle( JNIThread.JNICmd.CMD_SWITCHCLIENT ); m_jniThread.handle( JNIThread.JNICmd.CMD_SWITCHCLIENT );
@ -1249,14 +1249,14 @@ public class BoardActivity extends XWActivity
// public void yOffsetChange( int maxOffset, int oldOffset, int newOffset ) // public void yOffsetChange( int maxOffset, int oldOffset, int newOffset )
// { // {
// Utils.logf( "yOffsetChange(maxOffset=%d)", maxOffset ); // DbgUtils.logf( "yOffsetChange(maxOffset=%d)", maxOffset );
// m_view.setVerticalScrollBarEnabled( maxOffset > 0 ); // m_view.setVerticalScrollBarEnabled( maxOffset > 0 );
// } // }
@Override @Override
public boolean warnIllegalWord( String[] words, int turn, public boolean warnIllegalWord( String[] words, int turn,
boolean turnLost ) boolean turnLost )
{ {
Utils.logf( "warnIllegalWord" ); DbgUtils.logf( "warnIllegalWord" );
boolean accept = turnLost; boolean accept = turnLost;
StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();
@ -1280,7 +1280,7 @@ public class BoardActivity extends XWActivity
accept = 0 != waitBlockingDialog( QUERY_REQUEST_BLK, 0 ); accept = 0 != waitBlockingDialog( QUERY_REQUEST_BLK, 0 );
} }
Utils.logf( "warnIllegalWord=>%b", accept ); DbgUtils.logf( "warnIllegalWord=>%b", accept );
return accept; return accept;
} }
@ -1464,7 +1464,7 @@ public class BoardActivity extends XWActivity
{ {
int result = cancelResult; int result = cancelResult;
if ( m_blockingDlgPosted ) { // this has been true; dunno why if ( m_blockingDlgPosted ) { // this has been true; dunno why
Utils.logf( "waitBlockingDialog: dropping dlgID %d", dlgID ); DbgUtils.logf( "waitBlockingDialog: dropping dlgID %d", dlgID );
} else { } else {
setBlockingThread(); setBlockingThread();
m_resultCode = cancelResult; m_resultCode = cancelResult;
@ -1480,7 +1480,7 @@ public class BoardActivity extends XWActivity
m_forResultWait.acquire(); m_forResultWait.acquire();
m_blockingDlgPosted = false; m_blockingDlgPosted = false;
} catch ( java.lang.InterruptedException ie ) { } catch ( java.lang.InterruptedException ie ) {
Utils.logf( "waitBlockingDialog: got %s", ie.toString() ); DbgUtils.logf( "waitBlockingDialog: got %s", ie.toString() );
if ( m_blockingDlgPosted ) { if ( m_blockingDlgPosted ) {
dismissDialog( dlgID ); dismissDialog( dlgID );
m_blockingDlgPosted = false; m_blockingDlgPosted = false;
@ -1601,7 +1601,7 @@ public class BoardActivity extends XWActivity
if ( null == m_screenTimer ) { if ( null == m_screenTimer ) {
m_screenTimer = new Runnable() { m_screenTimer = new Runnable() {
public void run() { public void run() {
Utils.logf( "run() called for setKeepScreenOn()" ); DbgUtils.logf( "run() called for setKeepScreenOn()" );
if ( null != m_view ) { if ( null != m_view ) {
m_view.setKeepScreenOn( false ); m_view.setKeepScreenOn( false );
} }
@ -1619,7 +1619,7 @@ public class BoardActivity extends XWActivity
if ( canPost ) { if ( canPost ) {
m_handler.post( runnable ); m_handler.post( runnable );
} else { } else {
Utils.logf( "post: dropping because handler null" ); DbgUtils.logf( "post: dropping because handler null" );
} }
return canPost; return canPost;
} }
@ -1629,7 +1629,7 @@ public class BoardActivity extends XWActivity
if ( null != m_handler ) { if ( null != m_handler ) {
m_handler.postDelayed( runnable, when ); m_handler.postDelayed( runnable, when );
} else { } else {
Utils.logf( "postDelayed: dropping %d because handler null", when ); DbgUtils.logf( "postDelayed: dropping %d because handler null", when );
} }
} }
@ -1638,8 +1638,8 @@ public class BoardActivity extends XWActivity
if ( null != m_handler ) { if ( null != m_handler ) {
m_handler.removeCallbacks( which ); m_handler.removeCallbacks( which );
} else { } else {
Utils.logf( "removeCallbacks: dropping %h because handler null", DbgUtils.logf( "removeCallbacks: dropping %h because handler null",
which ); which );
} }
} }

View file

@ -34,17 +34,29 @@ import android.view.MotionEvent;
import android.graphics.drawable.Drawable; import android.graphics.drawable.Drawable;
import android.content.res.Resources; import android.content.res.Resources;
import android.graphics.Paint.FontMetricsInt; import android.graphics.Paint.FontMetricsInt;
import android.os.Build;
import android.os.Handler; import android.os.Handler;
import java.nio.IntBuffer; import java.nio.IntBuffer;
import android.util.FloatMath;
import junit.framework.Assert; import junit.framework.Assert;
public class BoardView extends View implements DrawCtx, BoardHandler, public class BoardView extends View implements DrawCtx, BoardHandler,
SyncedDraw { SyncedDraw {
public interface MultiHandlerIface {
boolean inactive();
void activate( MotionEvent event );
void deactivate();
int figureZoom( MotionEvent event );
int getSpacing( MotionEvent event );
}
private static final float MIN_FONT_DIPS = 14.0f; private static final float MIN_FONT_DIPS = 14.0f;
private static Bitmap s_bitmap; // the board private static Bitmap s_bitmap; // the board
private static final int IN_TRADE_ALPHA = 0x3FFFFFFF; private static final int IN_TRADE_ALPHA = 0x3FFFFFFF;
private static final int PINCH_THRESHOLD = 40;
private Context m_context; private Context m_context;
private Paint m_drawPaint; private Paint m_drawPaint;
@ -83,6 +95,8 @@ public class BoardView extends View implements DrawCtx, BoardHandler,
private int m_pendingScore; private int m_pendingScore;
private Handler m_viewHandler; private Handler m_viewHandler;
private MultiHandlerIface m_multiHandler = null;
// FontDims: exists to translate space available to the largest // FontDims: exists to translate space available to the largest
// font we can draw within that space taking advantage of our use // font we can draw within that space taking advantage of our use
// being limited to a known small subset of glyphs. We need two // being limited to a known small subset of glyphs. We need two
@ -93,20 +107,20 @@ public class BoardView extends View implements DrawCtx, BoardHandler,
// future wantHt by. Ditto for the descent // future wantHt by. Ditto for the descent
private class FontDims { private class FontDims {
FontDims( float askedHt, int topRow, int bottomRow, float width ) { FontDims( float askedHt, int topRow, int bottomRow, float width ) {
// Utils.logf( "FontDims(): askedHt=" + askedHt ); // DbgUtils.logf( "FontDims(): askedHt=" + askedHt );
// Utils.logf( "FontDims(): topRow=" + topRow ); // DbgUtils.logf( "FontDims(): topRow=" + topRow );
// Utils.logf( "FontDims(): bottomRow=" + bottomRow ); // DbgUtils.logf( "FontDims(): bottomRow=" + bottomRow );
// Utils.logf( "FontDims(): width=" + width ); // DbgUtils.logf( "FontDims(): width=" + width );
float gotHt = bottomRow - topRow + 1; float gotHt = bottomRow - topRow + 1;
m_htProportion = gotHt / askedHt; m_htProportion = gotHt / askedHt;
Assert.assertTrue( (bottomRow+1) >= askedHt ); Assert.assertTrue( (bottomRow+1) >= askedHt );
float descent = (bottomRow+1) - askedHt; float descent = (bottomRow+1) - askedHt;
// Utils.logf( "descent: " + descent ); // DbgUtils.logf( "descent: " + descent );
m_descentProportion = descent / askedHt; m_descentProportion = descent / askedHt;
Assert.assertTrue( m_descentProportion >= 0 ); Assert.assertTrue( m_descentProportion >= 0 );
m_widthProportion = width / askedHt; m_widthProportion = width / askedHt;
// Utils.logf( "m_htProportion: " + m_htProportion ); // DbgUtils.logf( "m_htProportion: " + m_htProportion );
// Utils.logf( "m_descentProportion: " + m_descentProportion ); // DbgUtils.logf( "m_descentProportion: " + m_descentProportion );
} }
private float m_htProportion; private float m_htProportion;
private float m_descentProportion; private float m_descentProportion;
@ -168,6 +182,15 @@ public class BoardView extends View implements DrawCtx, BoardHandler,
} }
m_viewHandler = new Handler(); m_viewHandler = new Handler();
try {
int sdk_int = Integer.decode( Build.VERSION.SDK );
if ( sdk_int >= Build.VERSION_CODES.ECLAIR ) {
m_multiHandler = new MultiHandler();
} else {
DbgUtils.logf( "OS version %d too old for multi-touch", sdk_int );
}
} catch ( Exception ex ) {}
} }
@Override @Override
@ -179,17 +202,41 @@ public class BoardView extends View implements DrawCtx, BoardHandler,
switch ( action ) { switch ( action ) {
case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_DOWN:
if ( null != m_multiHandler ) {
m_multiHandler.deactivate();
}
m_jniThread.handle( JNIThread.JNICmd.CMD_PEN_DOWN, xx, yy ); m_jniThread.handle( JNIThread.JNICmd.CMD_PEN_DOWN, xx, yy );
break; break;
case MotionEvent.ACTION_MOVE: case MotionEvent.ACTION_MOVE:
m_jniThread.handle( JNIThread.JNICmd.CMD_PEN_MOVE, xx, yy ); if ( null == m_multiHandler || m_multiHandler.inactive() ) {
m_jniThread.handle( JNIThread.JNICmd.CMD_PEN_MOVE, xx, yy );
} else {
int zoomBy = m_multiHandler.figureZoom( event );
if ( 0 != zoomBy ) {
m_jniThread.handle( JNIThread.JNICmd.CMD_ZOOM,
zoomBy < 0 ? -2 : 2 );
}
}
break; break;
case MotionEvent.ACTION_UP: case MotionEvent.ACTION_UP:
m_jniThread.handle( JNIThread.JNICmd.CMD_PEN_UP, xx, yy ); m_jniThread.handle( JNIThread.JNICmd.CMD_PEN_UP, xx, yy );
break; break;
case MotionEvent.ACTION_POINTER_DOWN:
case MotionEvent.ACTION_POINTER_2_DOWN:
if ( null != m_multiHandler ) {
m_jniThread.handle( JNIThread.JNICmd.CMD_PEN_UP, xx, yy );
m_multiHandler.activate( event );
}
break;
case MotionEvent.ACTION_POINTER_UP:
case MotionEvent.ACTION_POINTER_2_UP:
if ( null != m_multiHandler ) {
m_multiHandler.deactivate();
}
break;
default: default:
Utils.logf( "unknown action: %d", action ); DbgUtils.logf( "unknown action: %d", action );
Utils.logf( event.toString() ); break;
} }
return true; // required to get subsequent events return true; // required to get subsequent events
@ -215,7 +262,7 @@ public class BoardView extends View implements DrawCtx, BoardHandler,
int nCells = gi.boardSize; int nCells = gi.boardSize;
int cellSize = width / nCells; int cellSize = width / nCells;
int maxCellSize = 3 * m_defaultFontHt; int maxCellSize = 4 * m_defaultFontHt;
if ( cellSize > maxCellSize ) { if ( cellSize > maxCellSize ) {
cellSize = maxCellSize; cellSize = maxCellSize;
@ -313,7 +360,7 @@ public class BoardView extends View implements DrawCtx, BoardHandler,
drew = XwJNI.board_draw( m_jniGamePtr ); drew = XwJNI.board_draw( m_jniGamePtr );
} }
if ( !drew ) { if ( !drew ) {
Utils.logf( "draw not complete" ); DbgUtils.logf( "draw not complete" );
} }
} }
@ -720,7 +767,7 @@ public class BoardView extends View implements DrawCtx, BoardHandler,
int height = rect.height() - 4; // borders and padding, 2 each int height = rect.height() - 4; // borders and padding, 2 each
descent = fontDims.descentFor( height ); descent = fontDims.descentFor( height );
textSize = fontDims.heightFor( height ); textSize = fontDims.heightFor( height );
// Utils.logf( "using descent: " + descent + " and textSize: " // DbgUtils.logf( "using descent: " + descent + " and textSize: "
// + textSize + " in height " + height ); // + textSize + " in height " + height );
} }
m_fillPaint.setTextSize( textSize ); m_fillPaint.setTextSize( textSize );
@ -829,13 +876,13 @@ public class BoardView extends View implements DrawCtx, BoardHandler,
Canvas canvas = new Canvas( bitmap ); Canvas canvas = new Canvas( bitmap );
// FontMetrics fmi = paint.getFontMetrics(); // FontMetrics fmi = paint.getFontMetrics();
// Utils.logf( "ascent: " + fmi.ascent ); // DbgUtils.logf( "ascent: " + fmi.ascent );
// Utils.logf( "bottom: " + fmi.bottom ); // DbgUtils.logf( "bottom: " + fmi.bottom );
// Utils.logf( "descent: " + fmi.descent ); // DbgUtils.logf( "descent: " + fmi.descent );
// Utils.logf( "leading: " + fmi.leading ); // DbgUtils.logf( "leading: " + fmi.leading );
// Utils.logf( "top : " + fmi.top ); // DbgUtils.logf( "top : " + fmi.top );
// Utils.logf( "using as baseline: " + ht ); // DbgUtils.logf( "using as baseline: " + ht );
Rect bounds = new Rect(); Rect bounds = new Rect();
int maxWidth = 0; int maxWidth = 0;
@ -855,7 +902,7 @@ public class BoardView extends View implements DrawCtx, BoardHandler,
// int pixel = bitmap.getPixel( col, row ); // int pixel = bitmap.getPixel( col, row );
// sb.append( pixel==0? "." : "X" ); // sb.append( pixel==0? "." : "X" );
// } // }
// Utils.logf( sb.append(row).toString() ); // DbgUtils.logf( sb.append(row).toString() );
// } // }
int topRow = 0; int topRow = 0;
@ -949,4 +996,52 @@ public class BoardView extends View implements DrawCtx, BoardHandler,
} }
return color; return color;
} }
private class MultiHandler implements MultiHandlerIface {
private static final int INACTIVE = -1;
private int m_lastSpacing = INACTIVE;
public boolean inactive()
{
return INACTIVE == m_lastSpacing;
}
public void activate( MotionEvent event )
{
m_lastSpacing = getSpacing( event );
}
public void deactivate()
{
m_lastSpacing = INACTIVE;
}
public int getSpacing( MotionEvent event )
{
int result;
if ( 1 == event.getPointerCount() ) {
result = INACTIVE;
} else {
float xx = event.getX( 0 ) - event.getX( 1 );
float yy = event.getY( 0 ) - event.getY( 1 );
result = (int)FloatMath.sqrt( (xx * xx) + (yy * yy) );
}
return result;
}
public int figureZoom( MotionEvent event )
{
int zoomDir = 0;
if ( ! inactive() ) {
int newSpacing = getSpacing( event );
int diff = Math.abs( newSpacing - m_lastSpacing );
if ( diff > PINCH_THRESHOLD ) {
zoomDir = newSpacing < m_lastSpacing? -1 : 1;
m_lastSpacing = newSpacing;
}
}
return zoomDir;
}
}
} }

View file

@ -91,11 +91,11 @@ public class CommsTransport implements TransportProcs,
closeSocket(); closeSocket();
} catch ( java.io.IOException ioe ) { } catch ( java.io.IOException ioe ) {
Utils.logf( ioe.toString() ); DbgUtils.logf( ioe.toString() );
} catch ( UnresolvedAddressException uae ) { } catch ( UnresolvedAddressException uae ) {
Utils.logf( "bad address: name: %s; port: %s; exception: %s", DbgUtils.logf( "bad address: name: %s; port: %s; exception: %s",
m_addr.ip_relay_hostName, m_addr.ip_relay_port, m_addr.ip_relay_hostName, m_addr.ip_relay_port,
uae.toString() ); uae.toString() );
} }
m_thread = null; m_thread = null;
@ -118,15 +118,15 @@ public class CommsTransport implements TransportProcs,
try { try {
m_socketChannel = SocketChannel.open(); m_socketChannel = SocketChannel.open();
m_socketChannel.configureBlocking( false ); m_socketChannel.configureBlocking( false );
Utils.logf( "connecting to %s:%d", DbgUtils.logf( "connecting to %s:%d",
m_addr.ip_relay_hostName, m_addr.ip_relay_hostName,
m_addr.ip_relay_port ); m_addr.ip_relay_port );
InetSocketAddress isa = new InetSocketAddress isa = new
InetSocketAddress(m_addr.ip_relay_hostName, InetSocketAddress(m_addr.ip_relay_hostName,
m_addr.ip_relay_port ); m_addr.ip_relay_port );
m_socketChannel.connect( isa ); m_socketChannel.connect( isa );
} catch ( java.io.IOException ioe ) { } catch ( java.io.IOException ioe ) {
Utils.logf( ioe.toString() ); DbgUtils.logf( ioe.toString() );
failed = true; failed = true;
break outer_loop; break outer_loop;
} }
@ -134,7 +134,7 @@ public class CommsTransport implements TransportProcs,
if ( null != m_socketChannel ) { if ( null != m_socketChannel ) {
int ops = figureOps(); int ops = figureOps();
// Utils.logf( "calling with ops=%x", ops ); // DbgUtils.logf( "calling with ops=%x", ops );
m_socketChannel.register( m_selector, ops ); m_socketChannel.register( m_selector, ops );
} }
} }
@ -143,14 +143,14 @@ public class CommsTransport implements TransportProcs,
// we get this when relay goes down. Need to notify! // we get this when relay goes down. Need to notify!
failed = true; failed = true;
closeSocket(); closeSocket();
Utils.logf( "exiting: %s", cce.toString() ); DbgUtils.logf( "exiting: %s", cce.toString() );
break; // don't try again break; // don't try again
} catch ( java.io.IOException ioe ) { } catch ( java.io.IOException ioe ) {
closeSocket(); closeSocket();
Utils.logf( "exiting: %s", ioe.toString() ); DbgUtils.logf( "exiting: %s", ioe.toString() );
Utils.logf( ioe.toString() ); DbgUtils.logf( ioe.toString() );
} catch ( java.nio.channels.NoConnectionPendingException ncp ) { } catch ( java.nio.channels.NoConnectionPendingException ncp ) {
Utils.logf( "%s", ncp.toString() ); DbgUtils.logf( "%s", ncp.toString() );
closeSocket(); closeSocket();
break; break;
} }
@ -168,7 +168,7 @@ public class CommsTransport implements TransportProcs,
} }
if (key.isValid() && key.isReadable()) { if (key.isValid() && key.isReadable()) {
m_bytesIn.clear(); // will wipe any pending data! m_bytesIn.clear(); // will wipe any pending data!
// Utils.logf( "socket is readable; buffer has space for " // DbgUtils.logf( "socket is readable; buffer has space for "
// + m_bytesIn.remaining() ); // + m_bytesIn.remaining() );
int nRead = channel.read( m_bytesIn ); int nRead = channel.read( m_bytesIn );
if ( nRead == -1 ) { if ( nRead == -1 ) {
@ -181,17 +181,17 @@ public class CommsTransport implements TransportProcs,
getOut(); getOut();
if ( null != m_bytesOut ) { if ( null != m_bytesOut ) {
int nWritten = channel.write( m_bytesOut ); int nWritten = channel.write( m_bytesOut );
//Utils.logf( "wrote " + nWritten + " bytes" ); //DbgUtils.logf( "wrote " + nWritten + " bytes" );
} }
} }
} catch ( java.io.IOException ioe ) { } catch ( java.io.IOException ioe ) {
Utils.logf( "%s: cancelling key", ioe.toString() ); DbgUtils.logf( "%s: cancelling key", ioe.toString() );
key.cancel(); key.cancel();
failed = true; failed = true;
break outer_loop; break outer_loop;
} catch ( java.nio.channels. } catch ( java.nio.channels.
NoConnectionPendingException ncp ) { NoConnectionPendingException ncp ) {
Utils.logf( "%s", ncp.toString() ); DbgUtils.logf( "%s", ncp.toString() );
break outer_loop; break outer_loop;
} }
} }
@ -241,7 +241,7 @@ public class CommsTransport implements TransportProcs,
try { try {
m_socketChannel.close(); m_socketChannel.close();
} catch ( Exception e ) { } catch ( Exception e ) {
Utils.logf( "closing socket: %s", e.toString() ); DbgUtils.logf( "closing socket: %s", e.toString() );
} }
m_socketChannel = null; m_socketChannel = null;
} }
@ -319,7 +319,7 @@ public class CommsTransport implements TransportProcs,
try { try {
m_thread.join(100); // wait up to 1/10 second m_thread.join(100); // wait up to 1/10 second
} catch ( java.lang.InterruptedException ie ) { } catch ( java.lang.InterruptedException ie ) {
Utils.logf( "got InterruptedException: %s", ie.toString() ); DbgUtils.logf( "got InterruptedException: %s", ie.toString() );
} }
m_thread = null; m_thread = null;
} }
@ -331,7 +331,7 @@ public class CommsTransport implements TransportProcs,
public int transportSend( byte[] buf, final CommsAddrRec faddr ) public int transportSend( byte[] buf, final CommsAddrRec faddr )
{ {
//Utils.logf( "CommsTransport::transportSend(nbytes=%d)", buf.length ); //DbgUtils.logf( "CommsTransport::transportSend(nbytes=%d)", buf.length );
int nSent = -1; int nSent = -1;
if ( null == m_addr ) { if ( null == m_addr ) {
@ -362,7 +362,7 @@ public class CommsTransport implements TransportProcs,
// to verify. IFF the plan's to ship a version that // to verify. IFF the plan's to ship a version that
// doesn't do SMS. // doesn't do SMS.
// Utils.logf( "sending via sms to %s:%d", // DbgUtils.logf( "sending via sms to %s:%d",
// m_addr.sms_phone, m_addr.sms_port ); // m_addr.sms_phone, m_addr.sms_port );
// try { // try {
// Intent intent = new Intent( m_context, StatusReceiver.class); // Intent intent = new Intent( m_context, StatusReceiver.class);
@ -373,17 +373,17 @@ public class CommsTransport implements TransportProcs,
// SmsManager.getDefault().sendTextMessage( m_addr.sms_phone, // SmsManager.getDefault().sendTextMessage( m_addr.sms_phone,
// null, "Hello world", // null, "Hello world",
// pi, pi ); // pi, pi );
// Utils.logf( "called sendTextMessage" ); // DbgUtils.logf( "called sendTextMessage" );
// } else { // } else {
// SmsManager.getDefault(). // SmsManager.getDefault().
// sendDataMessage( m_addr.sms_phone, (String)null, // sendDataMessage( m_addr.sms_phone, (String)null,
// (short)m_addr.sms_port, // (short)m_addr.sms_port,
// buf, pi, pi ); // buf, pi, pi );
// Utils.logf( "called sendDataMessage" ); // DbgUtils.logf( "called sendDataMessage" );
// } // }
// nSent = buf.length; // nSent = buf.length;
// } catch ( java.lang.IllegalArgumentException iae ) { // } catch ( java.lang.IllegalArgumentException iae ) {
// Utils.logf( iae.toString() ); // DbgUtils.logf( iae.toString() );
// } // }
break; break;
case COMMS_CONN_BT: case COMMS_CONN_BT:
@ -395,17 +395,17 @@ public class CommsTransport implements TransportProcs,
// Keep this while debugging why the resend_all that gets // Keep this while debugging why the resend_all that gets
// fired on reconnect doesn't unstall a game but a manual // fired on reconnect doesn't unstall a game but a manual
// resend does. // resend does.
Utils.logf( "transportSend(%d)=>%d", buf.length, nSent ); DbgUtils.logf( "transportSend(%d)=>%d", buf.length, nSent );
return nSent; return nSent;
} }
public void relayStatus( CommsRelayState newState ) public void relayStatus( CommsRelayState newState )
{ {
//Utils.logf( "relayStatus called; state=%s", newState.toString() ); //DbgUtils.logf( "relayStatus called; state=%s", newState.toString() );
if ( null != m_jniThread ) { if ( null != m_jniThread ) {
m_jniThread.handle( JNICmd.CMD_DRAW_CONNS_STATUS, newState ); m_jniThread.handle( JNICmd.CMD_DRAW_CONNS_STATUS, newState );
} else { } else {
Utils.logf( "can't draw status yet" ); DbgUtils.logf( "can't draw status yet" );
} }
} }

View file

@ -123,7 +123,7 @@ public class DBHelper extends SQLiteOpenHelper {
@Override @Override
public void onUpgrade( SQLiteDatabase db, int oldVersion, int newVersion ) public void onUpgrade( SQLiteDatabase db, int oldVersion, int newVersion )
{ {
Utils.logf( "onUpgrade: old: %d; new: %d", oldVersion, newVersion ); DbgUtils.logf( "onUpgrade: old: %d; new: %d", oldVersion, newVersion );
switch( oldVersion ) { switch( oldVersion ) {
case 5: case 5:

View file

@ -456,7 +456,7 @@ public class DBUtils {
long result = db.replaceOrThrow( DBHelper.TABLE_NAME_OBITS, long result = db.replaceOrThrow( DBHelper.TABLE_NAME_OBITS,
"", values ); "", values );
} catch ( Exception ex ) { } catch ( Exception ex ) {
Utils.logf( "ex: %s", ex.toString() ); DbgUtils.logf( "ex: %s", ex.toString() );
} }
db.close(); db.close();
} }
@ -566,7 +566,7 @@ public class DBUtils {
Assert.fail(); Assert.fail();
// values.put( DBHelper.FILE_NAME, path ); // values.put( DBHelper.FILE_NAME, path );
// rowid = db.insert( DBHelper.TABLE_NAME_SUM, null, values ); // rowid = db.insert( DBHelper.TABLE_NAME_SUM, null, values );
// Utils.logf( "insert=>%d", rowid ); // DbgUtils.logf( "insert=>%d", rowid );
// Assert.assertTrue( row >= 0 ); // Assert.assertTrue( row >= 0 );
} }
db.close(); db.close();
@ -688,7 +688,7 @@ public class DBUtils {
values, selection, null ); values, selection, null );
db.close(); db.close();
if ( 0 == result ) { if ( 0 == result ) {
Utils.logf( "setName(%d,%s) failed", rowid, name ); DbgUtils.logf( "setName(%d,%s) failed", rowid, name );
} }
} }
} }

View file

@ -0,0 +1,100 @@
/* -*- compile-command: "cd ../../../../../; ant debug install"; -*- */
/*
* Copyright 2009-2011 by Eric House (xwords@eehouse.org). All
* rights reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package org.eehouse.android.xw4;
import java.lang.Thread;
import java.util.Formatter;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.text.format.Time;
import android.util.Log;
import android.widget.Toast;
public class DbgUtils {
static final String TAG = "XW4";
static boolean s_doLog = true;
private static Time s_time = new Time();
public static void logEnable( boolean enable )
{
s_doLog = enable;
}
public static void logEnable( Context context )
{
SharedPreferences sp
= PreferenceManager.getDefaultSharedPreferences( context );
String key = context.getString( R.string.key_logging_on );
boolean on = sp.getBoolean( key, false );
logEnable( on );
}
public static void logf( String msg )
{
if ( s_doLog ) {
s_time.setToNow();
String time = s_time.format("[%H:%M:%S]");
long id = Thread.currentThread().getId();
Log.d( TAG, time + "-" + id + "-" + msg );
}
} // logf
public static void logf( String format, Object... args )
{
if ( s_doLog ) {
Formatter formatter = new Formatter();
logf( formatter.format( format, args ).toString() );
}
} // logf
public static void showf( Context context, String format, Object... args )
{
Formatter formatter = new Formatter();
String msg = formatter.format( format, args ).toString();
Toast.makeText( context, msg, Toast.LENGTH_SHORT ).show();
} // showf
public static void showf( Context context, int formatid, Object... args )
{
showf( context, context.getString( formatid ), args );
} // showf
public static void printStack( StackTraceElement[] trace )
{
if ( s_doLog ) {
for ( int ii = 0; ii < trace.length; ++ii ) {
DbgUtils.logf( "ste %d: %s", ii, trace[ii].toString() );
}
}
}
public static void printStack()
{
if ( s_doLog ) {
printStack( Thread.currentThread().getStackTrace() );
}
}
private DbgUtils() {}
}

View file

@ -214,7 +214,7 @@ public class DictBrowseActivity extends XWListActivity
try { try {
super.finalize(); super.finalize();
} catch ( java.lang.Throwable err ){ } catch ( java.lang.Throwable err ){
Utils.logf( "%s", err.toString() ); DbgUtils.logf( "%s", err.toString() );
} }
} }
@ -268,8 +268,8 @@ public class DictBrowseActivity extends XWListActivity
if ( 0 <= pos ) { if ( 0 <= pos ) {
getListView().setSelection( pos ); getListView().setSelection( pos );
} else { } else {
Utils.showf( this, R.string.dict_browse_nowordsf, DbgUtils.showf( this, R.string.dict_browse_nowordsf,
m_name, text ); m_name, text );
} }
} }
} }

View file

@ -56,7 +56,7 @@ public class DictImportActivity extends XWActivity {
long totalSize = 0; long totalSize = 0;
for ( int ii = 0; ii < count; ii++ ) { for ( int ii = 0; ii < count; ii++ ) {
Uri uri = uris[ii]; Uri uri = uris[ii];
Utils.logf( "trying %s", uri ); DbgUtils.logf( "trying %s", uri );
try { try {
URI jUri = new URI( uri.getScheme(), URI jUri = new URI( uri.getScheme(),
@ -66,11 +66,11 @@ public class DictImportActivity extends XWActivity {
m_saved = saveDict( is, uri.getPath() ); m_saved = saveDict( is, uri.getPath() );
is.close(); is.close();
} catch ( java.net.URISyntaxException use ) { } catch ( java.net.URISyntaxException use ) {
Utils.logf( "URISyntaxException: %s", use.toString() ); DbgUtils.logf( "URISyntaxException: %s", use.toString() );
} catch ( java.net.MalformedURLException mue ) { } catch ( java.net.MalformedURLException mue ) {
Utils.logf( "MalformedURLException: %s", mue.toString() ); DbgUtils.logf( "MalformedURLException: %s", mue.toString() );
} catch ( java.io.IOException ioe ) { } catch ( java.io.IOException ioe ) {
Utils.logf( "IOException: %s", ioe.toString() ); DbgUtils.logf( "IOException: %s", ioe.toString() );
} }
} }
return totalSize; return totalSize;
@ -79,7 +79,7 @@ public class DictImportActivity extends XWActivity {
@Override @Override
protected void onPostExecute( Long result ) protected void onPostExecute( Long result )
{ {
Utils.logf( "onPostExecute passed %d", result ); DbgUtils.logf( "onPostExecute passed %d", result );
if ( null != m_saved ) { if ( null != m_saved ) {
DictLangCache.inval( DictImportActivity.this, m_saved, DictLangCache.inval( DictImportActivity.this, m_saved,
s_saveWhere, true ); s_saveWhere, true );
@ -105,7 +105,7 @@ public class DictImportActivity extends XWActivity {
if ( null != uri) { if ( null != uri) {
if ( null != intent.getType() if ( null != intent.getType()
&& intent.getType().equals( "application/x-xwordsdict" ) ) { && intent.getType().equals( "application/x-xwordsdict" ) ) {
Utils.logf( "based on MIME type" ); DbgUtils.logf( "based on MIME type" );
new DownloadFilesTask().execute( uri ); new DownloadFilesTask().execute( uri );
} else if ( uri.toString().endsWith( XWConstants.DICT_EXTN ) ) { } else if ( uri.toString().endsWith( XWConstants.DICT_EXTN ) ) {
String fmt = getString( R.string.downloading_dictf ); String fmt = getString( R.string.downloading_dictf );
@ -114,7 +114,7 @@ public class DictImportActivity extends XWActivity {
view.setText( txt ); view.setText( txt );
new DownloadFilesTask().execute( uri ); new DownloadFilesTask().execute( uri );
} else { } else {
Utils.logf( "bogus intent: %s/%s", intent.getType(), uri ); DbgUtils.logf( "bogus intent: %s/%s", intent.getType(), uri );
finish(); finish();
} }
} }

View file

@ -389,7 +389,7 @@ public class DictLangCache {
s_nameToLang.put( dal, info ); s_nameToLang.put( dal, info );
} else { } else {
info = null; info = null;
Utils.logf( "getInfo(): unable to open dict %s", dal.name ); DbgUtils.logf( "getInfo(): unable to open dict %s", dal.name );
} }
} }
return info; return info;

View file

@ -242,9 +242,9 @@ public class DictUtils {
success = true; success = true;
} catch ( java.io.FileNotFoundException fnfe ) { } catch ( java.io.FileNotFoundException fnfe ) {
Utils.logf( "%s", fnfe.toString() ); DbgUtils.logf( "%s", fnfe.toString() );
} catch ( java.io.IOException ioe ) { } catch ( java.io.IOException ioe ) {
Utils.logf( "%s", ioe.toString() ); DbgUtils.logf( "%s", ioe.toString() );
} finally { } finally {
try { try {
// Order should match assignment order to above in // Order should match assignment order to above in
@ -252,7 +252,7 @@ public class DictUtils {
channelIn.close(); channelIn.close();
channelOut.close(); channelOut.close();
} catch ( Exception e ) { } catch ( Exception e ) {
Utils.logf( "%s", e.toString() ); DbgUtils.logf( "%s", e.toString() );
} }
} }
return success; return success;
@ -305,13 +305,13 @@ public class DictUtils {
bytes = new byte[len]; bytes = new byte[len];
int nRead = dict.read( bytes, 0, len ); int nRead = dict.read( bytes, 0, len );
if ( nRead != len ) { if ( nRead != len ) {
Utils.logf( "**** warning ****; read only %d of %d bytes.", DbgUtils.logf( "**** warning ****; read only %d of %d bytes.",
nRead, len ); nRead, len );
} }
// check that with len bytes we've read the whole file // check that with len bytes we've read the whole file
Assert.assertTrue( -1 == dict.read() ); Assert.assertTrue( -1 == dict.read() );
} catch ( java.io.IOException ee ){ } catch ( java.io.IOException ee ){
Utils.logf( "%s failed to open; likely not built-in", name ); DbgUtils.logf( "%s failed to open; likely not built-in", name );
} }
} }
@ -323,7 +323,7 @@ public class DictUtils {
if ( loc == DictLoc.UNKNOWN || loc == DictLoc.DOWNLOAD ) { if ( loc == DictLoc.UNKNOWN || loc == DictLoc.DOWNLOAD ) {
File path = getDownloadsPathFor( name ); File path = getDownloadsPathFor( name );
if ( null != path && path.exists() ) { if ( null != path && path.exists() ) {
Utils.logf( "loading %s from Download", name ); DbgUtils.logf( "loading %s from Download", name );
fis = new FileInputStream( path ); fis = new FileInputStream( path );
} }
} }
@ -331,13 +331,13 @@ public class DictUtils {
if ( loc == DictLoc.UNKNOWN || loc == DictLoc.EXTERNAL ) { if ( loc == DictLoc.UNKNOWN || loc == DictLoc.EXTERNAL ) {
File sdFile = getSDPathFor( context, name ); File sdFile = getSDPathFor( context, name );
if ( null != sdFile && sdFile.exists() ) { if ( null != sdFile && sdFile.exists() ) {
Utils.logf( "loading %s from SD", name ); DbgUtils.logf( "loading %s from SD", name );
fis = new FileInputStream( sdFile ); fis = new FileInputStream( sdFile );
} }
} }
if ( null == fis ) { if ( null == fis ) {
if ( loc == DictLoc.UNKNOWN || loc == DictLoc.INTERNAL ) { if ( loc == DictLoc.UNKNOWN || loc == DictLoc.INTERNAL ) {
Utils.logf( "loading %s from private storage", name ); DbgUtils.logf( "loading %s from private storage", name );
fis = context.openFileInput( name ); fis = context.openFileInput( name );
} }
} }
@ -345,11 +345,11 @@ public class DictUtils {
bytes = new byte[len]; bytes = new byte[len];
fis.read( bytes, 0, len ); fis.read( bytes, 0, len );
fis.close(); fis.close();
Utils.logf( "Successfully loaded %s", name ); DbgUtils.logf( "Successfully loaded %s", name );
} catch ( java.io.FileNotFoundException fnf ) { } catch ( java.io.FileNotFoundException fnf ) {
Utils.logf( fnf.toString() ); DbgUtils.logf( fnf.toString() );
} catch ( java.io.IOException ioe ) { } catch ( java.io.IOException ioe ) {
Utils.logf( ioe.toString() ); DbgUtils.logf( ioe.toString() );
} }
} }
@ -449,10 +449,10 @@ public class DictUtils {
invalDictList(); invalDictList();
success = true; success = true;
} catch ( java.io.FileNotFoundException fnf ) { } catch ( java.io.FileNotFoundException fnf ) {
Utils.logf( "saveDict: FileNotFoundException: %s", DbgUtils.logf( "saveDict: FileNotFoundException: %s",
fnf.toString() ); fnf.toString() );
} catch ( java.io.IOException ioe ) { } catch ( java.io.IOException ioe ) {
Utils.logf( "saveDict: IOException: %s", ioe.toString() ); DbgUtils.logf( "saveDict: IOException: %s", ioe.toString() );
deleteDict( context, name ); deleteDict( context, name );
} }
} }
@ -498,7 +498,7 @@ public class DictUtils {
AssetManager am = context.getAssets(); AssetManager am = context.getAssets();
return am.list(""); return am.list("");
} catch( java.io.IOException ioe ) { } catch( java.io.IOException ioe ) {
Utils.logf( ioe.toString() ); DbgUtils.logf( ioe.toString() );
return new String[0]; return new String[0];
} }
} }
@ -523,7 +523,7 @@ public class DictUtils {
if ( !result.exists() ) { if ( !result.exists() ) {
result.mkdirs(); result.mkdirs();
if ( !result.exists() ) { if ( !result.exists() ) {
Utils.logf( "unable to create sd dir %s", packdir ); DbgUtils.logf( "unable to create sd dir %s", packdir );
result = null; result = null;
} }
} }

View file

@ -306,8 +306,8 @@ public class DictsActivity extends ExpandableListActivity
rowView.cache( toLoc ); rowView.cache( toLoc );
rowView.invalidate(); rowView.invalidate();
} else { } else {
Utils.logf( "moveDict(%s) failed", DbgUtils.logf( "moveDict(%s) failed",
rowView.getText() ); rowView.getText() );
} }
} }
}; };
@ -480,7 +480,7 @@ public class DictsActivity extends ExpandableListActivity
getPackedPositionChild( packedPosition ); getPackedPositionChild( packedPosition );
// int groupPosition = ExpandableListView. // int groupPosition = ExpandableListView.
// getPackedPositionGroup( packedPosition ); // getPackedPositionGroup( packedPosition );
// Utils.logf( "onCreateContextMenu: group: %d; child: %d", // DbgUtils.logf( "onCreateContextMenu: group: %d; child: %d",
// groupPosition, childPosition ); // groupPosition, childPosition );
// We don't have a menu yet for languages, just for their dict // We don't have a menu yet for languages, just for their dict
@ -509,7 +509,7 @@ public class DictsActivity extends ExpandableListActivity
try { try {
info = (ExpandableListContextMenuInfo)item.getMenuInfo(); info = (ExpandableListContextMenuInfo)item.getMenuInfo();
} catch (ClassCastException e) { } catch (ClassCastException e) {
Utils.logf( "bad menuInfo: %s", e.toString() ); DbgUtils.logf( "bad menuInfo: %s", e.toString() );
return false; return false;
} }
@ -596,7 +596,7 @@ public class DictsActivity extends ExpandableListActivity
// MountEventReceiver.SDCardNotifiee interface // MountEventReceiver.SDCardNotifiee interface
public void cardMounted( boolean nowMounted ) public void cardMounted( boolean nowMounted )
{ {
Utils.logf( "DictsActivity.cardMounted(%b)", nowMounted ); DbgUtils.logf( "DictsActivity.cardMounted(%b)", nowMounted );
// post so other SDCardNotifiee implementations get a chance // post so other SDCardNotifiee implementations get a chance
// to process first: avoid race conditions // to process first: avoid race conditions
new Handler().post( new Runnable() { new Handler().post( new Runnable() {

View file

@ -64,7 +64,7 @@ public class DispatchNotify extends Activity {
} }
if ( mustLaunch ) { if ( mustLaunch ) {
Utils.logf( "DispatchNotify: nothing running" ); DbgUtils.logf( "DispatchNotify: nothing running" );
Intent intent = new Intent( this, GamesList.class ); Intent intent = new Intent( this, GamesList.class );
/* Flags. Tried Intent.FLAG_ACTIVITY_NEW_TASK. I don't /* Flags. Tried Intent.FLAG_ACTIVITY_NEW_TASK. I don't

View file

@ -49,7 +49,7 @@ public class FirstRunDialog {
thisVersion = context.getPackageManager() thisVersion = context.getPackageManager()
.getPackageInfo(context.getPackageName(), 0) .getPackageInfo(context.getPackageName(), 0)
.versionCode; .versionCode;
Utils.logf( "versionCode: %d", thisVersion ); DbgUtils.logf( "versionCode: %d", thisVersion );
} catch ( Exception e ) { } catch ( Exception e ) {
} }
} }
@ -96,7 +96,7 @@ public class FirstRunDialog {
page = stringBuilder.toString(); page = stringBuilder.toString();
} }
catch ( IOException ioe ) { catch ( IOException ioe ) {
Utils.logf( ioe.toString() ); DbgUtils.logf( ioe.toString() );
} }
finally { finally {
// could just catch NPE.... // could just catch NPE....
@ -104,7 +104,7 @@ public class FirstRunDialog {
try { try {
inputStream.close(); inputStream.close();
} catch ( IOException ioe ) { } catch ( IOException ioe ) {
Utils.logf( ioe.toString() ); DbgUtils.logf( ioe.toString() );
} }
} }
} }

View file

@ -613,7 +613,7 @@ public class GameConfig extends XWActivity
} }
} else { } else {
Utils.logf( "unknown v: " + view.toString() ); DbgUtils.logf( "unknown v: " + view.toString() );
} }
} // onClick } // onClick
@ -793,8 +793,8 @@ public class GameConfig extends XWActivity
setting = 2; setting = 2;
break; break;
default: default:
Utils.logf( "setSmartnessSpinner got %d from getRobotSmartness()", DbgUtils.logf( "setSmartnessSpinner got %d from getRobotSmartness()",
m_gi.getRobotSmartness() ); m_gi.getRobotSmartness() );
Assert.fail(); Assert.fail();
} }
m_smartnessSpinner.setSelection( setting ); m_smartnessSpinner.setSelection( setting );
@ -837,7 +837,7 @@ public class GameConfig extends XWActivity
private void adjustPlayersLabel() private void adjustPlayersLabel()
{ {
Utils.logf( "adjustPlayersLabel()" ); DbgUtils.logf( "adjustPlayersLabel()" );
String label; String label;
if ( m_notNetworkedGame ) { if ( m_notNetworkedGame ) {
label = getString( R.string.players_label_standalone ); label = getString( R.string.players_label_standalone );
@ -970,8 +970,8 @@ public class GameConfig extends XWActivity
if ( !m_notNetworkedGame ) { if ( !m_notNetworkedGame ) {
m_car.ip_relay_seeksPublicRoom = m_joinPublicCheck.isChecked(); m_car.ip_relay_seeksPublicRoom = m_joinPublicCheck.isChecked();
Utils.logf( "ip_relay_seeksPublicRoom: %b", DbgUtils.logf( "ip_relay_seeksPublicRoom: %b",
m_car.ip_relay_seeksPublicRoom ); m_car.ip_relay_seeksPublicRoom );
m_car.ip_relay_advertiseRoom = m_car.ip_relay_advertiseRoom =
Utils.getChecked( this, R.id.advertise_new_room_check ); Utils.getChecked( this, R.id.advertise_new_room_check );
if ( m_car.ip_relay_seeksPublicRoom ) { if ( m_car.ip_relay_seeksPublicRoom ) {

View file

@ -109,7 +109,7 @@ public class GameListAdapter extends XWListAdapter {
@Override @Override
protected Void doInBackground( Void... unused ) protected Void doInBackground( Void... unused )
{ {
// Utils.logf( "doInBackground(id=%d)", m_id ); // DbgUtils.logf( "doInBackground(id=%d)", m_id );
View layout = m_factory.inflate( R.layout.game_list_item, null ); View layout = m_factory.inflate( R.layout.game_list_item, null );
boolean hideTitle = false;//CommonPrefs.getHideTitleBar(m_context); boolean hideTitle = false;//CommonPrefs.getHideTitleBar(m_context);
GameSummary summary = DBUtils.getSummary( m_context, m_rowid, false ); GameSummary summary = DBUtils.getSummary( m_context, m_rowid, false );
@ -221,7 +221,7 @@ public class GameListAdapter extends XWListAdapter {
@Override @Override
protected void onPostExecute( Void unused ) protected void onPostExecute( Void unused )
{ {
// Utils.logf( "onPostExecute(id=%d)", m_id ); // DbgUtils.logf( "onPostExecute(id=%d)", m_id );
if ( -1 != m_rowid ) { if ( -1 != m_rowid ) {
m_cb.itemLoaded( m_rowid ); m_cb.itemLoaded( m_rowid );
} }

View file

@ -68,7 +68,7 @@ public class GameUtils {
m_rowid = rowid; m_rowid = rowid;
m_isForWrite = isForWrite; m_isForWrite = isForWrite;
m_lockCount = 0; m_lockCount = 0;
// Utils.logf( "GameLock.GameLock(%s,%s) done", m_path, // DbgUtils.logf( "GameLock.GameLock(%s,%s) done", m_path,
// m_isForWrite?"T":"F" ); // m_isForWrite?"T":"F" );
} }
@ -101,18 +101,18 @@ public class GameUtils {
public GameLock lock() public GameLock lock()
{ {
long stopTime = System.currentTimeMillis() + 1000; long stopTime = System.currentTimeMillis() + 1000;
// Utils.logf( "GameLock.lock(%s)", m_path ); // DbgUtils.logf( "GameLock.lock(%s)", m_path );
// Utils.printStack(); // Utils.printStack();
for ( ; ; ) { for ( ; ; ) {
if ( tryLock() ) { if ( tryLock() ) {
break; break;
} }
// Utils.logf( "GameLock.lock() failed; sleeping" ); // DbgUtils.logf( "GameLock.lock() failed; sleeping" );
// Utils.printStack(); // Utils.printStack();
try { try {
Thread.sleep( 25 ); // milliseconds Thread.sleep( 25 ); // milliseconds
} catch( InterruptedException ie ) { } catch( InterruptedException ie ) {
Utils.logf( "GameLock.lock(): %s", ie.toString() ); DbgUtils.logf( "GameLock.lock(): %s", ie.toString() );
break; break;
} }
if ( System.currentTimeMillis() >= stopTime ) { if ( System.currentTimeMillis() >= stopTime ) {
@ -120,13 +120,13 @@ public class GameUtils {
Assert.fail(); Assert.fail();
} }
} }
// Utils.logf( "GameLock.lock(%s) done", m_path ); // DbgUtils.logf( "GameLock.lock(%s) done", m_path );
return this; return this;
} }
public void unlock() public void unlock()
{ {
// Utils.logf( "GameLock.unlock(%s)", m_path ); // DbgUtils.logf( "GameLock.unlock(%s)", m_path );
synchronized( s_locks ) { synchronized( s_locks ) {
Assert.assertTrue( this == s_locks.get(m_rowid) ); Assert.assertTrue( this == s_locks.get(m_rowid) );
if ( 1 == m_lockCount ) { if ( 1 == m_lockCount ) {
@ -136,7 +136,7 @@ public class GameUtils {
} }
--m_lockCount; --m_lockCount;
} }
// Utils.logf( "GameLock.unlock(%s) done", m_path ); // DbgUtils.logf( "GameLock.unlock(%s) done", m_path );
} }
public long getRowid() public long getRowid()
@ -311,7 +311,7 @@ public class GameUtils {
String[] dictNames = gi.dictNames(); String[] dictNames = gi.dictNames();
DictUtils.DictPairs pairs = DictUtils.openDicts( context, dictNames ); DictUtils.DictPairs pairs = DictUtils.openDicts( context, dictNames );
if ( pairs.anyMissing( dictNames ) ) { if ( pairs.anyMissing( dictNames ) ) {
Utils.logf( "loadMakeGame() failing: dict unavailable" ); DbgUtils.logf( "loadMakeGame() failing: dict unavailable" );
} else { } else {
gamePtr = XwJNI.initJNI(); gamePtr = XwJNI.initJNI();
@ -612,7 +612,7 @@ public class GameUtils {
lock.unlock(); lock.unlock();
} }
} }
Utils.logf( "feedMessages=>%b", draw ); DbgUtils.logf( "feedMessages=>%b", draw );
return draw; return draw;
} // feedMessages } // feedMessages

View file

@ -491,7 +491,7 @@ public class GamesList extends XWListActivity
try { try {
info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
} catch (ClassCastException e) { } catch (ClassCastException e) {
Utils.logf( "bad menuInfo: %s", e.toString() ); DbgUtils.logf( "bad menuInfo: %s", e.toString() );
return false; return false;
} }

View file

@ -189,7 +189,7 @@ public class LookupView extends LinearLayout
private void lookupWord( String word, String fmt ) private void lookupWord( String word, String fmt )
{ {
if ( false ) { if ( false ) {
Utils.logf( "skipping lookupWord(%s)", word ); DbgUtils.logf( "skipping lookupWord(%s)", word );
} else { } else {
String langCode = s_langCodes[s_lang]; String langCode = s_langCodes[s_lang];
String dict_url = String.format( fmt, langCode, word ); String dict_url = String.format( fmt, langCode, word );
@ -200,7 +200,7 @@ public class LookupView extends LinearLayout
try { try {
m_context.startActivity( intent ); m_context.startActivity( intent );
} catch ( android.content.ActivityNotFoundException anfe ) { } catch ( android.content.ActivityNotFoundException anfe ) {
Utils.logf( "%s", anfe.toString() ); DbgUtils.logf( "%s", anfe.toString() );
} }
} }
} // lookupWord } // lookupWord

View file

@ -37,7 +37,7 @@ public class MountEventReceiver extends BroadcastReceiver {
@Override @Override
public void onReceive( Context context, Intent intent ) public void onReceive( Context context, Intent intent )
{ {
Utils.logf( "MountEventReceiver.onReceive(%s)", intent.getAction() ); DbgUtils.logf( "MountEventReceiver.onReceive(%s)", intent.getAction() );
synchronized( s_procs ) { synchronized( s_procs ) {
do { do {
if ( s_procs.isEmpty() ) { if ( s_procs.isEmpty() ) {

View file

@ -31,7 +31,7 @@
// @Override // @Override
// public void onReceive( Context context, Intent intent ) // public void onReceive( Context context, Intent intent )
// { // {
// Utils.logf( "NBSReceiver::onReceive(intent=%s)!!!!", // DbgUtils.logf( "NBSReceiver::onReceive(intent=%s)!!!!",
// intent.toString() ); // intent.toString() );
// } // }
@ -46,9 +46,9 @@
// data, null, null ); // data, null, null );
// // PendingIntent sentIntent, // // PendingIntent sentIntent,
// // PendingIntent deliveryIntent ); // // PendingIntent deliveryIntent );
// Utils.logf( "sendDataMessage finished" ); // DbgUtils.logf( "sendDataMessage finished" );
// } catch ( IllegalArgumentException iae ) { // } catch ( IllegalArgumentException iae ) {
// Utils.logf( "%s", iae.toString() ); // DbgUtils.logf( "%s", iae.toString() );
// } // }
// } // }
// } // }

View file

@ -84,7 +84,7 @@ public class NetLaunchInfo {
nPlayers = Integer.decode( np ); nPlayers = Integer.decode( np );
m_valid = true; m_valid = true;
} catch ( Exception e ) { } catch ( Exception e ) {
Utils.logf( "unable to parse \"%s\"", data.toString() ); DbgUtils.logf( "unable to parse \"%s\"", data.toString() );
} }
} }
} }

View file

@ -100,8 +100,8 @@ public class NetStateCache {
NetworkInfo ni = (NetworkInfo)intent. NetworkInfo ni = (NetworkInfo)intent.
getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO); getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
Utils.logf( "CommsBroadcastReceiver.onReceive: %s", DbgUtils.logf( "CommsBroadcastReceiver.onReceive: %s",
ni.getState().toString() ); ni.getState().toString() );
boolean netAvail; boolean netAvail;
switch ( ni.getState() ) { switch ( ni.getState() ) {

View file

@ -64,9 +64,9 @@ public class NetUtils {
socket.setSoTimeout( timeoutMillis ); socket.setSoTimeout( timeoutMillis );
} catch ( java.net.UnknownHostException uhe ) { } catch ( java.net.UnknownHostException uhe ) {
Utils.logf( uhe.toString() ); DbgUtils.logf( uhe.toString() );
} catch( java.io.IOException ioe ) { } catch( java.io.IOException ioe ) {
Utils.logf( ioe.toString() ); DbgUtils.logf( ioe.toString() );
} }
return socket; return socket;
} }
@ -113,7 +113,7 @@ public class NetUtils {
DBUtils.clearObits( m_context, m_obits ); DBUtils.clearObits( m_context, m_obits );
} }
} catch ( java.io.IOException ioe ) { } catch ( java.io.IOException ioe ) {
Utils.logf( ioe.toString() ); DbgUtils.logf( ioe.toString() );
} }
} }
} }
@ -176,16 +176,16 @@ public class NetUtils {
} }
if ( 0 != dis.available() ) { if ( 0 != dis.available() ) {
msgs = null; msgs = null;
Utils.logf( "format error: bytes left over in stream" ); DbgUtils.logf( "format error: bytes left over in stream" );
} }
socket.close(); socket.close();
} catch( java.net.UnknownHostException uhe ) { } catch( java.net.UnknownHostException uhe ) {
Utils.logf( uhe.toString() ); DbgUtils.logf( uhe.toString() );
} catch( java.io.IOException ioe ) { } catch( java.io.IOException ioe ) {
Utils.logf( ioe.toString() ); DbgUtils.logf( ioe.toString() );
} catch( NullPointerException npe ) { } catch( NullPointerException npe ) {
Utils.logf( npe.toString() ); DbgUtils.logf( npe.toString() );
} }
return msgs; return msgs;
} // queryRelay } // queryRelay
@ -202,7 +202,7 @@ public class NetUtils {
if ( null != msgHash ) { if ( null != msgHash ) {
Utils.logf( "sendToRelay called" ); DbgUtils.logf( "sendToRelay called" );
try { try {
// Build up a buffer containing everything but the total // Build up a buffer containing everything but the total
// message length and number of relayIDs in the message. // message length and number of relayIDs in the message.
@ -215,7 +215,7 @@ public class NetUtils {
Iterator<String> iter = msgHash.keySet().iterator(); Iterator<String> iter = msgHash.keySet().iterator();
while ( iter.hasNext() ) { while ( iter.hasNext() ) {
String relayID = iter.next(); String relayID = iter.next();
Utils.logf( "sendToRelay: sending for %s", relayID ); DbgUtils.logf( "sendToRelay: sending for %s", relayID );
int thisLen = 1 + relayID.length(); // string and '\n' int thisLen = 1 + relayID.length(); // string and '\n'
thisLen += 2; // message count thisLen += 2; // message count
@ -239,7 +239,7 @@ public class NetUtils {
outBuf.write( msg ); outBuf.write( msg );
} }
msgLen += thisLen; msgLen += thisLen;
Utils.logf( "sendToRelay: %d bytes so far", msgLen ); DbgUtils.logf( "sendToRelay: %d bytes so far", msgLen );
} }
// Now open a real socket, write size and proto, and // Now open a real socket, write size and proto, and
@ -254,12 +254,12 @@ public class NetUtils {
outStream.write( store.toByteArray() ); outStream.write( store.toByteArray() );
outStream.flush(); outStream.flush();
socket.close(); socket.close();
Utils.logf( "sendToRelay: done", msgLen ); DbgUtils.logf( "sendToRelay: done", msgLen );
} catch ( java.io.IOException ioe ) { } catch ( java.io.IOException ioe ) {
Utils.logf( "%s", ioe.toString() ); DbgUtils.logf( "%s", ioe.toString() );
} }
} else { } else {
Utils.logf( "sendToRelay: null msgs" ); DbgUtils.logf( "sendToRelay: null msgs" );
} }
} // sendToRelay } // sendToRelay

View file

@ -146,7 +146,7 @@ public class PrefsActivity extends PreferenceActivity
public void onSharedPreferenceChanged( SharedPreferences sp, String key ) public void onSharedPreferenceChanged( SharedPreferences sp, String key )
{ {
if ( key.equals( m_keyLogging ) ) { if ( key.equals( m_keyLogging ) ) {
Utils.logEnable( sp.getBoolean( key, false ) ); DbgUtils.logEnable( sp.getBoolean( key, false ) );
} }
} }

View file

@ -31,7 +31,7 @@ public class ReceiveNBS extends BroadcastReceiver {
@Override @Override
public void onReceive( Context context, Intent intent ) public void onReceive( Context context, Intent intent )
{ {
Utils.logf( "onReceive called: %s", intent.toString() ); DbgUtils.logf( "onReceive called: %s", intent.toString() );
Bundle bundle = intent.getExtras(); Bundle bundle = intent.getExtras();
SmsMessage[] smsarr = null; SmsMessage[] smsarr = null;
@ -40,7 +40,7 @@ public class ReceiveNBS extends BroadcastReceiver {
smsarr = new SmsMessage[pdus.length]; smsarr = new SmsMessage[pdus.length];
for ( int ii = 0; ii < pdus.length; ii++){ for ( int ii = 0; ii < pdus.length; ii++){
smsarr[ii] = SmsMessage.createFromPdu((byte[])pdus[ii]); smsarr[ii] = SmsMessage.createFromPdu((byte[])pdus[ii]);
Utils.logf( "from %s", smsarr[ii].getOriginatingAddress() ); DbgUtils.logf( "from %s", smsarr[ii].getOriginatingAddress() );
// buf.append( smsarr[ii].getMessageBody() ); // buf.append( smsarr[ii].getMessageBody() );
// XwJni.handle( XwJni.JNICmd.CMD_RECEIVE, // XwJni.handle( XwJni.JNICmd.CMD_RECEIVE,
// smsarr[ii].getMessageBody() ); // smsarr[ii].getMessageBody() );

View file

@ -67,7 +67,7 @@ public class RefreshNamesTask extends AsyncTask<Void, Void, String[]> {
protected String[] doInBackground( Void...unused ) protected String[] doInBackground( Void...unused )
{ {
ArrayList<String> names = new ArrayList<String>(); ArrayList<String> names = new ArrayList<String>();
Utils.logf( "doInBackground()" ); DbgUtils.logf( "doInBackground()" );
try { try {
Socket socket = NetUtils.MakeProxySocket( m_context, 15000 ); Socket socket = NetUtils.MakeProxySocket( m_context, 15000 );
@ -87,7 +87,7 @@ public class RefreshNamesTask extends AsyncTask<Void, Void, String[]> {
new DataInputStream(socket.getInputStream()); new DataInputStream(socket.getInputStream());
short len = dis.readShort(); short len = dis.readShort();
short nRooms = dis.readShort(); short nRooms = dis.readShort();
Utils.logf( "%s: got %d rooms", "doInBackground", nRooms ); DbgUtils.logf( "%s: got %d rooms", "doInBackground", nRooms );
// Can't figure out how to read a null-terminated string // Can't figure out how to read a null-terminated string
// from DataInputStream so parse it myself. // from DataInputStream so parse it myself.
@ -101,16 +101,16 @@ public class RefreshNamesTask extends AsyncTask<Void, Void, String[]> {
++index; ++index;
} }
String name = new String( bytes, lastIndex, index - lastIndex ); String name = new String( bytes, lastIndex, index - lastIndex );
Utils.logf( "got public room name: %s", name ); DbgUtils.logf( "got public room name: %s", name );
int indx = name.lastIndexOf( "/" ); int indx = name.lastIndexOf( "/" );
indx = name.lastIndexOf( "/", indx-1 ); indx = name.lastIndexOf( "/", indx-1 );
names.add( name.substring(0, indx ) ); names.add( name.substring(0, indx ) );
} }
} }
} catch ( java.io.IOException ioe ) { } catch ( java.io.IOException ioe ) {
Utils.logf( "%s", ioe.toString() ); DbgUtils.logf( "%s", ioe.toString() );
} }
Utils.logf( "doInBackground() returning" ); DbgUtils.logf( "doInBackground() returning" );
return names.toArray( new String[names.size()] ); return names.toArray( new String[names.size()] );
} }
@ -121,7 +121,7 @@ public class RefreshNamesTask extends AsyncTask<Void, Void, String[]> {
@Override @Override
protected void onPostExecute( String[] result ) protected void onPostExecute( String[] result )
{ {
Utils.logf( "onPostExecute()" ); DbgUtils.logf( "onPostExecute()" );
ArrayAdapter<String> adapter = ArrayAdapter<String> adapter =
new ArrayAdapter<String>( m_context, new ArrayAdapter<String>( m_context,
android.R.layout.simple_spinner_item, android.R.layout.simple_spinner_item,
@ -136,6 +136,6 @@ public class RefreshNamesTask extends AsyncTask<Void, Void, String[]> {
m_nnf.NoNameFound(); m_nnf.NoNameFound();
} }
Utils.logf( "onPostExecute() done" ); DbgUtils.logf( "onPostExecute() done" );
} }
} }

View file

@ -49,10 +49,10 @@ public class RelayReceiver extends BroadcastReceiver {
{ {
if ( null != intent && null != intent.getAction() if ( null != intent && null != intent.getAction()
&& intent.getAction().equals( Intent.ACTION_BOOT_COMPLETED ) ) { && intent.getAction().equals( Intent.ACTION_BOOT_COMPLETED ) ) {
Utils.logf( "launching timer on boot" ); DbgUtils.logf( "launching timer on boot" );
RestartTimer( context ); RestartTimer( context );
} else { } else {
// Utils.logf( "RelayReceiver::onReceive()" ); // DbgUtils.logf( "RelayReceiver::onReceive()" );
// if ( XWConstants.s_showProxyToast ) { // if ( XWConstants.s_showProxyToast ) {
// Toast.makeText(context, "RelayReceiver: fired", // Toast.makeText(context, "RelayReceiver: fired",
// Toast.LENGTH_SHORT).show(); // Toast.LENGTH_SHORT).show();
@ -83,7 +83,7 @@ public class RelayReceiver extends BroadcastReceiver {
PendingIntent pi = PendingIntent.getBroadcast( context, 0, intent, 0 ); PendingIntent pi = PendingIntent.getBroadcast( context, 0, intent, 0 );
if ( interval_millis > 0 || force ) { if ( interval_millis > 0 || force ) {
// Utils.logf( "setting alarm for %d millis", interval_millis ); // DbgUtils.logf( "setting alarm for %d millis", interval_millis );
am.setInexactRepeating( AlarmManager.ELAPSED_REALTIME_WAKEUP, am.setInexactRepeating( AlarmManager.ELAPSED_REALTIME_WAKEUP,
0, // first firing 0, // first firing
interval_millis, pi ); interval_millis, pi );

View file

@ -29,7 +29,7 @@ public class StatusReceiver extends BroadcastReceiver {
@Override @Override
public void onReceive( Context context, Intent intent ) public void onReceive( Context context, Intent intent )
{ {
Utils.logf( "StatusReceiver.onReceive called: %s", intent.toString() ); DbgUtils.logf( "StatusReceiver.onReceive called: %s", intent.toString() );
} }
} }

View file

@ -20,98 +20,27 @@
package org.eehouse.android.xw4; package org.eehouse.android.xw4;
import android.util.Log;
import java.lang.Thread;
import android.app.Activity; import android.app.Activity;
import android.app.Dialog; import android.app.Dialog;
import android.content.DialogInterface; import android.content.DialogInterface;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.widget.CheckBox; import android.widget.CheckBox;
import android.widget.Toast; import android.widget.Toast;
import android.widget.EditText; import android.widget.EditText;
import android.widget.TextView; import android.widget.TextView;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.View; import android.view.View;
import android.text.format.Time;
import java.util.Formatter;
import junit.framework.Assert; import junit.framework.Assert;
import org.eehouse.android.xw4.jni.*; import org.eehouse.android.xw4.jni.*;
public class Utils { public class Utils {
static final String TAG = "XW4";
static final String DB_PATH = "XW_GAMES"; static final String DB_PATH = "XW_GAMES";
static boolean s_doLog = true;
private static Time s_time = new Time();
private Utils() {} private Utils() {}
public static void logEnable( boolean enable )
{
s_doLog = enable;
}
public static void logEnable( Context context )
{
SharedPreferences sp
= PreferenceManager.getDefaultSharedPreferences( context );
String key = context.getString( R.string.key_logging_on );
boolean on = sp.getBoolean( key, false );
logEnable( on );
}
public static void logf( String msg )
{
if ( s_doLog ) {
s_time.setToNow();
String time = s_time.format("[%H:%M:%S]");
long id = Thread.currentThread().getId();
Log.d( TAG, time + "-" + id + "-" + msg );
}
} // logf
public static void logf( String format, Object... args )
{
if ( s_doLog ) {
Formatter formatter = new Formatter();
logf( formatter.format( format, args ).toString() );
}
} // logf
public static void showf( Context context, String format, Object... args )
{
Formatter formatter = new Formatter();
String msg = formatter.format( format, args ).toString();
Toast.makeText( context, msg, Toast.LENGTH_SHORT ).show();
} // showf
public static void showf( Context context, int formatid, Object... args )
{
showf( context, context.getString( formatid ), args );
} // showf
public static void printStack( StackTraceElement[] trace )
{
if ( s_doLog ) {
for ( int ii = 0; ii < trace.length; ++ii ) {
Utils.logf( "ste %d: %s", ii, trace[ii].toString() );
}
}
}
public static void printStack()
{
if ( s_doLog ) {
printStack( Thread.currentThread().getStackTrace() );
}
}
public static void notImpl( Context context ) public static void notImpl( Context context )
{ {
CharSequence text = "Feature coming soon"; CharSequence text = "Feature coming soon";

View file

@ -40,7 +40,7 @@ public class XWActivity extends Activity
@Override @Override
protected void onCreate( Bundle savedInstanceState ) protected void onCreate( Bundle savedInstanceState )
{ {
Utils.logf( "%s.onCreate(this=%H)", getClass().getName(), this ); DbgUtils.logf( "%s.onCreate(this=%H)", getClass().getName(), this );
super.onCreate( savedInstanceState ); super.onCreate( savedInstanceState );
m_delegate = new DlgDelegate( this, this, savedInstanceState ); m_delegate = new DlgDelegate( this, this, savedInstanceState );
} }
@ -48,7 +48,7 @@ public class XWActivity extends Activity
@Override @Override
protected void onStart() protected void onStart()
{ {
Utils.logf( "%s.onStart(this=%H)", getClass().getName(), this ); DbgUtils.logf( "%s.onStart(this=%H)", getClass().getName(), this );
super.onStart(); super.onStart();
DispatchNotify.SetRunning( this ); DispatchNotify.SetRunning( this );
} }
@ -56,21 +56,21 @@ public class XWActivity extends Activity
@Override @Override
protected void onResume() protected void onResume()
{ {
Utils.logf( "%s.onResume(this=%H)", getClass().getName(), this ); DbgUtils.logf( "%s.onResume(this=%H)", getClass().getName(), this );
super.onResume(); super.onResume();
} }
@Override @Override
protected void onPause() protected void onPause()
{ {
Utils.logf( "%s.onPause(this=%H)", getClass().getName(), this ); DbgUtils.logf( "%s.onPause(this=%H)", getClass().getName(), this );
super.onPause(); super.onPause();
} }
@Override @Override
protected void onStop() protected void onStop()
{ {
Utils.logf( "%s.onStop(this=%H)", getClass().getName(), this ); DbgUtils.logf( "%s.onStop(this=%H)", getClass().getName(), this );
DispatchNotify.ClearRunning( this ); DispatchNotify.ClearRunning( this );
super.onStop(); super.onStop();
} }
@ -78,8 +78,8 @@ public class XWActivity extends Activity
@Override @Override
protected void onDestroy() protected void onDestroy()
{ {
Utils.logf( "%s.onDestroy(this=%H); isFinishing=%b", DbgUtils.logf( "%s.onDestroy(this=%H); isFinishing=%b",
getClass().getName(), this, isFinishing() ); getClass().getName(), this, isFinishing() );
super.onDestroy(); super.onDestroy();
} }
@ -95,7 +95,7 @@ public class XWActivity extends Activity
{ {
Dialog dialog = super.onCreateDialog( id ); Dialog dialog = super.onCreateDialog( id );
if ( null == dialog ) { if ( null == dialog ) {
Utils.logf( "%s.onCreateDialog() called", getClass().getName() ); DbgUtils.logf( "%s.onCreateDialog() called", getClass().getName() );
dialog = m_delegate.onCreateDialog( id ); dialog = m_delegate.onCreateDialog( id );
} }
return dialog; return dialog;

View file

@ -27,8 +27,9 @@ public class XWApp extends Application {
@Override @Override
public void onCreate() public void onCreate()
{ {
Utils.logEnable( this ); DbgUtils.logEnable( this );
Utils.logf( "XWApp.onCreate(); git_rev=%s", getString(R.string.git_rev) ); DbgUtils.logf( "XWApp.onCreate(); git_rev=%s",
getString(R.string.git_rev) );
super.onCreate(); super.onCreate();
} }
} }

View file

@ -37,7 +37,7 @@ public class XWListActivity extends ListActivity
@Override @Override
protected void onCreate( Bundle savedInstanceState ) protected void onCreate( Bundle savedInstanceState )
{ {
Utils.logf( "%s.onCreate(this=%H)", getClass().getName(), this ); DbgUtils.logf( "%s.onCreate(this=%H)", getClass().getName(), this );
super.onCreate( savedInstanceState ); super.onCreate( savedInstanceState );
m_delegate = new DlgDelegate( this, this, savedInstanceState ); m_delegate = new DlgDelegate( this, this, savedInstanceState );
} }
@ -45,7 +45,7 @@ public class XWListActivity extends ListActivity
@Override @Override
protected void onStart() protected void onStart()
{ {
Utils.logf( "%s.onStart(this=%H)", getClass().getName(), this ); DbgUtils.logf( "%s.onStart(this=%H)", getClass().getName(), this );
super.onStart(); super.onStart();
DispatchNotify.SetRunning( this ); DispatchNotify.SetRunning( this );
} }
@ -53,21 +53,21 @@ public class XWListActivity extends ListActivity
@Override @Override
protected void onResume() protected void onResume()
{ {
Utils.logf( "%s.onResume(this=%H)", getClass().getName(), this ); DbgUtils.logf( "%s.onResume(this=%H)", getClass().getName(), this );
super.onResume(); super.onResume();
} }
@Override @Override
protected void onPause() protected void onPause()
{ {
Utils.logf( "%s.onPause(this=%H)", getClass().getName(), this ); DbgUtils.logf( "%s.onPause(this=%H)", getClass().getName(), this );
super.onPause(); super.onPause();
} }
@Override @Override
protected void onStop() protected void onStop()
{ {
Utils.logf( "%s.onStop(this=%H)", getClass().getName(), this ); DbgUtils.logf( "%s.onStop(this=%H)", getClass().getName(), this );
DispatchNotify.ClearRunning( this ); DispatchNotify.ClearRunning( this );
super.onStop(); super.onStop();
} }
@ -75,8 +75,8 @@ public class XWListActivity extends ListActivity
@Override @Override
protected void onDestroy() protected void onDestroy()
{ {
Utils.logf( "%s.onDestroy(this=%H); isFinishing=%b", DbgUtils.logf( "%s.onDestroy(this=%H); isFinishing=%b",
getClass().getName(), this, isFinishing() ); getClass().getName(), this, isFinishing() );
super.onDestroy(); super.onDestroy();
} }
@ -90,7 +90,7 @@ public class XWListActivity extends ListActivity
@Override @Override
protected Dialog onCreateDialog( final int id ) protected Dialog onCreateDialog( final int id )
{ {
Utils.logf( "%s.onCreateDialog() called", getClass().getName() ); DbgUtils.logf( "%s.onCreateDialog() called", getClass().getName() );
Dialog dialog = m_delegate.onCreateDialog( id ); Dialog dialog = m_delegate.onCreateDialog( id );
if ( null == dialog ) { if ( null == dialog ) {
dialog = super.onCreateDialog( id ); dialog = super.onCreateDialog( id );

View file

@ -164,7 +164,7 @@ public class CommonPrefs {
result = Integer.parseInt( val ); result = Integer.parseInt( val );
} catch ( Exception ex ) { } catch ( Exception ex ) {
} }
// Utils.logf( "getDefaultProxyPort=>%d", result ); // DbgUtils.logf( "getDefaultProxyPort=>%d", result );
return result; return result;
} }

View file

@ -26,7 +26,7 @@ import java.util.HashSet;
import java.util.Arrays; import java.util.Arrays;
import junit.framework.Assert; import junit.framework.Assert;
import org.eehouse.android.xw4.Utils; import org.eehouse.android.xw4.DbgUtils;
import org.eehouse.android.xw4.DictUtils; import org.eehouse.android.xw4.DictUtils;
import org.eehouse.android.xw4.R; import org.eehouse.android.xw4.R;
import org.eehouse.android.xw4.DictLangCache; import org.eehouse.android.xw4.DictLangCache;
@ -216,7 +216,7 @@ public class CurGameInfo {
++count; ++count;
} }
} }
Utils.logf( "remoteCount()=>%d", count ); DbgUtils.logf( "remoteCount()=>%d", count );
return count; return count;
} }

View file

@ -21,7 +21,6 @@
package org.eehouse.android.xw4.jni; package org.eehouse.android.xw4.jni;
import org.eehouse.android.xw4.Utils;
import android.content.Context; import android.content.Context;
import java.lang.InterruptedException; import java.lang.InterruptedException;
import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.LinkedBlockingQueue;
@ -32,6 +31,7 @@ import android.graphics.Paint;
import android.graphics.Rect; import android.graphics.Rect;
import org.eehouse.android.xw4.R; import org.eehouse.android.xw4.R;
import org.eehouse.android.xw4.DbgUtils;
import org.eehouse.android.xw4.BoardDims; import org.eehouse.android.xw4.BoardDims;
import org.eehouse.android.xw4.GameUtils; import org.eehouse.android.xw4.GameUtils;
import org.eehouse.android.xw4.DBUtils; import org.eehouse.android.xw4.DBUtils;
@ -163,7 +163,7 @@ public class JNIThread extends Thread {
join(); join();
// Assert.assertFalse( isAlive() ); // Assert.assertFalse( isAlive() );
} catch ( java.lang.InterruptedException ie ) { } catch ( java.lang.InterruptedException ie ) {
Utils.logf( "JNIThread.waitToStop() got %s", ie.toString() ); DbgUtils.logf( "JNIThread.waitToStop() got %s", ie.toString() );
} }
} }
@ -290,7 +290,7 @@ public class JNIThread extends Thread {
try { try {
elem = m_queue.take(); elem = m_queue.take();
} catch ( InterruptedException ie ) { } catch ( InterruptedException ie ) {
Utils.logf( "interrupted; killing thread" ); DbgUtils.logf( "interrupted; killing thread" );
break; break;
} }
boolean draw = false; boolean draw = false;
@ -565,7 +565,7 @@ public class JNIThread extends Thread {
public void handle( JNICmd cmd, boolean isUI, Object... args ) public void handle( JNICmd cmd, boolean isUI, Object... args )
{ {
QueueElem elem = new QueueElem( cmd, isUI, args ); QueueElem elem = new QueueElem( cmd, isUI, args );
// Utils.logf( "adding: %s", cmd.toString() ); // DbgUtils.logf( "adding: %s", cmd.toString() );
m_queue.add( elem ); m_queue.add( elem );
} }

View file

@ -56,7 +56,7 @@ public class JNIUtilsImpl implements JNIUtils {
try { try {
isr = new InputStreamReader( bais, isUTF8? "UTF8" : "ISO8859_1" ); isr = new InputStreamReader( bais, isUTF8? "UTF8" : "ISO8859_1" );
} catch( java.io.UnsupportedEncodingException uee ) { } catch( java.io.UnsupportedEncodingException uee ) {
Utils.logf( "splitFaces: %s", uee.toString() ); DbgUtils.logf( "splitFaces: %s", uee.toString() );
isr = new InputStreamReader( bais ); isr = new InputStreamReader( bais );
} }
@ -67,7 +67,7 @@ public class JNIUtilsImpl implements JNIUtils {
try { try {
chr = isr.read(); chr = isr.read();
} catch ( java.io.IOException ioe ) { } catch ( java.io.IOException ioe ) {
Utils.logf( ioe.toString() ); DbgUtils.logf( ioe.toString() );
} }
if ( -1 == chr ) { if ( -1 == chr ) {
break; break;

View file

@ -22,7 +22,7 @@ package org.eehouse.android.xw4.jni;
import android.content.Context; import android.content.Context;
import org.eehouse.android.xw4.Utils; import org.eehouse.android.xw4.DbgUtils;
import org.eehouse.android.xw4.R; import org.eehouse.android.xw4.R;
public class UtilCtxtImpl implements UtilCtxt { public class UtilCtxtImpl implements UtilCtxt {
@ -173,7 +173,7 @@ public class UtilCtxtImpl implements UtilCtxt {
id = R.string.strd_turn_score; id = R.string.strd_turn_score;
break; break;
default: default:
Utils.logf( "no such stringCode: %d", stringCode ); DbgUtils.logf( "no such stringCode: %d", stringCode );
} }
String result; String result;
@ -227,7 +227,7 @@ public class UtilCtxtImpl implements UtilCtxt {
} }
private void subclassOverride( String name ) { private void subclassOverride( String name ) {
Utils.logf( "%s::%s() called", getClass().getName(), name ); DbgUtils.logf( "%s::%s() called", getClass().getName(), name );
} }
} }

View file

@ -7,7 +7,7 @@ cd ../XWords4
# create local.properties for 1.6 sdk (target id 4). Use 'android # create local.properties for 1.6 sdk (target id 4). Use 'android
# list targets' to get the full set. # list targets' to get the full set.
android update project --path . --target 4 android update project --path . --target 6
echo "local.properties looks like this:" echo "local.properties looks like this:"
echo "" echo ""

View file

@ -65,7 +65,7 @@
#include "dragdrpp.h" #include "dragdrpp.h"
#include "dbgutil.h" #include "dbgutil.h"
#ifndef MAX_BOARD_ZOOM #ifndef MAX_BOARD_ZOOM /* width in cells visible at max zoom */
/* too big looks bad */ /* too big looks bad */
# define MAX_BOARD_ZOOM 4 # define MAX_BOARD_ZOOM 4
#endif #endif

View file

@ -52,6 +52,11 @@
#endif #endif
#define STREAM_SAVE_PREVWORDS 0x11 #define STREAM_SAVE_PREVWORDS 0x11
#define STREAM_VERS_SERVER_SAVES_TOSHOW 0x10 #define STREAM_VERS_SERVER_SAVES_TOSHOW 0x10
/* STREAM_VERS_PLAYERDICTS affects stream sent between devices. May not be
able to upgrade somebody who's this far back to something with
STREAM_VERS_BIGBOARD defined. It was added in rev 3b7b4802, on 2011-04-01,
which makes it part of android_beta_25 (tag added Apr 29 2011).
*/
#define STREAM_VERS_PLAYERDICTS 0x0F #define STREAM_VERS_PLAYERDICTS 0x0F
#define STREAM_SAVE_PREVMOVE 0x0E /* server saves prev move explanation */ #define STREAM_SAVE_PREVMOVE 0x0E /* server saves prev move explanation */
#define STREAM_VERS_ROBOTIQ STREAM_SAVE_PREVMOVE /* robots have different smarts */ #define STREAM_VERS_ROBOTIQ STREAM_SAVE_PREVMOVE /* robots have different smarts */

View file

@ -700,15 +700,11 @@ setModelTileRaw( ModelCtxt* model, XP_U16 col, XP_U16 row, CellTile tile )
static CellTile static CellTile
getModelTileRaw( const ModelCtxt* model, XP_U16 col, XP_U16 row ) getModelTileRaw( const ModelCtxt* model, XP_U16 col, XP_U16 row )
{ {
CellTile tile;
XP_U16 nCols = model->nCols; XP_U16 nCols = model->nCols;
XP_ASSERT( model->nRows == nCols ); XP_ASSERT( model->nRows == nCols );
if ( col < nCols && row < nCols ) { XP_ASSERT( col < nCols );
tile = model->vol.tiles[(row*nCols) + col]; XP_ASSERT( row < nCols );
} else { return model->vol.tiles[(row*nCols) + col];
tile = TILE_EMPTY_BIT;
}
return tile;
} /* getModelTileRaw */ } /* getModelTileRaw */
static void static void

View file

@ -318,10 +318,11 @@ static XP_Bool
modelIsEmptyAt( const ModelCtxt* model, XP_U16 col, XP_U16 row ) modelIsEmptyAt( const ModelCtxt* model, XP_U16 col, XP_U16 row )
{ {
Tile tile; Tile tile;
XP_Bool found; XP_U16 nCols = model_numCols( model );
XP_Bool found = col < nCols
found = model_getTile( model, col, row, XP_FALSE, -1, &tile, && row < nCols
NULL, NULL, NULL ); && model_getTile( model, col, row, XP_FALSE, -1, &tile,
NULL, NULL, NULL );
return !found; return !found;
} /* modelIsEmptyAt */ } /* modelIsEmptyAt */
@ -722,11 +723,12 @@ find_end( const ModelCtxt* model, XP_U16 col, XP_U16 row,
XP_Bool isHorizontal ) XP_Bool isHorizontal )
{ {
XP_U16* incr = isHorizontal? &col: &row; XP_U16* incr = isHorizontal? &col: &row;
XP_U16 limit = isHorizontal? MAX_COLS-1:MAX_ROWS-1; XP_U16 nCols = model_numCols( model );
XP_U16 limit = nCols - 1;
XP_U16 lastGood = *incr; XP_U16 lastGood = *incr;
XP_ASSERT( col < MAX_COLS ); XP_ASSERT( col < nCols );
XP_ASSERT( row < MAX_ROWS ); XP_ASSERT( row < nCols );
for ( ; ; ) { for ( ; ; ) {
XP_ASSERT( *incr <= limit ); XP_ASSERT( *incr <= limit );

View file

@ -292,9 +292,8 @@ getNV( XWStreamCtxt* stream, ServerNonvolatiles* nv, XP_U16 nPlayers )
nv->addresses[ii].channelNo = nv->addresses[ii].channelNo =
(XP_PlayerAddr)stream_getBits( stream, 16 ); (XP_PlayerAddr)stream_getBits( stream, 16 );
#ifdef STREAM_VERS_BIGBOARD #ifdef STREAM_VERS_BIGBOARD
if ( STREAM_VERS_BIGBOARD <= version ) { nv->addresses[ii].streamVersion = STREAM_VERS_BIGBOARD <= version ?
nv->addresses[ii].streamVersion = stream_getBits( stream, 8 ); stream_getBits( stream, 8 ) : STREAM_SAVE_PREVWORDS;
}
#endif #endif
} }
#ifdef STREAM_VERS_BIGBOARD #ifdef STREAM_VERS_BIGBOARD
@ -641,8 +640,20 @@ setStreamVersion( ServerCtxt* server )
XP_LOGF( "%s: setting streamVersion: %d", __func__, streamVersion ); XP_LOGF( "%s: setting streamVersion: %d", __func__, streamVersion );
server->nv.streamVersion = streamVersion; server->nv.streamVersion = streamVersion;
} }
static void
checkResizeBoard( ServerCtxt* server )
{
CurGameInfo* gi = server->vol.gi;
if ( STREAM_VERS_BIGBOARD > server->nv.streamVersion && gi->boardSize > 15) {
XP_LOGF( "%s: dropping board size from %d to 15", __func__, gi->boardSize );
gi->boardSize = 15;
model_setSize( server->vol.model, 15 );
}
}
# else # else
# define setStreamVersion(s) # define setStreamVersion(s)
# define checkResizeBoard(s)
# endif # endif
static XP_Bool static XP_Bool
@ -691,6 +702,7 @@ handleRegistrationMsg( ServerCtxt* server, XWStreamCtxt* stream )
if ( server->nv.pendingRegistrations == 0 ) { if ( server->nv.pendingRegistrations == 0 ) {
XP_ASSERT( ii == playersInMsg ); /* otherwise malformed */ XP_ASSERT( ii == playersInMsg ); /* otherwise malformed */
setStreamVersion( server ); setStreamVersion( server );
checkResizeBoard( server );
assignTilesToAll( server ); assignTilesToAll( server );
SETSTATE( server, XWSTATE_RECEIVED_ALL_REG ); SETSTATE( server, XWSTATE_RECEIVED_ALL_REG );
} }
@ -1170,7 +1182,7 @@ client_readInitialMessage( ServerCtxt* server, XWStreamCtxt* stream )
DictionaryCtxt* curDict; DictionaryCtxt* curDict;
XP_U16 nPlayers, nCols; XP_U16 nPlayers, nCols;
XP_PlayerAddr channelNo; XP_PlayerAddr channelNo;
short i; XP_U16 ii;
ModelCtxt* model = server->vol.model; ModelCtxt* model = server->vol.model;
CurGameInfo* gi = server->vol.gi; CurGameInfo* gi = server->vol.gi;
CurGameInfo localGI; CurGameInfo localGI;
@ -1181,6 +1193,7 @@ client_readInitialMessage( ServerCtxt* server, XWStreamCtxt* stream )
XP_U8 streamVersion = stream_getU8( stream ); XP_U8 streamVersion = stream_getU8( stream );
XP_LOGF( "%s: set streamVersion to %d", __func__, streamVersion ); XP_LOGF( "%s: set streamVersion to %d", __func__, streamVersion );
stream_setVersion( stream, streamVersion ); stream_setVersion( stream, streamVersion );
// XP_ASSERT( streamVersion <= CUR_STREAM_VERS ); /* else do what? */
gameID = stream_getU32( stream ); gameID = stream_getU32( stream );
XP_LOGF( "read gameID of %lx; calling comms_setConnID", gameID ); XP_LOGF( "read gameID of %lx; calling comms_setConnID", gameID );
@ -1237,21 +1250,21 @@ client_readInitialMessage( ServerCtxt* server, XWStreamCtxt* stream )
/* now read the assigned tiles for each player from the stream, and /* now read the assigned tiles for each player from the stream, and
remove them from the newly-created local pool. */ remove them from the newly-created local pool. */
for ( i = 0; i < nPlayers; ++i ) { for ( ii = 0; ii < nPlayers; ++ii ) {
TrayTileSet tiles; TrayTileSet tiles;
traySetFromStream( stream, &tiles ); traySetFromStream( stream, &tiles );
XP_ASSERT( tiles.nTiles <= MAX_TRAY_TILES ); XP_ASSERT( tiles.nTiles <= MAX_TRAY_TILES );
XP_STATUSF( "got %d tiles for player %d", tiles.nTiles, i ); XP_LOGF( "%s: got %d tiles for player %d", __func__, tiles.nTiles, ii );
model_assignPlayerTiles( model, i, &tiles ); model_assignPlayerTiles( model, ii, &tiles );
/* remove what the server's assigned so we won't conflict /* remove what the server's assigned so we won't conflict
later. */ later. */
pool_removeTiles( pool, &tiles ); pool_removeTiles( pool, &tiles );
sortTilesIf( server, i ); sortTilesIf( server, ii );
} }
syncPlayers( server ); syncPlayers( server );
@ -1283,25 +1296,25 @@ makeSendableGICopy( ServerCtxt* server, CurGameInfo* giCopy,
{ {
XP_U16 nPlayers; XP_U16 nPlayers;
LocalPlayer* clientPl; LocalPlayer* clientPl;
XP_U16 i; XP_U16 ii;
XP_MEMCPY( giCopy, server->vol.gi, sizeof(*giCopy) ); XP_MEMCPY( giCopy, server->vol.gi, sizeof(*giCopy) );
nPlayers = giCopy->nPlayers; nPlayers = giCopy->nPlayers;
for ( clientPl = giCopy->players, i = 0; for ( clientPl = giCopy->players, ii = 0;
i < nPlayers; ++clientPl, ++i ) { ii < nPlayers; ++clientPl, ++ii ) {
/* adjust isLocal to client's perspective */ /* adjust isLocal to client's perspective */
clientPl->isLocal = server->players[i].deviceIndex == deviceIndex; clientPl->isLocal = server->players[ii].deviceIndex == deviceIndex;
} }
giCopy->dictName = (XP_UCHAR*)NULL; /* so we don't sent the bytes; Isn't this giCopy->dictName = (XP_UCHAR*)NULL; /* so we don't sent the bytes */
a leak? PENDING */
} /* makeSendableGICopy */ } /* makeSendableGICopy */
static void static void
server_sendInitialMessage( ServerCtxt* server ) server_sendInitialMessage( ServerCtxt* server )
{ {
short i; XP_U16 ii;
XP_U16 deviceIndex; XP_U16 deviceIndex;
ModelCtxt* model = server->vol.model; ModelCtxt* model = server->vol.model;
XP_U16 nPlayers = server->vol.gi->nPlayers; XP_U16 nPlayers = server->vol.gi->nPlayers;
@ -1319,7 +1332,12 @@ server_sendInitialMessage( ServerCtxt* server )
stream_open( stream ); stream_open( stream );
writeProto( server, stream, XWPROTO_CLIENT_SETUP ); writeProto( server, stream, XWPROTO_CLIENT_SETUP );
#ifdef STREAM_VERS_BIGBOARD
XP_ASSERT( 0 < server->nv.streamVersion );
stream_putU8( stream, server->nv.streamVersion );
#else
stream_putU8( stream, CUR_STREAM_VERS ); stream_putU8( stream, CUR_STREAM_VERS );
#endif
XP_LOGF( "putting gameID %lx into msg", gameID ); XP_LOGF( "putting gameID %lx into msg", gameID );
stream_putU32( stream, gameID ); stream_putU32( stream, gameID );
@ -1330,8 +1348,8 @@ server_sendInitialMessage( ServerCtxt* server )
dict_writeToStream( dict, stream ); dict_writeToStream( dict, stream );
/* send tiles currently in tray */ /* send tiles currently in tray */
for ( i = 0; i < nPlayers; ++i ) { for ( ii = 0; ii < nPlayers; ++ii ) {
model_trayToStream( model, i, stream ); model_trayToStream( model, ii, stream );
} }
stream_destroy( stream ); stream_destroy( stream );
@ -1692,7 +1710,7 @@ static void
assignTilesToAll( ServerCtxt* server ) assignTilesToAll( ServerCtxt* server )
{ {
XP_U16 numAssigned; XP_U16 numAssigned;
short i; XP_U16 ii;
ModelCtxt* model = server->vol.model; ModelCtxt* model = server->vol.model;
XP_U16 nPlayers = server->vol.gi->nPlayers; XP_U16 nPlayers = server->vol.gi->nPlayers;
@ -1712,11 +1730,11 @@ assignTilesToAll( ServerCtxt* server )
if ( numAssigned > MAX_TRAY_TILES ) { if ( numAssigned > MAX_TRAY_TILES ) {
numAssigned = MAX_TRAY_TILES; numAssigned = MAX_TRAY_TILES;
} }
for ( i = 0; i < nPlayers; ++i ) { for ( ii = 0; ii < nPlayers; ++ii ) {
TrayTileSet newTiles; TrayTileSet newTiles;
fetchTiles( server, i, numAssigned, NULL, &newTiles ); fetchTiles( server, ii, numAssigned, NULL, &newTiles );
model_assignPlayerTiles( model, i, &newTiles ); model_assignPlayerTiles( model, ii, &newTiles );
sortTilesIf( server, i ); sortTilesIf( server, ii );
} }
} /* assignTilesToAll */ } /* assignTilesToAll */

View file

@ -560,7 +560,7 @@ configure_event( GtkWidget* widget, GdkEventConfigure* XP_UNUSED(event),
/* move tray up if part of board's meant to be hidden */ /* move tray up if part of board's meant to be hidden */
trayTop -= vscale * globals->cGlobals.params->nHidden; trayTop -= vscale * globals->cGlobals.params->nHidden;
board_setPos( globals->cGlobals.game.board, GTK_BOARD_LEFT, boardTop, board_setPos( globals->cGlobals.game.board, GTK_BOARD_LEFT, boardTop,
hscale * nCols, vscale * nRows, hscale * 2, XP_FALSE ); hscale * nCols, vscale * nRows, hscale * 4, XP_FALSE );
/* board_setScale( globals->cGlobals.game.board, hscale, vscale ); */ /* board_setScale( globals->cGlobals.game.board, hscale, vscale ); */
globals->gridOn = XP_TRUE; globals->gridOn = XP_TRUE;
@ -1056,9 +1056,11 @@ disenable_buttons( GtkAppGlobals* globals )
gtk_widget_set_sensitive( globals->prevhint_button, canHing ); gtk_widget_set_sensitive( globals->prevhint_button, canHing );
gtk_widget_set_sensitive( globals->nexthint_button, canHing ); gtk_widget_set_sensitive( globals->nexthint_button, canHing );
#ifdef XWFEATURE_CHAT
XP_Bool canChat = !!globals->cGlobals.game.comms XP_Bool canChat = !!globals->cGlobals.game.comms
&& comms_canChat( globals->cGlobals.game.comms ); && comms_canChat( globals->cGlobals.game.comms );
gtk_widget_set_sensitive( globals->chat_button, canChat ); gtk_widget_set_sensitive( globals->chat_button, canChat );
#endif
} }
static gboolean static gboolean
@ -1894,12 +1896,13 @@ makeVerticalBar( GtkAppGlobals* globals, GtkWidget* XP_UNUSED(window) )
gtk_box_pack_start( GTK_BOX(vbox), button, FALSE, TRUE, 0 ); gtk_box_pack_start( GTK_BOX(vbox), button, FALSE, TRUE, 0 );
button = makeShowButtonFromBitmap( globals, "../done.xpm", "-", button = makeShowButtonFromBitmap( globals, "../done.xpm", "-",
G_CALLBACK(handle_zoomout_button) ); G_CALLBACK(handle_zoomout_button) );
gtk_box_pack_start( GTK_BOX(vbox), button, FALSE, TRUE, 0 );
#ifdef XWFEATURE_CHAT #ifdef XWFEATURE_CHAT
button = makeShowButtonFromBitmap( globals, "", "chat", button = makeShowButtonFromBitmap( globals, "", "chat",
G_CALLBACK(handle_chat_button) ); G_CALLBACK(handle_chat_button) );
globals->chat_button = button; globals->chat_button = button;
#endif
gtk_box_pack_start( GTK_BOX(vbox), button, FALSE, TRUE, 0 ); gtk_box_pack_start( GTK_BOX(vbox), button, FALSE, TRUE, 0 );
#endif
gtk_widget_show( vbox ); gtk_widget_show( vbox );
return vbox; return vbox;

View file

@ -1,62 +1,28 @@
#!/bin/bash #!/bin/bash
set -u -e set -u -e
NGAMES=${NGAMES:-1} APP_NEW=""
NROOMS=${NROOMS:-$NGAMES} NGAMES=""
HOST=${HOST:-localhost} UPGRADE_ODDS=""
PORT=${PORT:-10997} NROOMS=""
TIMEOUT=${TIMEOUT:-$((NGAMES*60+500))} HOST=""
DICTS=${DICTS:-dict.xwd} PORT=""
SAVE_GOOD=${SAVE_GOOD:-YES} TIMEOUT=""
MINDEVS=${MINDEVS:-2} SAVE_GOOD=""
MAXDEVS=${MAXDEVS:-4} MINDEVS=""
RESIGN_RATIO=${RESIGN_RATIO:-1000} MAXDEVS=""
DROP_N=${DROP_N:-0} RESIGN_RATIO=""
DROP_N=""
MINRUN=2 MINRUN=2
ONE_PER_ROOM="" ONE_PER_ROOM=""
USE_GTK=""
ALL_VIA_RQ=${ALL_VIA_RQ:-FALSE} ALL_VIA_RQ=${ALL_VIA_RQ:-FALSE}
SEED=${SEED:-""} SEED=""
#BOARD_SIZES=(15 17) BOARD_SIZES_OLD=(15)
BOARD_SIZES=(15) BOARD_SIZES_NEW=(15)
declare -a DICTS_ARR
for DICT in $DICTS; do
DICTS_ARR[${#DICTS_ARR[*]}]=$DICT
done
NAMES=(UNUSED Brynn Ariela Kati Eric) NAMES=(UNUSED Brynn Ariela Kati Eric)
[ -n "$SEED" ] && RANDOM=$SEED [ -n "$SEED" ] && RANDOM=$SEED
LOGDIR=$(basename $0)_logs
RESUME=""
for FILE in $(ls $LOGDIR/*.{xwg,txt} 2>/dev/null); do
if [ -e $FILE ]; then
echo "Unfinished games found in $LOGDIR; continue with them (or discard)?"
read -p "<yes/no> " ANSWER
case "$ANSWER" in
y|yes|Y|YES)
RESUME=1
;;
*)
;;
esac
fi
break
done
if [ -z "$RESUME" -a -d $LOGDIR ];then
mv $LOGDIR /tmp/${LOGDIR}_$$
fi
mkdir -p $LOGDIR
if [ "$SAVE_GOOD" = YES ]; then
DONEDIR=$LOGDIR/done
mkdir -p $DONEDIR
fi
DEADDIR=$LOGDIR/dead
mkdir -p $DEADDIR
USE_GTK=${USE_GTK:-FALSE}
declare -A PIDS declare -A PIDS
declare -A APPS declare -A APPS
@ -66,42 +32,17 @@ declare -A FILES
declare -A LOGS declare -A LOGS
declare -A MINEND declare -A MINEND
declare -A ROOM_PIDS declare -A ROOM_PIDS
# if [ TRUE = "$ALL_VIA_RQ" ]; then declare -a APPS_OLD
# declare -A PIPES declare -A CHECKED_ROOMS
# fi
PLAT_PARMS="" function connName() {
if [ $USE_GTK = FALSE ]; then
PLAT_PARMS="--curses --close-stdin"
fi
usage() {
echo "usage: [env=val *] $0" 1>&2
echo " current env variables and their values: " 1>&2
for VAR in NGAMES NROOMS USE_GTK TIMEOUT HOST PORT DICTS SAVE_GOOD \
MINDEVS MAXDEVS RESIGN_RATIO DROP_N ALL_VIA_RQ SEED; do
echo "$VAR:" $(eval "echo \$${VAR}") 1>&2
done
exit 1
}
connName() {
LOG=$1 LOG=$1
grep 'got_connect_cmd: connName' $LOG | \ grep 'got_connect_cmd: connName' $LOG | \
tail -n 1 | \ tail -n 1 | \
sed 's,^.*connName: \"\(.*\)\"$,\1,' sed 's,^.*connName: \"\(.*\)\"$,\1,'
} }
while [ "$#" -gt 0 ]; do function check_room() {
case $1 in
*) usage
;;
esac
shift
done
declare -A CHECKED_ROOMS
check_room() {
ROOM=$1 ROOM=$1
if [ -z ${CHECKED_ROOMS[$ROOM]:-""} ]; then if [ -z ${CHECKED_ROOMS[$ROOM]:-""} ]; then
NUM=$(echo "SELECT COUNT(*) FROM games "\ NUM=$(echo "SELECT COUNT(*) FROM games "\
@ -120,15 +61,26 @@ check_room() {
fi fi
} }
print_cmdline() {
local COUNTER=$1
local LOG=${LOGS[$COUNTER]}
echo "New cmdline: ${APPS[$COUNTER]} ${ARGS[$COUNTER]}" >> $LOG
}
build_cmds() { build_cmds() {
COUNTER=0 COUNTER=0
PLAT_PARMS=""
if [ $USE_GTK = FALSE ]; then
PLAT_PARMS="--curses --close-stdin"
fi
for GAME in $(seq 1 $NGAMES); do for GAME in $(seq 1 $NGAMES); do
ROOM=$(printf "ROOM_%.3d" $((GAME % NROOMS))) ROOM=$(printf "ROOM_%.3d" $((GAME % NROOMS)))
ROOM_PIDS[$ROOM]=0 ROOM_PIDS[$ROOM]=0
check_room $ROOM check_room $ROOM
NDEVS=$(( $RANDOM % ($MAXDEVS-1) + 2 )) NDEVS=$(( $RANDOM % ($MAXDEVS-1) + 2 ))
[ $NDEVS -lt $MINDEVS ] && NDEVS=$MINDEVS [ $NDEVS -lt $MINDEVS ] && NDEVS=$MINDEVS
DICT=${DICTS_ARR[$((GAME%${#DICTS_ARR[*]}))]} DICT=${DICTS[$((GAME%${#DICTS[*]}))]}
# make one in three games public # make one in three games public
PUBLIC="" PUBLIC=""
[ $((RANDOM%3)) -eq 0 ] && PUBLIC="--make-public --join-public" [ $((RANDOM%3)) -eq 0 ] && PUBLIC="--make-public --join-public"
@ -141,15 +93,24 @@ build_cmds() {
for DEV in $(seq $NDEVS); do for DEV in $(seq $NDEVS); do
FILE="${LOGDIR}/GAME_${GAME}_${DEV}.xwg" FILE="${LOGDIR}/GAME_${GAME}_${DEV}.xwg"
LOG=${LOGDIR}/${GAME}_${DEV}_LOG.txt LOG=${LOGDIR}/${GAME}_${DEV}_LOG.txt
> $LOG # clear the log
touch $LOG # so greps won't show errors touch $LOG # so greps won't show errors
APPS[$COUNTER]=./obj_linux_memdbg/xwords PARAMS=""
PARAMS="--room $ROOM" APPS[$COUNTER]="$APP_NEW"
BOARD_SIZE="--board-size ${BOARD_SIZES_NEW[$((RANDOM%${#BOARD_SIZES_NEW[*]}))]}"
if [ xx = "${APPS_OLD+xx}" ]; then
# 50% chance of starting out with old app
if [ 0 -eq $((RANDOM%2)) ]; then
APPS[$COUNTER]=${APPS_OLD[$((RANDOM%${#APPS_OLD[*]}))]}
BOARD_SIZE="--board-size ${BOARD_SIZES_OLD[$((RANDOM%${#BOARD_SIZES_OLD[*]}))]}"
fi
fi
PARAMS="$PARAMS $BOARD_SIZE --room $ROOM"
PARAMS="$PARAMS --robot ${NAMES[$DEV]} --robot-iq $((1 + (RANDOM%100))) " PARAMS="$PARAMS --robot ${NAMES[$DEV]} --robot-iq $((1 + (RANDOM%100))) "
PARAMS="$PARAMS $OTHERS --game-dict $DICT --port $PORT --host $HOST " PARAMS="$PARAMS $OTHERS --game-dict $DICT --port $PORT --host $HOST "
PARAMS="$PARAMS --file $FILE --slow-robot 1:3 --skip-confirm" PARAMS="$PARAMS --file $FILE --slow-robot 1:3 --skip-confirm"
PARAMS="$PARAMS --drop-nth-packet $DROP_N $PLAT_PARMS" PARAMS="$PARAMS --drop-nth-packet $DROP_N $PLAT_PARMS"
[ -n "$SEED" ] && PARAMS="$PARAMS --seed $RANDOM" [ -n "$SEED" ] && PARAMS="$PARAMS --seed $RANDOM"
PARAMS="$PARAMS --board-size ${BOARD_SIZES[$((RANDOM%${#BOARD_SIZES[*]}))]}"
PARAMS="$PARAMS $PUBLIC" PARAMS="$PARAMS $PUBLIC"
ARGS[$COUNTER]=$PARAMS ARGS[$COUNTER]=$PARAMS
ROOMS[$COUNTER]=$ROOM ROOMS[$COUNTER]=$ROOM
@ -157,7 +118,7 @@ build_cmds() {
LOGS[$COUNTER]=$LOG LOGS[$COUNTER]=$LOG
PIDS[$COUNTER]=0 PIDS[$COUNTER]=0
echo "${APPS[$COUNTER]} ${PARAMS}" > $LOG print_cmdline $COUNTER
COUNTER=$((COUNTER+1)) COUNTER=$((COUNTER+1))
done done
@ -268,6 +229,19 @@ maybe_resign() {
fi fi
} }
try_upgrade() {
KEY=$1
if [ xx = "${APPS_OLD+xx}" ]; then
if [ $APP_NEW != ${APPS[$KEY]} ]; then
# one in five chance of upgrading
if [ 0 -eq $((RANDOM % UPGRADE_ODDS)) ]; then
APPS[$KEY]=$APP_NEW
print_cmdline $KEY
fi
fi
fi
}
check_game() { check_game() {
KEY=$1 KEY=$1
LOG=${LOGS[$KEY]} LOG=${LOGS[$KEY]}
@ -330,7 +304,6 @@ run_cmds() {
ENDTIME=$(($(date +%s) + TIMEOUT)) ENDTIME=$(($(date +%s) + TIMEOUT))
while :; do while :; do
COUNT=${#ARGS[*]} COUNT=${#ARGS[*]}
echo "COUNT: $COUNT"
[ 0 -ge $COUNT ] && break [ 0 -ge $COUNT ] && break
NOW=$(date '+%s') NOW=$(date '+%s')
[ $NOW -ge $ENDTIME ] && break [ $NOW -ge $ENDTIME ] && break
@ -342,6 +315,7 @@ run_cmds() {
if [ -n "$ONE_PER_ROOM" -a 0 -ne ${ROOM_PIDS[$ROOM]} ]; then if [ -n "$ONE_PER_ROOM" -a 0 -ne ${ROOM_PIDS[$ROOM]} ]; then
continue continue
fi fi
try_upgrade $KEY
launch $KEY & launch $KEY &
PID=$! PID=$!
PIDS[$KEY]=$PID PIDS[$KEY]=$PID
@ -408,10 +382,141 @@ run_via_rq() {
done done
} # run_via_rq } # run_via_rq
print_stats() { function getArg() {
: [ 1 -lt "$#" ] || usage "$1 requires an argument"
echo $2
} }
function usage() {
[ $# -gt 0 ] && echo "Error: $1" >&2
echo "Usage: $(basename $0) \\" >&2
echo " [--dict <path/to/dict>]* \\" >&2
echo " [--old-app <path/to/app]* \\" >&2
echo " [--new-app <path/to/app] \\" >&2
echo " [--min-devs <int>] \\" >&2
echo " [--max-devs <int>] \\" >&2
echo " [--help] \\" >&2
echo " [--num-games <int>] \\" >&2
echo " [--num-rooms <int>] \\" >&2
echo " [--host <hostname>] \\" >&2
echo " [--port <int>] \\" >&2
echo " [--seed <int>] \\" >&2
echo " [--help] \\" >&2
exit 1
}
#######################################################
##################### MAIN begins #####################
#######################################################
while [ "$#" -gt 0 ]; do
case $1 in
--num-games)
NGAMES=$(getArg $*)
shift
;;
--num-rooms)
NROOMS=$(getArg $*)
shift
;;
--old-app)
APPS_OLD[${#APPS_OLD[@]}]=$(getArg $*)
shift
;;
--new-app)
APP_NEW=$(getArg $*)
shift
;;
--dict)
DICTS[${#DICTS[@]}]=$(getArg $*)
shift
;;
--min-devs)
MINDEVS=$(getArg $*)
shift
;;
--max-devs)
MAXDEVS=$(getArg $*)
shift
;;
--host)
HOST=$(getArg $*)
shift
;;
--port)
PORT=$(getArg $*)
shift
;;
--seed)
SEED=$(getArg $*)
shift
;;
--help)
usage
;;
*) usage "unrecognized option $1"
;;
esac
shift
done
# Assign defaults
#[ 0 -eq ${#DICTS[@]} ] && DICTS=(dict.xwd)
[ xx = "${DICTS+xx}" ] || DICTS=(dict.xwd)
[ -z "$APP_NEW" ] && APP_NEW=./obj_linux_memdbg/xwords
[ -z "$MINDEVS" ] && MINDEVS=2
[ -z "$MAXDEVS" ] && MAXDEVS=4
[ -z "$NGAMES" ] && NGAMES=1
[ -z "$NROOMS" ] && NROOMS=$NGAMES
[ -z "$HOST" ] && HOST=localhost
[ -z "$PORT" ] && PORT=10997
[ -z "$TIMEOUT" ] && TIMEOUT=$((NGAMES*60+500))
[ -z "$SAVE_GOOD" ] && SAVE_GOOD=YES
[ -z "$RESIGN_RATIO" ] && RESIGN_RATIO=1000
[ -z "$DROP_N" ] && DROP_N=0
[ -z "$USE_GTK" ] && USE_GTK=FALSE
[ -z "$UPGRADE_ODDS" ] && UPGRADE_ODDS=10
#$((NGAMES/50))
[ 0 -eq $UPGRADE_ODDS ] && UPGRADE_ODDS=1
LOGDIR=$(basename $0)_logs
RESUME=""
for FILE in $(ls $LOGDIR/*.{xwg,txt} 2>/dev/null); do
if [ -e $FILE ]; then
echo "Unfinished games found in $LOGDIR; continue with them (or discard)?"
read -p "<yes/no> " ANSWER
case "$ANSWER" in
y|yes|Y|YES)
RESUME=1
;;
*)
;;
esac
fi
break
done
if [ -z "$RESUME" -a -d $LOGDIR ];then
mv $LOGDIR /tmp/${LOGDIR}_$$
fi
mkdir -p $LOGDIR
if [ "$SAVE_GOOD" = YES ]; then
DONEDIR=$LOGDIR/done
mkdir -p $DONEDIR
fi
DEADDIR=$LOGDIR/dead
mkdir -p $DEADDIR
for VAR in NGAMES NROOMS USE_GTK TIMEOUT HOST PORT SAVE_GOOD \
MINDEVS MAXDEVS RESIGN_RATIO DROP_N ALL_VIA_RQ SEED \
APP_NEW; do
echo "$VAR:" $(eval "echo \$${VAR}") 1>&2
done
echo "DICTS: ${DICTS[*]}"
echo -n "APPS_OLD: "; [ xx = "${APPS_OLD[*]+xx}" ] && echo "APPS_OLD: ${APPS_OLD[*]}" || echo ""
echo "*********$0 starting: $(date)**************" echo "*********$0 starting: $(date)**************"
STARTTIME=$(date +%s) STARTTIME=$(date +%s)
[ -z "$RESUME" ] && build_cmds || read_resume_cmds [ -z "$RESUME" ] && build_cmds || read_resume_cmds
@ -420,7 +525,6 @@ if [ TRUE = "$ALL_VIA_RQ" ]; then
else else
run_cmds run_cmds
fi fi
print_stats
wait wait