Vous êtes sur la page 1sur 47

private ChessBoard cb;

private ChessController ctrl = null;


private boolean mShowThinking;
private boolean mShowBookHints;
private int maxNumArrows;
private GameMode gameMode;
private boolean boardFlipped;
private boolean autoSwapSides;
private int maxDepth;

private TextView status;


private ScrollView moveListScroll;
private TextView moveList;
private TextView thinking;
SharedPreferences settings;

private float scrollSensitivity;


private boolean invertScrollDirection;
private boolean soundEnabled;
private MediaPlayer moveSound;

private final String bookDir = "ChessTastic";


private final String pgnDir = "ChessTastic" + File.separator + "pgn";
private String currentBookFile = "";
private PGNOptions pgnOptions = new PGNOptions();

private long lastVisibleMillis;


private long lastComputationMillis; // Time when engine last showed that it
// was computing.

PgnScreenText gameTextListener;

private DrawerLayout drawerLayoutt;


private ListView listView;
private ActionBarDrawerToggle actionBarDrawerToggle;
private String[] navigationDrawerItems;
private MyAdapter myadapter;

int choice,theme;
public static Context contextOfApplication;

private boolean shouldGoInvisible;


private static final float ALPHA_DIM_VALUE = 1f;

ShowcaseView sv;
private ViewTarget target;
private LinearLayout homelayout;
private SharedPreferences sharedPreferences;
private Toolbar toolbar;

/** Called when the activity is first created. */


@SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

sharedPreferences =
PreferenceManager.getDefaultSharedPreferences(ChessTastic.this);
theme = sharedPreferences.getInt("Theme",R.style.AppThemeGrey);
loadTheme();
super.setTheme(theme);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {

getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
choice = sharedPreferences.getInt("Choice",4);
switch(choice)
{

default:getWindow().setStatusBarColor(getResources().getColor(R.color.darkgrey));br
eak;
}
}

settings = PreferenceManager.getDefaultSharedPreferences(this);
settings.registerOnSharedPreferenceChangeListener(new
OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(
SharedPreferences sharedPreferences, String key) {
readPrefs();
ctrl.setGameMode(gameMode);
ctrl.setMaxDepth(maxDepth);
}
});
Log.d("tag","here is the execution flow",new Exception());
contextOfApplication = this;

initUI(true);

gameTextListener = new PgnScreenText(pgnOptions);


ctrl = new ChessController(this, gameTextListener, pgnOptions);
ctrl.newGame(new GameMode(GameMode.TWO_PLAYERS));

readPrefs();
ctrl.setMaxDepth(maxDepth);
ctrl.newGame(gameMode);
{
byte[] data = null;
if (savedInstanceState != null) {
data = savedInstanceState.getByteArray("gameState");
} else {
String dataStr = settings.getString("gameState", null);
if (dataStr != null)
data = strToByteArr(dataStr);
}
if (data != null)
ctrl.fromByteArray(data);
}

ctrl.setGuiPaused(true);
ctrl.setGuiPaused(false);
ctrl.startGame();

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void dimView(LinearLayout view) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
view.setAlpha(ALPHA_DIM_VALUE);
}
}

@Override
public void onShowcaseViewHide(ShowcaseView showcaseView) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
homelayout.setAlpha(1f);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {

getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
choice = sharedPreferences.getInt("Choice",4);
switch(choice)
{

default:getWindow().setStatusBarColor(getResources().getColor(R.color.darkgrey));br
eak;
}
}
}
}

@Override
public void onShowcaseViewDidHide(ShowcaseView showcaseView) {

@Override
public void onShowcaseViewShow(ShowcaseView showcaseView) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {

getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(getResources().getColor(R.color.darkgrey));}
dimView(homelayout);
}

