New algorithm. Transliteration

master
ubulem 2016-02-11 16:26:38 +03:00
parent a721088e4d
commit 6b1e289987
5 changed files with 504 additions and 363 deletions

View File

@ -13,6 +13,16 @@ public class MCNativeActivity extends NativeActivity {
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
Log.e("WTF", e.getLocalizedMessage());
}
}
}, 2000);
m_MessagReturnCode = -1; m_MessagReturnCode = -1;
m_MessageReturnValue = ""; m_MessageReturnValue = "";
} }

View File

@ -1,18 +1,5 @@
package mobi.MultiCraft; package mobi.MultiCraft;
import static mobi.MultiCraft.PreferencesHelper.TAG_BUILD_NUMBER;
import static mobi.MultiCraft.PreferencesHelper.TAG_SHORTCUT_CREATED;
import static mobi.MultiCraft.PreferencesHelper.getBuildNumber;
import static mobi.MultiCraft.PreferencesHelper.isCreateShortcut;
import static mobi.MultiCraft.PreferencesHelper.loadSettings;
import static mobi.MultiCraft.PreferencesHelper.saveSettings;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.Manifest; import android.Manifest;
import android.annotation.SuppressLint; import android.annotation.SuppressLint;
import android.app.Activity; import android.app.Activity;
@ -35,260 +22,289 @@ import android.view.View;
import android.view.WindowManager; import android.view.WindowManager;
import android.widget.ProgressBar; import android.widget.ProgressBar;
import android.widget.Toast; import android.widget.Toast;
import net.MultiCraft.Official.R;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import static mobi.MultiCraft.PreferencesHelper.TAG_BUILD_NUMBER;
import static mobi.MultiCraft.PreferencesHelper.TAG_SHORTCUT_CREATED;
import static mobi.MultiCraft.PreferencesHelper.getBuildNumber;
import static mobi.MultiCraft.PreferencesHelper.isCreateShortcut;
import static mobi.MultiCraft.PreferencesHelper.loadSettings;
import static mobi.MultiCraft.PreferencesHelper.saveSettings;
public class MainActivity extends Activity { public class MainActivity extends Activity {
public final static String TAG = "Error"; public final static String TAG = "Error";
public final static String CREATE_SHORTCUT = "com.android.launcher.action.INSTALL_SHORTCUT"; public final static String CREATE_SHORTCUT = "com.android.launcher.action.INSTALL_SHORTCUT";
public final static String FILES = Environment.getExternalStorageDirectory() + "/Files.zip"; public final static String FILES = Environment.getExternalStorageDirectory() + "/Files.zip";
public final static String WORLDS = Environment.getExternalStorageDirectory() + "/worlds.zip"; public final static String WORLDS = Environment.getExternalStorageDirectory() + "/worlds.zip";
public final static String GAMES = Environment.getExternalStorageDirectory() + "/games.zip"; public final static String GAMES = Environment.getExternalStorageDirectory() + "/games.zip";
public final static String NOMEDIA = ".nomedia"; public final static String NOMEDIA = ".nomedia";
private final static int REQUEST_STORAGE = 0; private final static int REQUEST_STORAGE = 0;
private ProgressDialog mProgressDialog; private ProgressDialog mProgressDialog;
private String dataFolder = "/Android/data/net.MultiCraft.Official/files/"; private String oldDataFolder = "/MultiCraft";
private String unzipLocation = Environment.getExternalStorageDirectory() + dataFolder; private String dataFolder = "/Android/data/mobi.MultiCraft/files/";
private ProgressBar mProgressBar; private String unzipLocation = Environment.getExternalStorageDirectory() + dataFolder;
private Utilities util; private String oldUnzipLocation = Environment.getExternalStorageDirectory() + oldDataFolder;
private String oldWorldLocation = oldUnzipLocation + "/worlds";
private String oldGamesLocation = oldUnzipLocation + "/games/MultiCraft_game";
private String newWorldLocation = unzipLocation + "/worlds";
private String newGamesLocation = unzipLocation + "/games/MultiCraft_game";
private ProgressBar mProgressBar;
private Utilities util;
private boolean isCopyOld = false;
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); setContentView(R.layout.activity_main);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
loadSettings(this); loadSettings(this);
IntentFilter filter = new IntentFilter(UnzipService.ACTION_UPDATE); IntentFilter filter = new IntentFilter(UnzipService.ACTION_UPDATE);
registerReceiver(myReceiver, filter); registerReceiver(myReceiver, filter);
if (!isTaskRoot()) { if (!isTaskRoot()) {
finish(); finish();
return; return;
} }
if (ActivityCompat.checkSelfPermission(this, if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestStoragePermission(); requestStoragePermission();
} else { } else {
init(); init();
} }
} }
@Override @Override
protected void onDestroy() { protected void onDestroy() {
super.onDestroy(); super.onDestroy();
dismissProgressDialog(); dismissProgressDialog();
unregisterReceiver(myReceiver); unregisterReceiver(myReceiver);
} }
private void addShortcut() { private void addShortcut() {
saveSettings(TAG_SHORTCUT_CREATED, false); saveSettings(TAG_SHORTCUT_CREATED, false);
Intent shortcutIntent = new Intent(getApplicationContext(), MainActivity.class); Intent shortcutIntent = new Intent(getApplicationContext(), MainActivity.class);
shortcutIntent.setAction(Intent.ACTION_MAIN); shortcutIntent.setAction(Intent.ACTION_MAIN);
Intent addIntent = new Intent(); Intent addIntent = new Intent();
addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent); addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.app_name)); addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.app_name));
addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
Intent.ShortcutIconResource.fromContext(getApplicationContext(), R.drawable.ic_launcher)); Intent.ShortcutIconResource.fromContext(getApplicationContext(), R.drawable.ic_launcher));
addIntent.setAction(CREATE_SHORTCUT); addIntent.setAction(CREATE_SHORTCUT);
getApplicationContext().sendBroadcast(addIntent); getApplicationContext().sendBroadcast(addIntent);
} }
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public void init() { public void init() {
if (isCreateShortcut()) if (isCreateShortcut())
addShortcut(); addShortcut();
mProgressBar = (ProgressBar) findViewById(R.id.PB1); mProgressBar = (ProgressBar) findViewById(R.id.PB1);
Drawable draw; Drawable draw;
draw = getResources().getDrawable(R.drawable.custom_progress_bar); draw = getResources().getDrawable(R.drawable.custom_progress_bar);
mProgressBar.setProgressDrawable(draw); mProgressBar.setProgressDrawable(draw);
util = new Utilities(); util = new Utilities();
util.createDirAndFiles(); util.createDataFolder();
if (getBuildNumber().equals("0")) { util.checkVersion();
saveSettings(TAG_BUILD_NUMBER, getString(R.string.ver)); }
util.startDeletion(true);
} else {
util.checkVersion();
}
}
private void requestPermissionAfterExplain() { private void requestPermissionAfterExplain() {
Toast.makeText(this, R.string.explain, Toast.LENGTH_LONG).show(); Toast.makeText(this, R.string.explain, Toast.LENGTH_LONG).show();
ActivityCompat.requestPermissions(MainActivity.this, ActivityCompat.requestPermissions(MainActivity.this,
new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, REQUEST_STORAGE); new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_STORAGE);
} }
private void requestStoragePermission() { private void requestStoragePermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
requestPermissionAfterExplain(); requestPermissionAfterExplain();
} else { } else {
ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
REQUEST_STORAGE); REQUEST_STORAGE);
} }
} }
@Override @Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) { @NonNull int[] grantResults) {
// Check if the only required permission has been granted // Check if the only required permission has been granted
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
init(); init();
} else { } else {
requestStoragePermission(); requestStoragePermission();
} }
} }
private void showSpinnerDialog(int message) { private void showSpinnerDialog(int message) {
if (mProgressDialog == null) { if (mProgressDialog == null) {
mProgressDialog = new ProgressDialog(MainActivity.this); mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mProgressDialog.setCancelable(false); mProgressDialog.setCancelable(false);
} }
mProgressDialog.setMessage(getString(message)); mProgressDialog.setMessage(getString(message));
mProgressDialog.show(); mProgressDialog.show();
} }
private void dismissProgressDialog() { private void dismissProgressDialog() {
if (mProgressDialog != null && mProgressDialog.isShowing()) { if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.dismiss(); mProgressDialog.dismiss();
} }
} }
public void runGame() { public void runGame() {
Intent intent = new Intent(MainActivity.this, MCNativeActivity.class); util.deleteZip(FILES);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK); util.deleteZip(WORLDS);
startActivity(intent); util.deleteZip(GAMES);
if (isFinishing()) Intent intent = new Intent(MainActivity.this, MCNativeActivity.class);
return; intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK);
dismissProgressDialog(); startActivity(intent);
util.deleteZip(FILES); }
util.deleteZip(WORLDS);
util.deleteZip(GAMES);
}
private void startUnzipService(String[] file) throws IOException { private void startUnzipService(String[] file) throws IOException {
// Start MyIntentService // Start MyIntentService
Intent intentMyIntentService = new Intent(this, UnzipService.class); Intent intentMyIntentService = new Intent(this, UnzipService.class);
intentMyIntentService.putExtra(UnzipService.EXTRA_KEY_IN_FILE, file); intentMyIntentService.putExtra(UnzipService.EXTRA_KEY_IN_FILE, file);
intentMyIntentService.putExtra(UnzipService.EXTRA_KEY_IN_LOCATION, unzipLocation); intentMyIntentService.putExtra(UnzipService.EXTRA_KEY_IN_LOCATION, unzipLocation);
startService(intentMyIntentService); startService(intentMyIntentService);
} }
private BroadcastReceiver myReceiver = new BroadcastReceiver() { private BroadcastReceiver myReceiver = new BroadcastReceiver() {
@Override @Override
public void onReceive(Context context, Intent intent) { public void onReceive(Context context, Intent intent) {
int progress = intent.getIntExtra(UnzipService.ACTION_PROGRESS, 0); int progress = intent.getIntExtra(UnzipService.ACTION_PROGRESS, 0);
if (progress >= 0) { if (progress >= 0) {
mProgressBar.setVisibility(View.VISIBLE); mProgressBar.setVisibility(View.VISIBLE);
mProgressBar.setProgress(progress); mProgressBar.setProgress(progress);
} else { } else {
runGame(); util.createNomedia();
} if (isCopyOld) {
} new CopyFolderTask().execute(new String[]{oldWorldLocation, newWorldLocation}, new String[]{oldGamesLocation, newGamesLocation});
}; } else {
runGame();
}
}
}
};
private class DeleteTask extends AsyncTask<String, Void, Void> { private class DeleteTask extends AsyncTask<String, Void, Void> {
String location; String location;
@Override @Override
protected void onPreExecute() { protected void onPreExecute() {
super.onPreExecute(); super.onPreExecute();
showSpinnerDialog(R.string.rm_old); showSpinnerDialog(R.string.rm_old);
} }
@Override @Override
protected Void doInBackground(String... params) { protected Void doInBackground(String... params) {
location = params[0]; location = params[0];
for (String p : params) { for (String p : params) {
deleteFiles(p); util.deleteFiles(p);
} }
return null; return null;
} }
@Override @Override
protected void onPostExecute(Void result) { protected void onPostExecute(Void result) {
if (isFinishing()) if (isFinishing())
return; return;
dismissProgressDialog(); dismissProgressDialog();
if (unzipLocation.equals(location)) { if (unzipLocation.equals(location)) {
new CopyZip().execute(FILES, WORLDS, GAMES); new CopyZip().execute(FILES, WORLDS, GAMES);
} else { } else {
new CopyZip().execute(FILES, GAMES); new CopyZip().execute(FILES, GAMES);
} }
} }
private void deleteFiles(String path) {
File file = new File(path);
if (file.exists()) {
String deleteCmd = "rm -r " + path;
Runtime runtime = Runtime.getRuntime();
try {
runtime.exec(deleteCmd);
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage());
}
}
}
}
private class CopyZip extends AsyncTask<String, Void, String> { }
String[] zips;
@Override private class CopyFolderTask extends AsyncTask<String[], Void, Void> {
protected void onPreExecute() {
super.onPreExecute();
}
@Override @Override
protected String doInBackground(String... params) { protected Void doInBackground(String[]... params) {
zips = params; for (String[] p : params) {
for (String s : zips) { File src = new File(p[0]);
copyAssets(s); File dest = new File(p[1]);
} try {
return "Done"; util.copyDirectory(src, dest);
} catch (IOException e) {
Log.e(TAG, "copy failed: " + e.getMessage());
}
}
return null;
}
} @Override
protected void onPostExecute(Void aVoid) {
util.deleteFiles(oldUnzipLocation);
runGame();
}
}
@Override private class CopyZip extends AsyncTask<String, Void, String> {
protected void onPostExecute(String result) { String[] zips;
if (util.getAvailableSpaceInMB() > 25) {
try {
startUnzipService(zips);
} catch (IOException e) {
Log.e(TAG, e.getMessage());
}
} else
Toast.makeText(MainActivity.this, R.string.not_enough_space, Toast.LENGTH_LONG).show();
}
private void copyAssets(String zipName) { @Override
String filename = zipName.substring(zipName.lastIndexOf("/") + 1); protected void onPreExecute() {
InputStream in; super.onPreExecute();
OutputStream out; }
try {
in = getAssets().open(filename);
out = new FileOutputStream(zipName);
copyFile(in, out);
in.close();
out.flush();
out.close();
} catch (IOException e) {
Log.e(TAG, "Failed to copy asset file: " + e.getMessage());
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException { @Override
byte[] buffer = new byte[1024]; protected String doInBackground(String... params) {
int read; zips = params;
while ((read = in.read(buffer)) != -1) { for (String s : zips) {
out.write(buffer, 0, read); copyAssets(s);
} }
} return "Done";
}
private class Utilities { }
@Override
protected void onPostExecute(String result) {
if (util.getAvailableSpaceInMB() > 25) {
try {
startUnzipService(zips);
} catch (IOException e) {
Log.e(TAG, "unzip failed: " + e.getMessage());
}
} else
Toast.makeText(MainActivity.this, R.string.not_enough_space, Toast.LENGTH_LONG).show();
}
private void copyAssets(String zipName) {
String filename = zipName.substring(zipName.lastIndexOf("/") + 1);
InputStream in;
OutputStream out;
try {
in = getAssets().open(filename);
out = new FileOutputStream(zipName);
copyFile(in, out);
in.close();
out.flush();
out.close();
} catch (IOException e) {
Log.e(TAG, "Failed to copy asset file: " + e.getMessage());
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
}
}
private class Utilities {
/* /*
* private void createLangFile() { PrintWriter writer; try { writer = * private void createLangFile() { PrintWriter writer; try { writer =
* new PrintWriter(unzipLocation + "lang.txt", "UTF-8"); if * new PrintWriter(unzipLocation + "lang.txt", "UTF-8"); if
* ("Russian".equals(Locale.getDefault().getDisplayLanguage())) { * ("Russian".equals(Locale.getDefault().getDisplayLanguage())) {
* writer.println("ru"); } else { writer.println("en"); } * writer.println("ru"); } else { writer.println("en"); }
@ -298,65 +314,119 @@ public class MainActivity extends Activity {
* } * }
*/ */
private void createDirAndFiles() { private void createDataFolder() {
try { File folder = new File(unzipLocation);
File folder = new File(unzipLocation); if (!(folder.exists()))
if (!(folder.exists())) folder.mkdirs();
folder.mkdirs(); }
File myFile = new File(unzipLocation, NOMEDIA);
if (!myFile.exists())
myFile.createNewFile();
// createLangFile();
} catch (IOException e) {
Log.e(TAG, e.getMessage());
}
}
private void deleteZip(String fileName) { private void deleteZip(String fileName) {
File file = new File(fileName); File file = new File(fileName);
if (file.exists()) if (file.exists())
file.delete(); file.delete();
} }
private void startDeletion(boolean isAll) { private void startDeletion(boolean isAll) {
if (isAll) { if (isAll) {
new DeleteTask().execute(unzipLocation); new DeleteTask().execute(unzipLocation);
} else { } else {
new DeleteTask().execute(unzipLocation + "textures", unzipLocation + "games", unzipLocation + "builtin", new DeleteTask().execute(unzipLocation + "textures", unzipLocation + "games/MultiCraft", unzipLocation + "builtin",
unzipLocation + "fonts", unzipLocation + "debug.txt"); unzipLocation + "fonts", unzipLocation + "debug.txt");
} }
}
} @SuppressWarnings("deprecation")
@SuppressLint("NewApi")
private long getAvailableSpaceInMB() {
final long SIZE_KB = 1024L;
final long SIZE_MB = SIZE_KB * SIZE_KB;
long availableSpace;
StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
if (Build.VERSION.SDK_INT > 17) {
availableSpace = stat.getAvailableBlocksLong() * stat.getBlockSizeLong();
} else {
availableSpace = (long) stat.getAvailableBlocks() * (long) stat.getBlockSize();
}
return availableSpace / SIZE_MB;
}
@SuppressWarnings("deprecation") private boolean isFolderEmpty(String folder) {
@SuppressLint("NewApi") File location = new File(folder);
private long getAvailableSpaceInMB() { File[] contents = location.listFiles();
final long SIZE_KB = 1024L; return contents == null || contents.length == 0;
final long SIZE_MB = SIZE_KB * SIZE_KB; }
long availableSpace;
StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
if (Build.VERSION.SDK_INT > 17) {
availableSpace = stat.getAvailableBlocksLong() * stat.getBlockSizeLong();
} else {
availableSpace = (long) stat.getAvailableBlocks() * (long) stat.getBlockSize();
}
return availableSpace / SIZE_MB;
}
public void checkVersion() { public void checkVersion() {
File location = new File(unzipLocation); if (isFolderEmpty(oldUnzipLocation) && isFolderEmpty(unzipLocation)) {
File[] contents = location.listFiles(); saveSettings(TAG_BUILD_NUMBER, getString(R.string.ver));
if (contents == null) { startDeletion(true);
Log.e(TAG, "Wrong path to unzip"); } else if (!isFolderEmpty(oldUnzipLocation)) {
} else if (contents.length == 1) { saveSettings(TAG_BUILD_NUMBER, getString(R.string.ver));
saveSettings(TAG_BUILD_NUMBER, getString(R.string.ver)); isCopyOld = true;
startDeletion(true); startDeletion(true);
} else if (getBuildNumber().equals(getString(R.string.ver))) { } else if (getBuildNumber().equals(getString(R.string.ver))) {
runGame(); runGame();
} else { } else {
saveSettings(TAG_BUILD_NUMBER, getString(R.string.ver)); saveSettings(TAG_BUILD_NUMBER, getString(R.string.ver));
startDeletion(false); startDeletion(false);
} }
} }
}
public void copyDirectory(File sourceLocation, File targetLocation)
throws IOException {
if (sourceLocation.isDirectory()) {
if (!targetLocation.exists() && !targetLocation.mkdirs()) {
throw new IOException("Cannot create dir " + targetLocation.getAbsolutePath());
}
String[] children = sourceLocation.list();
for (String aChildren : children) {
copyDirectory(new File(sourceLocation, aChildren),
new File(targetLocation, aChildren));
}
} else {
// make sure the directory we plan to store the recording in exists
File directory = targetLocation.getParentFile();
if (directory != null && !directory.exists() && !directory.mkdirs()) {
throw new IOException("Cannot create dir " + directory.getAbsolutePath());
}
InputStream in = new FileInputStream(sourceLocation);
OutputStream out = new FileOutputStream(targetLocation);
// Copy the bits from in stream to out stream
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
}
private void deleteFiles(String path) {
File file = new File(path);
if (file.exists()) {
String deleteCmd = "rm -r " + path;
Runtime runtime = Runtime.getRuntime();
try {
runtime.exec(deleteCmd);
} catch (IOException e) {
Log.e(TAG, "delete files failed: " + e.getLocalizedMessage());
}
}
}
public void createNomedia() {
File myFile = new File(unzipLocation, NOMEDIA);
if (!myFile.exists())
try {
myFile.createNewFile();
} catch (IOException e) {
Log.e(TAG, "nomedia has not been created: " + e.getMessage());
}
}
}
} }

View File

@ -5,92 +5,82 @@ import android.app.AlertDialog;
import android.content.DialogInterface; import android.content.DialogInterface;
import android.content.Intent; import android.content.Intent;
import android.os.Bundle; import android.os.Bundle;
import android.text.InputFilter;
import android.text.InputType; import android.text.InputType;
import android.text.Spanned;
import android.view.KeyEvent; import android.view.KeyEvent;
import android.view.View; import android.view.View;
import android.view.View.OnKeyListener; import android.view.View.OnKeyListener;
import android.widget.EditText; import android.widget.EditText;
import net.MultiCraft.Official.R;
public class MultiCraftTextEntry extends Activity { public class MultiCraftTextEntry extends Activity {
public AlertDialog mTextInputDialog; public AlertDialog mTextInputDialog;
public EditText mTextInputWidget; public EditText mTextInputWidget;
private final int MultiLineTextInput = 1; private final int MultiLineTextInput = 1;
private final int SingleLinePasswordInput = 3; private final int SingleLinePasswordInput = 3;
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
Bundle b = getIntent().getExtras(); Bundle b = getIntent().getExtras();
String acceptButton = b.getString("EnterButton"); String acceptButton = b.getString("EnterButton");
// String hint = b.getString("hint"); // String hint = b.getString("hint");
String hint = getString(R.string.name); String hint = getString(R.string.name);
String current = b.getString("current"); String current = b.getString("current");
int editType = b.getInt("editType"); int editType = b.getInt("editType");
AlertDialog.Builder builder = new AlertDialog.Builder(this); AlertDialog.Builder builder = new AlertDialog.Builder(this);
mTextInputWidget = new EditText(this); mTextInputWidget = new EditText(this);
mTextInputWidget.setHint(hint); mTextInputWidget.setHint(hint);
mTextInputWidget.setText(current); mTextInputWidget.setText(current);
mTextInputWidget.setMinWidth(300); mTextInputWidget.setMinWidth(300);
if (editType == SingleLinePasswordInput) { if (editType == SingleLinePasswordInput) {
mTextInputWidget.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); mTextInputWidget.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
} else { } else {
mTextInputWidget.setInputType(InputType.TYPE_CLASS_TEXT); mTextInputWidget.setInputType(InputType.TYPE_CLASS_TEXT);
mTextInputWidget.setFilters(new InputFilter[] { new InputFilter() { }
public CharSequence filter(CharSequence src, int start, int end, Spanned dst, int dstart, int dend) {
if (src.equals("")) { // for backspace
return src;
}
if (!src.toString().matches("[à-ÿÀ-ß]+")) {
return src;
}
return "";
}
} });
}
builder.setView(mTextInputWidget); builder.setView(mTextInputWidget);
if (editType == MultiLineTextInput) { if (editType == MultiLineTextInput) {
builder.setPositiveButton(acceptButton, new DialogInterface.OnClickListener() { builder.setPositiveButton(acceptButton, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) { public void onClick(DialogInterface dialog, int whichButton) {
pushResult(mTextInputWidget.getText().toString()); pushResult(mTextInputWidget.getText().toString());
} }
}); });
} }
builder.setOnCancelListener(new DialogInterface.OnCancelListener() { builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) { public void onCancel(DialogInterface dialog) {
pushResult(mTextInputWidget.getText().toString()); pushResult(mTextInputWidget.getText().toString());
} }
}); });
mTextInputWidget.setOnKeyListener(new OnKeyListener() { mTextInputWidget.setOnKeyListener(new OnKeyListener() {
@Override @Override
public boolean onKey(View view, int KeyCode, KeyEvent event) { public boolean onKey(View view, int KeyCode, KeyEvent event) {
if (KeyCode == KeyEvent.KEYCODE_ENTER) { if (KeyCode == KeyEvent.KEYCODE_ENTER) {
pushResult(mTextInputWidget.getText().toString()); pushResult(mTextInputWidget.getText().toString());
return true; return true;
} }
return false; return false;
} }
}); });
mTextInputDialog = builder.create(); mTextInputDialog = builder.create();
mTextInputDialog.show(); mTextInputDialog.show();
} }
public void pushResult(String text) { public void pushResult(String text) {
Intent resultData = new Intent(); if (text.matches(".*[А-я].*")) {
resultData.putExtra("text", text); text = Transliteration.toLatin(text);
setResult(Activity.RESULT_OK, resultData); }
mTextInputDialog.dismiss(); Intent resultData = new Intent();
finish(); resultData.putExtra("text", text);
} setResult(Activity.RESULT_OK, resultData);
mTextInputDialog.dismiss();
finish();
}
} }

