Compare commits

...
29 Commits
Author SHA1 Message Date
seven332 d1cac3c1ac Merge branch 'axlecho-master' into dict 2016-04-14 20:49:03 +08:00
seven332 3924de80b7 Add DictActivity 2016-04-07 16:27:36 +08:00
seven332 dc1e327caa Add busy flag to protect dict db when importing 2016-04-05 23:16:08 +08:00
seven332 84808429cf Clean up 2016-04-05 16:45:37 +08:00
seven332 766c265cd6 Use utf4 table to speed up 2016-04-05 16:45:15 +08:00
seven332 4cce07e0aa Control import dict log with DEBUG variable 2016-04-05 15:23:03 +08:00
seven332 e56467dd4d Add missing icon 2016-04-05 15:21:32 +08:00
seven332 90c0d832d7 Add missing string 2016-04-05 15:21:05 +08:00
seven332 729bef38fb Improve import dict notification 2016-04-05 15:16:14 +08:00
seven332 59aab0498e Make import dict safer 2016-04-05 14:43:00 +08:00
seven332 863170e013 Fix typo and clean up Import Dict 2016-04-05 14:36:25 +08:00
seven332 e62b86bf7d Improve importing dict speed 2016-04-05 14:29:03 +08:00
seven332 0e018581a0 Fix cancel import dict Null error 2016-04-05 14:18:25 +08:00
seven332 a19f1e2d6d Improve dict import layout 2016-04-05 14:16:06 +08:00
seven332 987ef9ecf4 Improve dict import intent-filter and text 2016-04-05 13:58:16 +08:00
seven332 3de272ae5e Merge branch 'master' of https://github.com/axlecho/EhViewer into axlecho-master 2016-04-05 13:12:07 +08:00
axlecho 247bbec87d merge fix 2016-04-04 14:16:52 +08:00
axlecho e839c1e9b5 change the proxy 2016-04-04 14:01:16 +08:00
axlecho d756b0e451 delete test file 2016-04-04 13:47:57 +08:00
axlecho 663cb2b5b6 do the refactoring 2016-04-04 13:47:57 +08:00
axlecho 3e16c02e50 change the file associations 2016-04-04 13:47:57 +08:00
axlecho 80ca110702 add en pattern 2016-04-04 13:47:57 +08:00
axlecho 5f6a589dd8 when task done or abort,service will go to die 2016-04-04 13:47:57 +08:00
axlecho 342028eef1 add background notification 2016-04-04 13:47:57 +08:00
axlecho 0e96ee7eeb dict function ok 2016-04-04 13:47:57 +08:00
axlecho 3bd52e00d9 add async task for import dict 2016-04-04 13:47:57 +08:00
axlecho f612c912a7 add dict import service 2016-04-04 13:47:57 +08:00
axlecho 5dee677ce3 add dict test 2016-04-04 13:46:24 +08:00
axlecho 19ab3adc9a for my setting 2016-04-04 13:42:28 +08:00
26 changed files with 1255 additions and 19 deletions

No files matched your search