@Override
public void onShowcaseViewTouchBlocked(MotionEvent motionEvent) {

@Override
protected void onStart() {
super.onStart();
}

public static Context getContextOfApplication(){


return contextOfApplication;
}

protected void saveTheme(int str)


{
SharedPreferences sharedPreferences =
PreferenceManager.getDefaultSharedPreferences(ChessTastic.this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("Theme", str);
editor.commit();
}
protected void loadTheme()
{
SharedPreferences sharedPreferences =
PreferenceManager.getDefaultSharedPreferences(ChessTastic.this);
theme = sharedPreferences.getInt("Theme",R.style.AppThemeGrey);
super.setTheme(theme);
}

private final byte[] strToByteArr(String str) {


int nBytes = str.length() / 2;
byte[] ret = new byte[nBytes];
for (int i = 0; i < nBytes; i++) {
int c1 = str.charAt(i * 2) - 'A';
int c2 = str.charAt(i * 2 + 1) - 'A';
ret[i] = (byte) (c1 * 16 + c2);
}
return ret;
}

private final String byteArrToString(byte[] data) {


StringBuilder ret = new StringBuilder(32768);
int nBytes = data.length;
for (int i = 0; i < nBytes; i++) {
int b = data[i];
if (b < 0)
b += 256;
char c1 = (char) ('A' + (b / 16));
char c2 = (char) ('A' + (b & 15));
ret.append(c1);
ret.append(c2);
}
return ret.toString();
}

@Override
public void onBackPressed() {
if(drawerLayoutt.isDrawerOpen(Gravity.START|Gravity.LEFT)){
drawerLayoutt.closeDrawers();
return;
}
super.onBackPressed();
}

private void displayShowcaseViewOne() {


target = new ViewTarget(R.id.chessboard, this);
sv = new ShowcaseView.Builder(this, true)
.setTarget(target)
.setContentTitle("Welcome")
.setContentText("To play, tap a Chess Piece and then tap the
destination square to move.")
.setStyle(R.style.CustomShowcaseTheme2)
.setShowcaseEventListener(new OnShowcaseEventListener() {

@Override
public void onShowcaseViewShow(final ShowcaseView scv) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
{
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);

getWindow().setStatusBarColor(getResources().getColor(R.color.darkgrey));
}
dimView(homelayout);
}

@Override
public void onShowcaseViewTouchBlocked(MotionEvent motionEvent)
{

@Override
public void onShowcaseViewHide(final ShowcaseView scv) {
scv.setVisibility(View.GONE);
showOverlayTutorialTwo();
}

@Override
public void onShowcaseViewDidHide(final ShowcaseView scv) {
}

})
.build();
}

public void showOverlayTutorialTwo() {


target = new ViewTarget(R.id.moveList, this);
sv = new ShowcaseView.Builder(this, true)
.setTarget(target)
.setContentTitle("Move List")
.setContentText("This box shows the details of the moves in the
game. The text size can be adjusted in settings.")
.setStyle(R.style.CustomShowcaseTheme2)
.setShowcaseEventListener(new OnShowcaseEventListener() {

@Override
public void onShowcaseViewShow(final ShowcaseView scv) {
}

@Override
public void onShowcaseViewTouchBlocked(MotionEvent motionEvent)
{

@Override
public void onShowcaseViewHide(final ShowcaseView scv) {
showOverlayTutorialThree();
scv.setVisibility(View.GONE);
}

@Override
public void onShowcaseViewDidHide(final ShowcaseView scv) {
}

})
.build();
}

public void showOverlayTutorialThree() {


//target = new ViewTarget(R.id.moveList, this);
Target viewTarget = new Target() {
@Override
public Point getPoint() {
return new
ViewTarget(toolbar.findViewById(R.id.item_redo)).getPoint();
}
};
sv = new ShowcaseView.Builder(this, true)
.setTarget(viewTarget)
.setContentTitle("Undo and Redo")
.setContentText("Use the Undo and Redo Buttons to go back and forth
between moves.")
.setStyle(R.style.CustomShowcaseTheme2)
.setShowcaseEventListener(new OnShowcaseEventListener() {

@Override
public void onShowcaseViewShow(final ShowcaseView scv) { }

@Override
public void onShowcaseViewTouchBlocked(MotionEvent motionEvent)
{

@Override
public void onShowcaseViewHide(final ShowcaseView scv) {
drawerLayoutt.openDrawer(Gravity.LEFT);
showOverlayTutorialFour();
scv.setVisibility(View.GONE);
}

@Override
public void onShowcaseViewDidHide(final ShowcaseView scv) { }

})
.build();

public void showOverlayTutorialFour() {


sv = new ShowcaseView.Builder(this, true)
.setTarget(new
ViewTarget( ((ViewGroup)findViewById(R.id.my_awesome_toolbar2)).getChildAt(0) ) )
.setContentTitle("More Options")
.setContentText("Slide from the left to reveal more options.")
.setStyle(R.style.CustomShowcaseTheme3)
.setShowcaseEventListener(new OnShowcaseEventListener() {

@Override
public void onShowcaseViewShow(final ShowcaseView scv) {
}
@Override
public void onShowcaseViewTouchBlocked(MotionEvent motionEvent)
{

@Override
public void onShowcaseViewHide(final ShowcaseView scv) {
drawerLayoutt.closeDrawers();
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion >= Build.VERSION_CODES.HONEYCOMB) {
homelayout.setAlpha(1f);
if (Build.VERSION.SDK_INT >=
Build.VERSION_CODES.LOLLIPOP) {

getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
choice = sharedPreferences.getInt("Choice",4);
switch(choice)
{
default:

getWindow().setStatusBarColor(getResources().getColor(R.color.darkgrey));break;
}
}
}
scv.setVisibility(View.GONE);
}

@Override
public void onShowcaseViewDidHide(final ShowcaseView scv) { }

})
.build();

@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
actionBarDrawerToggle.onConfigurationChanged(newConfig);
ChessBoard oldCB = cb;
String statusStr = status.getText().toString();
initUI(false);
readPrefs();
ctrl.setMaxDepth(maxDepth);
cb.cursorX = oldCB.cursorX;
cb.cursorY = oldCB.cursorY;
cb.cursorVisible = oldCB.cursorVisible;
cb.setPosition(oldCB.pos);
cb.setFlipped(oldCB.flipped);
cb.oneTouchMoves = oldCB.oneTouchMoves;
setSelection(oldCB.selectedSquare);
setStatusString(statusStr);
moveListUpdated();
updateThinkingInfo();
}
private final void initUI(boolean initTitle) {
setContentView(R.layout.main);

toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar2);


navigationDrawerItems =
getResources().getStringArray(R.array.navigation_drawer_items);
drawerLayoutt = (DrawerLayout) findViewById(R.id.drawer_layout);
myadapter=new MyAdapter(this);
listView = (ListView) findViewById(R.id.left_drawer);
SpannableString s = new SpannableString("CHESSMASTER");
s.setSpan(new TypefaceSpan(this, "KlinicSlabBold.otf"), 0, s.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
TextView txt1 = (TextView) findViewById(R.id.status);
TextView txt2 = (TextView) findViewById(R.id.moveList);
TextView txt3 = (TextView) findViewById(R.id.thinking);
Typeface font = Typeface.createFromAsset(getAssets(),
"fonts/KlinicSlabMedium.otf");
Typeface font1 = Typeface.createFromAsset(getAssets(),
"fonts/KlinicSlabBold.otf");
txt1.setTypeface(font1);
txt2.setTypeface(font);
txt3.setTypeface(font);

if (toolbar != null) {
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(s);

//drawerLayoutt.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
// set up the drawer's list view with items and click listener
listView.setAdapter(myadapter);
listView.setOnItemClickListener(new DrawerItemClickListener());
//actionBarDrawerToggle = new ActionBarDrawerToggle(this,
drawerLayoutt, toolbar, R.string.app_name, R.string.app_name);

actionBarDrawerToggle=new ActionBarDrawerToggle(this, drawerLayoutt,


toolbar, R.string.app_name, R.string.app_name){

float mPreviousOffset = 0f;

@Override
public void onDrawerClosed(View arg0) {
super.onDrawerClosed(arg0);
shouldGoInvisible = false;
invalidateOptionsMenu(); // creates call to
onPrepareOptionsMenu()
}

@Override
public void onDrawerOpened(View arg0) {
super.onDrawerOpened(arg0);
shouldGoInvisible = true;
invalidateOptionsMenu(); // creates call to
onPrepareOptionsMenu()
}

@Override
public void onDrawerSlide(View arg0, float slideOffset) {
super.onDrawerSlide(arg0, slideOffset);
if(slideOffset > mPreviousOffset && !shouldGoInvisible){
shouldGoInvisible = true;
invalidateOptionsMenu();
}else if(mPreviousOffset > slideOffset && slideOffset < 0.5f &&
shouldGoInvisible){
shouldGoInvisible = false;
invalidateOptionsMenu();
}
mPreviousOffset = slideOffset;

@Override
public void onDrawerStateChanged(int arg0) {
// or use states of the drawer to hide/show the items

}};
drawerLayoutt.setDrawerListener(actionBarDrawerToggle);
// enable ActionBar app icon to behave as action to toggle nav drawer
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
/*if (savedInstanceState == null) {
selectItem(0);
}*/

final String PREFS_NAME = "MyPrefsFile";

SharedPreferences settings2 = getSharedPreferences(PREFS_NAME, 0);

if (settings2.getBoolean("my_first_time", true)) {
//the app is being launched for first time, do something
homelayout=(LinearLayout)findViewById(R.id.my_home);

displayShowcaseViewOne();

// first time task

// record the fact that the app has been started at least once
settings2.edit().putBoolean("my_first_time", false).commit();
}

status = (TextView) findViewById(R.id.status);


moveListScroll = (ScrollView) findViewById(R.id.scrollView);
moveList = (TextView) findViewById(R.id.moveList);
thinking = (TextView) findViewById(R.id.thinking);
status.setFocusable(false);
moveListScroll.setFocusable(false);
moveList.setFocusable(false);
thinking.setFocusable(false);

cb = (ChessBoard) findViewById(R.id.chessboard);
cb.setFocusable(true);
cb.requestFocus();
cb.setClickable(true);

final GestureDetector gd = new GestureDetector(


new GestureDetector.SimpleOnGestureListener() {
private float scrollX = 0;
private float scrollY = 0;

public boolean onDown(MotionEvent e) {


scrollX = 0;
scrollY = 0;
return false;
}

public boolean onScroll(MotionEvent e1, MotionEvent


e2,
float distanceX, float distanceY) {
cb.cancelLongPress();
if (invertScrollDirection) {
distanceX = -distanceX;
distanceY = -distanceY;
}
if (scrollSensitivity > 0) {
scrollX += distanceX;
scrollY += distanceY;
float scrollUnit = cb.sqSize *
scrollSensitivity;
if (Math.abs(scrollX) >=
Math.abs(scrollY)) {
// Undo/redo
int nRedo = 0, nUndo = 0;
while (scrollX > scrollUnit) {
nRedo++;
scrollX -= scrollUnit;
}
while (scrollX < -scrollUnit) {
nUndo++;
scrollX += scrollUnit;
}
if (nUndo + nRedo > 0)
scrollY = 0;
if (nRedo + nUndo > 1) {
boolean analysis =
gameMode.analysisMode();
boolean human =
gameMode.playerWhite()
||
gameMode.playerBlack();
if (analysis || !human)
ctrl.setGameMode(new
GameMode(

GameMode.TWO_PLAYERS));
}
for (int i = 0; i < nRedo; i++)
ctrl.redoMove();
for (int i = 0; i < nUndo; i++)
ctrl.undoMove();
ctrl.setGameMode(gameMode);
} else {
// Next/previous variation
int varDelta = 0;
while (scrollY > scrollUnit) {
varDelta++;
scrollY -= scrollUnit;
}
while (scrollY < -scrollUnit) {
varDelta--;
scrollY += scrollUnit;
}
if (varDelta != 0)
scrollX = 0;
ctrl.changeVariation(varDelta);
}
}
return true;
}

public boolean onSingleTapUp(MotionEvent e) {


cb.cancelLongPress();
handleClick(e);
return true;
}

public boolean onDoubleTapEvent(MotionEvent e) {


if (e.getAction() == MotionEvent.ACTION_UP)
handleClick(e);
return true;
}

private final void handleClick(MotionEvent e) {


if (ctrl.humansTurn()) {
int sq = cb.eventToSquare(e);
Move m = cb.mousePressed(sq);
if (m != null)
ctrl.makeHumanMove(m);
}
}
});
cb.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
return gd.onTouchEvent(event);
}
});
cb.setOnTrackballListener(new ChessBoard.OnTrackballListener() {
public void onTrackballEvent(MotionEvent event) {
if (ctrl.humansTurn()) {
Move m = cb.handleTrackballEvent(event);
if (m != null) {
ctrl.makeHumanMove(m);
}
}
}
});
cb.setOnLongClickListener(new OnLongClickListener() {
public boolean onLongClick(View v) {
removeDialog(CLIPBOARD_DIALOG);
showDialog(CLIPBOARD_DIALOG);
return true;
}
});
}

@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (ctrl != null) {
byte[] data = ctrl.toByteArray();
outState.putByteArray("gameState", data);
}
}

@Override
protected void onResume() {
lastVisibleMillis = 0;
if (ctrl != null) {
ctrl.setGuiPaused(false);
}
updateNotification();
super.onResume();
loadTheme();
}

@Override
protected void onPause() {
if (ctrl != null) {
ctrl.setGuiPaused(true);
byte[] data = ctrl.toByteArray();
Editor editor = settings.edit();
String dataStr = byteArrToString(data);
editor.putString("gameState", dataStr);
editor.commit();
}

lastVisibleMillis = System.currentTimeMillis();
updateNotification();
super.onPause();
}

@Override
protected void onDestroy() {
if (ctrl != null) {
ctrl.shutdownEngine();
}
setNotification(false);
super.onDestroy();
}

private final void readPrefs() {


String tmp = settings.getString("gameMode", "1");
int modeNr = Integer.parseInt(tmp);
gameMode = new GameMode(modeNr);
maxDepth = Integer
.parseInt(settings.getString("difficultyDepth", "2"));
boardFlipped = settings.getBoolean("boardFlipped", false);
autoSwapSides = settings.getBoolean("autoSwapSides", false);
setBoardFlip();
cb.oneTouchMoves = settings.getBoolean("oneTouchMoves", false);

mShowThinking = settings.getBoolean("showThinking", false);


tmp = settings.getString("thinkingArrows", "2");
maxNumArrows = Integer.parseInt(tmp);
mShowBookHints = settings.getBoolean("bookHints", false);

tmp = settings.getString("timeControl", "15000");


int timeControl = Integer.parseInt(tmp);
tmp = settings.getString("movesPerSession", "60");
int movesPerSession = Integer.parseInt(tmp);
tmp = settings.getString("timeIncrement", "0");
int timeIncrement = Integer.parseInt(tmp);
ctrl.setTimeLimit(timeControl, movesPerSession, timeIncrement);

tmp = settings.getString("scrollSensitivity", "0");


scrollSensitivity = Float.parseFloat(tmp);
invertScrollDirection = settings.getBoolean("invertScrollDirection",
false);

tmp = settings.getString("fontSize", "20");


int fontSize = Integer.parseInt(tmp);
status.setTextSize(fontSize);
moveList.setTextSize(fontSize);
thinking.setTextSize(fontSize);
thinking.setPadding(24, 2, 24, 2);
status.setPadding(24, 2, 24, 2);
moveList.setPadding(24, 2, 24, 2);
soundEnabled = settings.getBoolean("soundEnabled", false);

String bookFile = settings.getString("bookFile", "");


setBookFile(bookFile);
updateThinkingInfo();

pgnOptions.view.variations = settings
.getBoolean("viewVariations", true);
pgnOptions.view.comments = settings.getBoolean("viewComments", true);
pgnOptions.view.nag = settings.getBoolean("viewNAG", true);
pgnOptions.view.headers = settings.getBoolean("viewHeaders", false);
pgnOptions.imp.variations = settings.getBoolean("importVariations",
true);
pgnOptions.imp.comments = settings.getBoolean("importComments", true);
pgnOptions.imp.nag = settings.getBoolean("importNAG", true);
pgnOptions.exp.variations = settings.getBoolean("exportVariations",
true);
pgnOptions.exp.comments = settings.getBoolean("exportComments", true);
pgnOptions.exp.nag = settings.getBoolean("exportNAG", true);
pgnOptions.exp.playerAction = settings.getBoolean("exportPlayerAction",
false);
pgnOptions.exp.clockInfo = settings.getBoolean("exportTime", false);

cb.setColors();

gameTextListener.clear();
ctrl.prefsChanged();
}
private final void setBookFile(String bookFile) {
currentBookFile = bookFile;
if (bookFile.length() > 0) {
File extDir = Environment.getExternalStorageDirectory();
String sep = File.separator;
bookFile = extDir.getAbsolutePath() + sep + bookDir + sep
+ bookFile;
}
ctrl.setBookFileName(bookFile);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.options_menu, menu);
return true;
}

public boolean onPrepareOptionsMenu(Menu menu) {


//final MenuItem bluetoothSubmenuItem = (MenuItem) menu
// .findItem(R.id.bluetooth_submenu);
final MenuItem undoMenuItem = (MenuItem) menu.findItem(R.id.item_undo);
final MenuItem redoMenuItem = (MenuItem) menu.findItem(R.id.item_redo);
/*final MenuItem gotoMoveMenuItem = (MenuItem) menu
.findItem(R.id.item_goto_move);
final MenuItem loadPGNMenuItem = (MenuItem) menu
.findItem(R.id.item_load_pgn_file);
final MenuItem editBoardMenuItem = (MenuItem) menu
.findItem(R.id.item_editboard);
final MenuItem forceMoveMenuItem = (MenuItem) menu
.findItem(R.id.item_force_move);
final MenuItem resignMenuItem = (MenuItem) menu
.findItem(R.id.item_resign);
// final MenuItem drawMenuItem = (MenuItem)
// menu.findItem(R.id.item_draw);
if (gameMode.bluetoothMode()) {
bluetoothSubmenuItem.setEnabled(true);
undoMenuItem.setEnabled(false);
redoMenuItem.setEnabled(false);
gotoMoveMenuItem.setEnabled(false);
loadPGNMenuItem.setEnabled(false);
editBoardMenuItem.setEnabled(false);
forceMoveMenuItem.setEnabled(false);
resignMenuItem.setEnabled(false);
} else {
bluetoothSubmenuItem.setEnabled(false);
undoMenuItem.setEnabled(true);
redoMenuItem.setEnabled(true);
gotoMoveMenuItem.setEnabled(true);
loadPGNMenuItem.setEnabled(true);
editBoardMenuItem.setEnabled(true);
forceMoveMenuItem.setEnabled(true);
resignMenuItem.setEnabled(true);
}

if (ctrl != null && ctrl.computerBusy()) {


forceMoveMenuItem.setEnabled(true);
} else {
forceMoveMenuItem.setEnabled(false);
}*/
boolean drawerOpen = shouldGoInvisible;
hideMenuItems(menu, !drawerOpen);
return super.onPrepareOptionsMenu(menu);
}

private void hideMenuItems(Menu menu, boolean visible)


{

for(int i = 0; i < menu.size(); i++){

menu.getItem(i).setVisible(visible);

}
}

static private final int RESULT_EDITBOARD = 0;


static private final int RESULT_SETTINGS = 1;
static private final int RESULT_LOAD_PGN = 2;
static private final int REQUEST_CONNECT_DEVICE = 3;
static private final int REQUEST_ENABLE_BT = 4;

@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
try{
actionBarDrawerToggle.syncState();}
catch(Exception e){};
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
try{
if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
}
catch(Exception e){};

switch (item.getItemId()) {
case R.id.item_undo:
ctrl.undoMove();
return true;
case R.id.item_redo:
ctrl.redoMove();
return true;
}

return false;
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
switch (requestCode) {
case RESULT_SETTINGS:
readPrefs();
ctrl.setGameMode(gameMode);
ctrl.setMaxDepth(maxDepth);
break;
case RESULT_EDITBOARD:
if (resultCode == RESULT_OK) {
try {
String fen = data.getAction();
ctrl.setFENOrPGN(fen);
} catch (ChessParseError e) {
}
}
break;
case RESULT_LOAD_PGN:
if (resultCode == RESULT_OK) {
try {
String pgn = data.getAction();
ctrl.setFENOrPGN(pgn);
} catch (ChessParseError e) {
Toast.makeText(getApplicationContext(),
e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
break;
}
}

private final void flipBoard() {


boardFlipped = !boardFlipped;

Editor editor = settings.edit();


editor.putBoolean("boardFlipped", boardFlipped);
editor.apply();

setBoardFlip();
}

private final void setBoardFlip() {


boolean flipped = boardFlipped;
if (autoSwapSides) {
if (gameMode.analysisMode()) {
flipped = !cb.pos.whiteMove;
} else if (gameMode.playerWhite() && gameMode.playerBlack()) {
flipped = !cb.pos.whiteMove;
} else if (gameMode.playerWhite()) {
flipped = false;
} else if (gameMode.playerBlack()) {
flipped = true;
} else { // two computers
flipped = !cb.pos.whiteMove;
}
}
cb.setFlipped(flipped);
}

@Override
public void setSelection(int sq) {
cb.setSelection(sq);
}
@Override
public void setStatusString(String str) {
status.setText(str);
}

@Override
public void moveListUpdated() {
moveList.setText("\n"+gameTextListener.getSpannableData());
if (gameTextListener.atEnd())
moveListScroll.fullScroll(ScrollView.FOCUS_DOWN);
}

@Override
public void setPosition(Position pos, String variantInfo,
List<Move> variantMoves) {
variantStr = variantInfo;
this.variantMoves = variantMoves;
cb.setPosition(pos);
setBoardFlip();
updateThinkingInfo();
}

private String thinkingStr = "";


private String bookInfoStr = "";
private String variantStr = "";
private List<Move> pvMoves = null;
private List<Move> bookMoves = null;
private List<Move> variantMoves = null;

@Override
public void setThinkingInfo(String pvStr, String bookInfo,
List<Move> pvMoves, List<Move> bookMoves) {
thinkingStr = pvStr;
bookInfoStr = bookInfo;
this.pvMoves = pvMoves;
this.bookMoves = bookMoves;

updateThinkingInfo();

if (ctrl.computerBusy())
lastComputationMillis = System.currentTimeMillis();
else
lastComputationMillis = 0;

updateNotification();
}

private final void updateThinkingInfo() {


boolean thinkingEmpty = true;
{
String s = "";
if (mShowThinking || gameMode.analysisMode()) {
s = thinkingStr;
}
thinking.setText(s, TextView.BufferType.SPANNABLE);
if (s.length() > 0)
thinkingEmpty = false;
}
if (mShowBookHints && (bookInfoStr.length() > 0)) {
String s = "";
if (!thinkingEmpty)
s += "<br>";
s += "<b>Book:</b>" + bookInfoStr;
thinking.append(Html.fromHtml(s));
thinkingEmpty = false;
}
if (variantStr.indexOf(' ') >= 0) {
String s = "";
if (!thinkingEmpty)
s += "<br>";
s += "<b>Var:</b> " + variantStr;
thinking.append(Html.fromHtml(s));
}

List<Move> hints = null;


if (mShowThinking || gameMode.analysisMode())
hints = pvMoves;
if ((hints == null) && mShowBookHints)
hints = bookMoves;
if ((variantMoves != null) && variantMoves.size() > 1) {
hints = variantMoves;
}
if ((hints != null) && (hints.size() > maxNumArrows)) {
hints = hints.subList(0, maxNumArrows);
}
cb.setMoveHints(hints);
}

static final int PROMOTE_DIALOG = 0;


static final int CLIPBOARD_DIALOG = 1;
static final int ABOUT_DIALOG = 2;
static final int SELECT_MOVE_DIALOG = 3;
static final int SELECT_BOOK_DIALOG = 4;
static final int SELECT_PGN_FILE_DIALOG = 5;
static final int SET_COLOR_THEME_DIALOG = 6;
static final int CONFIRM_RESIGN_DIALOG = 7;

@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case PROMOTE_DIALOG: {
final CharSequence[] items = { getString(R.string.queen),
getString(R.string.rook), getString(R.string.bishop),
getString(R.string.knight) };
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.promote_pawn_to);
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
ctrl.reportPromotePiece(item);
}
});
AlertDialog alert = builder.create();
return alert;
}
case CLIPBOARD_DIALOG: {
final int COPY_GAME = 0;
final int COPY_POSITION = 1;
final int PASTE = 2;
final int LOAD_GAME = 3;
final int REMOVE_VARIATION = 4;

List<CharSequence> lst = new ArrayList<CharSequence>();


List<Integer> actions = new ArrayList<Integer>();
lst.add(getString(R.string.copy_game));
actions.add(COPY_GAME);
lst.add(getString(R.string.copy_position));
actions.add(COPY_POSITION);
lst.add(getString(R.string.paste));
actions.add(PASTE);
lst.add(getString(R.string.load_game));
actions.add(LOAD_GAME);
if (ctrl.humansTurn() && (ctrl.numVariations() > 1)) {
lst.add(getString(R.string.remove_variation));
actions.add(REMOVE_VARIATION);
}
final List<Integer> finalActions = actions;
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.tools_menu);
builder.setItems(lst.toArray(new CharSequence[4]),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int
item) {
switch (finalActions.get(item)) {
case COPY_GAME: {
String pgn = ctrl.getPGN();
ClipboardManager clipboard =
(ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
clipboard.setText(pgn);
break;
}
case COPY_POSITION: {
String fen = ctrl.getFEN() + "\n";
ClipboardManager clipboard =
(ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
clipboard.setText(fen);
break;
}
case PASTE: {
ClipboardManager clipboard =
(ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
if (clipboard.hasText()) {
String fenPgn =
clipboard.getText()
.toString();
try {

ctrl.setFENOrPGN(fenPgn);
} catch (ChessParseError e) {

Toast.makeText(getApplicationContext(),

e.getMessage(),

Toast.LENGTH_SHORT).show();
}
}
break;
}
case LOAD_GAME:

removeDialog(SELECT_PGN_FILE_DIALOG);
showDialog(SELECT_PGN_FILE_DIALOG);
break;
case REMOVE_VARIATION:
ctrl.removeVariation();
break;
}
}
});
AlertDialog alert = builder.create();
return alert;
}
case ABOUT_DIALOG: {
AlertDialog.Builder builder = new AlertDialog.Builder(this);

builder.setTitle(R.string.app_name_pop).setMessage(R.string.about_info);
AlertDialog alert = builder.create();
//alert.getWindow().setLayout(600, 400);
return alert;
}
case SELECT_MOVE_DIALOG: {
//final Dialog dialog = new Dialog(this);
final AlertDialog.Builder dialog = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.select_move_number, null);
dialog.setView(dialogView);
//dialog.setContentView(R.layout.select_move_number);
dialog.setTitle(R.string.goto_move);
final EditText moveNrView = (EditText)
dialogView.findViewById(R.id.selmove_number);
Button ok = (Button) dialogView.findViewById(R.id.selmove_ok);
Button cancel = (Button)
dialogView.findViewById(R.id.selmove_cancel);
final AlertDialog alertDialog = dialog.create();
moveNrView.setText("1");
final Runnable gotoMove = new Runnable() {
public void run() {
try {
int moveNr =
Integer.parseInt(moveNrView.getText()
.toString());
ctrl.gotoMove(moveNr);
alertDialog.dismiss();
} catch (NumberFormatException nfe) {
Toast.makeText(getApplicationContext(),
R.string.invalid_number_format,
Toast.LENGTH_SHORT).show();
}
}
};
moveNrView.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if ((event.getAction() == KeyEvent.ACTION_DOWN)
&& (keyCode == KeyEvent.KEYCODE_ENTER)) {
gotoMove.run();
return true;
}
return false;
}
});
ok.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
gotoMove.run();
}
});
cancel.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
alertDialog.dismiss();
}
});