View File

@ -0,0 +1,72 @@
package mobi.MultiCraft;
public class Transliteration {
private static final String[] CHAR_TABLE = new String[81];
private static final char START_CHAR = 'Ё';
static {
CHAR_TABLE['А' - START_CHAR] = "A";
CHAR_TABLE['Б' - START_CHAR] = "B";
CHAR_TABLE['В' - START_CHAR] = "V";
CHAR_TABLE['Г' - START_CHAR] = "G";
CHAR_TABLE['Д' - START_CHAR] = "D";
CHAR_TABLE['Е' - START_CHAR] = "E";
CHAR_TABLE['Ё' - START_CHAR] = "E";
CHAR_TABLE['Ж' - START_CHAR] = "ZH";
CHAR_TABLE['З' - START_CHAR] = "Z";
CHAR_TABLE['И' - START_CHAR] = "I";
CHAR_TABLE['Й' - START_CHAR] = "J";
CHAR_TABLE['К' - START_CHAR] = "K";
CHAR_TABLE['Л' - START_CHAR] = "L";
CHAR_TABLE['М' - START_CHAR] = "M";
CHAR_TABLE['Н' - START_CHAR] = "N";
CHAR_TABLE['О' - START_CHAR] = "O";
CHAR_TABLE['П' - START_CHAR] = "P";
CHAR_TABLE['Р' - START_CHAR] = "R";
CHAR_TABLE['С' - START_CHAR] = "TS";
CHAR_TABLE['Т' - START_CHAR] = "T";
CHAR_TABLE['У' - START_CHAR] = "U";
CHAR_TABLE['Ф' - START_CHAR] = "F";
CHAR_TABLE['Х' - START_CHAR] = "H";
CHAR_TABLE['Ц' - START_CHAR] = "C";
CHAR_TABLE['Ч' - START_CHAR] = "CH";
CHAR_TABLE['Ш' - START_CHAR] = "SH";
CHAR_TABLE['Щ' - START_CHAR] = "SHCH";
CHAR_TABLE['Ъ' - START_CHAR] = "";
CHAR_TABLE['Ы' - START_CHAR] = "Y";
CHAR_TABLE['Ь' - START_CHAR] = "";
CHAR_TABLE['Э' - START_CHAR] = "E";
CHAR_TABLE['Ю' - START_CHAR] = "U";
CHAR_TABLE['Я' - START_CHAR] = "YA";
for (int i = 0; i < CHAR_TABLE.length; i++) {
char idx = (char) ((char) i + START_CHAR);
char lower = new String(new char[]{idx}).toLowerCase().charAt(0);
if (CHAR_TABLE[i] != null) {
CHAR_TABLE[lower - START_CHAR] = CHAR_TABLE[i].toLowerCase();
}
}
}
/**
* Переводит русский текст в транслит. В результирующей строке
* каждая русская буква будет заменена на соответствующую английскую.
* Не русские символы останутся прежними.
*/
public static String toLatin(String text) {
char charBuffer[] = text.toCharArray();
StringBuilder sb = new StringBuilder(text.length());
for (char symbol : charBuffer) {
int i = symbol - START_CHAR;
if (i >= 0 && i < CHAR_TABLE.length) {
String replace = CHAR_TABLE[i];
sb.append(replace == null ? symbol : replace);
} else {
sb.append(symbol);
}
}
return sb.toString();
}
}

View File

@ -15,7 +15,6 @@ import android.app.NotificationManager;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.util.Log; import android.util.Log;
import net.MultiCraft.Official.R;
public class UnzipService extends IntentService { public class UnzipService extends IntentService {
public final String TAG = UnzipService.class.getSimpleName(); public final String TAG = UnzipService.class.getSimpleName();