+37
View File
@@ -105,6 +105,32 @@
</intent-filter>
</activity-alias>
<activity
android:name="com.hippo.ehviewer.ui.DictImportActivity"
android:configChanges="screenSize|uiMode"
android:icon="@mipmap/ic_launcher"
android:label="@string/dict_import"
android:launchMode="singleTask"
android:theme="@style/AppTheme.Dialog">
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:scheme="file"/>
<data android:host="*"/>
<data android:pathPattern=".*\\.ehdict"/>
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:scheme="file"/>
<data android:host="*"/>
<data android:mimeType="*/*"/>
<data android:pathPattern=".*\\.ehdict"/>
</intent-filter>
</activity>
<activity
android:name="com.hippo.ehviewer.ui.GalleryActivity"
android:configChanges="screenSize|uiMode"
@@ -152,6 +178,12 @@
android:theme="@style/AppTheme.NoActionBar"
android:label="@string/license"/>
<activity
android:name="com.hippo.ehviewer.ui.DictActivity"
android:configChanges="screenSize|uiMode"
android:theme="@style/AppTheme.NoActionBar"
android:label="@string/dict"/>
<activity
android:name="com.hippo.ehviewer.ui.FilterActivity"
android:configChanges="screenSize|uiMode"
@@ -169,5 +201,10 @@
android:icon="@mipmap/ic_launcher"
android:label="@string/download_service_label"/>
<service
android:name="com.hippo.dict.DictImportService"
android:icon="@mipmap/ic_launcher"
android:label="@string/import_dict_service">
</service>
</application>
</manifest>
@@ -0,0 +1,240 @@
package com.hippo.dict;
/*
* Copyright (C) 2015 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import android.net.Uri;
import android.text.TextUtils;
import android.util.JsonReader;
import android.util.Log;
import com.hippo.util.SqlUtils;
import com.hippo.yorozuya.ArrayUtils;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
public class DictDatabase {
private static final String TAG = DictDatabase.class.getSimpleName();
private static final boolean DEBUG = false;
public static final String COLUMN_PARENT = "parent";
public static final String COLUMN_DATA = "data";
public static final String COLUMN_DICT = "dict_name";
private static final String DATABASE_NAME = "dict_database.db";
private static final String TABLE_DICT = "dictionary";
private static final String SEPARATOR = "@@@";
private final SQLiteDatabase mDatabase;
private static DictDatabase sInstance;
private String mDictName;
private boolean mAbortFlag = false;
private final AtomicBoolean mBusyFlag = new AtomicBoolean();
public static DictDatabase getInstance(Context context) {
if (sInstance == null) {
sInstance = new DictDatabase(context.getApplicationContext());
}
return sInstance;
}
private DictDatabase(Context context) {
DatabaseHelper databaseHelper = new DatabaseHelper(context);
mDatabase = databaseHelper.getWritableDatabase();
}
public String[] getSuggestions(String prefix) {
if (TextUtils.isEmpty(prefix) || mBusyFlag.get()) {
return ArrayUtils.EMPTY_STRING_ARRAY;
}
String command = "SELECT * FROM " + TABLE_DICT + " WHERE " + COLUMN_DATA +
" MATCH '" + SqlUtils.sqlEscapeString(prefix) + "' LIMIT 5;";
Cursor cursor = mDatabase.rawQuery(command, null);
Set<String> queryList = new HashSet<>();
int queryIndex = cursor.getColumnIndex(COLUMN_DATA);
if (cursor.moveToFirst()) {
while (!cursor.isAfterLast()) {
String datum = cursor.getString(queryIndex);
String data[] = datum.split(SEPARATOR);
for (String item : data) {
if (TextUtils.isEmpty(item) || datum.equals(prefix)) {
continue;
}
queryList.add(item);
}
cursor.moveToNext();
}
}
cursor.close();
return queryList.toArray(new String[queryList.size()]);
}
public void importDict(Context context, final Uri dictUri, final DictImportService.ProcessListener listener) throws IOException, URISyntaxException {
mAbortFlag = false;
int itemNum = -1;
InputStream inputStream = context.getContentResolver().openInputStream(dictUri);
if (null == inputStream) {
throw new FileNotFoundException("Can't find " + dictUri);
}
JsonReader jsonReader = new JsonReader(new InputStreamReader(inputStream, "UTF-8"));
jsonReader.beginObject();
while (jsonReader.hasNext()) {
String field = jsonReader.nextName();
if (field.equals("dict")) {
mDictName = jsonReader.nextString();
if (DEBUG) {
Log.d(TAG, "[importDict] parse the dict name -- " + mDictName);
}
} else if (field.equals("num")) {
if (TextUtils.isEmpty(mDictName)) {
break;
}
itemNum = jsonReader.nextInt();
listener.processTotal(itemNum);
if (DEBUG) {
Log.d(TAG, "[importDict] parse the item number -- " + itemNum);
}
} else if (field.equals("data")) {
if (TextUtils.isEmpty(mDictName) || itemNum <= 0) {
break;
}
deleteDict(mDictName);
parseData(jsonReader, listener);
}
}
jsonReader.endObject();
jsonReader.close();
listener.processComplete();
}
public void deleteDict(String dict) {
if (mBusyFlag.get()) {
return;
}
if (DEBUG) {
Log.d(TAG, "[deleteDict] dict:" + dict);
}
mDatabase.delete(TABLE_DICT, COLUMN_DICT + "=?", new String[]{dict});
}
public void importAbort() {
if (DEBUG) {
Log.d(TAG, "[importAbort] set mAbortFlag true");
}
mAbortFlag = true;
}
/**
* Builds the database. This version has extra support for using the version field
* as a mode flags field, and configures the database columns depending on the mode bits
* (features) requested by the extending class.
*/
private static class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE VIRTUAL TABLE " + TABLE_DICT + " USING fts4 (" +
COLUMN_DATA +
", " + COLUMN_PARENT +
", " + COLUMN_DICT +
", tokenize=icu th_ZH" +
");");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_DICT);
onCreate(db);
}
}
private void parseData(JsonReader jsonReader, final DictImportService.ProcessListener listener) throws IOException {
mBusyFlag.lazySet(true);
int process = 1;
SQLiteStatement insStmt = mDatabase.compileStatement("INSERT INTO " + TABLE_DICT + " VALUES (?, ?, ?);");
mDatabase.beginTransaction();
jsonReader.beginArray();
try {
while (jsonReader.hasNext()) {
synchronized (this) {
if (mAbortFlag) {
if (DEBUG) {
Log.d(TAG, "[parseData] import abort, delete the dict -- " + mDictName);
}
deleteDict(mDictName);
return;
}
}
parseSingleData(jsonReader, insStmt);
listener.process(process);
process++;
}
jsonReader.endArray();
mDatabase.setTransactionSuccessful();
} finally {
mDatabase.endTransaction();
mBusyFlag.lazySet(false);
}
}
private void parseSingleData(JsonReader jsonReader, SQLiteStatement insStmt) throws IOException {
StringBuilder sb = new StringBuilder();
String parent = "";
sb.append(SEPARATOR);
jsonReader.beginObject();
while (jsonReader.hasNext()) {
String name = jsonReader.nextName();
String content = jsonReader.nextString();
if (name.equals("parent")) {
parent = content;
} else {
sb.append(content);
sb.append(SEPARATOR);
}
}
jsonReader.endObject();
if (DEBUG) {
Log.d(TAG, "[parseSingleData] item:" + parent + " " + sb.toString());
}
insStmt.bindString(1, sb.toString());
insStmt.bindString(2, parent);
insStmt.bindString(3, mDictName);
insStmt.executeInsert();
}
}
@@ -0,0 +1,218 @@
package com.hippo.dict;
import android.app.Service;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import com.hippo.util.TextUrl;
import java.util.ArrayList;
import java.util.List;
public class DictImportService extends Service {
private static final String TAG = "DictImportService";
private static final boolean DEBUG = false;
private DictManager mDictManager;
private final List<ProcessListener> mListeners = new ArrayList<>();
private ProcessListener mDictProcessListener;
private AsyncTask mImportAsyncTask;
private DictNotification mDictNotification;
// current task information
private int mItemNum;
private Uri mDictUri;
private boolean mRunningFlag = false;
public DictImportService() {}
private final Binder serviceBinder = new DictImportServiceBinder();
@Override
public IBinder onBind(Intent intent) {
return serviceBinder;
}
@Override
public void onCreate() {
super.onCreate();
mDictManager = new DictManager(this);
mDictNotification = new DictNotification(this);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
public interface ProcessListener {
void process(int progress);
void processTotal(int total);
void processComplete();
}
public class DictImportServiceBinder extends Binder {
public DictImportService getService() {
return DictImportService.this;
}
}
public void importDict(Uri dictUri) {
if (dictUri == null) {
// TODO error tip
if (DEBUG) {
Log.e(TAG, "[importDict] dictUri is null");
}
return;
}
if (DEBUG) {
Log.d(TAG, "[importDict] start import async task");
}
mImportAsyncTask = new ImportAsyncTask(dictUri).execute();
}
public void abortImport() {
if (mImportAsyncTask == null) {
if (DEBUG) {
Log.e(TAG, "[abortImport] mImportAsyncTask is null");
}
return;
}
if (DEBUG) {
Log.d(TAG, "[abortImport] import abort");
}
// fixme
// this i just set a flag to abort the parse thread,it may cause a exception
// it there may be a elegant way to shut the worker thread down
mDictManager.importAbort();
// just for service go die
mImportAsyncTask.cancel(true);
}
public Uri getUri() {
return mDictUri;
}
public int getItemNum() {
return mItemNum;
}
public boolean isRunning() {
return mRunningFlag;
}
public void setOnProgressListener(ProcessListener onProgressListener) {
if (onProgressListener != null) {
mListeners.add(onProgressListener);
mListeners.remove(mDictNotification.mNotificationListener);
mDictNotification.stopNotify();
}
}
public void removeOnProgressListener(ProcessListener onProgressListener) {
if (onProgressListener != null) {
mListeners.remove(onProgressListener);
}
// if there is no listener in listener list,we is in the background mostly
// we post the process progress information to a notification
if (mListeners.size() == 0 && null != mDictUri) {
mDictNotification.setMax(mItemNum);
mDictNotification.setFileName(TextUrl.getFileName(mDictUri.toString()));
mListeners.add(mDictNotification.mNotificationListener);
}
}
class ImportAsyncTask extends AsyncTask<Void, Integer, Void> {
public ImportAsyncTask(Uri dictUri) {
mDictUri = dictUri;
mRunningFlag = true;
mDictProcessListener = new ProcessListener() {
@Override
public void process(int progress) {
if (DEBUG) {
Log.d(TAG, "[process] progress:" + progress);
}
publishProgress(progress);
}
@Override
public void processTotal(int total) {
if (DEBUG) {
Log.d(TAG, "process total " + total);
}
mItemNum = total;
for (ProcessListener listener : mListeners) {
listener.processTotal(total);
}
}
@Override
public void processComplete() {
// we don't do any thing here,let async task handle this
if (DEBUG) {
Log.d(TAG, "processComplete");
}
}
};
}
@Override
protected Void doInBackground(Void... voids) {
try {
mDictManager.importDict(DictImportService.this, mDictUri, mDictProcessListener);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
if (DEBUG) {
Log.d(TAG, "[onProgressUpdate] process item " + progress[0]);
}
for (ProcessListener listener : mListeners) {
listener.process(progress[0]);
}
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
for (ProcessListener listener : mListeners) {
listener.processComplete();
}
mRunningFlag = false;
DictImportService.this.goDie();
}
@Override
protected void onCancelled() {
super.onCancelled();
DictImportService.this.goDie();
}
}
public void goDie() {
if (DEBUG) {
Log.d(TAG, "[goDie] task done or abort,go to die");
}
this.stopSelf();
}
}
@@ -0,0 +1,57 @@
package com.hippo.dict;
import android.content.Context;
import android.net.Uri;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
// TODO Singleton
// TODO Add add-dict callback for DictActivity
public class DictManager {
// pattern for language
private static final String enRegEx = "^[0-9a-zA-Z_\\s]+$";
// private static final String zhRegEx = "";
private final DictDatabase mDictDatabase;
public DictManager(Context context) {
mDictDatabase = DictDatabase.getInstance(context);
}
public void importDict(Context context, final Uri dictUri, final DictImportService.ProcessListener listener)
throws IOException, URISyntaxException {
mDictDatabase.importDict(context, dictUri, listener);
}
public void deletDict(String dict) {
mDictDatabase.deleteDict(dict);
}
public String[] getSuggestions(String prefix) {
List<String> result = new ArrayList<>();
String databaseResult[] = mDictDatabase.getSuggestions(prefix);
for (String s : databaseResult) {
if (filter(s)) {
result.add(s);
}
}
return result.toArray(new String[result.size()]);
}
public void importAbort() {
mDictDatabase.importAbort();
}
public boolean filter(String item) {
// return true;
Pattern en = Pattern.compile(enRegEx);
Matcher m = en.matcher(item);
return m.matches();
}
}
@@ -0,0 +1,100 @@
package com.hippo.dict;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.SystemClock;
import android.support.v7.app.NotificationCompat;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.ui.DictImportActivity;
import com.hippo.ehviewer.ui.MainActivity;
public class DictNotification {
private final Context mContext;
private final NotificationManager mNotifyManager;
private final NotificationCompat.Builder mBuilder;
private int mMax = 100;
private final int mId = 1;
private long mLastUpdateTime;
private final PendingIntent mImportIntent;
private final PendingIntent mDoneIntent;
public DictNotification(Context context) {
mContext = context;
mNotifyManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
mBuilder = new NotificationCompat.Builder(mContext);
mImportIntent = PendingIntent.getActivity(context, 0, new Intent(context, DictImportActivity.class), 0);
Intent intent = new Intent(context, MainActivity.class);
intent.setAction(Intent.ACTION_MAIN);
mDoneIntent = PendingIntent.getActivity(context, 0, intent, 0);
mBuilder.setContentTitle(mContext.getResources().getString(R.string.dict_import))
.setContentText("0/" + mMax)
.setSmallIcon(R.drawable.ic_stat_import)
.setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.ic_launcher))
.setContentIntent(mImportIntent)
.setOngoing(true);
}
public DictImportService.ProcessListener mNotificationListener = new DictImportService.ProcessListener() {
@Override
public void process(int progress) {
DictNotification.this.notify(progress);
}
@Override
public void processTotal(int total) {
// this may useless
mMax = total;
}
@Override
public void processComplete() {
DictNotification.this.notifyDone();
}
};
public void setMax(int max) {
mMax = max;
mBuilder.setContentText("0/" + mMax);
}
public void setFileName(String fileName) {
mBuilder.setContentTitle(mContext.getString(R.string.dict_import) + " " + fileName);
}
public void notify(int progress) {
// Avoid update frequently
long now = SystemClock.currentThreadTimeMillis();
if (now - mLastUpdateTime < 500L) {
return;
}
mLastUpdateTime = now;
mBuilder.setContentIntent(mImportIntent);
mBuilder.setProgress(mMax, progress, false);
mBuilder.setContentText(progress + "/" + mMax);
mNotifyManager.notify(mId, mBuilder.build());
}
public void notifyDone() {
mBuilder.setContentIntent(mDoneIntent);
mBuilder.setContentTitle(mContext.getString(R.string.dict_import_successfully));
mBuilder.setContentText(mMax + "/" + mMax);
mBuilder.setProgress(0, 0, false);
mBuilder.setOngoing(false);
mBuilder.setAutoCancel(true);
mNotifyManager.notify(mId, mBuilder.build());
}
public void stopNotify() {
mNotifyManager.cancel(mId);
}
}
@@ -0,0 +1,106 @@
/*
* Copyright 2016 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer.ui;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import com.hippo.easyrecyclerview.EasyRecyclerView;
import com.hippo.ehviewer.R;
import com.hippo.view.ViewTransition;
import com.hippo.yorozuya.ViewUtils;
public class DictActivity extends ToolbarActivity {
private static final int REQUEST_CODE_SELECT_DICT_FILE = 0;
@Nullable
private EasyRecyclerView mRecyclerView;
@Nullable
private ViewTransition mViewTransition;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dict);
setNavigationIcon(R.drawable.v_arrow_left_dark_x24);
mRecyclerView = (EasyRecyclerView) ViewUtils.$$(this, R.id.recycler_view);
TextView tip = (TextView) ViewUtils.$$(this, R.id.tip);
mViewTransition = new ViewTransition(mRecyclerView, tip);
}
@Override
protected void onDestroy() {
super.onDestroy();
mRecyclerView = null;
mViewTransition = null;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.activity_dict, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
case R.id.action_import:
Intent intent = new Intent();
intent.setType("application/octet-stream");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
getString(R.string.select_dict_file)), REQUEST_CODE_SELECT_DICT_FILE);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (REQUEST_CODE_SELECT_DICT_FILE == requestCode) {
if (Activity.RESULT_OK != resultCode) {
return;
}
Uri uri = data.getData();
if (null == uri) {
return;
}
Intent intent = new Intent(this, DictImportActivity.class);
intent.setAction(Intent.ACTION_VIEW);
intent.setData(uri);
startActivity(intent);
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
}
@@ -0,0 +1,213 @@
package com.hippo.ehviewer.ui;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.hippo.dict.DictImportService;
import com.hippo.ehviewer.R;
import com.hippo.util.TextUrl;
public class DictImportActivity extends EhActivity {
private final static String TAG = "DictImportActivity";
private static final boolean DEBUG = false;
private DictImportService serviceBinder;
private int mItemNum = 0;
private Button mConfirmBtn;
private Button mCancelBtn;
private Button mHideBtn;
private ProgressBar mProgressBar;
private TextView mProgressTipView;
private TextView mTipView;
private Uri mDictUri;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dict_improt);
Intent intent = new Intent(DictImportActivity.this, DictImportService.class);
if (DEBUG) {
Log.d(TAG, "[onCreate] bind service");
}
bindService(intent, conn, Context.BIND_AUTO_CREATE);
startService(intent);
mConfirmBtn = (Button) findViewById(R.id.btn_confirm);
mCancelBtn = (Button) findViewById(R.id.btn_cancel);
mHideBtn = (Button) findViewById(R.id.btn_hide);
mProgressBar = (ProgressBar) findViewById(R.id.bar_import);
mProgressTipView = (TextView) findViewById(R.id.tv_progress);
mTipView = (TextView) findViewById(R.id.tv_tip);
mConfirmBtn.setOnClickListener(confirmListener);
mCancelBtn.setOnClickListener(cancelListener);
mHideBtn.setOnClickListener(hideListener);
}
private final ServiceConnection conn = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
if (DEBUG) {
Log.w(TAG, "[onServiceConnected] disconnect to service");
}
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
serviceBinder = ((DictImportService.DictImportServiceBinder) service).getService();
serviceBinder.setOnProgressListener(importListener);
// if we are doing a task,we load improt infomation from service
// and ignore the newer import task
if (serviceBinder.isRunning()) {
initFromService();
} else {
initFromIntent();
}
if (DEBUG) {
Log.d(TAG, "[onServiceConnected] connect to service");
}
}
};
private final DictImportService.ProcessListener importListener = new DictImportService.ProcessListener() {
@Override
public void process(int progress) {
if (DEBUG) {
Log.i(TAG, "[process] " + progress);
}
mProgressBar.setProgress(progress);
mProgressTipView.setText(progress + "/" + mItemNum);
}
@Override
public void processTotal(int total) {
mItemNum = total;
mProgressBar.setMax(mItemNum);
}
@Override
public void processComplete() {
mCancelBtn.setText(getResources().getString(R.string.done));
mHideBtn.setVisibility(View.GONE);
}
};
private final View.OnClickListener cancelListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
DictImportActivity.this.finish();
}
};
private final View.OnClickListener abortListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
if (DEBUG) {
Log.d(TAG, "[onClick] abort");
}
if (serviceBinder != null) {
serviceBinder.abortImport();
}
DictImportActivity.this.finish();
}
};
private final View.OnClickListener confirmListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
if (DEBUG) {
Log.d(TAG, "[onClick] confirm");
}
if (serviceBinder == null) {
// todo error tip
if (DEBUG) {
Log.e(TAG, "[onClick] service is not connected");
}
return;
}
if (mDictUri == null) {
// todo error tip
if (DEBUG) {
Log.e(TAG, "[onClick] mDictUri is not be init");
}
return;
}
serviceBinder.importDict(mDictUri);
view.setVisibility(View.GONE);
mCancelBtn.setOnClickListener(abortListener);
mHideBtn.setVisibility(View.VISIBLE);
mProgressBar.setVisibility(View.VISIBLE);
}
};
private final View.OnClickListener hideListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
if (DEBUG) {
Log.d(TAG, "[onClick] hide");
}
DictImportActivity.this.finish();
}
};
@Override
protected void onDestroy() {
serviceBinder.removeOnProgressListener(importListener);
unbindService(conn);
super.onDestroy();
}
private void initFromService() {
mDictUri = serviceBinder.getUri();
if (mDictUri == null) {
if (DEBUG) {
Log.e(TAG, "[initFromService] error use of initFromService,you may use initFromIntent instead");
}
return;
}
if (DEBUG) {
Log.d(TAG, "[initFromService] " + mDictUri.toString());
}
mItemNum = serviceBinder.getItemNum();
mProgressBar.setMax(mItemNum);
mConfirmBtn.setVisibility(View.GONE);
mHideBtn.setVisibility(View.VISIBLE);
mProgressBar.setVisibility(View.VISIBLE);
mTipView.setText(TextUrl.getFileName(mDictUri.toString()));
mCancelBtn.setOnClickListener(abortListener);
}
private void initFromIntent() {
mDictUri = getIntent().getData();
if (DEBUG) {
Log.d(TAG, "[initFromIntent] " + mDictUri.toString());
}
mTipView.setText(TextUrl.getFileName(mDictUri.toString()));
}
}
@@ -43,6 +43,7 @@ import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.hippo.dict.DictManager;
import com.hippo.ehviewer.R;
import com.hippo.view.ViewTransition;
import com.hippo.yorozuya.AnimationUtils;
@@ -85,6 +86,7 @@ public class SearchBar extends FrameLayout implements View.OnClickListener,
private ViewTransition mViewTransition;
private SearchDatabase mSearchDatabase;
private DictManager mDictManager;
private List<String> mSuggestionList;
private ArrayAdapter mSuggestionAdapter;
@@ -114,6 +116,7 @@ public class SearchBar extends FrameLayout implements View.OnClickListener,
setBackgroundResource(R.drawable.card_white_no_padding_2dp);
mSearchDatabase = SearchDatabase.getInstance(getContext());
mDictManager = new DictManager(getContext());
LayoutInflater inflater = LayoutInflater.from(context);
inflater.inflate(R.layout.widget_search_bar, this);
@@ -170,8 +173,11 @@ public class SearchBar extends FrameLayout implements View.OnClickListener,
private void updateSuggestions() {
String prefix = mEditText.getText().toString();
String[] dictSuggestions = mDictManager.getSuggestions(prefix);
String[] suggestions = mSearchDatabase.getSuggestions(prefix);
mSuggestionList.clear();
Collections.addAll(mSuggestionList, dictSuggestions);
Collections.addAll(mSuggestionList, suggestions);
if (mSuggestionList.size() == 0) {
removeListHeader();
@@ -479,10 +485,15 @@ public class SearchBar extends FrameLayout implements View.OnClickListener,
public interface Helper {
void onClickTitle();
void onClickLeftIcon();
void onClickRightIcon();
void onSearchEditTextClick();
void onApplySearch(String query);
void onSearchEditTextBackPressed();
}
@@ -60,7 +60,6 @@ public class SearchDatabase {
public String[] getSuggestions(String prefix) {
List<String> queryList = new LinkedList<>();
// TODO add limit
StringBuilder sb = new StringBuilder();
sb.append("SELECT * FROM ").append(TABLE_SUGGESTIONS);
if (!TextUtils.isEmpty(prefix)) {
@@ -56,4 +56,13 @@ public final class TextUrl {
return spannable == null ? content : spannable;
}
public static String getFileName(String path) {
if (path == null) {
return path;
}
int start = path.lastIndexOf("/");
return start == -1 ? path : path.substring(start + 1);
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 165 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 127 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 176 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 220 B

@@ -0,0 +1,29 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright 2016 Hippo Seven
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<vector
xmlns:android="http://schemas.android.com/apk/res/android"
android:height="24dp"
android:width="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="@color/primary_drawable_dark"
android:pathData="@string/pd_import"/>
</vector>
+39
View File
@@ -0,0 +1,39 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright 2016 Hippo Seven
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.hippo.easyrecyclerview.EasyRecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="@dimen/keyline_margin"/>
<TextView
android:id="@+id/tip"
android:layout_width="228dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center_horizontal"
android:drawablePadding="16dp"
android:text="@string/no_dict"
style="@style/TextAppearance.AppCompat.Medium"/>
</FrameLayout>
@@ -0,0 +1,79 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingLeft="?attr/dialogPreferredPadding"
android:paddingTop="@dimen/abc_dialog_padding_top_material"
android:paddingRight="?attr/dialogPreferredPadding">
<RelativeLayout
android:id="@+id/layout_content"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/tv_tip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<ProgressBar
android:id="@+id/bar_import"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/tv_tip"
android:max="100"
android:visibility="invisible"/>
<TextView
android:id="@+id/tv_progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@id/tv_tip"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_below="@id/bar_import"/>
</RelativeLayout>
<android.support.v7.widget.ButtonBarLayout
android:id="@+id/buttonPanel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingLeft="12dp"
android:paddingRight="12dp"
android:paddingTop="4dp"
android:paddingBottom="4dp"
android:gravity="bottom"
style="?attr/buttonBarStyle">
<Button
android:id="@+id/btn_cancel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="@android:string/cancel"
style="?attr/buttonBarPositiveButtonStyle"/>
<Button
android:id="@+id/btn_hide"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="@string/hide"
android:visibility="gone"
style="?attr/buttonBarPositiveButtonStyle"/>
<Button
android:id="@+id/btn_confirm"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="@string/_import"
style="?attr/buttonBarPositiveButtonStyle"/>
</android.support.v7.widget.ButtonBarLayout>
</LinearLayout>
+28
View File
@@ -0,0 +1,28 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright 2016 Hippo Seven
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<menu
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/action_import"
android:icon="@drawable/v_import_dark_x24"
android:title="@string/_import"
app:showAsAction="always"/>
</menu>
@@ -382,6 +382,8 @@
<string name="settings_eh_show_jpn_title_summary_off">显示默认标题。一般是英文标题</string>
<string name="settings_eh_filter">过滤</string>
<string name="settings_eh_filter_summary">过滤标题,上传者,标签和标签组</string>
<string name="settings_eh_dict">字典</string>
<string name="settings_eh_dict_summary">搜索关键字字典</string>
<string name="settings_read">阅读</string>
<string name="settings_read_screen_rotation">屏幕方向</string>
@@ -531,6 +533,20 @@
<!-- License -->
<string name="license">开源许可</string>
<!-- Dict -->
<string name="dict">字典</string>
<string name="no_dict">这里是字典</string>
<string name="select_dict_file">选择字典文件</string>
<!-- Import Dict -->
<string name="import_dict_service">导入字典服务</string>
<string name="dict_import">导入字典</string>
<string name="dict_import_successfully">导入字典成功</string>
<string name="_import">导入</string>
<string name="abort">中止</string>
<string name="hide">隐藏</string>
<string name="done">完成</string>
<!-- Dir Picker-->
<string name="dir_picker">选择文件夹</string>
<string name="directory_not_writable">该文件夹不可写</string>
@@ -382,6 +382,8 @@
<string name="settings_eh_show_jpn_title_summary_off">顯示默認標題。一般是英文標題</string>
<string name="settings_eh_filter">過濾</string>
<string name="settings_eh_filter_summary">過濾標題,上傳者,標籤和標籤組</string>
<string name="settings_eh_dict">字典</string>
<string name="settings_eh_dict_summary">搜索關鍵字字典</string>
<string name="settings_read">閲讀</string>
<string name="settings_read_screen_rotation">屏幕方向</string>
@@ -531,6 +533,20 @@
<!-- License -->
<string name="license">開源許可</string>
<!-- Dict -->
<string name="dict">字典</string>
<string name="no_dict">這裏是字典</string>
<string name="select_dict_file">選擇字典文件</string>
<!-- Import Dict -->
<string name="import_dict_service">導入字典服務</string>
<string name="dict_import">導入字典</string>
<string name="dict_import_successfully">導入字典成功</string>
<string name="_import">導入</string>
<string name="abort">中止</string>
<string name="hide">隱藏</string>
<string name="done">完成</string>
<!-- Dir Picker-->
<string name="dir_picker">選擇文件夾</string>
<string name="directory_not_writable">該文件夾不可寫</string>
@@ -382,6 +382,8 @@
<string name="settings_eh_show_jpn_title_summary_off">顯示預設標題。一般是英文標題</string>
<string name="settings_eh_filter">過濾</string>
<string name="settings_eh_filter_summary">過濾標題,上傳者,標籤和標籤組</string>
<string name="settings_eh_dict">字典</string>
<string name="settings_eh_dict_summary">搜尋關鍵字字典</string>
<string name="settings_read">閱讀</string>
<string name="settings_read_screen_rotation">螢幕方向</string>
@@ -531,6 +533,20 @@
<!-- License -->
<string name="license">開源許可</string>
<!-- Dict -->
<string name="dict">字典</string>
<string name="no_dict">這裡是字典</string>
<string name="select_dict_file">選擇字典檔案</string>
<!-- Import Dict -->
<string name="import_dict_service">匯入字典服務</string>
<string name="dict_import">匯入字典</string>
<string name="dict_import_successfully">匯入字典成功</string>
<string name="_import">匯入</string>
<string name="abort">中止</string>
<string name="hide">隱藏</string>
<string name="done">完成</string>
<!-- Dir Picker-->
<string name="dir_picker">選擇資料夾</string>
<string name="directory_not_writable">該資料夾不可寫</string>
+1
View File
@@ -60,6 +60,7 @@
<string name="pd_similar" translatable="false">M2,20L17,10L22,22M14,9L2,8L11,2Z</string>
<string name="pd_refresh" translatable="false">M17.65,6.35C16.2,4.9 14.21,4 12,4A8,8 0 0,0 4,12A8,8 0 0,0 12,20C15.73,20 18.84,17.45 19.73,14H17.65C16.83,16.33 14.61,18 12,18A6,6 0 0,1 6,12A6,6 0 0,1 12,6C13.66,6 15.14,6.69 16.22,7.78L13,11H20V4L17.65,6.35Z</string>
<string name="pd_file_find" translatable="false">M9,13A3,3 0 0,0 12,16A3,3 0 0,0 15,13A3,3 0 0,0 12,10A3,3 0 0,0 9,13M20,19.59V8L14,2H6A2,2 0 0,0 4,4V20A2,2 0 0,0 6,22H18C18.45,22 18.85,21.85 19.19,21.6L14.76,17.17C13.96,17.69 13,18 12,18A5,5 0 0,1 7,13A5,5 0 0,1 12,8A5,5 0 0,1 17,13C17,14 16.69,14.96 16.17,15.75L20,19.59Z</string>
<string name="pd_import" translatable="false">M14,12L10,8V11H2V13H10V16M20,18V6C20,4.89 19.1,4 18,4H6A2,2 0 0,0 4,6V9H6V6H18V18H6V15H4V18A2,2 0 0,0 6,20H18A2,2 0 0,0 20,18Z</string>
<string name="pd_big_label" translatable="false">M12.88,2H4V11L14.97,22.14L24,13.1L12.88,2ZM7.26,5.26C7.96,4.58,9.06,4.58,9.74,5.26C10.42,5.96,10.42,7.06,9.74,7.74S7.94,8.42,7.26,7.74S6.58,5.94,7.26,5.26ZM14.98,19.3L8.76,12.95L14.88,6.83L21.18,13.11L14.98,19.31ZM11.6,21.56L10.23,23L0,12.74V5H2V11.9L11.6,21.56Z</string>
<string name="pd_big_search" translatable="false">M20.46,14.65C21.86,16.15,20.31,18.6,18.32,17.87C19.78,17.57,20.79,16.37,20.46,14.65ZM4.32,17.87C6.32,18.6,7.86,16.17,6.46,14.65C6.79,16.38,5.78,17.55,4.32,17.87ZM16.87,4.3C16.6,3.56,15.87,3,15,3C13.7,3,12.7,4.24,13.1,5.58C14.2,5.18,15.44,4.48,16.87,4.31ZM24,16C24,18.76,21.76,21,19,21C14.96,21,14.84,16.88,12,16.88S9.04,21,5,21C2.24,21,0,18.76,0,16C0,13.87,1.53,11.43,3.94,7.18C5.84,3.81,8.69,5.92,10.76,6.58C11.54,6.85,12.41,6.88,13.24,6.58C15.3,5.92,18.14,3.81,20.06,7.18C22.46,11.43,24,13.88,24,16ZM8,16C8,14.35,6.65,13,5,13S2,14.35,2,16S3.35,19,5,19S8,17.65,8,16ZM13,14C13,13.45,12.55,13,12,13S11,13.45,11,14S11.45,15,12,15S13,14.55,13,14ZM22,16C22,14.35,20.65,13,19,13S16,14.35,16,16S17.35,19,19,19S22,17.65,22,16ZM9,3C8.14,3,7.4,3.55,7.13,4.3C8.56,4.48,9.79,5.2,10.9,5.58C11.3,4.24,10.3,3,9,3Z</string>
+16
View File
@@ -424,6 +424,8 @@
<string name="settings_eh_show_jpn_title_summary_off">Show default title. It is usually English title</string>
<string name="settings_eh_filter">Filter</string>
<string name="settings_eh_filter_summary">Filter by title, uploader, tag and tag namespace</string>
<string name="settings_eh_dict">Dictionary</string>
<string name="settings_eh_dict_summary">Search keyword dictionary</string>
<string name="settings_read">Read</string>
<string name="settings_read_screen_rotation">Screen orientation</string>
@@ -574,6 +576,20 @@
<!-- License -->
<string name="license">License</string>
<!-- Dict -->
<string name="dict">Dictionary</string>
<string name="no_dict">Dictionaries will be shown here</string>
<string name="select_dict_file">Select dictionary file</string>
<!-- Import Dict -->
<string name="import_dict_service">Import dictionary service</string>
<string name="dict_import">Import dictionary</string>
<string name="dict_import_successfully">Import dictionary successfully</string>
<string name="_import">Import</string>
<string name="abort">Abort</string>
<string name="hide">Hide</string>
<string name="done">Done</string>
<!-- Dir Picker-->
<string name="dir_picker">Dir picker</string>
<string name="directory_not_writable">The directory is not writable</string>
+4
View File
@@ -31,6 +31,10 @@
<item name="windowNoTitle">true</item>
</style>
<style name="AppTheme.Dialog" parent="Theme.AppCompat.Light.Dialog">
<item name="android:windowCloseOnTouchOutside">false</item>
</style>
<style name="AppTheme.Translucent">
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:colorBackgroundCacheHint">@null</item>
+6
View File
@@ -89,4 +89,10 @@
android:summary="@string/settings_eh_filter_summary"
app:activity="com.hippo.ehviewer.ui.FilterActivity"/>
<com.hippo.preference.ActivityPreference
android:key="dict"
android:title="@string/settings_eh_dict"
android:summary="@string/settings_eh_dict_summary"
app:activity="com.hippo.ehviewer.ui.DictActivity"/>
</PreferenceScreen>
+14 -18
View File
@@ -1,18 +1,14 @@
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
# Default value: -Xmx10248m -XX:MaxPermSize=256m
# org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
## Project-wide Gradle settings.
#
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
#
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
# Default value: -Xmx10248m -XX:MaxPermSize=256m
# org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
#
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true