alertDialog.show();
return null;
}
case SELECT_BOOK_DIALOG: {
String[] fileNames = findFilesInDirectory(bookDir);
final int numFiles = fileNames.length;
CharSequence[] items = new CharSequence[numFiles + 1];
for (int i = 0; i < numFiles; i++)
items[i] = fileNames[i];
items[numFiles] = getString(R.string.internal_book);
final CharSequence[] finalItems = items;
int defaultItem = numFiles;
for (int i = 0; i < numFiles; i++) {
if (currentBookFile.equals(items[i])) {
defaultItem = i;
break;
}
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.select_opening_book_file);
builder.setSingleChoiceItems(items, defaultItem,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int
item) {
Editor editor = settings.edit();
String bookFile = "";
if (item < numFiles)
bookFile =
finalItems[item].toString();
editor.putString("bookFile", bookFile);
editor.commit();
setBookFile(bookFile);
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
return alert;
}
case SELECT_PGN_FILE_DIALOG: {
final String[] fileNames = findFilesInDirectory(pgnDir);
final int numFiles = fileNames.length;
if (numFiles == 0) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.app_name).setMessage(
R.string.no_pgn_files);
AlertDialog alert = builder.create();
return alert;
}
int defaultItem = 0;
String currentPGNFile = settings.getString("currentPGNFile", "");
for (int i = 0; i < numFiles; i++) {
if (currentPGNFile.equals(fileNames[i])) {
defaultItem = i;
break;
}
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.select_pgn_file);
builder.setSingleChoiceItems(fileNames, defaultItem,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int
item) {
Editor editor = settings.edit();
String pgnFile =
fileNames[item].toString();
editor.putString("currentPGNFile",
pgnFile);
editor.commit();
String sep = File.separator;
String pathName = Environment
.getExternalStorageDirectory(
)
+ sep
+ pgnDir + sep + pgnFile;
Intent i = new Intent(ChessTastic.this,
LoadPGN.class);
i.setAction(pathName);
startActivityForResult(i,
RESULT_LOAD_PGN);
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
Toast.makeText(getApplicationContext(), "After you select a game from
the pgn, use the undo and redo buttons to go back and forth in the game.",
Toast.LENGTH_LONG).show();
return alert;
}
case CONFIRM_RESIGN_DIALOG: {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to resign?")
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface
dialog,
int id) {
if (ctrl.humansTurn()) {
ctrl.resignGame();
}
}
})
.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface
dialog,
int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
return alert;
}
}
return null;
}

