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
gen
libs
proguard.cfg

View file

@ -34,7 +34,7 @@
<!-- <uses-permission android:name="android.permission.RECEIVE_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"
android:label="@string/app_name"

View file

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

View file

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

View file

@ -34,17 +34,29 @@ import android.view.MotionEvent;
import android.graphics.drawable.Drawable;
import android.content.res.Resources;
import android.graphics.Paint.FontMetricsInt;
import android.os.Build;
import android.os.Handler;
import java.nio.IntBuffer;
import android.util.FloatMath;
import junit.framework.Assert;
public class BoardView extends View implements DrawCtx, BoardHandler,
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 Bitmap s_bitmap; // the board
private static final int IN_TRADE_ALPHA = 0x3FFFFFFF;
private static final int PINCH_THRESHOLD = 40;
private Context m_context;
private Paint m_drawPaint;
@ -83,6 +95,8 @@ public class BoardView extends View implements DrawCtx, BoardHandler,
private int m_pendingScore;
private Handler m_viewHandler;
private MultiHandlerIface m_multiHandler = null;
// FontDims: exists to translate space available to the largest
// font we can draw within that space taking advantage of our use
// 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
private class FontDims {
FontDims( float askedHt, int topRow, int bottomRow, float width ) {
// Utils.logf( "FontDims(): askedHt=" + askedHt );
// Utils.logf( "FontDims(): topRow=" + topRow );
// Utils.logf( "FontDims(): bottomRow=" + bottomRow );
// Utils.logf( "FontDims(): width=" + width );
// DbgUtils.logf( "FontDims(): askedHt=" + askedHt );
// DbgUtils.logf( "FontDims(): topRow=" + topRow );
// DbgUtils.logf( "FontDims(): bottomRow=" + bottomRow );
// DbgUtils.logf( "FontDims(): width=" + width );
float gotHt = bottomRow - topRow + 1;
m_htProportion = gotHt / askedHt;
Assert.assertTrue( (bottomRow+1) >= askedHt );
float descent = (bottomRow+1) - askedHt;
// Utils.logf( "descent: " + descent );
// DbgUtils.logf( "descent: " + descent );
m_descentProportion = descent / askedHt;
Assert.assertTrue( m_descentProportion >= 0 );
m_widthProportion = width / askedHt;
// Utils.logf( "m_htProportion: " + m_htProportion );
// Utils.logf( "m_descentProportion: " + m_descentProportion );
// DbgUtils.logf( "m_htProportion: " + m_htProportion );
// DbgUtils.logf( "m_descentProportion: " + m_descentProportion );
}
private float m_htProportion;
private float m_descentProportion;
@ -168,6 +182,15 @@ public class BoardView extends View implements DrawCtx, BoardHandler,
}
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
@ -179,17 +202,41 @@ public class BoardView extends View implements DrawCtx, BoardHandler,
switch ( action ) {
case MotionEvent.ACTION_DOWN:
if ( null != m_multiHandler ) {
m_multiHandler.deactivate();
}
m_jniThread.handle( JNIThread.JNICmd.CMD_PEN_DOWN, xx, yy );
break;
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;
case MotionEvent.ACTION_UP:
m_jniThread.handle( JNIThread.JNICmd.CMD_PEN_UP, xx, yy );
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:
Utils.logf( "unknown action: %d", action );
Utils.logf( event.toString() );
DbgUtils.logf( "unknown action: %d", action );
break;
}
return true; // required to get subsequent events
@ -215,7 +262,7 @@ public class BoardView extends View implements DrawCtx, BoardHandler,
int nCells = gi.boardSize;
int cellSize = width / nCells;
int maxCellSize = 3 * m_defaultFontHt;
int maxCellSize = 4 * m_defaultFontHt;
if ( cellSize > maxCellSize ) {
cellSize = maxCellSize;
@ -313,7 +360,7 @@ public class BoardView extends View implements DrawCtx, BoardHandler,
drew = XwJNI.board_draw( m_jniGamePtr );
}
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
descent = fontDims.descentFor( height );
textSize = fontDims.heightFor( height );
// Utils.logf( "using descent: " + descent + " and textSize: "
// DbgUtils.logf( "using descent: " + descent + " and textSize: "
// + textSize + " in height " + height );
}
m_fillPaint.setTextSize( textSize );
@ -829,13 +876,13 @@ public class BoardView extends View implements DrawCtx, BoardHandler,
Canvas canvas = new Canvas( bitmap );
// FontMetrics fmi = paint.getFontMetrics();
// Utils.logf( "ascent: " + fmi.ascent );
// Utils.logf( "bottom: " + fmi.bottom );
// Utils.logf( "descent: " + fmi.descent );
// Utils.logf( "leading: " + fmi.leading );
// Utils.logf( "top : " + fmi.top );
// DbgUtils.logf( "ascent: " + fmi.ascent );
// DbgUtils.logf( "bottom: " + fmi.bottom );
// DbgUtils.logf( "descent: " + fmi.descent );
// DbgUtils.logf( "leading: " + fmi.leading );
// DbgUtils.logf( "top : " + fmi.top );
// Utils.logf( "using as baseline: " + ht );
// DbgUtils.logf( "using as baseline: " + ht );
Rect bounds = new Rect();
int maxWidth = 0;
@ -855,7 +902,7 @@ public class BoardView extends View implements DrawCtx, BoardHandler,
// int pixel = bitmap.getPixel( col, row );
// sb.append( pixel==0? "." : "X" );
// }
// Utils.logf( sb.append(row).toString() );
// DbgUtils.logf( sb.append(row).toString() );
// }
int topRow = 0;
@ -949,4 +996,52 @@ public class BoardView extends View implements DrawCtx, BoardHandler,
}
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();
} catch ( java.io.IOException ioe ) {
Utils.logf( ioe.toString() );
DbgUtils.logf( ioe.toString() );
} catch ( UnresolvedAddressException uae ) {
Utils.logf( "bad address: name: %s; port: %s; exception: %s",
m_addr.ip_relay_hostName, m_addr.ip_relay_port,
uae.toString() );
DbgUtils.logf( "bad address: name: %s; port: %s; exception: %s",
m_addr.ip_relay_hostName, m_addr.ip_relay_port,
uae.toString() );
}
m_thread = null;
@ -118,15 +118,15 @@ public class CommsTransport implements TransportProcs,
try {
m_socketChannel = SocketChannel.open();
m_socketChannel.configureBlocking( false );
Utils.logf( "connecting to %s:%d",
m_addr.ip_relay_hostName,
m_addr.ip_relay_port );
DbgUtils.logf( "connecting to %s:%d",
m_addr.ip_relay_hostName,
m_addr.ip_relay_port );
InetSocketAddress isa = new
InetSocketAddress(m_addr.ip_relay_hostName,
m_addr.ip_relay_port );
m_socketChannel.connect( isa );
} catch ( java.io.IOException ioe ) {
Utils.logf( ioe.toString() );
DbgUtils.logf( ioe.toString() );
failed = true;
break outer_loop;
}
@ -134,7 +134,7 @@ public class CommsTransport implements TransportProcs,
if ( null != m_socketChannel ) {
int ops = figureOps();
// Utils.logf( "calling with ops=%x", ops );
// DbgUtils.logf( "calling with ops=%x", 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!
failed = true;
closeSocket();
Utils.logf( "exiting: %s", cce.toString() );
DbgUtils.logf( "exiting: %s", cce.toString() );
break; // don't try again
} catch ( java.io.IOException ioe ) {
closeSocket();
Utils.logf( "exiting: %s", ioe.toString() );
Utils.logf( ioe.toString() );
DbgUtils.logf( "exiting: %s", ioe.toString() );
DbgUtils.logf( ioe.toString() );
} catch ( java.nio.channels.NoConnectionPendingException ncp ) {
Utils.logf( "%s", ncp.toString() );
DbgUtils.logf( "%s", ncp.toString() );
closeSocket();
break;
}
@ -168,7 +168,7 @@ public class CommsTransport implements TransportProcs,
}
if (key.isValid() && key.isReadable()) {
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() );
int nRead = channel.read( m_bytesIn );
if ( nRead == -1 ) {
@ -181,17 +181,17 @@ public class CommsTransport implements TransportProcs,
getOut();
if ( null != m_bytesOut ) {
int nWritten = channel.write( m_bytesOut );
//Utils.logf( "wrote " + nWritten + " bytes" );
//DbgUtils.logf( "wrote " + nWritten + " bytes" );
}
}
} catch ( java.io.IOException ioe ) {
Utils.logf( "%s: cancelling key", ioe.toString() );
DbgUtils.logf( "%s: cancelling key", ioe.toString() );
key.cancel();
failed = true;
break outer_loop;
} catch ( java.nio.channels.
NoConnectionPendingException ncp ) {
Utils.logf( "%s", ncp.toString() );
DbgUtils.logf( "%s", ncp.toString() );
break outer_loop;
}
}
@ -241,7 +241,7 @@ public class CommsTransport implements TransportProcs,
try {
m_socketChannel.close();
} catch ( Exception e ) {
Utils.logf( "closing socket: %s", e.toString() );
DbgUtils.logf( "closing socket: %s", e.toString() );
}
m_socketChannel = null;
}
@ -319,7 +319,7 @@ public class CommsTransport implements TransportProcs,
try {
m_thread.join(100); // wait up to 1/10 second
} catch ( java.lang.InterruptedException ie ) {
Utils.logf( "got InterruptedException: %s", ie.toString() );
DbgUtils.logf( "got InterruptedException: %s", ie.toString() );
}
m_thread = null;
}
@ -331,7 +331,7 @@ public class CommsTransport implements TransportProcs,
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;
if ( null == m_addr ) {
@ -362,7 +362,7 @@ public class CommsTransport implements TransportProcs,
// to verify. IFF the plan's to ship a version that
// 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 );
// try {
// Intent intent = new Intent( m_context, StatusReceiver.class);
@ -373,17 +373,17 @@ public class CommsTransport implements TransportProcs,
// SmsManager.getDefault().sendTextMessage( m_addr.sms_phone,
// null, "Hello world",
// pi, pi );
// Utils.logf( "called sendTextMessage" );
// DbgUtils.logf( "called sendTextMessage" );
// } else {
// SmsManager.getDefault().
// sendDataMessage( m_addr.sms_phone, (String)null,
// (short)m_addr.sms_port,
// buf, pi, pi );
// Utils.logf( "called sendDataMessage" );
// DbgUtils.logf( "called sendDataMessage" );
// }
// nSent = buf.length;
// } catch ( java.lang.IllegalArgumentException iae ) {
// Utils.logf( iae.toString() );
// DbgUtils.logf( iae.toString() );
// }
break;
case COMMS_CONN_BT:
@ -395,17 +395,17 @@ public class CommsTransport implements TransportProcs,
// Keep this while debugging why the resend_all that gets
// fired on reconnect doesn't unstall a game but a manual
// resend does.
Utils.logf( "transportSend(%d)=>%d", buf.length, nSent );
DbgUtils.logf( "transportSend(%d)=>%d", buf.length, nSent );
return nSent;
}
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 ) {
m_jniThread.handle( JNICmd.CMD_DRAW_CONNS_STATUS, newState );
} 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
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 ) {
case 5:

View file

@ -456,7 +456,7 @@ public class DBUtils {
long result = db.replaceOrThrow( DBHelper.TABLE_NAME_OBITS,
"", values );
} catch ( Exception ex ) {
Utils.logf( "ex: %s", ex.toString() );
DbgUtils.logf( "ex: %s", ex.toString() );
}
db.close();
}
@ -566,7 +566,7 @@ public class DBUtils {
Assert.fail();
// values.put( DBHelper.FILE_NAME, path );
// rowid = db.insert( DBHelper.TABLE_NAME_SUM, null, values );
// Utils.logf( "insert=>%d", rowid );
// DbgUtils.logf( "insert=>%d", rowid );
// Assert.assertTrue( row >= 0 );
}
db.close();
@ -688,7 +688,7 @@ public class DBUtils {
values, selection, null );
db.close();
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 {
super.finalize();
} 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 ) {
getListView().setSelection( pos );
} else {
Utils.showf( this, R.string.dict_browse_nowordsf,
m_name, text );
DbgUtils.showf( this, R.string.dict_browse_nowordsf,
m_name, text );
}
}
}

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -109,7 +109,7 @@ public class GameListAdapter extends XWListAdapter {
@Override
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 );
boolean hideTitle = false;//CommonPrefs.getHideTitleBar(m_context);
GameSummary summary = DBUtils.getSummary( m_context, m_rowid, false );
@ -221,7 +221,7 @@ public class GameListAdapter extends XWListAdapter {
@Override
protected void onPostExecute( Void unused )
{
// Utils.logf( "onPostExecute(id=%d)", m_id );
// DbgUtils.logf( "onPostExecute(id=%d)", m_id );
if ( -1 != m_rowid ) {
m_cb.itemLoaded( m_rowid );
}

View file

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

View file

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

View file

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

View file

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

View file

@ -31,7 +31,7 @@
// @Override
// public void onReceive( Context context, Intent intent )
// {
// Utils.logf( "NBSReceiver::onReceive(intent=%s)!!!!",
// DbgUtils.logf( "NBSReceiver::onReceive(intent=%s)!!!!",
// intent.toString() );
// }
@ -46,9 +46,9 @@
// data, null, null );
// // PendingIntent sentIntent,
// // PendingIntent deliveryIntent );
// Utils.logf( "sendDataMessage finished" );
// DbgUtils.logf( "sendDataMessage finished" );
// } 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 );
m_valid = true;
} 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.
getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
Utils.logf( "CommsBroadcastReceiver.onReceive: %s",
ni.getState().toString() );
DbgUtils.logf( "CommsBroadcastReceiver.onReceive: %s",
ni.getState().toString() );
boolean netAvail;
switch ( ni.getState() ) {

View file

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

View file

@ -146,7 +146,7 @@ public class PrefsActivity extends PreferenceActivity
public void onSharedPreferenceChanged( SharedPreferences sp, String key )
{
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
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();
SmsMessage[] smsarr = null;
@ -40,7 +40,7 @@ public class ReceiveNBS extends BroadcastReceiver {
smsarr = new SmsMessage[pdus.length];
for ( int ii = 0; ii < pdus.length; 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() );
// XwJni.handle( XwJni.JNICmd.CMD_RECEIVE,
// smsarr[ii].getMessageBody() );

View file

@ -67,7 +67,7 @@ public class RefreshNamesTask extends AsyncTask<Void, Void, String[]> {
protected String[] doInBackground( Void...unused )
{
ArrayList<String> names = new ArrayList<String>();
Utils.logf( "doInBackground()" );
DbgUtils.logf( "doInBackground()" );
try {
Socket socket = NetUtils.MakeProxySocket( m_context, 15000 );
@ -87,7 +87,7 @@ public class RefreshNamesTask extends AsyncTask<Void, Void, String[]> {
new DataInputStream(socket.getInputStream());
short len = 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
// from DataInputStream so parse it myself.
@ -101,16 +101,16 @@ public class RefreshNamesTask extends AsyncTask<Void, Void, String[]> {
++index;
}
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( "/" );
indx = name.lastIndexOf( "/", indx-1 );
names.add( name.substring(0, indx ) );
}
}
} 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()] );
}
@ -121,7 +121,7 @@ public class RefreshNamesTask extends AsyncTask<Void, Void, String[]> {
@Override
protected void onPostExecute( String[] result )
{
Utils.logf( "onPostExecute()" );
DbgUtils.logf( "onPostExecute()" );
ArrayAdapter<String> adapter =
new ArrayAdapter<String>( m_context,
android.R.layout.simple_spinner_item,
@ -136,6 +136,6 @@ public class RefreshNamesTask extends AsyncTask<Void, Void, String[]> {
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()
&& intent.getAction().equals( Intent.ACTION_BOOT_COMPLETED ) ) {
Utils.logf( "launching timer on boot" );
DbgUtils.logf( "launching timer on boot" );
RestartTimer( context );
} else {
// Utils.logf( "RelayReceiver::onReceive()" );
// DbgUtils.logf( "RelayReceiver::onReceive()" );
// if ( XWConstants.s_showProxyToast ) {
// Toast.makeText(context, "RelayReceiver: fired",
// Toast.LENGTH_SHORT).show();
@ -83,7 +83,7 @@ public class RelayReceiver extends BroadcastReceiver {
PendingIntent pi = PendingIntent.getBroadcast( context, 0, intent, 0 );
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,
0, // first firing
interval_millis, pi );

View file

@ -29,7 +29,7 @@ public class StatusReceiver extends BroadcastReceiver {
@Override
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;
import android.util.Log;
import java.lang.Thread;
import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.widget.CheckBox;
import android.widget.Toast;
import android.widget.EditText;
import android.widget.TextView;
import android.view.LayoutInflater;
import android.view.View;
import android.text.format.Time;
import java.util.Formatter;
import junit.framework.Assert;
import org.eehouse.android.xw4.jni.*;
public class Utils {
static final String TAG = "XW4";
static final String DB_PATH = "XW_GAMES";
static boolean s_doLog = true;
private static Time s_time = new Time();
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 )
{
CharSequence text = "Feature coming soon";

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -22,7 +22,7 @@ package org.eehouse.android.xw4.jni;
import android.content.Context;
import org.eehouse.android.xw4.Utils;
import org.eehouse.android.xw4.DbgUtils;
import org.eehouse.android.xw4.R;
public class UtilCtxtImpl implements UtilCtxt {
@ -173,7 +173,7 @@ public class UtilCtxtImpl implements UtilCtxt {
id = R.string.strd_turn_score;
break;
default:
Utils.logf( "no such stringCode: %d", stringCode );
DbgUtils.logf( "no such stringCode: %d", stringCode );
}
String result;
@ -227,7 +227,7 @@ public class UtilCtxtImpl implements UtilCtxt {
}
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
# 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 ""

View file

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

View file

@ -52,6 +52,11 @@
#endif
#define STREAM_SAVE_PREVWORDS 0x11
#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_SAVE_PREVMOVE 0x0E /* server saves prev move explanation */
#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
getModelTileRaw( const ModelCtxt* model, XP_U16 col, XP_U16 row )
{
CellTile tile;
XP_U16 nCols = model->nCols;
XP_ASSERT( model->nRows == nCols );
if ( col < nCols && row < nCols ) {
tile = model->vol.tiles[(row*nCols) + col];
} else {
tile = TILE_EMPTY_BIT;
}
return tile;
XP_ASSERT( col < nCols );
XP_ASSERT( row < nCols );
return model->vol.tiles[(row*nCols) + col];
} /* getModelTileRaw */
static void

View file

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

View file

@ -292,9 +292,8 @@ getNV( XWStreamCtxt* stream, ServerNonvolatiles* nv, XP_U16 nPlayers )
nv->addresses[ii].channelNo =
(XP_PlayerAddr)stream_getBits( stream, 16 );
#ifdef STREAM_VERS_BIGBOARD
if ( STREAM_VERS_BIGBOARD <= version ) {
nv->addresses[ii].streamVersion = stream_getBits( stream, 8 );
}
nv->addresses[ii].streamVersion = STREAM_VERS_BIGBOARD <= version ?
stream_getBits( stream, 8 ) : STREAM_SAVE_PREVWORDS;
#endif
}
#ifdef STREAM_VERS_BIGBOARD
@ -641,8 +640,20 @@ setStreamVersion( ServerCtxt* server )
XP_LOGF( "%s: setting streamVersion: %d", __func__, 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
# define setStreamVersion(s)
# define checkResizeBoard(s)
# endif
static XP_Bool
@ -691,6 +702,7 @@ handleRegistrationMsg( ServerCtxt* server, XWStreamCtxt* stream )
if ( server->nv.pendingRegistrations == 0 ) {
XP_ASSERT( ii == playersInMsg ); /* otherwise malformed */
setStreamVersion( server );
checkResizeBoard( server );
assignTilesToAll( server );
SETSTATE( server, XWSTATE_RECEIVED_ALL_REG );
}
@ -1170,7 +1182,7 @@ client_readInitialMessage( ServerCtxt* server, XWStreamCtxt* stream )
DictionaryCtxt* curDict;
XP_U16 nPlayers, nCols;
XP_PlayerAddr channelNo;
short i;
XP_U16 ii;
ModelCtxt* model = server->vol.model;
CurGameInfo* gi = server->vol.gi;
CurGameInfo localGI;
@ -1181,6 +1193,7 @@ client_readInitialMessage( ServerCtxt* server, XWStreamCtxt* stream )
XP_U8 streamVersion = stream_getU8( stream );
XP_LOGF( "%s: set streamVersion to %d", __func__, streamVersion );
stream_setVersion( stream, streamVersion );
// XP_ASSERT( streamVersion <= CUR_STREAM_VERS ); /* else do what? */
gameID = stream_getU32( stream );
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
remove them from the newly-created local pool. */
for ( i = 0; i < nPlayers; ++i ) {
for ( ii = 0; ii < nPlayers; ++ii ) {
TrayTileSet tiles;
traySetFromStream( stream, &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
later. */
pool_removeTiles( pool, &tiles );
sortTilesIf( server, i );
sortTilesIf( server, ii );
}
syncPlayers( server );
@ -1283,25 +1296,25 @@ makeSendableGICopy( ServerCtxt* server, CurGameInfo* giCopy,
{
XP_U16 nPlayers;
LocalPlayer* clientPl;
XP_U16 i;
XP_U16 ii;
XP_MEMCPY( giCopy, server->vol.gi, sizeof(*giCopy) );
nPlayers = giCopy->nPlayers;
for ( clientPl = giCopy->players, i = 0;
i < nPlayers; ++clientPl, ++i ) {
for ( clientPl = giCopy->players, ii = 0;
ii < nPlayers; ++clientPl, ++ii ) {
/* 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
a leak? PENDING */
giCopy->dictName = (XP_UCHAR*)NULL; /* so we don't sent the bytes */
} /* makeSendableGICopy */
static void
server_sendInitialMessage( ServerCtxt* server )
{
short i;
XP_U16 ii;
XP_U16 deviceIndex;
ModelCtxt* model = server->vol.model;
XP_U16 nPlayers = server->vol.gi->nPlayers;
@ -1319,7 +1332,12 @@ server_sendInitialMessage( ServerCtxt* server )
stream_open( stream );
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 );
#endif
XP_LOGF( "putting gameID %lx into msg", gameID );
stream_putU32( stream, gameID );
@ -1330,8 +1348,8 @@ server_sendInitialMessage( ServerCtxt* server )
dict_writeToStream( dict, stream );
/* send tiles currently in tray */
for ( i = 0; i < nPlayers; ++i ) {
model_trayToStream( model, i, stream );
for ( ii = 0; ii < nPlayers; ++ii ) {
model_trayToStream( model, ii, stream );
}
stream_destroy( stream );
@ -1692,7 +1710,7 @@ static void
assignTilesToAll( ServerCtxt* server )
{
XP_U16 numAssigned;
short i;
XP_U16 ii;
ModelCtxt* model = server->vol.model;
XP_U16 nPlayers = server->vol.gi->nPlayers;
@ -1712,11 +1730,11 @@ assignTilesToAll( ServerCtxt* server )
if ( numAssigned > MAX_TRAY_TILES ) {
numAssigned = MAX_TRAY_TILES;
}
for ( i = 0; i < nPlayers; ++i ) {
for ( ii = 0; ii < nPlayers; ++ii ) {
TrayTileSet newTiles;
fetchTiles( server, i, numAssigned, NULL, &newTiles );
model_assignPlayerTiles( model, i, &newTiles );
sortTilesIf( server, i );
fetchTiles( server, ii, numAssigned, NULL, &newTiles );
model_assignPlayerTiles( model, ii, &newTiles );
sortTilesIf( server, ii );
}
} /* 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 */
trayTop -= vscale * globals->cGlobals.params->nHidden;
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 ); */
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->nexthint_button, canHing );
#ifdef XWFEATURE_CHAT
XP_Bool canChat = !!globals->cGlobals.game.comms
&& comms_canChat( globals->cGlobals.game.comms );
gtk_widget_set_sensitive( globals->chat_button, canChat );
#endif
}
static gboolean
@ -1894,12 +1896,13 @@ makeVerticalBar( GtkAppGlobals* globals, GtkWidget* XP_UNUSED(window) )
gtk_box_pack_start( GTK_BOX(vbox), button, FALSE, TRUE, 0 );
button = makeShowButtonFromBitmap( globals, "../done.xpm", "-",
G_CALLBACK(handle_zoomout_button) );
gtk_box_pack_start( GTK_BOX(vbox), button, FALSE, TRUE, 0 );
#ifdef XWFEATURE_CHAT
button = makeShowButtonFromBitmap( globals, "", "chat",
G_CALLBACK(handle_chat_button) );
globals->chat_button = button;
#endif
gtk_box_pack_start( GTK_BOX(vbox), button, FALSE, TRUE, 0 );
#endif
gtk_widget_show( vbox );
return vbox;

View file

@ -1,62 +1,28 @@
#!/bin/bash
set -u -e
NGAMES=${NGAMES:-1}
NROOMS=${NROOMS:-$NGAMES}
HOST=${HOST:-localhost}
PORT=${PORT:-10997}
TIMEOUT=${TIMEOUT:-$((NGAMES*60+500))}
DICTS=${DICTS:-dict.xwd}
SAVE_GOOD=${SAVE_GOOD:-YES}
MINDEVS=${MINDEVS:-2}
MAXDEVS=${MAXDEVS:-4}
RESIGN_RATIO=${RESIGN_RATIO:-1000}
DROP_N=${DROP_N:-0}
APP_NEW=""
NGAMES=""
UPGRADE_ODDS=""
NROOMS=""
HOST=""
PORT=""
TIMEOUT=""
SAVE_GOOD=""
MINDEVS=""
MAXDEVS=""
RESIGN_RATIO=""
DROP_N=""
MINRUN=2
ONE_PER_ROOM=""
USE_GTK=""
ALL_VIA_RQ=${ALL_VIA_RQ:-FALSE}
SEED=${SEED:-""}
#BOARD_SIZES=(15 17)
BOARD_SIZES=(15)
declare -a DICTS_ARR
for DICT in $DICTS; do
DICTS_ARR[${#DICTS_ARR[*]}]=$DICT
done
SEED=""
BOARD_SIZES_OLD=(15)
BOARD_SIZES_NEW=(15)
NAMES=(UNUSED Brynn Ariela Kati Eric)
[ -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 APPS
@ -66,42 +32,17 @@ declare -A FILES
declare -A LOGS
declare -A MINEND
declare -A ROOM_PIDS
# if [ TRUE = "$ALL_VIA_RQ" ]; then
# declare -A PIPES
# fi
declare -a APPS_OLD
declare -A CHECKED_ROOMS
PLAT_PARMS=""
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() {
function connName() {
LOG=$1
grep 'got_connect_cmd: connName' $LOG | \
tail -n 1 | \
sed 's,^.*connName: \"\(.*\)\"$,\1,'
}
while [ "$#" -gt 0 ]; do
case $1 in
*) usage
;;
esac
shift
done
declare -A CHECKED_ROOMS
check_room() {
function check_room() {
ROOM=$1
if [ -z ${CHECKED_ROOMS[$ROOM]:-""} ]; then
NUM=$(echo "SELECT COUNT(*) FROM games "\
@ -120,15 +61,26 @@ check_room() {
fi
}
print_cmdline() {
local COUNTER=$1
local LOG=${LOGS[$COUNTER]}
echo "New cmdline: ${APPS[$COUNTER]} ${ARGS[$COUNTER]}" >> $LOG
}
build_cmds() {
COUNTER=0
PLAT_PARMS=""
if [ $USE_GTK = FALSE ]; then
PLAT_PARMS="--curses --close-stdin"
fi
for GAME in $(seq 1 $NGAMES); do
ROOM=$(printf "ROOM_%.3d" $((GAME % NROOMS)))
ROOM_PIDS[$ROOM]=0
check_room $ROOM
NDEVS=$(( $RANDOM % ($MAXDEVS-1) + 2 ))
[ $NDEVS -lt $MINDEVS ] && NDEVS=$MINDEVS
DICT=${DICTS_ARR[$((GAME%${#DICTS_ARR[*]}))]}
DICT=${DICTS[$((GAME%${#DICTS[*]}))]}
# make one in three games public
PUBLIC=""
[ $((RANDOM%3)) -eq 0 ] && PUBLIC="--make-public --join-public"
@ -141,15 +93,24 @@ build_cmds() {
for DEV in $(seq $NDEVS); do
FILE="${LOGDIR}/GAME_${GAME}_${DEV}.xwg"
LOG=${LOGDIR}/${GAME}_${DEV}_LOG.txt
> $LOG # clear the log
touch $LOG # so greps won't show errors
APPS[$COUNTER]=./obj_linux_memdbg/xwords
PARAMS="--room $ROOM"
PARAMS=""
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 $OTHERS --game-dict $DICT --port $PORT --host $HOST "
PARAMS="$PARAMS --file $FILE --slow-robot 1:3 --skip-confirm"
PARAMS="$PARAMS --drop-nth-packet $DROP_N $PLAT_PARMS"
[ -n "$SEED" ] && PARAMS="$PARAMS --seed $RANDOM"
PARAMS="$PARAMS --board-size ${BOARD_SIZES[$((RANDOM%${#BOARD_SIZES[*]}))]}"
PARAMS="$PARAMS $PUBLIC"
ARGS[$COUNTER]=$PARAMS
ROOMS[$COUNTER]=$ROOM
@ -157,7 +118,7 @@ build_cmds() {
LOGS[$COUNTER]=$LOG
PIDS[$COUNTER]=0
echo "${APPS[$COUNTER]} ${PARAMS}" > $LOG
print_cmdline $COUNTER
COUNTER=$((COUNTER+1))
done
@ -268,6 +229,19 @@ maybe_resign() {
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() {
KEY=$1
LOG=${LOGS[$KEY]}
@ -330,7 +304,6 @@ run_cmds() {
ENDTIME=$(($(date +%s) + TIMEOUT))
while :; do
COUNT=${#ARGS[*]}
echo "COUNT: $COUNT"
[ 0 -ge $COUNT ] && break
NOW=$(date '+%s')
[ $NOW -ge $ENDTIME ] && break
@ -342,6 +315,7 @@ run_cmds() {
if [ -n "$ONE_PER_ROOM" -a 0 -ne ${ROOM_PIDS[$ROOM]} ]; then
continue
fi
try_upgrade $KEY
launch $KEY &
PID=$!
PIDS[$KEY]=$PID
@ -408,10 +382,141 @@ run_via_rq() {
done
} # 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)**************"
STARTTIME=$(date +%s)
[ -z "$RESUME" ] && build_cmds || read_resume_cmds
@ -420,7 +525,6 @@ if [ TRUE = "$ALL_VIA_RQ" ]; then
else
run_cmds
fi
print_stats
wait