Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
PgnScreenText gameTextListener;
int choice,theme;
public static Context contextOfApplication;
ShowcaseView sv;
private ViewTarget target;
private LinearLayout homelayout;
private SharedPreferences sharedPreferences;
private Toolbar toolbar;
sharedPreferences =
PreferenceManager.getDefaultSharedPreferences(ChessTastic.this);
theme = sharedPreferences.getInt("Theme",R.style.AppThemeGrey);
loadTheme();
super.setTheme(theme);
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);
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();
}
@Override
public void onBackPressed() {
if(drawerLayoutt.isDrawerOpen(Gravity.START|Gravity.LEFT)){
drawerLayoutt.closeDrawers();
return;
}
super.onBackPressed();
}
@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();
}
@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();
}
@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();
@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);
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);
@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);
}*/
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();
// record the fact that the app has been started at least once
settings2.edit().putBoolean("my_first_time", false).commit();
}
cb = (ChessBoard) findViewById(R.id.chessboard);
cb.setFocusable(true);
cb.requestFocus();
cb.setClickable(true);
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;
}
@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();
}
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;
}
menu.getItem(i).setVisible(visible);
}
}
@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;
}
}
setBoardFlip();
}
@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();
}
@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();
}
@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;
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;
}
@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);
}
setNotification(warn);
}
mNotificationManager.notify(cpuUsage, notification);
} else {
mNotificationManager.cancel(cpuUsage);
}
}
PgnScreenText(PGNOptions options) {
nodeToCharPos = new HashMap<Node, NodeInfo>();
this.options = options;
}
int paraStart = 0;
int paraIndent = 0;
boolean paraBold = false;
@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;
}
@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) {
}
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");
// 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;
setColors();
}
selectedSquarePaint.setColor(Appearance.getColor(Appearance.SELECTED_SQUARE));
cursorSquarePaint.setColor(Appearance.getColor(Appearance.CURSOR_SQUARE));
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();
}
}
@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);
}
@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);
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);
/**
* 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;
}
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;
}
@Override
public boolean onTrackballEvent(MotionEvent event) {
if (otbl != null) {
otbl.onTrackballEvent(event);
return true;
}
return false;
}
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);
}
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;
}
});
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
sendBackResult();
return true;
}
return super.onKeyDown(keyCode, event);
}
@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;
}
}
}