private final String[] findFilesInDirectory(String dirName) {


File extDir = Environment.getExternalStorageDirectory();
String sep = File.separator;
File dir = new File(extDir.getAbsolutePath() + sep + dirName);
File[] files = dir.listFiles(new FileFilter() {
public boolean accept(File pathname) {
return pathname.isFile();
}
});
if (files == null)
files = new File[0];
final int numFiles = files.length;
String[] fileNames = new String[numFiles];
for (int i = 0; i < files.length; i++)
fileNames[i] = files[i].getName();
Arrays.sort(fileNames, String.CASE_INSENSITIVE_ORDER);
return fileNames;
}

@Override
public void requestPromotePiece() {
runOnUIThread(new Runnable() {
public void run() {
showDialog(PROMOTE_DIALOG);
}
});
}

@Override
public void reportInvalidMove(Move m) {
String msg = String.format("Invalid move %s-%s",
TextIO.squareToString(m.from),
TextIO.squareToString(m.to));
Toast.makeText(getApplicationContext(), msg,
Toast.LENGTH_SHORT).show();
}

@Override
public void computerMoveMade() {
if (soundEnabled) {
if (moveSound != null)
moveSound.release();
moveSound = MediaPlayer.create(this, R.raw.movesound);
moveSound.start();
}
}
@Override
public void runOnUIThread(Runnable runnable) {
runOnUiThread(runnable);
}

/** Decide if user should be warned about heavy CPU usage. */


private final void updateNotification() {
boolean warn = false;
if (lastVisibleMillis != 0) { // GUI not visible
warn = lastComputationMillis >= lastVisibleMillis + 30000;
}

setNotification(warn);
}

private boolean notificationActive = false;

/** Set/clear the "heavy CPU usage" notification. */


private final void setNotification(boolean show) {
if (notificationActive == show)
return;
notificationActive = show;
final int cpuUsage = 1;
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(ns);
if (show) {
int icon = R.drawable.ic_launcher;
CharSequence tickerText = "Heavy CPU usage";
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText,
when);
notification.flags |= Notification.FLAG_ONGOING_EVENT;

Context context = getApplicationContext();


CharSequence contentTitle = "Background processing";
CharSequence contentText = "ChessTastic is using a lot of CPU
power";
Intent notificationIntent = new Intent(this, CPUWarning.class);

PendingIntent contentIntent = PendingIntent.getActivity(this, 0,


notificationIntent, 0);
// notification.setLatestEventInfo(context, contentTitle,
contentText,
// contentIntent);

mNotificationManager.notify(cpuUsage, notification);
} else {
mNotificationManager.cancel(cpuUsage);
}
}

public void setRemainingTime(long wTime, long bTime, long nextUpdate) {


}

static class PgnScreenText implements PgnToken.PgnTokenReceiver {


private SpannableStringBuilder sb = new SpannableStringBuilder();
private int prevType = PgnToken.EOF;
int nestLevel = 0;
boolean col0 = true;
Node currNode = null;
final int indentStep = 15;
int currPos = 0, endPos = 0;
boolean upToDate = false;
PGNOptions options;

private static class NodeInfo {


int l0, l1;

NodeInfo(int ls, int le) {


l0 = ls;
l1 = le;
}
}

HashMap<Node, NodeInfo> nodeToCharPos;

PgnScreenText(PGNOptions options) {
nodeToCharPos = new HashMap<Node, NodeInfo>();
this.options = options;
}

public final SpannableStringBuilder getSpannableData() {


return sb;
}

public final boolean atEnd() {


return currPos >= endPos - 10;
}

public boolean isUpToDate() {


return upToDate;
}

int paraStart = 0;
int paraIndent = 0;
boolean paraBold = false;

private final void newLine() {


if (!col0) {
if (paraIndent > 0) {
int paraEnd = sb.length();
int indent = paraIndent * indentStep;
sb.setSpan(new LeadingMarginSpan.Standard(indent),
paraStart, paraEnd,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
if (paraBold) {
int paraEnd = sb.length();
sb.setSpan(new StyleSpan(Typeface.BOLD), paraStart,
paraEnd,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
sb.append('\n');
paraStart = sb.length();
paraIndent = nestLevel;
paraBold = false;
}
col0 = true;
}

boolean pendingNewLine = false;

public void processToken(Node node, int type, String token) {


if ((prevType == PgnToken.RIGHT_BRACKET)
&& (type != PgnToken.LEFT_BRACKET)) {
if (options.view.headers) {
col0 = false;
newLine();
} else {
sb.clear();
paraBold = false;
}
}
if (pendingNewLine) {
if (type != PgnToken.RIGHT_PAREN) {
newLine();
pendingNewLine = false;
}
}
switch (type) {
case PgnToken.STRING:
sb.append(" \"");
sb.append(token);
sb.append('"');
break;
case PgnToken.INTEGER:
if ((prevType != PgnToken.LEFT_PAREN)
&& (prevType != PgnToken.RIGHT_BRACKET) && !
col0)
sb.append(' ');
sb.append(token);
col0 = false;
break;
case PgnToken.PERIOD:
sb.append('.');
col0 = false;
break;
case PgnToken.ASTERISK:
sb.append(" *");
col0 = false;
break;
case PgnToken.LEFT_BRACKET:
sb.append('[');
col0 = false;
break;
case PgnToken.RIGHT_BRACKET:
sb.append("]\n");
col0 = false;
break;
case PgnToken.LEFT_PAREN:
nestLevel++;
if (col0)
paraIndent++;
newLine();
sb.append('(');
col0 = false;
break;
case PgnToken.RIGHT_PAREN:
sb.append(')');
nestLevel--;
pendingNewLine = true;
break;
case PgnToken.NAG:
sb.append(Node.nagStr(Integer.parseInt(token)));
col0 = false;
break;
case PgnToken.SYMBOL: {
if ((prevType != PgnToken.RIGHT_BRACKET)
&& (prevType != PgnToken.LEFT_BRACKET) && !
col0)
sb.append(' ');
int l0 = sb.length();
sb.append(token);
int l1 = sb.length();
nodeToCharPos.put(node, new NodeInfo(l0, l1));
if (endPos < l0)
endPos = l0;
col0 = false;
if (nestLevel == 0)
paraBold = true;
break;
}
case PgnToken.COMMENT:
if (prevType == PgnToken.RIGHT_BRACKET) {
} else if (nestLevel == 0) {
nestLevel++;
newLine();
nestLevel--;
} else {
if ((prevType != PgnToken.LEFT_PAREN) && !col0) {
sb.append(' ');
}
}
sb.append(token.replaceAll("[ \t\r\n]+", " ").trim());
col0 = false;
if (nestLevel == 0)
newLine();
break;
case PgnToken.EOF:
newLine();
upToDate = true;
break;
}
prevType = type;
}

@Override
public void clear() {
sb.clear();
prevType = PgnToken.EOF;
nestLevel = 0;
col0 = true;
currNode = null;
currPos = 0;
endPos = 0;
nodeToCharPos.clear();
paraStart = 0;
paraIndent = 0;
paraBold = false;
pendingNewLine = false;

upToDate = false;
}

BackgroundColorSpan bgSpan = new BackgroundColorSpan(0xff888888);

@Override
public void setCurrent(Node node) {
sb.removeSpan(bgSpan);
NodeInfo ni = nodeToCharPos.get(node);
if (ni != null) {
sb.setSpan(bgSpan, ni.l0, ni.l1,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
currPos = ni.l0;
}
currNode = node;
}
}

@Override
public void humanMoveMade(Move m) {
}

private class DrawerItemClickListener implements ListView.OnItemClickListener


{
@SuppressWarnings("deprecation")
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
//selectItem(position);
switch(position)
{
case 0:
drawerLayoutt.closeDrawers();
if (autoSwapSides && (gameMode.playerWhite() !=
gameMode.playerBlack())) {
int gameModeType;
if (gameMode.playerWhite()) {
gameModeType = GameMode.PLAYER_BLACK;
} else {
gameModeType = GameMode.PLAYER_WHITE;
}
Editor editor = settings.edit();
String gameModeStr = String.format("%d",
gameModeType);
editor.putString("gameMode", gameModeStr);
editor.commit();
gameMode = new GameMode(gameModeType);
}

ctrl.newGame(gameMode);
ctrl.startGame();
break;
case 1: {
Intent i = new Intent(ChessTastic.this, EditBoard.class);
i.setAction(ctrl.getFEN());
startActivityForResult(i, RESULT_EDITBOARD);
break;
}
case 2: {
drawerLayoutt.closeDrawers();
ChessTastic.this.flipBoard();
break;
}
case 5: {
Intent i = new Intent(ChessTastic.this, Preferences.class);
startActivityForResult(i, RESULT_SETTINGS);
break;
}

case 7: {
drawerLayoutt.closeDrawers();
showDialog(SELECT_MOVE_DIALOG);
break;
}
case 8: {
drawerLayoutt.closeDrawers();
if (ctrl != null && ctrl.computerBusy())
ctrl.stopSearch();
else
Toast.makeText(getApplicationContext(), "Busy",
Toast.LENGTH_SHORT).show();
break;
}
/*
* case R.id.item_draw: { if (ctrl.humansTurn()) { if
* (!ctrl.claimDrawIfPossible()) {
* Toast.makeText(getApplicationContext(),
R.string.offer_draw,
* Toast.LENGTH_SHORT).show(); } } return true; }
*/
case 6: {

if (ctrl.humansTurn()) {
removeDialog(CONFIRM_RESIGN_DIALOG);
showDialog(CONFIRM_RESIGN_DIALOG);
}
break;
}
case 9:
removeDialog(SELECT_BOOK_DIALOG);
showDialog(SELECT_BOOK_DIALOG);
break;
case 4:
removeDialog(SELECT_PGN_FILE_DIALOG);
showDialog(SELECT_PGN_FILE_DIALOG);
break;
case 3:
Toast.makeText(getApplicationContext(), "Bluetooth is
currently a work in progress.",
Toast.LENGTH_LONG).show();
break;

case 10:
//rate
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
ChessTastic.this);

// set title
alertDialogBuilder.setTitle("Rating and Feedback");

// set dialog message


alertDialogBuilder
.setMessage("Do you like this app? Press Rate to add a good
rating and some kind words on the Play Store. Are you facing any problems? Press
the Feedback button below to send me an email!")
.setCancelable(true)
.setPositiveButton("Rate",new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
final String appPackageName = getPackageName(); //
getPackageName() from Context or Activity object
try {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("market://details?id=" + appPackageName)));
} catch (android.content.ActivityNotFoundException
anfe) {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("https://play.google.com/store/apps/details?id=" + appPackageName)));
}
}
})
.setNegativeButton("Feedback",new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
Toast.makeText(getApplicationContext(), "Opening
email. Please tell me your problems. ", Toast.LENGTH_LONG).show();
/*Intent i = new
Intent(android.content.Intent.ACTION_SEND);
i.putExtra(android.content.Intent.EXTRA_EMAIL, new
String[] {"avijitg22@gmail.com"});
i.putExtra(android.content.Intent.EXTRA_SUBJECT,
"ChessTastic™ Beta");
//i.putExtra(Intent.EXTRA_TEXT,
"\n\n\n\n"+"-----------------------------------------------------------------------
"+"\n"+raw);
i.setType("plain/text");
startActivity(i);*/
Intent emailIntent = new
Intent(Intent.ACTION_SENDTO, Uri.fromParts(
"mailto","avijitg22@gmail.com", null));
emailIntent.putExtra(Intent.EXTRA_SUBJECT,
"ChessTastic™ Beta");
startActivity(Intent.createChooser(emailIntent,
"Send email..."));
}
});

// create alert dialog


AlertDialog alertDialog = alertDialogBuilder.create();

// show it
alertDialog.show();
break;
case 11:
showDialog(ABOUT_DIALOG);
break;
}
}
}

}
class MyAdapter extends BaseAdapter{

String[] options;
int[]
images={R.drawable.newg,R.drawable.edit,R.drawable.flip,R.drawable.bt,R.drawable.pg
n,R.drawable.settings,R.drawable.resign,R.drawable.goton,R.drawable.force,R.drawabl
e.book,R.drawable.thumb,R.drawable.about};
private Context context;

MyAdapter(Context context)
{
this.context=context;

options=context.getResources().getStringArray(R.array.navigation_drawer_items);
}

@Override
public int getCount() {
// TODO Auto-generated method stub
return options.length;
}

@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return options[position];
}

@Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View row=null;
if(convertView==null)
{
LayoutInflater inflater=(LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row=inflater.inflate(R.layout.drawer_list_item, parent, false);
}
else
{
row=convertView;
}
TextView tv1=(TextView) row.findViewById(R.id.text1);
ImageView iv1=(ImageView) row.findViewById(R.id.image1);
RelativeLayout lLayout = (RelativeLayout)
row.findViewById(R.id.parentLayout);
if(position==3)
{
tv1.setText(options[position]);

tv1.setTextColor(ChessTastic.getContextOfApplication().getResources().getColor(R.co
lor.disabled));
iv1.setImageResource(images[position]);
//row.setVisibility(View.GONE);
lLayout.setVisibility(View.GONE);

}
else{
tv1.setText(options[position]);
iv1.setImageResource(images[position]);
lLayout.setVisibility(View.VISIBLE);
}

return row;
}

Position pos;

int selectedSquare;
float cursorX, cursorY;
boolean cursorVisible;
protected int x0, y0, sqSize;
boolean flipped;
boolean oneTouchMoves;

List<Move> moveHints;

protected Paint darkPaint;


protected Paint brightPaint;
private Paint selectedSquarePaint;
private Paint cursorSquarePaint;

private ArrayList<Paint> moveMarkPaint;

public ChessBoard(Context context, AttributeSet attrs) {


super(context, attrs);
pos = new Position();
selectedSquare = -1;
cursorX = cursorY = 0;
cursorVisible = false;
x0 = y0 = sqSize = 0;
flipped = false;
oneTouchMoves = false;

darkPaint = new Paint();


brightPaint = new Paint();

selectedSquarePaint = new Paint();


selectedSquarePaint.setStyle(Paint.Style.STROKE);
selectedSquarePaint.setAntiAlias(true);

cursorSquarePaint = new Paint();


cursorSquarePaint.setStyle(Paint.Style.STROKE);
cursorSquarePaint.setAntiAlias(true);

moveMarkPaint = new ArrayList<Paint>();


for (int i = 0; i < 6; i++) {
Paint p = new Paint();
p.setStyle(Paint.Style.FILL);
p.setAntiAlias(true);
moveMarkPaint.add(p);
}

setColors();
}

/** Configure the board's colors. */


final void setColors() {
brightPaint.setColor(Appearance.getColor(Appearance.BRIGHT_SQUARE));
darkPaint.setColor(Appearance.getColor(Appearance.DARK_SQUARE));

selectedSquarePaint.setColor(Appearance.getColor(Appearance.SELECTED_SQUARE));

cursorSquarePaint.setColor(Appearance.getColor(Appearance.CURSOR_SQUARE));

for (int i = 0; i < 6; i++)

moveMarkPaint.get(i).setColor(Appearance.getColor(Appearance.ARROW_0 + i));

invalidate();
}

/**
* Set the board to a given state.
*
* @param pos
*/
final public void setPosition(Position pos) {
if (!this.pos.equals(pos)) {
this.pos = new Position(pos);
invalidate();
}
}

/**
* Set/clear the board flipped status.
*
* @param flipped
*/
final public void setFlipped(boolean flipped) {
if (this.flipped != flipped) {
this.flipped = flipped;
invalidate();
}
}

/**
* Set/clear the selected square.
*
* @param square
* The square to select, or -1 to clear selection.
*/
final public void setSelection(int square) {
if (square != selectedSquare) {
selectedSquare = square;
invalidate();
}
}

protected int getWidth(int sqSize) {


return sqSize * 8;
}

protected int getHeight(int sqSize) {


return sqSize * 8;
}

protected int getSqSizeW(int width) {


return width / 8;
}

protected int getSqSizeH(int height) {


return height / 8;
}

protected int getMaxHeightPercentage() {


return 75;
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int width = getMeasuredWidth();
int height = getMeasuredHeight();
int sqSizeW = getSqSizeW(width);
int sqSizeH = getSqSizeH(height);
int sqSize = Math.min(sqSizeW, sqSizeH);
if (height > width) {
int p = getMaxHeightPercentage();
height = Math.min(getHeight(sqSize), height * p / 100);
} else {
width = Math.min(getWidth(sqSize), width * 65 / 100);
}
setMeasuredDimension(width, height);
}

protected void computeOrigin(int width, int height) {


x0 = (width - sqSize * 8) / 2;
y0 = (height - sqSize * 8) / 2;
}

protected int getXFromSq(int sq) {


return Position.getX(sq);
}

protected int getYFromSq(int sq) {


return Position.getY(sq);
}

@Override
protected void onDraw(Canvas canvas) {
final int width = getWidth();
final int height = getHeight();
sqSize = Math.min(getSqSizeW(width), getSqSizeH(height));
computeOrigin(width, height);
for (int x = 0; x < 8; x++) {
for (int y = 0; y < 8; y++) {
final int xCrd = getXCrd(x);
final int yCrd = getYCrd(y);
Paint paint = Position.darkSquare(x, y) ? darkPaint
: brightPaint;
canvas.drawRect(xCrd, yCrd, xCrd + sqSize, yCrd + sqSize,
paint);

int sq = Position.getSquare(x, y);


int p = pos.getPiece(sq);
drawPiece(canvas, xCrd + sqSize / 2, yCrd + sqSize / 2, p);
}
}
drawExtraSquares(canvas);
if (selectedSquare != -1) {
int selX = getXFromSq(selectedSquare);
int selY = getYFromSq(selectedSquare);
selectedSquarePaint.setStrokeWidth(sqSize / (float) 16);
int x0 = getXCrd(selX);
int y0 = getYCrd(selY);
canvas.drawRect(x0, y0, x0 + sqSize, y0 + sqSize,
selectedSquarePaint);
}
if (cursorVisible) {
int x = Math.round(cursorX);
int y = Math.round(cursorY);
int x0 = getXCrd(x);
int y0 = getYCrd(y);
cursorSquarePaint.setStrokeWidth(sqSize / (float) 16);
canvas.drawRect(x0, y0, x0 + sqSize, y0 + sqSize,
cursorSquarePaint);
}
drawMoveHints(canvas);
}

private final void drawMoveHints(Canvas canvas) {


if (moveHints == null)
return;
float h = (float) (sqSize / 2.0);
float d = (float) (sqSize / 8.0);
double v = 35 * Math.PI / 180;
double cosv = Math.cos(v);
double sinv = Math.sin(v);
double tanv = Math.tan(v);
int n = Math.min(moveMarkPaint.size(), moveHints.size());
for (int i = 0; i < n; i++) {
Move m = moveHints.get(i);
float x0 = getXCrd(Position.getX(m.from)) + h;
float y0 = getYCrd(Position.getY(m.from)) + h;
float x1 = getXCrd(Position.getX(m.to)) + h;
float y1 = getYCrd(Position.getY(m.to)) + h;

float x2 = (float) (Math.hypot(x1 - x0, y1 - y0) + d);


float y2 = 0;
float x3 = (float) (x2 - h * cosv);
float y3 = (float) (y2 - h * sinv);
float x4 = (float) (x3 - d * sinv);
float y4 = (float) (y3 + d * cosv);
float x5 = (float) (x4 + (-d / 2 - y4) / tanv);
float y5 = (float) (-d / 2);
float x6 = 0;
float y6 = y5 / 2;
Path path = new Path();
path.moveTo(x2, y2);
path.lineTo(x3, y3);
// path.lineTo(x4, y4);
path.lineTo(x5, y5);
path.lineTo(x6, y6);
path.lineTo(x6, -y6);
path.lineTo(x5, -y5);
// path.lineTo(x4, -y4);
path.lineTo(x3, -y3);
path.close();
Matrix mtx = new Matrix();
mtx.postRotate((float) (Math.atan2(y1 - y0, x1 - x0) * 180 /
Math.PI));
mtx.postTranslate(x0, y0);
path.transform(mtx);
Paint p = moveMarkPaint.get(i);
canvas.drawPath(path, p);
}
}

protected void drawExtraSquares(Canvas canvas) {


}

protected final void drawPiece(Canvas canvas, int xCrd, int yCrd, int p) {
Drawable dr = null;

switch (p) {
default:
case Piece.EMPTY:
dr = null; // don't do anything
break;
case Piece.WKING:
dr = getContext().getResources().getDrawable(R.drawable.wk);
break;
case Piece.WQUEEN:
dr = getContext().getResources().getDrawable(R.drawable.wq);
break;
case Piece.WROOK:
dr = getContext().getResources().getDrawable(R.drawable.wr);
break;
case Piece.WBISHOP:
dr = getContext().getResources().getDrawable(R.drawable.wb);
break;
case Piece.WKNIGHT:
dr = getContext().getResources().getDrawable(R.drawable.wn);
break;
case Piece.WPAWN:
dr = getContext().getResources().getDrawable(R.drawable.wp);
break;
case Piece.BKING:
dr = getContext().getResources().getDrawable(R.drawable.bk);
break;
case Piece.BQUEEN:
dr = getContext().getResources().getDrawable(R.drawable.bq);
break;
case Piece.BROOK:
dr = getContext().getResources().getDrawable(R.drawable.br);
break;
case Piece.BBISHOP:
dr = getContext().getResources().getDrawable(R.drawable.bb);
break;
case Piece.BKNIGHT:
dr = getContext().getResources().getDrawable(R.drawable.bn);
break;
case Piece.BPAWN:
dr = getContext().getResources().getDrawable(R.drawable.bp);
break;
}
if (dr != null) {
int xOrigin = xCrd - (sqSize / 2);
int yOrigin = yCrd - (sqSize / 2);

dr.setBounds(xOrigin, yOrigin, xOrigin + sqSize, yOrigin +


sqSize);
dr.draw(canvas);
}
}

protected int getXCrd(int x) {


return x0 + sqSize * (flipped ? 7 - x : x);
}

protected int getYCrd(int y) {


return y0 + sqSize * (flipped ? y : 7 - y);
}

protected int getXSq(int xCrd) {


int t = (xCrd - x0) / sqSize;
return flipped ? 7 - t : t;
}

protected int getYSq(int yCrd) {


int t = (yCrd - y0) / sqSize;
return flipped ? t : 7 - t;
}

/**
* Compute the square corresponding to the coordinates of a mouse event.
*
* @param evt
* Details about the mouse event.
* @return The square corresponding to the mouse event, or -1 if outside
* board.
*/
int eventToSquare(MotionEvent evt) {
int xCrd = (int) (evt.getX());
int yCrd = (int) (evt.getY());

int sq = -1;
if (sqSize > 0) {
int x = getXSq(xCrd);
int y = getYSq(yCrd);
if ((x >= 0) && (x < 8) && (y >= 0) && (y < 8)) {
sq = Position.getSquare(x, y);
}
}
return sq;
}

final private boolean myColor(int piece) {


return (piece != Piece.EMPTY)
&& (Piece.isWhite(piece) == pos.whiteMove);
}

Move mousePressed(int sq) {


if (sq < 0)
return null;
cursorVisible = false;
if (selectedSquare != -1) {
int p = pos.getPiece(selectedSquare);
if (!myColor(p)) {
setSelection(-1); // Remove selection of opponents last
moving
// piece
}
}

int p = pos.getPiece(sq);
if (selectedSquare != -1) {
if (sq != selectedSquare) {
if (!myColor(p)) {
Move m = new Move(selectedSquare, sq, Piece.EMPTY);
setSelection(sq);
return m;
}
}
setSelection(-1);
} else {
if (oneTouchMoves) {
ArrayList<Move> moves = new
MoveGen().pseudoLegalMoves(pos);
moves = MoveGen.removeIllegal(pos, moves);
Move matchingMove = null;
int toSq = -1;
for (Move m : moves) {
if ((m.from == sq) || (m.to == sq)) {
if (matchingMove == null) {
matchingMove = m;
toSq = m.to;
} else {
matchingMove = null;
break;
}
}
}
if (matchingMove != null) {
setSelection(toSq);
return matchingMove;
}
}
if (myColor(p)) {
setSelection(sq);
}
}
return null;
}

public static class OnTrackballListener {


public void onTrackballEvent(MotionEvent event) {
}
}

private OnTrackballListener otbl = null;

public final void setOnTrackballListener(


OnTrackballListener onTrackballListener) {
otbl = onTrackballListener;
}

@Override
public boolean onTrackballEvent(MotionEvent event) {
if (otbl != null) {
otbl.onTrackballEvent(event);
return true;
}
return false;
}

protected int minValidY() {


return 0;
}

protected int getSquare(int x, int y) {


return Position.getSquare(x, y);
}

public final Move handleTrackballEvent(MotionEvent event) {


switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
invalidate();
if (cursorVisible) {
int x = Math.round(cursorX);
int y = Math.round(cursorY);
cursorX = x;
cursorY = y;
int sq = getSquare(x, y);
return mousePressed(sq);
}
return null;
}
cursorVisible = true;
int c = flipped ? -1 : 1;
cursorX += c * event.getX();
cursorY -= c * event.getY();
if (cursorX < 0)
cursorX = 0;
if (cursorX > 7)
cursorX = 7;
if (cursorY < minValidY())
cursorY = minValidY();
if (cursorY > 7)
cursorY = 7;
invalidate();
return null;
}

public final void setMoveHints(List<Move> moveHints) {


boolean equal = false;
if ((this.moveHints == null) || (moveHints == null)) {
equal = this.moveHints == moveHints;
} else {
equal = this.moveHints.equals(moveHints);
}
if (!equal) {
this.moveHints = moveHints;
invalidate();
}
}
}

private ChessBoardEdit cb;


private TextView status;
private Button okButton;
private Button cancelButton;
int choice,theme;
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

initUI();

SharedPreferences sharedPreferences =
PreferenceManager.getDefaultSharedPreferences(EditBoard.this);
theme = sharedPreferences.getInt("Theme",R.style.AppThemeGrey);
loadTheme();
super.setTheme(theme);
Intent i = getIntent();
Position pos;
try {
pos = TextIO.readFEN(i.getAction());
cb.setPosition(pos);
} catch (ChessParseError e) {
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {

getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
choice = sharedPreferences.getInt("Choice",4);
switch(choice)
{
default:

getWindow().setStatusBarColor(getResources().getColor(R.color.darkgrey));break;
}
}
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
ChessBoardEdit oldCB = cb;
String statusStr = status.getText().toString();
initUI();
cb.cursorX = oldCB.cursorX;
cb.cursorY = oldCB.cursorY;
cb.cursorVisible = oldCB.cursorVisible;
cb.setPosition(oldCB.pos);
cb.setSelection(oldCB.selectedSquare);
status.setText(statusStr);
}

private final void initUI() {


setContentView(R.layout.editboard);
cb = (ChessBoardEdit)findViewById(R.id.eb_chessboard);
status = (TextView)findViewById(R.id.eb_status);
okButton = (Button)findViewById(R.id.eb_ok);
cancelButton = (Button)findViewById(R.id.eb_cancel);

okButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
sendBackResult();
}
});
cancelButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
setResult(RESULT_CANCELED);
finish();
}
});

status.setFocusable(false);
cb.setFocusable(true);
cb.requestFocus();
cb.setClickable(true);
cb.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
int sq = cb.eventToSquare(event);
Move m = cb.mousePressed(sq);
if (m != null) {
doMove(m);
}
return false;
}
return false;
}
});
cb.setOnTrackballListener(new ChessBoard.OnTrackballListener() {
public void onTrackballEvent(MotionEvent event) {
Move m = cb.handleTrackballEvent(event);
if (m != null) {
doMove(m);
}
}
});
cb.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
showDialog(EDIT_DIALOG);
return true;
}
});
}

private void doMove(Move m) {


if (m.to < 0) {
if ((m.from < 0) || (cb.pos.getPiece(m.from) == Piece.EMPTY)) {
cb.setSelection(m.to);
return;
}
}
Position pos = new Position(cb.pos);
int piece = Piece.EMPTY;
if (m.from >= 0) {
piece = pos.getPiece(m.from);
} else {
piece = -(m.from + 2);
}
if (m.to >= 0)
pos.setPiece(m.to, piece);
if (m.from >= 0)
pos.setPiece(m.from, Piece.EMPTY);
cb.setPosition(pos);
cb.setSelection(-1);
checkValid();
}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
sendBackResult();
return true;
}
return super.onKeyDown(keyCode, event);
}

private final void sendBackResult() {


if (checkValid()) {
setPosFields();
String fen = TextIO.toFEN(cb.pos);
setResult(RESULT_OK, (new Intent()).setAction(fen));
} else {
setResult(RESULT_CANCELED);
}
finish();
}

private final void setPosFields() {


setEPFile(getEPFile()); // To handle sideToMove change
TextIO.fixupEPSquare(cb.pos);
TextIO.removeBogusCastleFlags(cb.pos);
}

private final int getEPFile() {


int epSquare = cb.pos.getEpSquare();
if (epSquare < 0) return 8;
return Position.getX(epSquare);
}

private final void setEPFile(int epFile) {


int epSquare = -1;
if ((epFile >= 0) && (epFile < 8)) {
int epRank = cb.pos.whiteMove ? 5 : 2;
epSquare = Position.getSquare(epFile, epRank);
}
cb.pos.setEpSquare(epSquare);
}

/** Test if a position is valid. */


private final boolean checkValid() {
try {
String fen = TextIO.toFEN(cb.pos);
TextIO.readFEN(fen);
status.setText("");
return true;
} catch (ChessParseError e) {
status.setText(e.getMessage());
}
return false;
}

static final int EDIT_DIALOG = 0;


static final int SIDE_DIALOG = 1;
static final int CASTLE_DIALOG = 2;
static final int EP_DIALOG = 3;
static final int MOVCNT_DIALOG = 4;

@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case EDIT_DIALOG: {
final CharSequence[] items = {
getString(R.string.side_to_move),
getString(R.string.clear_board),
getString(R.string.initial_position),
getString(R.string.castling_flags),
getString(R.string.en_passant_file),
getString(R.string.move_counters),
getString(R.string.copy_position),
getString(R.string.paste_position)
};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.edit_board);
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
switch (item) {
case 0: // Edit side to move
showDialog(SIDE_DIALOG);
cb.setSelection(-1);
checkValid();
break;
case 1: { // Clear board
Position pos = new Position();
cb.setPosition(pos);
cb.setSelection(-1);
checkValid();
break;
}
case 2: { // Set initial position
try {
Position pos =
TextIO.readFEN(TextIO.startPosFEN);
cb.setPosition(pos);
cb.setSelection(-1);
checkValid();
} catch (ChessParseError e) {
}
break;
}
case 3: // Edit castling flags
removeDialog(CASTLE_DIALOG);
showDialog(CASTLE_DIALOG);
cb.setSelection(-1);
checkValid();
break;
case 4: // Edit en passant file
removeDialog(EP_DIALOG);
showDialog(EP_DIALOG);
cb.setSelection(-1);
checkValid();
break;
case 5: // Edit move counters
removeDialog(MOVCNT_DIALOG);
showDialog(MOVCNT_DIALOG);
cb.setSelection(-1);
checkValid();
break;
case 6: { // Copy position
setPosFields();
String fen = TextIO.toFEN(cb.pos) + "\n";
ClipboardManager clipboard =
(ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
clipboard.setText(fen);
cb.setSelection(-1);
break;
}
case 7: { // Paste position
ClipboardManager clipboard =
(ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
if (clipboard.hasText()) {
String fen = clipboard.getText().toString();
try {
Position pos = TextIO.readFEN(fen);
cb.setPosition(pos);
} catch (ChessParseError e) {
if (e.pos != null)
cb.setPosition(e.pos);

Toast.makeText(getApplicationContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
cb.setSelection(-1);
checkValid();
}
break;
}
}
}
});
AlertDialog alert = builder.create();
return alert;
}
case SIDE_DIALOG: {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.select_side_to_move_first)
.setPositiveButton(R.string.white, new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
cb.pos.setWhiteMove(true);
checkValid();
dialog.cancel();
}
})
.setNegativeButton(R.string.black, new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
cb.pos.setWhiteMove(false);
checkValid();
dialog.cancel();
}
});
AlertDialog alert = builder.create();
return alert;
}
case CASTLE_DIALOG: {
final CharSequence[] items = {
getString(R.string.white_king_castle),
getString(R.string.white_queen_castle),
getString(R.string.black_king_castle),
getString(R.string.black_queen_castle)
};
boolean[] checkedItems = {
cb.pos.h1Castle(), cb.pos.a1Castle(),
cb.pos.h8Castle(), cb.pos.a8Castle()
};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.castling_flags);
builder.setMultiChoiceItems(items, checkedItems, new
DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which,
boolean isChecked) {
Position pos = new Position(cb.pos);
boolean a1Castle = pos.a1Castle();
boolean h1Castle = pos.h1Castle();
boolean a8Castle = pos.a8Castle();
boolean h8Castle = pos.h8Castle();
switch (which) {
case 0: h1Castle = isChecked; break;
case 1: a1Castle = isChecked; break;
case 2: h8Castle = isChecked; break;
case 3: a8Castle = isChecked; break;
}
int castleMask = 0;
if (a1Castle) castleMask |= 1 << Position.A1_CASTLE;
if (h1Castle) castleMask |= 1 << Position.H1_CASTLE;
if (a8Castle) castleMask |= 1 << Position.A8_CASTLE;
if (h8Castle) castleMask |= 1 << Position.H8_CASTLE;
pos.setCastleMask(castleMask);
cb.setPosition(pos);
checkValid();
}
});
AlertDialog alert = builder.create();
return alert;
}
case EP_DIALOG: {
final CharSequence[] items = {
"A", "B", "C", "D", "E", "F", "G", "H",
getString(R.string.none)
};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.select_en_passant_file);
builder.setSingleChoiceItems(items, getEPFile(), new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
setEPFile(item);
}
});
AlertDialog alert = builder.create();
return alert;
}
case MOVCNT_DIALOG: {
final Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.edit_move_counters);
dialog.setTitle(R.string.edit_move_counters);
final EditText halfMoveClock =
(EditText)dialog.findViewById(R.id.ed_cnt_halfmove);
final EditText fullMoveCounter =
(EditText)dialog.findViewById(R.id.ed_cnt_fullmove);
Button ok = (Button)dialog.findViewById(R.id.ed_cnt_ok);
Button cancel = (Button)dialog.findViewById(R.id.ed_cnt_cancel);
halfMoveClock.setText(String.format("%d", cb.pos.halfMoveClock));
fullMoveCounter.setText(String.format("%d",
cb.pos.fullMoveCounter));
final Runnable setCounters = new Runnable() {
public void run() {
try {
int halfClock =
Integer.parseInt(halfMoveClock.getText().toString());
int fullCount =
Integer.parseInt(fullMoveCounter.getText().toString());
cb.pos.halfMoveClock = halfClock;
cb.pos.fullMoveCounter = fullCount;
dialog.cancel();
} catch (NumberFormatException nfe) {
Toast.makeText(getApplicationContext(),
R.string.invalid_number_format, Toast.LENGTH_SHORT).show();
}
}
};
fullMoveCounter.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
(keyCode == KeyEvent.KEYCODE_ENTER)) {
setCounters.run();
return true;
}
return false;
}
});
ok.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
setCounters.run();
}
});
cancel.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
dialog.cancel();
}
});
return dialog;
}
}
return null;
}

protected void loadTheme()


{
SharedPreferences sharedPreferences =
PreferenceManager.getDefaultSharedPreferences(EditBoard.this);
theme = sharedPreferences.getInt("Theme",R.style.AppThemeRed);
super.setTheme(theme);

}
}