diff --git a/README.MD b/README.MD index 49e65f92..8b62e5ba 100644 --- a/README.MD +++ b/README.MD @@ -15,15 +15,15 @@ Improved version of [SMBSync2](https://github.com/Sentaroh/SMBSync2) ### License information - This software includes the work that is distributed in the Apache License 2.0. - - [Zip4J 2.2.3](https://github.com/srikanth-lingala/zip4j) + - [Zip4J 2.11.1](https://github.com/srikanth-lingala/zip4j) - [Metadata-extractor](https://github.com/drewnoakes/metadata-extractor) - This software includes the work that is distributed in the GNU Lesser General Public License v2.1. - - [jcifs-ng](https://github.com/AgNO3/jcifs-ng) - - [jcifs-1.3.17](https://jcifs.samba.org/) + - [jcifsng-2.1.17](https://github.com/AgNO3/jcifs-ng) + - [jcifs-1.3.19](https://jcifs.samba.org/) - This software includes the work that is distributed in the MOZILLA PUBLIC LICENSE 1.1. - [juniversalchardet-1.0.3](https://code.google.com/archive/p/juniversalchardet/) - This software includes the work that is distributed in the Bouncy Castle LICENSE. - - [Bouncy Castle Provider](https://mvnrepository.com/artifact/org.bouncycastle/bcprov-jdk15on/1.66) + - [Bouncy Castle Provider](https://mvnrepository.com/artifact/org.bouncycastle/bcprov-jdk15on/1.69) - This software includes the work that is distributed in the BSD 3-Clause "New" or "Revised" License - [markdownj](https://github.com/myabc/markdownj) - This software includes the work that is distributed in the MIT LICENSE. diff --git a/app/build.gradle b/app/build.gradle index 6dd55fd2..98683c8e 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -1,20 +1,16 @@ apply plugin: 'com.android.application' android { - compileSdkVersion 30 - buildToolsVersion "30.0.3"//"29.0.3" + compileSdk 33 + buildToolsVersion '33.0.0' //"29.0.3" defaultConfig { applicationId "com.sentaroh.android.SMBSync3" minSdkVersion 26 - targetSdkVersion 30 + targetSdkVersion 33 versionCode 2 versionName "1.0.1" } - lintOptions { - disable 'MissingTranslation' - abortOnError false - } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 @@ -42,7 +38,8 @@ android { } task copyDebugApkRelease(type: Copy) { - from 'build/outputs/apk/debug' +// from 'build/outputs/apk/debug' + from 'build/intermediates/apk/debug' into '../release/' // Into the project root, one level above the app folder include '*debug.apk' } @@ -51,10 +48,10 @@ android { // options.compilerArgs << '-Xlint:unchecked,deprecation' // } - afterEvaluate { +// afterEvaluate { packageDebug.finalizedBy(copyDebugApkRelease) // copyDebugApkRelease.finalizedBy(copyDebugApk) - } +// } } } @@ -81,27 +78,46 @@ android { } } + lint { + abortOnError false + disable 'MissingTranslation' + } + namespace 'com.sentaroh.android.SMBSync3' } dependencies { - implementation 'androidx.appcompat:appcompat:1.2.0' +// implementation 'androidx.appcompat:appcompat:1.2.0' + implementation 'androidx.appcompat:appcompat:1.5.1' //bug with duplicate lifecycle-viewmodel-2.5.0-runtime as it needs both java and ktx implementations +// implementation 'androidx.appcompat:appcompat:1.6.0-rc01' //compileSdkVersion 33 + + // Both lifecycle-viewmodel java/ktx implementations are needed for appcompat 1.5.1 + // The implementations can be removed in appcompat 1.6.0 + implementation 'androidx.lifecycle:lifecycle-viewmodel:2.5.1' + implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.5.1' + // implementation 'com.google.android.material:material:1.2.0' - implementation 'com.google.android.material:material:1.3.0' + implementation 'com.google.android.material:material:1.6.1' // implementation 'androidx.recyclerview:recyclerview:1.1.0' - implementation 'androidx.recyclerview:recyclerview:1.2.0' - - implementation files('libs/jcifs-ng-2.1.6-20201207-01.jar') - implementation files('libs/jcifs-1.3.17_patch.jar') - implementation files('libs/JcifsFile2-1.0.8.jar') - implementation files('libs/bcprov-jdk15to18-1.66.jar') +// implementation 'androidx.recyclerview:recyclerview:1.2.0' + implementation 'androidx.recyclerview:recyclerview:1.2.1' + implementation "androidx.constraintlayout:constraintlayout:2.1.4" + + implementation files('libs/jcifsng-latest.jar') + implementation files('libs/jcifs13-1.3.19.jar') + implementation files('libs/JcifsFile2-1.0.9.jar') +// implementation files('libs/bcprov-jdk15to18-1.66.jar') +// implementation files('libs/bcprov-jdk15to18-169.jar') + implementation 'org.bouncycastle:bcprov-jdk15to18:1.69' +// implementation 'org.bouncycastle:bcprov-jdk15to18:1.71' implementation files('libs/Utilities3-1.0.3.aar') implementation files('libs/metadata-extractor-2.11.0.jar') - implementation "androidx.work:work-runtime:2.5.0" +// implementation "androidx.work:work-runtime:2.5.0" + implementation "androidx.work:work-runtime:2.7.1" implementation files('libs/MarkDownJ_0.4.jar') @@ -112,5 +128,10 @@ dependencies { // implementation 'androidx.activity:activity:1.2.0-rc01' // implementation "androidx.fragment:fragment-ktx:1.3.0-rc01" // implementation "androidx.core:core-ktx:+" +// implementation "androidx.activity:activity:1.3.1" +// implementation "androidx.activity:activity-ktx:1.3.1" +// implementation "androidx.fragment:fragment:1.5.2" + + implementation 'androidx.preference:preference:1.2.0' } diff --git a/app/libs/JcifsFile2-1.0.8.jar b/app/libs/JcifsFile2-1.0.8.jar deleted file mode 100644 index 49960472..00000000 Binary files a/app/libs/JcifsFile2-1.0.8.jar and /dev/null differ diff --git a/app/libs/JcifsFile2-1.0.9.jar b/app/libs/JcifsFile2-1.0.9.jar new file mode 100644 index 00000000..f09e137a Binary files /dev/null and b/app/libs/JcifsFile2-1.0.9.jar differ diff --git a/app/libs/Utilities3-1.0.3.aar b/app/libs/Utilities3-1.0.3.aar index b9de1a9f..dd2a953a 100644 Binary files a/app/libs/Utilities3-1.0.3.aar and b/app/libs/Utilities3-1.0.3.aar differ diff --git a/app/libs/jcifs-1.3.17_patch.jar b/app/libs/jcifs-1.3.17_patch.jar deleted file mode 100644 index 882adad9..00000000 Binary files a/app/libs/jcifs-1.3.17_patch.jar and /dev/null differ diff --git a/app/libs/jcifs-ng-2.1.6-20201207-01.jar b/app/libs/jcifs-ng-2.1.6-20201207-01.jar deleted file mode 100644 index 2424b286..00000000 Binary files a/app/libs/jcifs-ng-2.1.6-20201207-01.jar and /dev/null differ diff --git a/app/libs/jcifs13-1.3.19.jar b/app/libs/jcifs13-1.3.19.jar new file mode 100644 index 00000000..ac1a3e16 Binary files /dev/null and b/app/libs/jcifs13-1.3.19.jar differ diff --git a/app/libs/jcifsng-latest.jar b/app/libs/jcifsng-latest.jar new file mode 100644 index 00000000..a15d9d3d Binary files /dev/null and b/app/libs/jcifsng-latest.jar differ diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 12b145b6..d5427b85 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -1,7 +1,6 @@ + xmlns:tools="http://schemas.android.com/tools"> @@ -59,12 +58,12 @@ + android:alwaysRetainTaskState="true" + android:exported="true"> @@ -79,14 +78,17 @@ + + + + android:excludeFromRecents="true" + android:exported="true"> diff --git a/app/src/main/java/com/sentaroh/android/SMBSync3/ActivityIntentHandler.java b/app/src/main/java/com/sentaroh/android/SMBSync3/ActivityIntentHandler.java index 76752b1c..52da0856 100644 --- a/app/src/main/java/com/sentaroh/android/SMBSync3/ActivityIntentHandler.java +++ b/app/src/main/java/com/sentaroh/android/SMBSync3/ActivityIntentHandler.java @@ -51,7 +51,7 @@ public class ActivityIntentHandler extends Activity { @Override protected void attachBaseContext(Context base) { - super.attachBaseContext(GlobalParameters.setNewLocale(base)); + super.attachBaseContext(GlobalParameters.setLocaleAndMetrics(base)); } @Override @@ -64,7 +64,7 @@ protected void onCreate(Bundle savedInstanceState) { if (mGp == null) { mGp =GlobalWorkArea.getGlobalParameter(c); } - if (mUtil == null) mUtil = mUtil = new CommonUtilities(c, "IntentHandler", mGp, null); + if (mUtil == null) mUtil = new CommonUtilities(c, "IntentHandler", mGp, null); mGp.loadConfigList(c, mUtil); @@ -72,7 +72,6 @@ protected void onCreate(Bundle savedInstanceState) { if (received_intent.getAction()!=null && !received_intent.getAction().equals("")) { if (received_intent.getAction().equals(QUERY_SYNC_TASK_INTENT)) { querySyncTask(c, received_intent); - finish(); } else { String action=received_intent.getAction(); String task_list=received_intent.getStringExtra(START_SYNC_EXTRA_PARM_SYNC_TASK); @@ -81,8 +80,8 @@ protected void onCreate(Bundle savedInstanceState) { } else { SyncWorker.startSyncWorkerByAction(c, mGp, mUtil, action, "", task_list); } - finish(); } + finish(); } } @@ -98,7 +97,8 @@ public void onDestroy() { } private void querySyncTask(Context c, Intent in) { - String reply_list = "", sep = ""; + StringBuilder reply_list = new StringBuilder(); + String sep = ""; String task_type = QUERY_SYNC_TASK_EXTRA_PARM_TASK_TYPE_AUTO; if (in.getStringExtra(QUERY_SYNC_TASK_EXTRA_PARM_TASK_TYPE) != null) task_type = in.getStringExtra(QUERY_SYNC_TASK_EXTRA_PARM_TASK_TYPE); @@ -109,24 +109,24 @@ private void querySyncTask(Context c, Intent in) { SyncTaskItem sti = mGp.syncTaskList.get(i); if (task_type.toLowerCase().equals(QUERY_SYNC_TASK_EXTRA_PARM_TASK_TYPE_TEST.toLowerCase())) { if (sti.isSyncTestMode()) { - reply_list += sep + sti.getSyncTaskName(); + reply_list.append(sep).append(sti.getSyncTaskName()); sep = NAME_LIST_SEPARATOR; reply_count++; } } else if (task_type.toLowerCase().equals(QUERY_SYNC_TASK_EXTRA_PARM_TASK_TYPE_AUTO.toLowerCase())) { if (sti.isSyncTaskAuto()) { - reply_list += sep + sti.getSyncTaskName(); + reply_list.append(sep).append(sti.getSyncTaskName()); sep = NAME_LIST_SEPARATOR; reply_count++; } } else if (task_type.toLowerCase().equals(QUERY_SYNC_TASK_EXTRA_PARM_TASK_TYPE_MANUAL.toLowerCase())) { if (!sti.isSyncTaskAuto()) { - reply_list += sep + sti.getSyncTaskName(); + reply_list.append(sep).append(sti.getSyncTaskName()); sep = NAME_LIST_SEPARATOR; reply_count++; } } else if (task_type.toLowerCase().equals(QUERY_SYNC_TASK_EXTRA_PARM_TASK_TYPE_ALL.toLowerCase())) { - reply_list += sep + sti.getSyncTaskName(); + reply_list.append(sep).append(sti.getSyncTaskName()); sep = NAME_LIST_SEPARATOR; reply_count++; } @@ -134,7 +134,7 @@ private void querySyncTask(Context c, Intent in) { } Intent reply = new Intent(REPLY_SYNC_TASK_INTENT); reply.putExtra(REPLY_SYNC_TASK_EXTRA_PARM_SYNC_COUNT, reply_count); - reply.putExtra(REPLY_SYNC_TASK_EXTRA_PARM_SYNC_ARRAY, reply_list); + reply.putExtra(REPLY_SYNC_TASK_EXTRA_PARM_SYNC_ARRAY, reply_list.toString()); mUtil.addDebugMsg(1, "I", "query result, count="+reply_count+", list=["+reply_list+"]"); c.sendBroadcast(reply); } diff --git a/app/src/main/java/com/sentaroh/android/SMBSync3/ActivityMain.java b/app/src/main/java/com/sentaroh/android/SMBSync3/ActivityMain.java index b48a993f..484f9f4f 100644 --- a/app/src/main/java/com/sentaroh/android/SMBSync3/ActivityMain.java +++ b/app/src/main/java/com/sentaroh/android/SMBSync3/ActivityMain.java @@ -24,6 +24,7 @@ this software and associated documentation files (the "Software"), to deal */ import android.Manifest; +import android.annotation.SuppressLint; import android.app.Activity; import android.app.Dialog; import android.content.ActivityNotFoundException; @@ -77,11 +78,18 @@ this software and associated documentation files (the "Software"), to deal import android.widget.TextView; import android.widget.Toast; +import androidx.activity.result.ActivityResult; +import androidx.activity.result.ActivityResultCallback; +import androidx.activity.result.ActivityResultLauncher; +import androidx.activity.result.contract.ActivityResultContracts; +import androidx.annotation.NonNull; +import androidx.annotation.RequiresApi; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; import androidx.core.content.FileProvider; import androidx.viewpager.widget.ViewPager; + import com.google.android.material.tabs.TabLayout; import com.sentaroh.android.SMBSync3.Log.LogManagementFragment; import com.sentaroh.android.SMBSync3.Log.LogUtil; @@ -115,11 +123,11 @@ this software and associated documentation files (the "Software"), to deal import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; +import java.util.Objects; import javax.crypto.SecretKey; import static com.sentaroh.android.SMBSync3.Constants.*; -import static com.sentaroh.android.SMBSync3.GlobalParameters.APPLICATION_LANGUAGE_SETTING_SYSTEM_DEFAULT; import static com.sentaroh.android.SMBSync3.ScheduleConstants.*; import static com.sentaroh.android.Utilities3.SafFile3.SAF_FILE_PRIMARY_UUID; @@ -142,9 +150,10 @@ public class ActivityMain extends AppCompatActivity { private final static int START_INITIALYZING = 2; private int appStartStaus = START_BEGINING; - private boolean appStartWithRestored =false; + //private boolean appStartWithRestored = false; + private Bundle mSavedInstanceState = null; - private Handler mUiHandler = new Handler(); + private final Handler mUiHandler = new Handler(); private ActionBar mActionBar = null; @@ -155,25 +164,26 @@ public class ActivityMain extends AppCompatActivity { private String mTabNameTask="Task", mTabNameSchedule="Schedule", mTabNameHistory="History", mTabNameMessage="Message", mTabNameGroup="Group"; @Override - protected void onSaveInstanceState(Bundle out) { + protected void onSaveInstanceState(@NonNull Bundle out) { super.onSaveInstanceState(out); mUtil.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName() + " entered."); out.putString("currentTab", mCurrentTab); } + // onRestoreInstanceState() is called only when recreating activity (onCreate()) after it was killed by the OS @Override protected void onRestoreInstanceState(Bundle in) { super.onRestoreInstanceState(in); mUtil.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName() + " entered."); mCurrentTab = in.getString("currentTab"); - appStartWithRestored =true; + //appStartWithRestored = true; } @Override protected void attachBaseContext(Context base) { - super.attachBaseContext(GlobalParameters.setNewLocale(base)); - GlobalParameters.setDisplayFontScale(base); + super.attachBaseContext(GlobalParameters.setLocaleAndMetrics(base)); + //GlobalParameters.setDisplayFontScale(base); } @Override @@ -185,17 +195,22 @@ public void onCreate(Bundle savedInstanceState) { // Log.v(APPLICATION_TAG, "onCreate entered"); mActivity = ActivityMain.this; mContext = mActivity; + mGp = GlobalWorkArea.getGlobalParameter(mActivity); + mUtil = new CommonUtilities(mContext, "Main", mGp, getSupportFragmentManager()); + mSavedInstanceState = savedInstanceState; + mPrevActivityKilled = mSavedInstanceState != null; // Intent splash=new Intent(mActivity, ActivitySplash.class); // startActivity(splash); - mGp= GlobalWorkArea.getGlobalParameter(mActivity); - GlobalParameters.setDisplayFontScale(mActivity); + + //GlobalParameters.setDisplayFontScale(mActivity); setTheme(mGp.applicationTheme); + mGp.themeColorList = ThemeUtil.getThemeColorList(mActivity); + mGp.setDeviceOrientation(mActivity); + super.onCreate(savedInstanceState); - mUtil = new CommonUtilities(mContext, "Main", mGp, getSupportFragmentManager()); setContentView(R.layout.main_screen); - mGp.themeColorList = ThemeUtil.getThemeColorList(mActivity); MyUncaughtExceptionHandler myUncaughtExceptionHandler = new MyUncaughtExceptionHandler(); myUncaughtExceptionHandler.init(mContext, myUncaughtExceptionHandler); @@ -204,31 +219,31 @@ public void onCreate(Bundle savedInstanceState) { if (mGp.syncHistoryList == null) mGp.syncHistoryList = mUtil.loadHistoryList(); mGp.syncHistoryListAdapter = new HistoryListAdapter(mActivity, R.layout.history_list_item, mGp.syncHistoryList); - mUtil.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName(), " entered, appStartStaus="+appStartStaus); + mUtil.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName(), " entered, appStartStaus=" + appStartStaus); mUtil.addLogMsg("I", "", - mContext.getString(R.string.msgs_smbsync_main_start) +" API=" + Build.VERSION.SDK_INT +", Version=" + SystemInfo.getApplVersionNameCode(mContext)); + mContext.getString(R.string.msgs_smbsync_main_start) +" API=" + Build.VERSION.SDK_INT + ", Version=" + SystemInfo.getApplVersionNameCode(mContext)); - mTabNameTask=getString(R.string.msgs_tab_name_task); - mTabNameSchedule=getString(R.string.msgs_tab_name_schedule); - mTabNameHistory=getString(R.string.msgs_tab_name_history); - mTabNameMessage=getString(R.string.msgs_tab_name_msg); - mTabNameGroup=getString(R.string.msgs_tab_name_group); + mTabNameTask = getString(R.string.msgs_tab_name_task); + mTabNameSchedule = getString(R.string.msgs_tab_name_schedule); + mTabNameHistory = getString(R.string.msgs_tab_name_history); + mTabNameMessage = getString(R.string.msgs_tab_name_msg); + mTabNameGroup = getString(R.string.msgs_tab_name_group); mCurrentTab = mTabNameTask; mActionBar = getSupportActionBar(); - mActionBar.setDisplayShowHomeEnabled(false); - mActionBar.setHomeButtonEnabled(false); - if (mGp.settingFixDeviceOrientationToPortrait) setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); - else setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); + if (mActionBar != null) { + mActionBar.setDisplayShowHomeEnabled(false); + mActionBar.setHomeButtonEnabled(false); + } mGp.syncTaskListAdapter = new TaskListAdapter(mActivity, R.layout.sync_task_item_view, mGp.syncTaskList, mGp); - Thread th=new Thread(){ + Thread th = new Thread(){ @Override public void run() { // makeCacheDirectory(); - if (mGp.syncTaskList.size()==0) { + if (mGp.syncTaskList.size() == 0) { mGp.loadConfigList(mContext, mUtil); } mTaskUtil = new TaskListUtils(mUtil, mActivity, mGp, mActivity.getSupportFragmentManager()); @@ -238,6 +253,7 @@ public void run() { th.start(); createTabView(); + initAdapterAndView(); listSettingsOption(); @@ -248,17 +264,16 @@ public void run() { private class MyUncaughtExceptionHandler extends AppUncaughtExceptionHandler { @Override public void appUniqueProcess(Throwable ex, String strace) { - log.error("UncaughtException detected, error="+ex); + log.error("UncaughtException detected, error=" + ex); log.error(strace); mUtil.flushLog(); } - }; + } @Override protected void onStart() { super.onStart(); mUtil.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName() + " entered, appStartStaus=" + appStartStaus); - } @Override @@ -267,7 +282,7 @@ protected void onResume() { mUtil.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName() + " entered, appStartStaus=" + appStartStaus); if (appStartStaus == START_BEGINING) { appStartStaus = START_INITIALYZING; - if (Build.VERSION.SDK_INT>=30) { + if (Build.VERSION.SDK_INT >= 30) { //ENable "ALL_FILE_ACCESS" if (!isAllFileAccessPermissionGranted()) { requestAllFileAccessPermission(new CallBackListener() { @@ -280,8 +295,9 @@ public void onCallBack(Context context, boolean b, Object[] objects) { initApplication(); } } else { - if (isLegacyStorageAccessGranted()) initApplication(); - else { + if (isLegacyStorageAccessGranted(mActivity)) { + initApplication(); + } else { requestLegacyStoragePermission(new CallBackListener(){ @Override public void onCallBack(Context c, boolean positive, Object[] o) { @@ -306,7 +322,7 @@ public void onCallBack(Context c, boolean positive, Object[] o) { private void initApplication() { setMediaStatusListener(); - checkStoredKey(new CallBackListener(){ + checkStoredKey(new CallBackListener() { @Override public void onCallBack(Context context, boolean positive, Object[] objects) { setActivityForeground(true); @@ -356,13 +372,21 @@ public void onCallBack(Context context, boolean positive, Object[] objects) { if (mGp.syncThreadActive) { mMainTabLayout.setCurrentTabByName(mTabNameMessage); } - if (!appStartWithRestored) { + //if (!appStartWithRestored) { + if (mSavedInstanceState == null) { + // app was created on a first start if (mGp.syncThreadActive) mMainTabLayout.setCurrentTabByName(mTabNameMessage); } else { - if (mGp.activityIsFinished) { - mUtil.addLogMsg("W", "", mContext.getString(R.string.msgs_smbsync_main_restart_by_killed)); - } else { + // there is an onCreate() savedInstanceState bundle. App was recreated because: + // + user changes app system permissions while in Settings activity (Android calls onCreate() if app system permissions are changed) + // + system kills MainActivity while in Activity Settings because of low memory + // + advanced Android system Developer option "Don't keep activities" was enabled by user + if (mGp.activityKilledByDeveloperOption) { + // ActivityMain probably killed in background by Android system developer's option "Don't keep activities" mUtil.addLogMsg("W", "", mContext.getString(R.string.msgs_smbsync_main_restart_by_destroyed)); + } else { + // ActivityMain killed in background (low memory, user changes system app permissions, force stop by user) + mUtil.addLogMsg("W", "", mContext.getString(R.string.msgs_smbsync_main_restart_by_killed)); } mMainTabLayout.setCurrentTabByName(mTabNameMessage); } @@ -400,7 +424,7 @@ private void checkStoredKey(CallBackListener cbl) { e.printStackTrace(); mUtil.showCommonDialogError(false, mContext.getString(R.string.msgs_security_stored_sectret_key_change_title), - mContext.getString(R.string.msgs_security_stored_sectret_key_change_error)+", "+e.toString(), null); + mContext.getString(R.string.msgs_security_stored_sectret_key_change_error)+", "+ e, null); result="key error"; } mUtil.addDebugMsg(1, "I", "checkStoredKey exit, result=\""+result+"\""); @@ -416,7 +440,7 @@ private void checkStoredKey(CallBackListener cbl) { e.printStackTrace(); mUtil.showCommonDialogError(false, mContext.getString(R.string.msgs_security_stored_sectret_key_change_title), - mContext.getString(R.string.msgs_security_stored_sectret_key_save_error)+", "+e.toString(), null); + mContext.getString(R.string.msgs_security_stored_sectret_key_save_error)+", "+ e, null); result="key not save"; } mUtil.addDebugMsg(1, "I", "checkStoredKey exit, result=\""+result+"\""); @@ -449,6 +473,142 @@ private ShortcutInfo createShortcutInfo(Activity a, int shortcut_key_value, Stri return info; } + public void requestLocalStoragePermission(final ActivityMain activity, + final GlobalParameters gp, final CommonUtilities ut, final NotifyEvent p_ntfy) { +// final Spinner sp_sync_folder_local_storage_selector = (Spinner) dialog.findViewById(R.id.edit_sync_folder_dlg_local_storage_selector); + NotifyEvent ntfy = new NotifyEvent(activity); + ntfy.setListener(new NotifyEvent.NotifyEventListener() { + @SuppressWarnings("unchecked") + @Override + public void positiveResponse(Context context, Object[] objects) { + ArrayListuuid_list = (ArrayList)objects[0]; + final NotifyEvent ntfy_response = new NotifyEvent(context); + ntfy_response.setListener(new NotifyEvent.NotifyEventListener() { + @Override + public void positiveResponse(Context context, Object[] objects) { + final int resultCode = (Integer)objects[0]; + final Intent data = (Intent)objects[1]; + final String uuid = (String)objects[2]; + + if (resultCode == Activity.RESULT_OK) { + if (data == null || data.getDataString() == null) { + String msg=activity.getString(R.string.msgs_storage_permission_msg_grant_permission_failed_null); + ut.showCommonDialogWarn(false, msg, "", null); + ut.addLogMsg("E", "", msg, ""); + return; + } + ut.addDebugMsg(1, "I", "Intent=" + data.getData().toString()); + if (!SafManager3.isRootTreeUri(data.getData())) { + ut.addDebugMsg(1, "I", "Selected UUID=" + SafManager3.getUuidFromUri(data.getData().toString())); + String em = gp.safMgr.getLastErrorMessage(); + if (em.length() > 0) ut.addDebugMsg(1, "I", "SafMessage="+em); + + NotifyEvent ntfy_retry = new NotifyEvent(context); + ntfy_retry.setListener(new NotifyEvent.NotifyEventListener() { + @Override + public void positiveResponse(Context c, Object[] o) { + requestStoragePermissionByUuid(activity, ut, uuid, ntfy_response); + } + + @Override + public void negativeResponse(Context c, Object[] o) {} + }); + ut.showCommonDialogWarn(true, context.getString(R.string.msgs_main_external_storage_select_retry_select_msg), + data.getData().getPath(), ntfy_retry); + } else { + ut.addDebugMsg(1, "I", "Selected UUID="+SafManager3.getUuidFromUri(data.getData().toString())); + String em = gp.safMgr.getLastErrorMessage(); + if (em.length() > 0) ut.addDebugMsg(1, "I", "SafMessage="+em); + boolean rc = gp.safMgr.addUuid(data.getData()); + if (!rc) { + String msg = activity.getString(R.string.msgs_storage_permission_msg_add_uuid_failed); + String saf_msg = gp.safMgr.getLastErrorMessage(); + ut.showCommonDialogWarn(false, msg, saf_msg, null); + ut.addLogMsg("E", "", msg, "\n", saf_msg); + } + if (p_ntfy != null) p_ntfy.notifyToListener(true, null); + } + } else { + ut.showCommonDialogWarn(false, + context.getString(R.string.msgs_main_external_storage_request_permission), + context.getString(R.string.msgs_main_external_storage_select_required_cancel_msg), null); + + } + } + + @Override + public void negativeResponse(Context context, Object[] objects) {} + }); + for(String uuid:uuid_list) { + requestStoragePermissionByUuid(activity, ut, uuid, ntfy_response); + } + } + + @Override + public void negativeResponse(Context context, Object[] objects) {} + }); + StoragePermission sp = new StoragePermission(activity, ntfy); + sp.showDialog(); + + } + + ActivityResultLauncher activityResultLaunchStoragePermissionByUuid = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), + new ActivityResultCallback() { + @Override + public void onActivityResult(ActivityResult result) { + if (mNtfyStoragePermissionByUuidListener != null) { + int resultCode = result.getResultCode(); + Intent data = result.getData(); + mNtfyStoragePermissionByUuidListener.notifyToListener(true, new Object[]{resultCode, data, mNtfyStoragePermissionByUuidListenerUUID}); + } + } + } + ); + + private NotifyEvent mNtfyStoragePermissionByUuidListener; + private String mNtfyStoragePermissionByUuidListenerUUID; + public void requestStoragePermissionByUuid(final ActivityMain a, final CommonUtilities cu, final String uuid, final NotifyEvent ntfy) { + cu.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName()+" enterd"); + Intent intent = null; + //StorageManager sm = (StorageManager) a.getSystemService(Context.STORAGE_SERVICE); + ArrayList vol_list = SafManager3.getStorageVolumeInfo(a); + for(SafManager3.StorageVolumeInfo svi:vol_list) { + if (svi.uuid.equals(uuid)) { + if (Build.VERSION.SDK_INT >= 29) { + if (!svi.uuid.equals(SAF_FILE_PRIMARY_UUID)) { + intent = svi.volume.createOpenDocumentTreeIntent(); + } + } else { //createAccessIntent only valid for Build.VERSION.SDK_INT <= 28 + if (!svi.uuid.equals(SAF_FILE_PRIMARY_UUID)) { + intent = svi.volume.createAccessIntent(null); + } + } + if (intent != null) { + try { + mNtfyStoragePermissionByUuidListener = ntfy; + mNtfyStoragePermissionByUuidListenerUUID = uuid; + a.activityResultLaunchStoragePermissionByUuid.launch(intent); +/* + a.launchActivityResult(a, "UUID", intent, + new CallBackListener() { + @Override + public void onCallBack(Context context, boolean positive, Object[] objects) { + ntfy.notifyToListener(true, new Object[]{positive ? 0:-1, objects[0], uuid}); + } + } + ); +*/ + } catch(Exception e) { + String st = MiscUtil.getStackTraceString(e); + cu.showCommonDialog(false, "E", + a.getString(R.string.msgs_storage_permission_msg_saf_error_occured), e.getMessage() + "\n" + st, null); + } + break; + } + } + } + } + private void showAddExternalStorageNotification() { mUtil.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName()+ " entered, isStoragePermissionRequired="+mGp.safMgr.isStoragePermissionRequired()+ @@ -457,7 +617,6 @@ private void showAddExternalStorageNotification() { if (mGp.safMgr.isStoragePermissionRequired() && !mGp.isSupressAddExternalStorageNotification()) { NotifyEvent ntfy=new NotifyEvent(mContext); ntfy.setListener(new NotifyEvent.NotifyEventListener() { - @SuppressWarnings("unchecked") @Override public void positiveResponse(Context context, Object[] objects) { boolean suppress=(boolean)objects[0]; @@ -473,10 +632,9 @@ public void positiveResponse(Context context, Object[] objects) { @Override public void negativeResponse(Context context, Object[] objects) {} }); - TaskEditor.requestLocalStoragePermission(mActivity, mGp, mUtil, ntfy_add); + requestLocalStoragePermission(mActivity, mGp, mUtil, ntfy_add); } - @SuppressWarnings("unchecked") @Override public void negativeResponse(Context context, Object[] objects) { boolean suppress=(boolean)objects[0]; @@ -486,9 +644,9 @@ public void negativeResponse(Context context, Object[] objects) { } }); ArrayListsvl=SafManager3.buildStoragePermissionRequiredList(mContext); - String new_storage=""; + StringBuilder new_storage= new StringBuilder(); for(SafManager3.StorageVolumeInfo si:svl) { - new_storage+=si.description+"("+si.uuid+")"+"\n"; + new_storage.append(si.description).append("(").append(si.uuid).append(")").append("\n"); } TaskEditor.showDialogWithHideOption(mActivity, mGp, mUtil, true, mContext.getString(R.string.msgs_common_dialog_ok), @@ -511,7 +669,7 @@ protected void onPause() { super.onPause(); mUtil.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName() + " entered, currentView=" + mCurrentTab + ", getChangingConfigurations=" + String.format("0x%08x", getChangingConfigurations())); - Thread th=new Thread() { + Thread th = new Thread() { @Override public void run() { CommonUtilities.saveMessageList(mContext, mGp); @@ -534,19 +692,34 @@ protected void onStop() { // mUtil.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName() + " entered"); // } +/* + onDestroy() called and isFinishing values: + - called if app uses finish() method + -> isFinishing() == true + - called if user quits the app (back button, clean screen from system recent apps) + -> isFinishing() == true + - called when app is killed because Android system Developer's option "Don't keep activities" is enabled and we enter another activity + -> isFinishing() == false !!!! + - called when app is killed by system for example because of low memory + -> isFinishing() == false !!!! + - not called when app killed because of: + + user modifies system app permissions + + user uses system "Force stop" on the app +*/ @Override protected void onDestroy() { super.onDestroy(); - mUtil.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName() + " entered, isFinishing=" + isFinishing() + - ", changingConfigurations=" + String.format("0x%08x", getChangingConfigurations())); - mGp.appPasswordAuthValidated=false; - mGp.activityIsFinished = isFinishing(); + mGp.appPasswordAuthValidated = false; + mGp.activityKilledByDeveloperOption = !isFinishing(); - mGp.callbackShowDialogWindow =null; - mGp.callbackHideDialogWindow =null; - mGp.callbackShowConfirmDialog =null; - mGp.callbackHideConfirmDialog =null; + mUtil.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName() + " entered, activityKilledByDeveloperOption=" + mGp.activityKilledByDeveloperOption + + ", changingConfigurations=" + String.format("0x%08x", getChangingConfigurations())); + + mGp.callbackShowDialogWindow = null; + mGp.callbackHideDialogWindow = null; + mGp.callbackShowConfirmDialog = null; + mGp.callbackHideConfirmDialog = null; LogUtil.flushLog(mContext); @@ -556,7 +729,7 @@ protected void onDestroy() { System.gc(); if (mGp.activityRestartRequired) { - mGp.activityRestartRequired=false; + mGp.activityRestartRequired = false; Handler hndl = new Handler(); hndl.postDelayed(new Runnable() { @Override @@ -569,7 +742,7 @@ public void run() { } } -// static public void exitCleanly(Context c, GlobalParameters gp) { +// public static void exitCleanly(Context c, GlobalParameters gp) { // if (gp.settingExitClean && !gp.activityRestartRequired) { // Handler hndl = new Handler(); // hndl.postDelayed(new Runnable() { @@ -587,10 +760,10 @@ public void run() { // } @Override - public void onConfigurationChanged(final android.content.res.Configuration newConfig) { + public void onConfigurationChanged(@NonNull final android.content.res.Configuration newConfig) { super.onConfigurationChanged(newConfig); if (mUtil != null) { - mUtil.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName() , " Entered, New orientation=" + newConfig.orientation, ", New language=", newConfig.locale.getLanguage()); + mUtil.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName() , " Entered, New orientation=" + newConfig.orientation, ", New language=", GlobalParameters.getLanguageCode(mContext)); } reloadScreen(false); } @@ -606,18 +779,18 @@ private void showSystemInfo() { dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(R.layout.common_dialog); - final LinearLayout ll_title=(LinearLayout) dialog.findViewById(R.id.common_dialog_title_view); + final LinearLayout ll_title= dialog.findViewById(R.id.common_dialog_title_view); ll_title.setBackgroundColor(mGp.themeColorList.title_background_color); - final TextView tv_title=(TextView)dialog.findViewById(R.id.common_dialog_title); + final TextView tv_title= dialog.findViewById(R.id.common_dialog_title); tv_title.setTextColor(mGp.themeColorList.title_text_color); - final TextView tv_msg_old=(TextView)dialog.findViewById(R.id.common_dialog_msg); + final TextView tv_msg_old= dialog.findViewById(R.id.common_dialog_msg); tv_msg_old.setVisibility(TextView.GONE); - final NonWordwrapTextView tv_msg=(NonWordwrapTextView)dialog.findViewById(R.id.common_dialog_custom_text_view); + final NonWordwrapTextView tv_msg= dialog.findViewById(R.id.common_dialog_custom_text_view); tv_msg.setVisibility(TextView.VISIBLE); // if (Build.VERSION.SDK_INT>=23) tv_msg.setBreakStrategy(Layout.BREAK_STRATEGY_HIGH_QUALITY); - final Button btn_copy=(Button)dialog.findViewById(R.id.common_dialog_btn_ok); - final Button btn_close=(Button)dialog.findViewById(R.id.common_dialog_btn_cancel); - final Button btn_send=(Button)dialog.findViewById(R.id.common_dialog_extra_button); + final Button btn_copy= dialog.findViewById(R.id.common_dialog_btn_ok); + final Button btn_close= dialog.findViewById(R.id.common_dialog_btn_cancel); + final Button btn_send= dialog.findViewById(R.id.common_dialog_extra_button); btn_send.setText(mContext.getString(R.string.msgs_info_storage_send_btn_title)); btn_send.setVisibility(Button.VISIBLE); @@ -626,17 +799,17 @@ private void showSystemInfo() { btn_copy.setText(mContext.getString(R.string.msgs_info_storage_copy_clipboard)); ArrayList sil= CommonUtilities.listSystemInfo(mContext, mGp); - String si_text=""; - for(String si_item:sil) si_text+=si_item+"\n"; + StringBuilder si_text= new StringBuilder(); + for(String si_item:sil) si_text.append(si_item).append("\n"); - tv_msg.setText(si_text); + tv_msg.setText(si_text.toString()); CommonDialog.setDlgBoxSizeLimit(dialog,true); btn_copy.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { - android.content.ClipboardManager cm=(android.content.ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE); + ClipboardManager cm=(ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE); cm.setPrimaryClip(ClipData.newPlainText("SMBSync3 System Info", tv_msg.getOriginalText().toString())); CommonDialog.showPopupMessageAsUpAnchorViewShort(mActivity, btn_copy, mContext.getString(R.string.msgs_info_storage_copy_completed)); } @@ -654,7 +827,6 @@ public void onClick(View view) { public void onClick(View view) { NotifyEvent ntfy=new NotifyEvent(mContext); ntfy.setListener(new NotifyEvent.NotifyEventListener() { - @SuppressWarnings("unchecked") @Override public void positiveResponse(Context context, Object[] objects) { String desc=(String)objects[0]; @@ -701,25 +873,25 @@ private void getProblemDescription(final NotifyEvent p_ntfy) { dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(R.layout.single_item_input_dlg); - LinearLayout ll_dlg_view = (LinearLayout) dialog.findViewById(R.id.single_item_input_dlg_view); + LinearLayout ll_dlg_view = dialog.findViewById(R.id.single_item_input_dlg_view); CommonUtilities.setDialogBoxOutline(mContext, ll_dlg_view); // ll_dlg_view.setBackgroundColor(mGp.themeColorList.dialog_msg_background_color); - final LinearLayout title_view = (LinearLayout) dialog.findViewById(R.id.single_item_input_title_view); - final TextView tv_title = (TextView) dialog.findViewById(R.id.single_item_input_title); + final LinearLayout title_view = dialog.findViewById(R.id.single_item_input_title_view); + final TextView tv_title = dialog.findViewById(R.id.single_item_input_title); title_view.setBackgroundColor(mGp.themeColorList.title_background_color); tv_title.setTextColor(mGp.themeColorList.title_text_color); tv_title.setText(mContext.getString(R.string.msgs_your_problem_title)); - final TextView tv_msg=(TextView)dialog.findViewById(R.id.single_item_input_msg); + final TextView tv_msg= dialog.findViewById(R.id.single_item_input_msg); tv_msg.setVisibility(TextView.GONE); - final TextView tv_desc=(TextView)dialog.findViewById(R.id.single_item_input_name); + final TextView tv_desc= dialog.findViewById(R.id.single_item_input_name); tv_desc.setText(mContext.getString(R.string.msgs_your_problem_msg)); - final EditText et_msg=(EditText)dialog.findViewById(R.id.single_item_input_dir); + final EditText et_msg= dialog.findViewById(R.id.single_item_input_dir); et_msg.setHint(mContext.getString(R.string.msgs_your_problem_hint)); et_msg.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE); - final Button btn_ok=(Button)dialog.findViewById(R.id.single_item_input_ok_btn); - final Button btn_cancel=(Button)dialog.findViewById(R.id.single_item_input_cancel_btn); + final Button btn_ok= dialog.findViewById(R.id.single_item_input_ok_btn); + final Button btn_cancel= dialog.findViewById(R.id.single_item_input_cancel_btn); // btn_cancel.setText(mContext.getString(R.string.msgs_common_dialog_close)); @@ -765,28 +937,29 @@ public void onCancel(DialogInterface dialogInterface) { dialog.show(); } + // Requires Build.VERSION.SDK_INT>=23 private void showBatteryOptimization() { - if (Build.VERSION.SDK_INT >= 23) { - Intent intent = new Intent(); -// String packageName = mContext.getPackageName(); -// PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE); -// if (pm.isIgnoringBatteryOptimizations(packageName)) { -// intent.setAction(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS); -// startActivity(intent); -// mUtil.addDebugMsg(1, "I", "Invoke battery optimization settings"); -// } else { -// intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS); -// intent.setData(Uri.parse("package:" + packageName)); -// startActivity(intent); -// mUtil.addDebugMsg(1, "I", "Request ignore battery optimization"); -// } + Intent intent = new Intent(); +/* + String packageName = mContext.getPackageName(); + PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE); + if (pm.isIgnoringBatteryOptimizations(packageName)) { intent.setAction(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS); startActivity(intent); mUtil.addDebugMsg(1, "I", "Invoke battery optimization settings"); + } else { + intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS); + intent.setData(Uri.parse("package:" + packageName)); + startActivity(intent); + mUtil.addDebugMsg(1, "I", "Request ignore battery optimization"); } +*/ + intent.setAction(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS); + startActivity(intent); + mUtil.addDebugMsg(1, "I", "Invoke battery optimization settings"); } - class ViewSaveArea { + private static class ViewSaveArea { public int current_tab_pos = 0; public int current_pager_pos = 0; public int task_list_view_pos_x = 0, task_list_view_pos_y = 0; @@ -816,7 +989,7 @@ class ViewSaveArea { public ButtonViewContent prog_spin_cancel = new ButtonViewContent(); } - class ButtonViewContent { + static class ButtonViewContent { public String button_text = ""; public boolean button_visible = true, button_enabled = true, button_clickable = true; } @@ -837,11 +1010,10 @@ private void restoreButtonStatus(Button btn, ButtonViewContent sv, OnClickListen private void reloadScreen(boolean force_reload) { mUtil.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName() + " Entered"); - ViewSaveArea vsa = null; - vsa = saveViewContent(); + ViewSaveArea vsa = saveViewContent(); - mGp.syncTaskView.setAdapter(null); - mGp.syncHistoryView.setAdapter(null); + //mGp.syncTaskView.setAdapter(null); + //mGp.syncHistoryView.setAdapter(null); setContentView(R.layout.main_screen); mActionBar = getSupportActionBar(); @@ -864,20 +1036,26 @@ private void reloadScreen(boolean force_reload) { createTabView(); - GlobalParameters.setDisplayFontScale(mActivity); + //GlobalParameters.setDisplayFontScale(mActivity); mGp.syncTaskListAdapter = new TaskListAdapter(mActivity, R.layout.sync_task_item_view, pfl, mGp); mGp.syncTaskListAdapter.setShowCheckBox(vsa.prof_adapter_show_cb); mGp.syncTaskListAdapter.notifyDataSetChanged(); if (mGp.syncTaskList.size()==0) mGp.syncTaskEmptyMessage.setVisibility(TextView.VISIBLE); else mGp.syncTaskEmptyMessage.setVisibility(TextView.GONE); + mGp.syncMessageListAdapter = new MessageListAdapter(mActivity, R.layout.message_list_item, mfl, mGp); + mGp.syncHistoryListAdapter = new HistoryListAdapter(mActivity, R.layout.history_list_item, vsa.sync_hist_list); mGp.syncHistoryListAdapter.setShowCheckBox(vsa.sync_adapter_show_cb); mGp.syncHistoryListAdapter.notifyDataSetChanged(); + mGp.syncScheduleListAdapter.setSelectMode(sync_schedule_adapter_select_mode); + mGp.syncGroupListAdapter.setSelectMode(sync_group_adapter_select_mode); + initAdapterAndView(); + restoreViewContent(vsa); setMessageContextButtonListener(); @@ -912,7 +1090,18 @@ private void reloadScreen(boolean force_reload) { if (isUiEnabled()) setUiEnabled(); else setUiDisabled(); - vsa = null; + } + + private void initAdapterAndView() { + mGp.syncMessageView.setAdapter(mGp.syncMessageListAdapter); + mGp.syncMessageView.setDrawingCacheEnabled(true); + mGp.syncMessageView.setSelection(mGp.syncMessageListAdapter.getCount() - 1); + + mGp.syncTaskView.setAdapter(mGp.syncTaskListAdapter); + mGp.syncTaskView.setDrawingCacheEnabled(true); + + mGp.syncHistoryView.setAdapter(mGp.syncHistoryListAdapter); + mGp.syncHistoryListAdapter.notifyDataSetChanged(); } // private int newSyncTaskListViewPos = -1; @@ -955,6 +1144,7 @@ private void restoreViewContent(ViewSaveArea vsa) { mMainTabLayout.setCurrentTabByPosition(vsa.current_tab_pos); mMainViewPager.setCurrentItem(vsa.current_pager_pos); mWhileRestoreViewProcess=false; + mGp.syncTaskView.setSelectionFromTop(vsa.task_list_view_pos_x, vsa.task_list_view_pos_y); mGp.syncMessageView.setSelectionFromTop(vsa.msg_list_view_pos_x, vsa.msg_list_view_pos_y); mGp.syncHistoryView.setSelectionFromTop(vsa.hist_list_view_pos_x, vsa.hist_list_view_pos_y); @@ -999,6 +1189,8 @@ private void restoreViewContent(ViewSaveArea vsa) { private CustomViewPager mMainViewPager; // private CustomViewPagerAdapter mMainViewPagerAdapter; private boolean mWhileRestoreViewProcess=false; + + @SuppressLint("InflateParams") private void createTabView() { LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); @@ -1147,7 +1339,7 @@ public void run() { mMainViewPager = (CustomViewPager) findViewById(R.id.main_screen_pager); mMainViewPager.setAdapter(mMainViewPagerAdapter); mMainViewPager.setOffscreenPageLimit(tab_view.length); - mMainViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() { + mMainViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageSelected(int position) { mUtil.addDebugMsg(2,"I","onPageSelected entered, pos="+position); @@ -1169,15 +1361,17 @@ public void onPageScrolled(int position, float positionOffset, int positionOffse mMainTabLayout.setCurrentTabByName(mTabNameTask); mMainViewPager.setCurrentItem(0); } - mMainTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { + mMainTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { String tabId=(String)tab.getTag(); mUtil.addDebugMsg(2, "I", CommonUtilities.getExecutedMethodName() + " entered. tab=" + tabId + ",v=" + mCurrentTab); - mActionBar.setIcon(R.drawable.smbsync); - mActionBar.setHomeButtonEnabled(false); - mActionBar.setTitle(R.string.app_name); + if (mActionBar != null) { + mActionBar.setIcon(R.drawable.smbsync); + mActionBar.setHomeButtonEnabled(false); + mActionBar.setTitle(R.string.app_name); + } mMainViewPager.setCurrentItem(mMainTabLayout.getSelectedTabPosition()); @@ -1246,17 +1440,6 @@ public void onTabUnselected(TabLayout.Tab tab) { public void onTabReselected(TabLayout.Tab tab) { } }); - - mGp.syncMessageView.setAdapter(mGp.syncMessageListAdapter); - mGp.syncMessageView.setDrawingCacheEnabled(true); - mGp.syncMessageView.setSelection(mGp.syncMessageListAdapter.getCount() - 1); - - mGp.syncTaskView.setAdapter(mGp.syncTaskListAdapter); - mGp.syncTaskView.setDrawingCacheEnabled(true); - - mGp.syncHistoryView.setAdapter(mGp.syncHistoryListAdapter); - mGp.syncHistoryListAdapter.notifyDataSetChanged(); - } @Override @@ -1270,7 +1453,7 @@ public boolean onCreateOptionsMenu(Menu menu) { @Override public boolean onPrepareOptionsMenu(Menu menu) { mUtil.addDebugMsg(2, "I", CommonUtilities.getExecutedMethodName(), " entered, isUiEnabled()="+isUiEnabled()); - boolean pm_bo = false; +// boolean pm_bo = false; // if (Build.VERSION.SDK_INT >= 23) { // menu.findItem(R.id.menu_top_show_battery_optimization).setVisible(true); // String packageName = mContext.getPackageName(); @@ -1287,10 +1470,10 @@ public boolean onPrepareOptionsMenu(Menu menu) { // LogCatUtil.prepareOptionMenu(mGp, mUtil, menu); menu.findItem(R.id.menu_top_request_all_file_access_permission).setVisible(false); - //Enable "ALL_FILE_ACCESS" -// if (CommonUtilities.isAllFileAccessAvailable()) { -// menu.findItem(R.id.menu_top_request_all_file_access_permission).setVisible(true); -// } + // Enable "ALL_FILE_ACCESS menu for SDK >= 30" + //if (CommonUtilities.isAllFileAccessAvailable()) { //checks if Build.VERSION.SDK_INT >= 30 + // menu.findItem(R.id.menu_top_request_all_file_access_permission).setVisible(true); + //} if (mGp.settingScheduleSyncEnabled) menu.findItem(R.id.menu_top_scheduler).setIcon(R.drawable.ic_64_schedule); else menu.findItem(R.id.menu_top_scheduler).setIcon(R.drawable.ic_64_schedule_disabled); @@ -1321,19 +1504,16 @@ public boolean onPrepareOptionsMenu(Menu menu) { if (isUiEnabled()) { setMenuItemEnabled(menu, menu.findItem(R.id.menu_top_housekeep), true); - if (mGp.syncThreadActive) menu.findItem(R.id.menu_top_housekeep).setVisible(false); - else menu.findItem(R.id.menu_top_housekeep).setVisible(true); + menu.findItem(R.id.menu_top_housekeep).setVisible(!mGp.syncThreadActive); if (mCurrentTab.equals(mTabNameTask)) { - if (mGp.syncTaskList.size()>0) menu.findItem(R.id.menu_top_sync).setVisible(true); - else menu.findItem(R.id.menu_top_sync).setVisible(false); + menu.findItem(R.id.menu_top_sync).setVisible(mGp.syncTaskList.size() > 0); } setMenuItemEnabled(menu, menu.findItem(R.id.menu_top_settings), true); setMenuItemEnabled(menu, menu.findItem(R.id.menu_top_export), true); setMenuItemEnabled(menu, menu.findItem(R.id.menu_top_import), true); setMenuItemEnabled(menu, menu.findItem(R.id.menu_top_log_management), true); - if (mGp.safMgr.isStoragePermissionRequired()) menu.findItem(R.id.menu_top_select_storage).setVisible(true); - else menu.findItem(R.id.menu_top_select_storage).setVisible(false); + menu.findItem(R.id.menu_top_select_storage).setVisible(mGp.safMgr.isStoragePermissionRequired()); // if (mGp.debuggable) menu.findItem(R.id.menu_top_select_storage).setVisible(true); // else menu.findItem(R.id.menu_top_select_storage).setVisible(false); @@ -1367,62 +1547,62 @@ private void setMenuItemEnabled(Menu menu, MenuItem menu_item, boolean enabled) } - private boolean mScheduleEditorAvailable = true; + //private boolean mScheduleEditorAvailable = true; @Override public boolean onOptionsItemSelected(MenuItem item) { - switch (item.getItemId()) { - case android.R.id.home: - processHomeButtonPress(); - return true; - case R.id.menu_top_sync: - confirmStartSync(); - return true; - case R.id.menu_top_show_hide_filter: - showHideFilterView(); - return true; - case R.id.menu_top_export: - exportSyncTaskAndParms(); - return true; - case R.id.menu_top_import: - importSyncTaskAndParms(); - setContextButtonNormalMode(); - return true; - case R.id.menu_top_log_management: - invokeLogManagement(); - setContextButtonNormalMode(); - return true; - case R.id.menu_top_scheduler: - toggleScheduleEnabled(); - return true; - case R.id.menu_top_about: - aboutApp(); - setContextButtonNormalMode(); - return true; - case R.id.menu_top_settings: - invokeSettingsActivity(); - setContextButtonNormalMode(); - return true; - case R.id.menu_top_kill: - killApplication(); - setContextButtonNormalMode(); - return true; - case R.id.menu_top_housekeep: - new HouseKeep(mActivity, mGp, mUtil); - return true; - case R.id.menu_top_show_battery_optimization: - showBatteryOptimization(); - return true; - case R.id.menu_top_list_storage: - showSystemInfo(); - return true; - case R.id.menu_top_select_storage: - invokeStorageRequestor(); - return true; - case R.id.menu_top_request_all_file_access_permission: - //ENable "ALL_FILE_ACCESS" - requestAllFileAccessPermission(null); - return true; + int itemId = item.getItemId(); + if (itemId == android.R.id.home) { + processHomeButtonPress(); + return true; + } else if (itemId == R.id.menu_top_sync) { + confirmStartSync(); + return true; + } else if (itemId == R.id.menu_top_show_hide_filter) { + showHideFilterView(); + return true; + } else if (itemId == R.id.menu_top_export) { + exportSyncTaskAndParms(); + return true; + } else if (itemId == R.id.menu_top_import) { + importSyncTaskAndParms(); + setContextButtonNormalMode(); + return true; + } else if (itemId == R.id.menu_top_log_management) { + invokeLogManagement(); + setContextButtonNormalMode(); + return true; + } else if (itemId == R.id.menu_top_scheduler) { + toggleScheduleEnabled(); + return true; + } else if (itemId == R.id.menu_top_about) { + aboutApp(); + setContextButtonNormalMode(); + return true; + } else if (itemId == R.id.menu_top_settings) { + invokeSettingsActivity(); + setContextButtonNormalMode(); + return true; + } else if (itemId == R.id.menu_top_kill) { + killApplication(); + setContextButtonNormalMode(); + return true; + } else if (itemId == R.id.menu_top_housekeep) { + new HouseKeep(mActivity, mGp, mUtil); + return true; + } else if (itemId == R.id.menu_top_show_battery_optimization) { + showBatteryOptimization(); + return true; + } else if (itemId == R.id.menu_top_list_storage) { + showSystemInfo(); + return true; + } else if (itemId == R.id.menu_top_select_storage) { + invokeStorageRequestor(); + return true; + } else if (itemId == R.id.menu_top_request_all_file_access_permission) { + //Enable "ALL_FILE_ACCESS" + if (Build.VERSION.SDK_INT >= 30) requestAllFileAccessPermission(null); + return true; } if (isUiEnabled()) { } @@ -1433,13 +1613,11 @@ private void confirmStartSync() { if (isUiEnabled()) { final ArrayListsync_task_list=new ArrayList(); if (mGp.syncTaskListAdapter.isShowCheckBox()) { - String sep=""; - String task_list=""; + StringBuilder task_list= new StringBuilder(); for(SyncTaskItem sti:mGp.syncTaskList) { if (!sti.isSyncTaskError() && sti.isChecked()) { - task_list+="-"+sti.getSyncTaskName()+"\n"; + task_list.append("-").append(sti.getSyncTaskName()).append("\n"); sync_task_list.add(sti); - sep=","; } } if (sync_task_list.size()>0) { @@ -1470,15 +1648,15 @@ public void negativeResponse(Context context, Object[] objects) { } } - String task_list=""; + StringBuilder task_list= new StringBuilder(); if (group_item==null || group_item.autoTaskOnly) { for(SyncTaskItem sti:mGp.syncTaskList) { if (sti.isSyncTaskAuto() && !sti.isSyncTestMode()) { - task_list+="-"+sti.getSyncTaskName()+"\n"; + task_list.append("-").append(sti.getSyncTaskName()).append("\n"); sync_task_list.add(sti); } } - if (task_list.equals("")) { + if (task_list.toString().equals("")) { mUtil.showCommonDialog(false, "W", mContext.getString(R.string.msgs_main_sync_button_confirmation_message_title), mContext.getString(R.string.msgs_main_sync_button_start_error_auto_task_does_not_exists)+"\n"+task_list, null); @@ -1494,7 +1672,7 @@ public void negativeResponse(Context context, Object[] objects) { mContext.getString(R.string.msgs_main_sync_button_start_error_task_not_found,item), null); return; } else { - task_list+=sti.getSyncTaskName()+"\n"; + task_list.append(sti.getSyncTaskName()).append("\n"); sync_task_list.add(sti); } } @@ -1502,7 +1680,6 @@ public void negativeResponse(Context context, Object[] objects) { NotifyEvent ntfy=new NotifyEvent(mContext); ntfy.setListener(new NotifyEvent.NotifyEventListener() { - @SuppressWarnings("unchecked") @Override public void positiveResponse(Context context, Object[] objects) { if (objects!=null) { @@ -1537,7 +1714,7 @@ public void negativeResponse(Context context, Object[] objects) { } private void showHideFilterView() { - LinearLayout ll_filter_view=(LinearLayout)mMessageView.findViewById(R.id.main_message_filter_view); + LinearLayout ll_filter_view= mMessageView.findViewById(R.id.main_message_filter_view); if (ll_filter_view.getVisibility()==LinearLayout.GONE) { ll_filter_view.setVisibility(LinearLayout.VISIBLE); } else { @@ -1557,7 +1734,7 @@ public void positiveResponse(Context context, Object[] objects) { @Override public void negativeResponse(Context context, Object[] objects) {} }); - TaskEditor.requestLocalStoragePermission(mActivity, mGp, mUtil, ntfy_esp); + requestLocalStoragePermission(mActivity, mGp, mUtil, ntfy_esp); } private void toggleScheduleEnabled() { @@ -1575,16 +1752,18 @@ public void positiveResponse(Context context, Object[] objects) { @Override public void negativeResponse(Context context, Object[] objects) {} }); - String msg=""; + String msg; if (mGp.settingScheduleSyncEnabled) msg=mContext.getString(R.string.msgs_schedule_list_edit_confirm_scheduler_to_disabled); else msg=mContext.getString(R.string.msgs_schedule_list_edit_confirm_scheduler_to_enabled); mUtil.showCommonDialogWarn(true,msg,"",ntfy); } private void setContextButtonNormalMode() { - mActionBar.setIcon(R.drawable.smbsync); - mActionBar.setHomeButtonEnabled(false); - mActionBar.setTitle(R.string.app_name); + if (mActionBar != null) { + mActionBar.setIcon(R.drawable.smbsync); + mActionBar.setHomeButtonEnabled(false); + mActionBar.setTitle(R.string.app_name); + } mGp.syncTaskListAdapter.setShowCheckBox(false); mGp.syncTaskListAdapter.setAllItemChecked(false); @@ -1608,6 +1787,7 @@ private void processHomeButtonPress() { setSyncTaskContextButtonNormalMode(); } } else if (mCurrentTab.equals(mTabNameMessage)) { + // nope } else if (mCurrentTab.equals(mTabNameHistory)) { if (mGp.syncHistoryListAdapter.isShowCheckBox()) { mGp.syncHistoryListAdapter.setShowCheckBox(false); @@ -1678,6 +1858,13 @@ public void positiveResponse(Context c, Object[] o) { public void negativeResponse(Context c, Object[] o) { } }); + // save current active settings that need a restart before any modification and a call to reloadSettingParms() + // if they are changed during import, we can trigger app restart + mPrevThemeSetting = GlobalParameters.getScreenTemeSetting(mContext); + mPrevLanguageSetting = GlobalParameters.getLanguageCode(mContext); + mPrevFontScaleSetting = GlobalParameters.getFontScaleFactorSetting(mContext); + mPrevAppSettingsDirectory = GlobalParameters.getAppManagementDirSetting(mContext); + TaskListImportExport eitl=new TaskListImportExport(mActivity, mGp, mUtil); eitl.importSyncTaskListDlg(ntfy); } @@ -1745,13 +1932,13 @@ private void aboutApp() { dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(R.layout.about_dialog); - final LinearLayout title_view = (LinearLayout) dialog.findViewById(R.id.about_dialog_title_view); - final TextView title = (TextView) dialog.findViewById(R.id.about_dialog_title); + final LinearLayout title_view = dialog.findViewById(R.id.about_dialog_title_view); + final TextView title = dialog.findViewById(R.id.about_dialog_title); title_view.setBackgroundColor(mGp.themeColorList.title_background_color); title.setTextColor(mGp.themeColorList.title_text_color); - title.setText(getString(R.string.msgs_dlg_title_about) + " (Ver" + SystemInfo.getApplVersionName(mContext) + ")"); + title.setText(String.format(getString(R.string.msgs_dlg_title_about), SystemInfo.getApplVersionName(mContext))); - final CustomTabLayout tab_layout = (CustomTabLayout) dialog.findViewById(R.id.tab_layout); + final CustomTabLayout tab_layout = dialog.findViewById(R.id.tab_layout); tab_layout.addTab(mContext.getString(R.string.msgs_about_dlg_func_btn)); tab_layout.addTab(mContext.getString(R.string.msgs_about_dlg_privacy_btn)); tab_layout.addTab(mContext.getString(R.string.msgs_about_dlg_change_btn)); @@ -1762,20 +1949,20 @@ private void aboutApp() { int zf=(int)((float)100* GlobalParameters.getFontScaleFactorValue(mActivity)); - LinearLayout ll_func = (LinearLayout) vi.inflate(R.layout.about_dialog_func, null); - final WebView func_view = (WebView) ll_func.findViewById(R.id.about_dialog_function_view); + @SuppressLint("InflateParams") LinearLayout ll_func = (LinearLayout) vi.inflate(R.layout.about_dialog_func, null); + final WebView func_view = ll_func.findViewById(R.id.about_dialog_function_view); func_view.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); func_view.setScrollbarFadingEnabled(false); CommonUtilities.setWebViewListener(mGp, func_view, zf); - LinearLayout ll_privacy = (LinearLayout) vi.inflate(R.layout.about_dialog_privacy, null); - final WebView privacy_view = (WebView) ll_privacy.findViewById(R.id.about_dialog_privacy_view); + @SuppressLint("InflateParams") LinearLayout ll_privacy = (LinearLayout) vi.inflate(R.layout.about_dialog_privacy, null); + final WebView privacy_view = ll_privacy.findViewById(R.id.about_dialog_privacy_view); privacy_view.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); privacy_view.setScrollbarFadingEnabled(false); CommonUtilities.setWebViewListener(mGp, privacy_view, zf); - LinearLayout ll_change = (LinearLayout) vi.inflate(R.layout.about_dialog_change, null); - final WebView change_view = (WebView) ll_change.findViewById(R.id.about_dialog_change_view); + @SuppressLint("InflateParams") LinearLayout ll_change = (LinearLayout) vi.inflate(R.layout.about_dialog_change, null); + final WebView change_view = ll_change.findViewById(R.id.about_dialog_change_view); change_view.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); change_view.setScrollbarFadingEnabled(false); CommonUtilities.setWebViewListener(mGp, change_view, zf); @@ -1791,15 +1978,16 @@ private void aboutApp() { final CustomViewPagerAdapter adapter = new CustomViewPagerAdapter(mActivity, new View[]{ll_func, ll_privacy, ll_change}); - final CustomViewPager viewPager = (CustomViewPager) dialog.findViewById(R.id.about_view_pager); + final CustomViewPager viewPager = dialog.findViewById(R.id.about_view_pager); viewPager.setAdapter(adapter); viewPager.setOffscreenPageLimit(3); viewPager.setSwipeEnabled(false); - viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener(){ + viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener(){ @Override public void onPageSelected(int position) { -// mUtil.addDebugMsg(2,"I","onPageSelected entered, pos="+position); - tab_layout.getTabAt(position).select(); + //mUtil.addDebugMsg(2,"I","onPageSelected entered, pos="+position); + //if (position >= 0 && position < tab_layout.getTabCount()) + Objects.requireNonNull(tab_layout.getTabAt(position)).select(); } @Override @@ -1809,11 +1997,11 @@ public void onPageScrollStateChanged(int state) { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { -// util.addDebugMsg(2,"I","onPageScrolled entered, pos="+position); +// util.addDebugMsg(2,"I","onPageScrolled entered, pos="+position); } }); - tab_layout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener(){ + tab_layout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener(){ @Override public void onTabSelected(TabLayout.Tab tab) { // mUtil.addDebugMsg(2,"I","onTabSelected entered, state="+tab); @@ -1832,7 +2020,7 @@ public void onTabReselected(TabLayout.Tab tab) { }); - final Button btnOk = (Button) dialog.findViewById(R.id.about_dialog_btn_ok); + final Button btnOk = dialog.findViewById(R.id.about_dialog_btn_ok); CommonDialog.setDlgBoxSizeLimit(dialog, true); @@ -1884,10 +2072,43 @@ public void onCallBack(Context c, boolean positive, Object[] objects) { }); } + ActivityResultLauncher activityResultLaunchSettings = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), + new ActivityResultCallback() { + @Override + public void onActivityResult(ActivityResult result) { + //if (result.getResultCode() == Activity.RESULT_OK) { + mUtil.addDebugMsg(1, "I", "Return from Setting activity."); + if (mPrevActivityKilled) { + // Activity was recreated on returning from activity settings: + // + user changes app system permissions while in Settings activity (Android calls onCreate() if app system permissions are changed) + // + system kills MainActivity while in Activity Settings because of low memory + // + advanced Android system Developer option "Don't keep activities" was enabled by user + // Android will call onCreate() in that case. However, Bundle savedInstanceState will not be null except on first app start + // No need to call reloadSettingParms() in that case as system settings were properly reloaded and applied during app recreation + mUtil.addDebugMsg(1, "I", "ActivityMain killed and recreated on returning from Setting activity."); + } else { + reloadSettingParms(); + } + //} + } + }); + private void invokeSettingsActivity() { mUtil.addDebugMsg(1, "I", "Invoke Setting activity."); - mPrevLanguageSetting=GlobalParameters.getLanguageCode(mContext); + + // save current active settings that need a restart before any modification and a call to reloadSettingParms() + // if they are changed in Settings Activity, we can trigger app restart + mPrevThemeSetting = GlobalParameters.getScreenTemeSetting(mContext); + mPrevLanguageSetting = GlobalParameters.getLanguageCode(mContext); + mPrevFontScaleSetting = GlobalParameters.getFontScaleFactorSetting(mContext); + mPrevAppSettingsDirectory = GlobalParameters.getAppManagementDirSetting(mContext); + mPrevActivityKilled = false; + + // Start settings activity Intent intent = new Intent(mContext, ActivitySettings.class); + activityResultLaunchSettings.launch(intent); +/* + // Deprecated startActivityForResult() launchActivityResult(mActivity, "Settings", intent, new CallBackListener() { @Override public void onCallBack(Context context, boolean b, Object[] objects) { @@ -1895,47 +2116,136 @@ public void onCallBack(Context context, boolean b, Object[] objects) { reloadSettingParms(); } }); +*/ } - private String mPrevLanguageSetting=APPLICATION_LANGUAGE_SETTING_SYSTEM_DEFAULT; +/* + reloadSettingParms(): Reloads settings from saved config. Called after: + - user changes settings in App Settings Activity: invokeSettingsActivity() + - user imports sync task config file: importSyncTaskAndParms() + + Before calling reloadSettingParms(), you must update the below variables with current active settings before calling the method that modifies them + - mPrevThemeSetting = GlobalParameters.getScreenTemeSetting(mContext); + - mPrevLanguageSetting = GlobalParameters.getLanguageCode(mContext); + - mPrevFontScaleSetting = GlobalParameters.getFontScaleFactorSetting(mContext); + - mPrevAppSettingsDirectory = GlobalParameters.getAppManagementDirSetting(mContext); + - mPrevActivityKilled = false; //Only before settings app + + WARNING: if MainActivity onCreate() gets called (activity recreated) when returning from Settings Activity, reloadSettingParms() will get called by onActivityResult() + - this can happen if: + + user changes app system permissions while in Settings activity (Android calls onCreate() if app system permissions are changed) + + system kills MainActivity while in Activity Settings because of low memory + + advanced Android system Developer option "Don't keep activities" was enabled by user + - an NPE will occur if reloadSettingParms() is called in that case because mPrev... variables are null on app start + - if we set mPrev... variables to defaults, this can trigger an app restart if the settings are set to other values than default + - this case is handled in onActivityResult(): reloadSettingParms() is not called as settings were properly loaded on activity creation +*/ + private String mPrevThemeSetting = null; //SCREEN_THEME_DEFAULT; + private String mPrevLanguageSetting = null; //GlobalParameters.APPLICATION_LANGUAGE_SETTING_SYSTEM_DEFAULT; + private String mPrevFontScaleSetting = null; //GlobalParameters.FONT_SCALE_FACTOR_SETTING_DEFAULT; + private String mPrevAppSettingsDirectory = null; //APP_SETTINGS_DIRECTORY_ROOT; + private boolean mPrevActivityKilled = false; + private void reloadSettingParms() { mUtil.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName() + " entered"); - String p_theme = mGp.settingScreenTheme; + mGp.loadSettingsParms(mContext); //reload settings from disk (Preference manager /data/data) - mGp.loadSettingsParms(mContext); + String new_theme = GlobalParameters.getScreenTemeSetting(mContext); + final boolean theme_changed = !new_theme.equals(mPrevThemeSetting); - String new_lc=GlobalParameters.getLanguageCode(mContext); - final boolean theme_lang_changed=!new_lc.equals(mPrevLanguageSetting); + String new_lc = GlobalParameters.getLanguageCode(mContext); + final boolean lang_changed = !new_lc.equals(mPrevLanguageSetting); - if (!p_theme.equals(mGp.settingScreenTheme) || theme_lang_changed) { - mUtil.showCommonDialogWarn(true, - mUtil.getStringWithLangCode(mActivity, new_lc, R.string.msgs_smbsync_main_settings_restart_title), - mUtil.getStringWithLangCode(mActivity, new_lc, R.string.msgs_smbsync_ui_settings_language_changed_restart), - mUtil.getStringWithLangCode(mActivity, new_lc, R.string.msgs_smbsync_ui_settings_language_changed_restart_immediate), - mUtil.getStringWithLangCode(mActivity, new_lc, R.string.msgs_smbsync_ui_settings_language_changed_restart_later), + String new_fs = GlobalParameters.getFontScaleFactorSetting(mContext); + final boolean font_scale_changed = !mPrevFontScaleSetting.equals(new_fs); + + String new_dirId = GlobalParameters.getAppManagementDirSetting(mContext); + final boolean app_settings_dir_changed = !new_dirId.equals(mPrevAppSettingsDirectory); + + if (app_settings_dir_changed) { + // app restart mandatory to save messages, history, logs, autosaved configs to new dircectory + mUtil.showCommonDialog(false, "W", + mContext.getString(R.string.msgs_smbsync_main_settings_restart_title), + mContext.getString(R.string.msgs_smbsync_security_settings_app_dir_changed_restart), new CallBackListener() { - @Override - public void onCallBack(Context c, boolean positive, Object[] objects) { - if (positive) { - mGp.activityRestartRequired=true; - mUtil.flushLog(); - mGp.settingExitClean=false; - finish(); + @Override + public void onCallBack(Context c, boolean positive, Object[] objects) { + if (positive) { + mGp.activityRestartRequired = true; + mUtil.flushLog(); + mGp.settingExitClean=false; + finish(); + } + } + }); + } else if (theme_changed || lang_changed || font_scale_changed) { + // app restart recommended + mUtil.showCommonDialogWarn(true, + mUtil.getStringWithLangCode(mActivity, new_lc, R.string.msgs_smbsync_main_settings_restart_title), + mUtil.getStringWithLangCode(mActivity, new_lc, R.string.msgs_smbsync_ui_settings_theme_changed_restart), + mUtil.getStringWithLangCode(mActivity, new_lc, R.string.msgs_smbsync_ui_settings_theme_changed_restart_immediate), + mUtil.getStringWithLangCode(mActivity, new_lc, R.string.msgs_smbsync_ui_settings_theme_changed_restart_later), + new CallBackListener() { + @Override + public void onCallBack(Context c, boolean positive, Object[] objects) { + if (positive) { + mGp.activityRestartRequired = true; + mUtil.flushLog(); + mGp.settingExitClean = false; + finish(); + } } } - }); + ); } - mGp.setDisplayFontScale(mActivity); + //GlobalParameters.setDisplayFontScale(mActivity); reloadScreen(false); if (mGp.settingFixDeviceOrientationToPortrait) setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); else setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); - checkJcifsOptionChanged(); + if (isJcifsOptionChanged()) { + // app restart required + listSettingsOption(); + NotifyEvent ntfy = new NotifyEvent(mContext); + ntfy.setListener(new NotifyEvent.NotifyEventListener() { + @Override + public void positiveResponse(Context context, Object[] objects) { + mUtil.flushLog(); + mGp.settingExitClean = true; + finish(); + } + @Override + public void negativeResponse(Context context, Object[] objects) { + mGp.settingExitClean = true; + } + }); + mUtil.showCommonDialog(true, "W", + mContext.getString(R.string.msgs_smbsync_main_settings_restart_title), + mContext.getString(R.string.msgs_smbsync_main_settings_jcifs_changed_restart), + ntfy); + } + } + + private boolean isJcifsOptionChanged() { + boolean changed = false; + + String prevSmbLmCompatibility = mGp.settingsSmbLmCompatibility, + prevSmbUseExtendedSecurity = mGp.settingsSmbUseExtendedSecurity; + String p_response_timeout=mGp.settingsSmbClientResponseTimeout; + String p_disable_plain_text_passwords=mGp.settingsSmbDisablePlainTextPasswords; + mGp.initJcifsOption(mContext); + + if (!mGp.settingsSmbLmCompatibility.equals(prevSmbLmCompatibility)) changed = true; + else if (!mGp.settingsSmbUseExtendedSecurity.equals(prevSmbUseExtendedSecurity)) changed = true; + else if (!mGp.settingsSmbClientResponseTimeout.equals(p_response_timeout)) changed = true; + else if (!mGp.settingsSmbDisablePlainTextPasswords.equals(p_disable_plain_text_passwords)) changed = true; + + return changed; } private void listSettingsOption() { @@ -1953,7 +2263,7 @@ private void listSettingsOption() { ", settingFixDeviceOrientationToPortrait=" + mGp.settingFixDeviceOrientationToPortrait + ", settingForceDeviceTabletViewInLandscape=" + mGp.settingForceDeviceTabletViewInLandscape + ", settingApplicationLanguage=" + GlobalParameters.getLanguageCode(mContext) + - ", settingApplicationFontScale=" + GlobalParameters.getFontScaleFactor(mContext) + + ", settingApplicationFontScale=" + GlobalParameters.getFontScaleFactorSetting(mContext) + ", settingExportedTaskEncryptRequired=" + mGp.settingExportedTaskEncryptRequired + ", settingScreenTheme=" + mGp.applicationTheme+//.settingScreenTheme + @@ -1962,61 +2272,109 @@ private void listSettingsOption() { ""); } - private boolean isLegacyStorageAccessGranted() { - if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) return true; - return false; + public static boolean isLegacyStorageAccessGranted(Activity a) { + return a.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED; } + // not used private boolean isPrimaryStorageAccessGranted() { - if (mGp.safMgr.isUuidRegistered(SAF_FILE_PRIMARY_UUID)) return true; - return false; + return mGp.safMgr.isUuidRegistered(SAF_FILE_PRIMARY_UUID); } + // Requires Build.VERSION.SDK_INT>=30 + @RequiresApi(api = Build.VERSION_CODES.R) + ActivityResultLauncher activityResultLaunchrequestAllFileAccessPermission = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), + new ActivityResultCallback() { + @Override + public void onActivityResult(ActivityResult result) { + //if (result.getResultCode() == Activity.RESULT_OK) { + if (isAllFileAccessPermissionGranted()) { + if (!previousAllFileAccessPermissionGranted) { + // properly reload history and messages from storage after permission request or app reinstall + mGp.syncHistoryList.addAll(mUtil.loadHistoryList()); + mGp.syncMessageList.addAll(CommonUtilities.loadMessageList(mContext, mGp)); + mGp.syncMessageListAdapter.notifyDataSetChanged(); + //mGp.syncMessageListAdapter.refresh(); + } + if (mAllFileAccessPermissionListener != null) mAllFileAccessPermissionListener.onCallBack(mContext, true, null); + } else { + mUtil.showCommonDialogWarn(false, + mContext.getString(R.string.msgs_storage_permission_all_file_access_title), + mContext.getString(R.string.msgs_storage_permission_all_file_access_denied_message), + new CallBackListener() { + @Override + public void onCallBack(Context context, boolean positive, Object[] objects) { + finish(); + } + } + ); + } + //} + } + }); + + private CallBackListener mAllFileAccessPermissionListener = null; + private boolean previousAllFileAccessPermissionGranted = false; + // Requires Build.VERSION.SDK_INT>=30 + @RequiresApi(api = Build.VERSION_CODES.R) private void requestAllFileAccessPermission(CallBackListener cbl) { -// Enable "ALL_FILE_ACCESS" - final boolean reload_required=!isAllFileAccessPermissionGranted(); + //final boolean reload_required=!isAllFileAccessPermissionGranted(); + mAllFileAccessPermissionListener = cbl; + previousAllFileAccessPermissionGranted = isAllFileAccessPermissionGranted(); NotifyEvent ntfy_all_file_access=new NotifyEvent(mContext); ntfy_all_file_access.setListener(new NotifyEvent.NotifyEventListener() { @Override public void positiveResponse(Context context, Object[] objects) { Intent intent = new Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION); + activityResultLaunchrequestAllFileAccessPermission.launch(intent); +/* + // Deprecated startActivityForResult() launchActivityResult(mActivity, "ALL_FILE_ACCESS", intent, new CallBackListener() { @Override public void onCallBack(Context context, boolean b, Object[] objects) { if (isAllFileAccessPermissionGranted()) { - if (reload_required) { + if (!reload_required) { + // properly reload history and messages from storage after permission request or app reinstall mGp.syncHistoryList.addAll(mUtil.loadHistoryList()); mGp.syncMessageList.addAll(CommonUtilities.loadMessageList(mContext, mGp)); + mGp.syncMessageListAdapter.notifyDataSetChanged(); + //mGp.syncMessageListAdapter.refresh(); } if (cbl!=null) cbl.onCallBack(mContext, true, null); } else { mUtil.showCommonDialogWarn(false, mContext.getString(R.string.msgs_storage_permission_all_file_access_title), - mContext.getString(R.string.msgs_storage_permission_all_file_access_denied_message), new CallBackListener(){ + mContext.getString(R.string.msgs_storage_permission_all_file_access_denied_message), + new CallBackListener() { @Override public void onCallBack(Context context, boolean positive, Object[] objects) { finish(); } - }); + } + ); } } }); +*/ } @Override public void negativeResponse(Context context, Object[] objects) { - NotifyEvent ntfy_denied=new NotifyEvent(mContext); - ntfy_denied.setListener(new NotifyEvent.NotifyEventListener() { - @Override - public void positiveResponse(Context context, Object[] objects) { - finish(); - } - @Override - public void negativeResponse(Context context, Object[] objects) {} - }); - mUtil.showCommonDialogWarn(false, - mContext.getString(R.string.msgs_storage_permission_all_file_access_title), - mContext.getString(R.string.msgs_storage_permission_all_file_access_denied_message), ntfy_denied); + if (!isAllFileAccessPermissionGranted()) { //case called from Menu, access is already allowed, but user answers no + NotifyEvent ntfy_denied=new NotifyEvent(mContext); + ntfy_denied.setListener(new NotifyEvent.NotifyEventListener() { + @Override + public void positiveResponse(Context context, Object[] objects) { + finish(); + } + @Override + public void negativeResponse(Context context, Object[] objects) {} + }); + mUtil.showCommonDialogWarn(false, + mContext.getString(R.string.msgs_storage_permission_all_file_access_title), + mContext.getString(R.string.msgs_storage_permission_all_file_access_denied_message), + ntfy_denied); + } else if (cbl!=null) cbl.onCallBack(mContext, true, null); } }); final Dialog dialog=new Dialog(mActivity, mGp.applicationTheme); @@ -2024,15 +2382,15 @@ public void negativeResponse(Context context, Object[] objects) {} dialog.setCanceledOnTouchOutside(false); dialog.setContentView(R.layout.request_all_file_access_dlg); - TextView dlg_title=(TextView)dialog.findViewById(R.id.request_all_file_dlg_title); - TextView dlg_msg=(TextView)dialog.findViewById(R.id.request_all_file_dlg_msg); - ImageView dlg_image=(ImageView)dialog.findViewById(R.id.request_all_file_dlg_image); + TextView dlg_title= dialog.findViewById(R.id.request_all_file_dlg_title); + TextView dlg_msg= dialog.findViewById(R.id.request_all_file_dlg_msg); + ImageView dlg_image= dialog.findViewById(R.id.request_all_file_dlg_image); - Button dlg_show_privacy_btn=(Button)dialog.findViewById(R.id.request_all_file_dlg_show_privacy_policy_button); + Button dlg_show_privacy_btn= dialog.findViewById(R.id.request_all_file_dlg_show_privacy_policy_button); dlg_show_privacy_btn.setVisibility(Button.VISIBLE); - Button dlg_ok=(Button)dialog.findViewById(R.id.request_all_file_dlg_btn_ok); - Button dlg_cancel=(Button)dialog.findViewById(R.id.request_all_file_dlg_btn_cancel); + Button dlg_ok= dialog.findViewById(R.id.request_all_file_dlg_btn_ok); + Button dlg_cancel= dialog.findViewById(R.id.request_all_file_dlg_btn_cancel); dlg_title.setText(mContext.getString(R.string.msgs_storage_permission_all_file_access_title)); dlg_msg.setText(mContext.getString(R.string.msgs_storage_permission_all_file_access_request_message)); @@ -2070,7 +2428,7 @@ public void onClick(View view) { @Override public void onClick(View view) { ntfy_all_file_access.notifyToListener(false, null); - dialog.dismiss();; + dialog.dismiss(); } }); @@ -2084,7 +2442,9 @@ public void onCancel(DialogInterface dialogInterface) { dialog.show(); } - private boolean isAllFileAccessPermissionGranted() { + //Build.VERSION.SDK_INT>=30 + @RequiresApi(api = Build.VERSION_CODES.R) + public static boolean isAllFileAccessPermissionGranted() { return Environment.isExternalStorageManager(); } @@ -2093,12 +2453,12 @@ private void showPrivacyPolicy() { dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(R.layout.show_privacy_policy_dlg); - final LinearLayout ll_title=(LinearLayout) dialog.findViewById(R.id.show_privacy_policy_dlg_title_view); + final LinearLayout ll_title= dialog.findViewById(R.id.show_privacy_policy_dlg_title_view); ll_title.setBackgroundColor(mGp.themeColorList.title_background_color); - final TextView tv_title=(TextView)dialog.findViewById(R.id.show_privacy_policy_dlg_title); + final TextView tv_title= dialog.findViewById(R.id.show_privacy_policy_dlg_title); tv_title.setTextColor(mGp.themeColorList.title_text_color); - final WebView web_view=(WebView)dialog.findViewById(R.id.agree_privacy_policy_dlg_webview); + final WebView web_view= dialog.findViewById(R.id.agree_privacy_policy_dlg_webview); web_view.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); web_view.setScrollbarFadingEnabled(false); int zf=(int)((float)100* GlobalParameters.getFontScaleFactorValue(mActivity)); @@ -2116,12 +2476,43 @@ public void onCancel(DialogInterface dialog) { } + ActivityResultLauncher requestPermissionLaunchLegacyStorage = registerForActivityResult(new ActivityResultContracts.RequestPermission(), + new ActivityResultCallback() { + @Override + public void onActivityResult(Boolean result) { + if (result) { + //permission granted + mGp.syncHistoryList.addAll(mUtil.loadHistoryList()); + mGp.syncMessageList.addAll(CommonUtilities.loadMessageList(mContext, mGp)); + if (mLegacyStoragePermissionListener != null) mLegacyStoragePermissionListener.onCallBack(mContext, true, null); + } else { + //permission not granted + mUtil.showCommonDialog(false, "W", + mContext.getString(R.string.msgs_main_permission_external_storage_title), + mContext.getString(R.string.msgs_main_permission_external_storage_denied_msg), + new CallBackListener() { + @Override + public void onCallBack(Context c, boolean positive, Object[] objects) { + //if (positive) finish(); + finish(); + } + } + ); + } + } + }); + + private CallBackListener mLegacyStoragePermissionListener = null; private void requestLegacyStoragePermission(final CallBackListener cbl) { - ArrayListssl=mGp.safMgr.getSafStorageList(); + //ArrayListssl=mGp.safMgr.getSafStorageList(); + mLegacyStoragePermissionListener = cbl; CallBackListener ok_cancel_cbl=new CallBackListener() { @Override public void onCallBack(Context c, boolean positive, Object[] objects) { if (positive) { + requestPermissionLaunchLegacyStorage.launch(Manifest.permission.WRITE_EXTERNAL_STORAGE); +/* + // Deprecated requestPermissions() launchRequestPermission(mActivity, Manifest.permission.WRITE_EXTERNAL_STORAGE, new CallBackListener() { @Override public void onCallBack(Context context, boolean isGranted, Object[] objects) { @@ -2131,30 +2522,37 @@ public void onCallBack(Context context, boolean isGranted, Object[] objects) { cbl.onCallBack(mContext, true, null); } else { mUtil.showCommonDialog(false, "W", - mContext.getString(R.string.msgs_main_permission_external_storage_title), - mContext.getString(R.string.msgs_main_permission_external_storage_denied_msg), new CallBackListener() { - @Override - public void onCallBack(Context c, boolean positive, Object[] objects) { - if (positive) finish(); - } - }); + mContext.getString(R.string.msgs_main_permission_external_storage_title), + mContext.getString(R.string.msgs_main_permission_external_storage_denied_msg), + new CallBackListener() { + @Override + public void onCallBack(Context c, boolean positive, Object[] objects) { + //if (positive) finish(); + finish(); + } + } + ); } } }); +*/ } else { mUtil.showCommonDialogWarn(false, - mContext.getString(R.string.msgs_main_permission_external_storage_title), - mContext.getString(R.string.msgs_main_permission_external_storage_denied_msg), new CallBackListener() { - @Override - public void onCallBack(Context c, boolean positive, Object[] objects) { - mUiHandler.post(new Runnable(){ - @Override - public void run() { - if (positive) finish(); - } - }); - } - }); + mContext.getString(R.string.msgs_main_permission_external_storage_title), + mContext.getString(R.string.msgs_main_permission_external_storage_denied_msg), + new CallBackListener() { + @Override + public void onCallBack(Context c, boolean positive, Object[] objects) { + mUiHandler.post(new Runnable(){ + @Override + public void run() { + //if (positive) finish(); + finish(); + } + }); + } + } + ); } } }; @@ -2173,14 +2571,15 @@ public void onCallBack(Context context, boolean b, Object[] objects) { mActivity.getString(R.string.msgs_privacy_policy_show_privacy_policy), ok_cancel_cbl, extra_cbl, false); } - - private class ActivityLaunchItem { +/* + // Call back listener implementation for deprecated onActivityResult and onRequestPermissionsResult() + private static class ActivityLaunchItem { private String requestorId=null; private int requestCode=0; private CallBackListener callBackListener=null; private String permission=null; - final static public int TYPE_ACTIVITY=0; - final static public int TYPE_PERMISSION=1; + final public static int TYPE_ACTIVITY=0; + final public static int TYPE_PERMISSION=1; private int type=TYPE_ACTIVITY; public ActivityLaunchItem(int req_code, String req_id, CallBackListener cbl) { this.requestorId=req_id; @@ -2200,7 +2599,7 @@ public ActivityLaunchItem(String permission, CallBackListener cbl) { public CallBackListener getCallBackListener() {return callBackListener;} } - private ArrayList mActivityLaunchList=new ArrayList(); + private final ArrayList mActivityLaunchList=new ArrayList(); public void launchActivityResult(Activity a, String req_id, Intent intent, CallBackListener cbl) { int req_code=mActivityLaunchList.size()+1; @@ -2213,13 +2612,14 @@ public void launchActivityResult(Activity a, String req_id, Intent intent, CallB @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { - mUtil.addDebugMsg(1, "I", "onActivityResult requestCode="+requestCode+", resultCode="+resultCode+", data="+data); + super.onActivityResult(requestCode, resultCode, data); + mUtil.addDebugMsg(1, "I", "onActivityResult requestCode=" + requestCode + ", resultCode=" + resultCode + ", data=" + data); synchronized (mActivityLaunchList) { - ArrayList remove_list=new ArrayList(); - for(ActivityLaunchItem item:mActivityLaunchList) { - if (item.getType()== ActivityLaunchItem.TYPE_ACTIVITY && item.getRequestCode()==requestCode) { - mUtil.addDebugMsg(1, "I", "onActivityResult Notify to listener. requestCode="+requestCode); - item.callBackListener.onCallBack(mContext, resultCode==0, new Object[]{data}); + ArrayList remove_list = new ArrayList(); + for (ActivityLaunchItem item : mActivityLaunchList) { + if (item.getType() == ActivityLaunchItem.TYPE_ACTIVITY && item.getRequestCode() == requestCode) { + mUtil.addDebugMsg(1, "I", "onActivityResult Notify to listener. requestCode=" + requestCode); + item.callBackListener.onCallBack(mContext, resultCode == 0, new Object[]{data}); remove_list.add(item); } } @@ -2237,21 +2637,22 @@ public void launchRequestPermission(Activity a, String permission, CallBackListe } @Override - public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { - mUtil.addDebugMsg(1, "I", "onRequestPermissionsResult requestCode="+requestCode+", permission="+permissions[0]+", result="+grantResults[0]); + public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { + super.onRequestPermissionsResult(requestCode, permissions, grantResults); + mUtil.addDebugMsg(1, "I", "onRequestPermissionsResult requestCode=" + requestCode + ", permission=" + permissions[0] + ", result=" + grantResults[0]); synchronized (mActivityLaunchList) { - ArrayList remove_list=new ArrayList(); - for(ActivityLaunchItem item:mActivityLaunchList) { - if (item.getType()== ActivityLaunchItem.TYPE_PERMISSION && item.getPermission().equals(permissions[0])) { - mUtil.addDebugMsg(1, "I", "onRequestPermissionsResult notify to listener. permission="+permissions[0]); - item.callBackListener.onCallBack(mContext, grantResults[0]==0, new Object[]{item.getPermission()}); + ArrayList remove_list = new ArrayList(); + for (ActivityLaunchItem item : mActivityLaunchList) { + if (item.getType() == ActivityLaunchItem.TYPE_PERMISSION && item.getPermission().equals(permissions[0])) { + mUtil.addDebugMsg(1, "I", "onRequestPermissionsResult notify to listener. permission=" + permissions[0]); + item.callBackListener.onCallBack(mContext, grantResults[0] == 0, new Object[]{item.getPermission()}); remove_list.add(item); } } mActivityLaunchList.removeAll(remove_list); } } - +*/ private void setHistoryViewListener() { mGp.syncHistoryView.setEnabled(true); mGp.syncHistoryView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @@ -2330,10 +2731,10 @@ public boolean onItemLongClick(AdapterView arg0, View arg1, int pos, long arg if (up_sel_pos != -1 && down_sel_pos == -1) { for (int i = pos; i < up_sel_pos; i++) mGp.syncHistoryListAdapter.getItem(i).isChecked = true; - } else if (up_sel_pos != -1 && down_sel_pos != -1) { + } else if (up_sel_pos != -1) { //&& down_sel_pos != -1 for (int i = down_sel_pos + 1; i < up_sel_pos; i++) mGp.syncHistoryListAdapter.getItem(i).isChecked = true; - } else if (up_sel_pos == -1 && down_sel_pos != -1) { + } else if (down_sel_pos != -1) { //&& up_sel_pos == -1 for (int i = down_sel_pos + 1; i <= pos; i++) mGp.syncHistoryListAdapter.getItem(i).isChecked = true; } @@ -2409,8 +2810,9 @@ public void run() { mUtil.showCommonDialog(false, "E", "History send error", e.getMessage()+"\n"+st, null); } } else { - lf.delete(); - MessageDialogFragment mdf = MessageDialogFragment.newInstance(false, "W", mContext.getString(R.string.msgs_log_file_list_dlg_send_zip_file_cancelled), ""); + String del_error = ""; + if (!lf.delete()) del_error = "ERROR: could not delete history zip file: "+zip_file_name; + MessageDialogFragment mdf = MessageDialogFragment.newInstance(false, "W", mContext.getString(R.string.msgs_log_file_list_dlg_send_zip_file_cancelled), del_error); mdf.showDialog(getSupportFragmentManager(), mdf, null); } } catch(Exception e) { @@ -2441,7 +2843,6 @@ private void setGroupContextButtonListener() { public void onClick(View view) { NotifyEvent ntfy = new NotifyEvent(mContext); ntfy.setListener(new NotifyEvent.NotifyEventListener() { - @SuppressWarnings("unchecked") @Override public void positiveResponse(Context context, Object[] objects) { GroupListAdapter.GroupListItem si = (GroupListAdapter.GroupListItem) objects[0]; @@ -2469,7 +2870,6 @@ public void onClick(View view) { if (item.isChecked) { NotifyEvent ntfy = new NotifyEvent(mContext); ntfy.setListener(new NotifyEvent.NotifyEventListener() { - @SuppressWarnings("unchecked") @Override public void positiveResponse(Context context, Object[] objects) { GroupListAdapter.GroupListItem si = (GroupListAdapter.GroupListItem) objects[0]; @@ -2602,7 +3002,6 @@ private void setGroupContextButtonMode(GroupListAdapter adapter) { private void setGroupListViewListener() { NotifyEvent ntfy_sync=new NotifyEvent(mContext); ntfy_sync.setListener(new NotifyEvent.NotifyEventListener() { - @SuppressWarnings("unchecked") @Override public void positiveResponse(Context context, Object[] o) { if (isUiEnabled()) { @@ -2632,10 +3031,9 @@ public void negativeResponse(Context context, Object[] objects) { } NotifyEvent ntfy_sw = new NotifyEvent(mContext); ntfy_sw.setListener(new NotifyEvent.NotifyEventListener() { - @SuppressWarnings("unchecked") @Override public void positiveResponse(Context context, Object[] objects) { - int pos=(int)objects[0]; + //int pos=(int)objects[0]; saveGroupList(); } @Override @@ -2660,11 +3058,7 @@ public void negativeResponse(Context context, Object[] objects) {} public void onItemClick(AdapterView adapterView, View view, int i, long l) { if (isUiEnabled()) { if (mGp.syncGroupListAdapter.isSelectMode()) { - if (mGp.syncGroupListAdapter.getItem(i).isChecked) { - mGp.syncGroupListAdapter.getItem(i).isChecked = false; - } else { - mGp.syncGroupListAdapter.getItem(i).isChecked = true; - } + mGp.syncGroupListAdapter.getItem(i).isChecked = !mGp.syncGroupListAdapter.getItem(i).isChecked; mGp.syncGroupListAdapter.notifyDataSetChanged(); setGroupContextButtonMode(mGp.syncGroupListAdapter); } else { @@ -2736,21 +3130,21 @@ private void renameGroup(final GroupListAdapter.GroupListItem si, final NotifyEv dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE); dialog.setContentView(R.layout.single_item_input_dlg); - LinearLayout ll_dlg_view = (LinearLayout) dialog.findViewById(R.id.single_item_input_dlg_view); + LinearLayout ll_dlg_view = dialog.findViewById(R.id.single_item_input_dlg_view); CommonUtilities.setDialogBoxOutline(mContext, ll_dlg_view); - final LinearLayout title_view = (LinearLayout) dialog.findViewById(R.id.single_item_input_title_view); - final TextView title = (TextView) dialog.findViewById(R.id.single_item_input_title); + final LinearLayout title_view = dialog.findViewById(R.id.single_item_input_title_view); + final TextView title = dialog.findViewById(R.id.single_item_input_title); title_view.setBackgroundColor(mGp.themeColorList.title_background_color); title.setTextColor(mGp.themeColorList.title_text_color); - final TextView dlg_msg = (TextView) dialog.findViewById(R.id.single_item_input_msg); + final TextView dlg_msg = dialog.findViewById(R.id.single_item_input_msg); dlg_msg.setTextColor(Color.YELLOW); dlg_msg.setVisibility(TextView.VISIBLE); - final TextView dlg_cmp = (TextView) dialog.findViewById(R.id.single_item_input_name); - final Button btn_ok = (Button) dialog.findViewById(R.id.single_item_input_ok_btn); - final Button btn_cancel = (Button) dialog.findViewById(R.id.single_item_input_cancel_btn); - final EditText etInput = (EditText) dialog.findViewById(R.id.single_item_input_dir); + final TextView dlg_cmp = dialog.findViewById(R.id.single_item_input_name); + final Button btn_ok = dialog.findViewById(R.id.single_item_input_ok_btn); + final Button btn_cancel = dialog.findViewById(R.id.single_item_input_cancel_btn); + final EditText etInput = dialog.findViewById(R.id.single_item_input_dir); title.setText(mContext.getString(R.string.msgs_group_cont_label_rename)); @@ -2792,9 +3186,8 @@ public void onClick(View v) { @Override public void positiveResponse(Context context, Object[] objects) { dialog.dismiss(); - String new_name = etInput.getText().toString(); - si.groupName = new_name; + si.groupName = etInput.getText().toString(); si.isChecked=false; saveGroupList(); if (p_ntfy!=null) p_ntfy.notifyToListener(true, null); @@ -2824,11 +3217,12 @@ public void onCancel(DialogInterface arg0) { } private void confirmGroupDelete() { - String del_name="", sep=""; + StringBuilder del_name= new StringBuilder(); + String sep=""; final ArrayListdel_list=new ArrayList(); for(GroupListAdapter.GroupListItem item:mGp.syncGroupList) { if (item.isChecked) { - del_name+=sep+item.groupName; + del_name.append(sep).append(item.groupName); sep=", "; del_list.add(item); } @@ -2850,7 +3244,7 @@ public void positiveResponse(Context context, Object[] objects) { @Override public void negativeResponse(Context context, Object[] objects) {} }); - mUtil.showCommonDialog(true, "W", mContext.getString(R.string.msgs_group_confirm_msg_delete), del_name, ntfy); + mUtil.showCommonDialog(true, "W", mContext.getString(R.string.msgs_group_confirm_msg_delete), del_name.toString(), ntfy); } @@ -2883,32 +3277,31 @@ private void setScheduleTabMessage() { mGp.syncScheduleListAdapter.notifyDataSetChanged(); } + // Requires Build.VERSION.SDK_INT>=23 private void checkBatteryOptimization() { - if (Build.VERSION.SDK_INT>=23) { - boolean check_required=false; - if (mGp.settingScheduleSyncEnabled) { - for(ScheduleListAdapter.ScheduleListItem item:mGp.syncScheduleList) { - if (item.scheduleEnabled) { - check_required=true; - break; - } + boolean check_required=false; + if (mGp.settingScheduleSyncEnabled) { + for(ScheduleListAdapter.ScheduleListItem item:mGp.syncScheduleList) { + if (item.scheduleEnabled) { + check_required=true; + break; } } - if (check_required) { - boolean ignored=CommonUtilities.isIgnoringBatteryOptimizations(mContext); - if (!ignored) { - mUtil.showCommonDialogWarn(true, - mContext.getString(R.string.msgs_schedule_battery_optimization_warning_title), - mContext.getString(R.string.msgs_schedule_battery_optimization_warning_msg), - new CallBackListener() { - @Override - public void onCallBack(Context context, boolean positive, Object[] objects) { - if (positive) { - showBatteryOptimization(); - } + } + if (check_required) { + boolean ignored=CommonUtilities.isIgnoringBatteryOptimizations(mContext); + if (!ignored) { + mUtil.showCommonDialogWarn(true, + mContext.getString(R.string.msgs_schedule_battery_optimization_warning_title), + mContext.getString(R.string.msgs_schedule_battery_optimization_warning_msg), + new CallBackListener() { + @Override + public void onCallBack(Context context, boolean positive, Object[] objects) { + if (positive) { + showBatteryOptimization(); } - }); - } + } + }); } } } @@ -2919,7 +3312,6 @@ private void setScheduleContextButtonListener() { public void onClick(View v) { NotifyEvent ntfy = new NotifyEvent(mContext); ntfy.setListener(new NotifyEvent.NotifyEventListener() { - @SuppressWarnings("unchecked") @Override public void positiveResponse(Context context, Object[] objects) { ScheduleListAdapter.ScheduleListItem si = (ScheduleListAdapter.ScheduleListItem) objects[0]; @@ -2965,14 +3357,15 @@ public void positiveResponse(Context context, Object[] objects) { @Override public void negativeResponse(Context context, Object[] objects) {} }); - String del_list = "", sep=""; + StringBuilder del_list = new StringBuilder(); + String sep=""; for (int i = 0; i < mGp.syncScheduleListAdapter.getCount(); i++) { if (mGp.syncScheduleListAdapter.getItem(i).isChecked) { - del_list +=sep+"-"+mGp.syncScheduleListAdapter.getItem(i).scheduleName; + del_list.append(sep).append("-").append(mGp.syncScheduleListAdapter.getItem(i).scheduleName); sep="\n"; } } - mUtil.showCommonDialog(true, "W", mContext.getString(R.string.msgs_schedule_confirm_msg_delete), del_list, ntfy); + mUtil.showCommonDialog(true, "W", mContext.getString(R.string.msgs_schedule_confirm_msg_delete), del_list.toString(), ntfy); } }); ContextButtonUtil.setButtonLabelListener(mActivity, mContextScheduleButtonDelete, mContext.getString(R.string.msgs_schedule_cont_label_delete)); @@ -3000,14 +3393,15 @@ public void positiveResponse(Context context, Object[] objects) { public void negativeResponse(Context context, Object[] objects) { } }); - String del_list = "", sep=""; + StringBuilder del_list = new StringBuilder(); + String sep=""; for (int i = 0; i adapterView, View view, int i, long l) { if (isUiEnabled()) { if (mGp.syncScheduleListAdapter.isSelectMode()) { - if (mGp.syncScheduleListAdapter.getItem(i).isChecked) { - mGp.syncScheduleListAdapter.getItem(i).isChecked = false; - } else { - mGp.syncScheduleListAdapter.getItem(i).isChecked = true; - } + mGp.syncScheduleListAdapter.getItem(i).isChecked = !mGp.syncScheduleListAdapter.getItem(i).isChecked; mGp.syncScheduleListAdapter.notifyDataSetChanged(); setScheduleContextButtonMode(mGp.syncScheduleListAdapter); } else { @@ -3324,7 +3709,6 @@ public boolean onItemLongClick(AdapterView adapterView, View view, int i, lon return true; } }); - } private void saveScheduleList() { @@ -3422,14 +3806,12 @@ private void setScheduleContextButtonMode(ScheduleListAdapter adapter) { } private boolean canListViewScrollDown(ListView lv) { - boolean result=false; - if (lv.getLastVisiblePosition()<(lv.getCount()-1)) result=true; + boolean result= lv.getLastVisiblePosition() < (lv.getCount() - 1); return result; } private boolean canListViewScrollUp(ListView lv) { - boolean result=false; - if (lv.getFirstVisiblePosition()>0) result=true; + boolean result= lv.getFirstVisiblePosition() > 0; return result; } @@ -3507,7 +3889,7 @@ public void onClick(View v) { y_offset = first_item_height; if (y_offset > lv_height) { //item is more than one page: position to the bottom, the current top exact last visible position, minus 3 text lines - TextView listTextView = (TextView) mGp.syncHistoryView.getChildAt(0).findViewById(R.id.history_list_view_date); + TextView listTextView = mGp.syncHistoryView.getChildAt(0).findViewById(R.id.history_list_view_date); int text_context_size = 0; if (listTextView != null) text_context_size = (int)(listTextView.getTextSize() * 3); y_offset = first_item_height - first_item_y_bottom + text_context_size; @@ -3531,7 +3913,7 @@ public void onClick(View v) { if (last_item_height > lv_height) { //item is more than one page: position to the top, the current bottom exat last visible position, minus 3 text lines - TextView listTextView = (TextView) mGp.syncHistoryView.getChildAt(last_item_pos).findViewById(R.id.history_list_view_date); + TextView listTextView = mGp.syncHistoryView.getChildAt(last_item_pos).findViewById(R.id.history_list_view_date); int text_context_size = 0; if (listTextView != null) text_context_size = (int)(listTextView.getTextSize() * 3); y_offset = -(lv_height - last_item_y_top - text_context_size); @@ -3596,7 +3978,8 @@ public void onClick(View v) { public void onClick(View v) { setContextButtonEnabled(mContextHistoryButtonHistiryCopyClipboard, false); if (isUiEnabled()) { - ClipboardManager cm = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); + //ClipboardManager cm = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); + ClipboardManager cm = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE); StringBuilder out = new StringBuilder(256); for (int i = 0; i < mGp.syncHistoryListAdapter.getCount(); i++) { if (mGp.syncHistoryListAdapter.getItem(i).isChecked) { @@ -3612,15 +3995,16 @@ public void onClick(View v) { out.append(mContext.getString(R.string.msgs_main_sync_history_status_cancel)).append("\n"); } out.append(mContext.getString(R.string.msgs_main_sync_history_count_copied)) - .append(Integer.toString(hli.sync_result_no_of_copied)).append(" "); + .append(hli.sync_result_no_of_copied).append(" "); out.append(mContext.getString(R.string.msgs_main_sync_history_count_deleted)) - .append(Integer.toString(hli.sync_result_no_of_deleted)).append(" "); + .append(hli.sync_result_no_of_deleted).append(" "); out.append(mContext.getString(R.string.msgs_main_sync_history_count_ignored)) - .append(Integer.toString(hli.sync_result_no_of_ignored)).append(" "); + .append(hli.sync_result_no_of_ignored).append(" "); out.append("\n").append(hli.sync_error_text); } } - if (out.length() > 0) cm.setText(out); + //if (out.length() > 0) cm.setText(out); + if (out.length() > 0) cm.setPrimaryClip(ClipData.newPlainText("mContextHistoryButtonHistiryCopyClipboard", out.toString())); CommonDialog.showPopupMessageAsUpAnchorViewShort(mActivity, mContextHistiryViewHistoryCopyClipboard, mContext.getString(R.string.msgs_main_sync_history_copy_completed)); mGp.syncHistoryListAdapter.setAllItemChecked(false); @@ -3723,16 +4107,14 @@ private void setHistoryItemSelectAll() { } private void confirmDeleteHistory() { - String conf_list = ""; + StringBuilder conf_list = new StringBuilder(); boolean del_all_history = false; int del_cnt = 0; String sep = ""; for (int i = 0; i < mGp.syncHistoryListAdapter.getCount(); i++) { if (mGp.syncHistoryListAdapter.getItem(i).isChecked) { del_cnt++; - conf_list += sep + mGp.syncHistoryListAdapter.getItem(i).sync_date + " " + - mGp.syncHistoryListAdapter.getItem(i).sync_time + " " + - mGp.syncHistoryListAdapter.getItem(i).sync_task + " "; + conf_list.append(sep).append(mGp.syncHistoryListAdapter.getItem(i).sync_date).append(" ").append(mGp.syncHistoryListAdapter.getItem(i).sync_time).append(" ").append(mGp.syncHistoryListAdapter.getItem(i).sync_task).append(" "); sep = "\n"; } } @@ -3769,7 +4151,7 @@ public void negativeResponse(Context c, Object[] o) { if (del_all_history) { mUtil.showCommonDialog(true, "W", getString(R.string.msgs_main_sync_history_del_conf_all_history), "", ntfy); } else { - mUtil.showCommonDialog(true, "W", getString(R.string.msgs_main_sync_history_del_conf_selected_history), conf_list, ntfy); + mUtil.showCommonDialog(true, "W", getString(R.string.msgs_main_sync_history_del_conf_selected_history), conf_list.toString(), ntfy); } } @@ -3793,8 +4175,9 @@ public void run() { item.setChecked(!item.isChecked()); setSyncTaskContextButtonSelectMode(); mGp.syncTaskView.setEnabled(true); - mGp.syncTaskListAdapter.notifyDataSetChanged(); } + // Mod: fix tasklist icon/path not updated in main view after edit + mGp.syncTaskListAdapter.notifyDataSetChanged(); } } }); @@ -3818,7 +4201,6 @@ public void negativeResponse(Context c, Object[] o) {} NotifyEvent ntfy_sync = new NotifyEvent(mContext); ntfy_sync.setListener(new NotifyEvent.NotifyEventListener() { - @SuppressWarnings("unchecked") @Override public void positiveResponse(Context c, Object[] o) { if (isUiEnabled()) { @@ -3863,25 +4245,23 @@ public boolean onItemLongClick(final AdapterView list_view, final View item_v if (up_sel_pos != -1 && down_sel_pos == -1) { for (int i = pos; i < up_sel_pos; i++) mGp.syncTaskListAdapter.getItem(i).setChecked(true); - } else if (up_sel_pos != -1 && down_sel_pos != -1) { + } else if (up_sel_pos != -1) { //&& down_sel_pos != -1 for (int i = down_sel_pos + 1; i < up_sel_pos; i++) mGp.syncTaskListAdapter.getItem(i).setChecked(true); - } else if (up_sel_pos == -1 && down_sel_pos != -1) { + } else if (down_sel_pos != -1) { //&& up_sel_pos == -1 for (int i = down_sel_pos + 1; i <= pos; i++) mGp.syncTaskListAdapter.getItem(i).setChecked(true); } - mGp.syncTaskListAdapter.notifyDataSetChanged(); } else { mGp.syncTaskListAdapter.setShowCheckBox(true); mGp.syncTaskListAdapter.getItem(pos).setChecked(true); - mGp.syncTaskListAdapter.notifyDataSetChanged(); } + mGp.syncTaskListAdapter.notifyDataSetChanged(); setSyncTaskContextButtonSelectMode(); } return true; } }); - } private LinearLayout mContextSyncTaskContextView=null; @@ -3989,9 +4369,10 @@ public boolean onItemLongClick(final AdapterView list_view, final View item_v private LinearLayout mContextMessageViewPageUp = null; private LinearLayout mContextMessageViewClear = null; + // not used private void releaseImageBtnRes(ImageButton ib) { ib.setImageDrawable(null); - ib.setBackgroundDrawable(null); + ib.setBackground(null); ib.setImageBitmap(null); } @@ -4176,7 +4557,7 @@ public void onClick(View v) { ntfy_check.setListener(new NotifyEvent.NotifyEventListener() { @Override public void positiveResponse(Context c, Object[] o) { - SyncTaskItem npfli = item.clone(); + SyncTaskItem npfli = item.cloneSerial(); npfli.setLastSyncResult(0); npfli.setLastSyncTime(""); if (mTaskEditor ==null) mTaskEditor = TaskEditor.newInstance(); @@ -4224,7 +4605,7 @@ public void onClick(View v) { } } }); - ContextButtonUtil.setButtonLabelListener(mActivity, mContextSyncTaskButtonRenameSyncTask, mContext.getString(R.string.msgs_task_cont_label_up)); + ContextButtonUtil.setButtonLabelListener(mActivity, mContextSyncTaskButtonRenameSyncTask, mContext.getString(R.string.msgs_task_cont_label_rename)); mContextSyncTaskButtonMoveToUp.setOnClickListener(new OnClickListener() { @Override @@ -4275,7 +4656,7 @@ public void run() { } } }); - ContextButtonUtil.setButtonLabelListener(mActivity, mContextSyncTaskButtonMoveToUp, mContext.getString(R.string.msgs_task_cont_label_down)); + ContextButtonUtil.setButtonLabelListener(mActivity, mContextSyncTaskButtonMoveToUp, mContext.getString(R.string.msgs_task_cont_label_up)); mContextSyncTaskButtonMoveToDown.setOnClickListener(new OnClickListener() { @Override @@ -4376,15 +4757,15 @@ public void positiveResponse(Context c, Object[] o) { public void negativeResponse(Context c, Object[] o) { } }); - String msg = ""; + StringBuilder msg = new StringBuilder(); String sep = ""; for (int i = 0; i < pa.getCount(); i++) { if (pa.getItem(i).isChecked() && !pa.getItem(i).isSyncTaskAuto()) { - msg += sep+"-" + pa.getItem(i).getSyncTaskName(); + msg.append(sep).append("-").append(pa.getItem(i).getSyncTaskName()); sep = "\n"; } } - mUtil.showCommonDialog(true, "W", mContext.getString(R.string.msgs_task_cont_to_auto_task), msg, ntfy); + mUtil.showCommonDialog(true, "W", mContext.getString(R.string.msgs_task_cont_to_auto_task), msg.toString(), ntfy); } private void confirmToManual(TaskListAdapter pa, final NotifyEvent p_ntfy) { @@ -4401,15 +4782,15 @@ public void positiveResponse(Context c, Object[] o) { public void negativeResponse(Context c, Object[] o) { } }); - String msg = ""; + StringBuilder msg = new StringBuilder(); String sep = ""; for (int i = 0; i < pa.getCount(); i++) { if (pa.getItem(i).isChecked() && pa.getItem(i).isSyncTaskAuto()) { - msg += sep+"-" + pa.getItem(i).getSyncTaskName(); + msg.append(sep).append("-").append(pa.getItem(i).getSyncTaskName()); sep = "\n"; } } - mUtil.showCommonDialog(true, "W", mContext.getString(R.string.msgs_task_cont_to_manual_task), msg, ntfy); + mUtil.showCommonDialog(true, "W", mContext.getString(R.string.msgs_task_cont_to_manual_task), msg.toString(), ntfy); } private void setSyncTaskContextButtonSelectMode() { @@ -4479,9 +4860,11 @@ private void setSyncTaskContextButtonSelectMode() { } private void setSyncTaskContextButtonHide() { - mActionBar.setIcon(R.drawable.smbsync); - mActionBar.setHomeButtonEnabled(false); - mActionBar.setTitle(R.string.app_name); + if (mActionBar != null) { + mActionBar.setIcon(R.drawable.smbsync); + mActionBar.setHomeButtonEnabled(false); + mActionBar.setTitle(R.string.app_name); + } mGp.syncTaskListAdapter.setAllItemChecked(false); mGp.syncTaskListAdapter.setShowCheckBox(false); @@ -4506,17 +4889,22 @@ private void setContextButtonVisibility(View v, int visiblity) { private void setActionBarSelectMode(int sel_cnt, int tot_cnt) { ActionBar actionBar = getSupportActionBar(); - actionBar.setHomeButtonEnabled(true); - actionBar.setDisplayHomeAsUpEnabled(true); - String sel_txt = "" + sel_cnt + "/" + tot_cnt; - actionBar.setTitle(sel_txt); + if (actionBar != null) { + actionBar.setHomeButtonEnabled(true); + actionBar.setDisplayHomeAsUpEnabled(true); + + String sel_txt = "" + sel_cnt + "/" + tot_cnt; + actionBar.setTitle(sel_txt); + } } private void setActionBarNormalMode() { ActionBar actionBar = getSupportActionBar(); - actionBar.setTitle(R.string.app_name); - actionBar.setHomeButtonEnabled(false); - actionBar.setDisplayHomeAsUpEnabled(false); + if (actionBar != null) { + actionBar.setTitle(R.string.app_name); + actionBar.setHomeButtonEnabled(false); + actionBar.setDisplayHomeAsUpEnabled(false); + } } private void setSyncTaskContextButtonNormalMode() { @@ -4573,7 +4961,7 @@ public void run() { }); } - private long timeLastMessagesTouchEvent = System.currentTimeMillis(); + //private long timeLastMessagesTouchEvent = System.currentTimeMillis(); private final static int MESSAGE_SCROLL_AMOUNT=1; private void setMessageContextButtonListener() { setMessageScrollButtonVisibility(); @@ -4624,7 +5012,7 @@ public void onClick(View v) { y_offset = first_item_height; if (y_offset > lv_height) { //item is more than one page: position to the bottom, the current top exact last visible position, minus 3 text lines - TextView listTextView = (TextView) mGp.syncMessageView.getChildAt(0).findViewById(R.id.message_list_item_date); + TextView listTextView = mGp.syncMessageView.getChildAt(0).findViewById(R.id.message_list_item_date); int text_context_size = 0; if (listTextView != null) text_context_size = (int)(listTextView.getTextSize() * 3); y_offset = first_item_height - first_item_y_bottom + text_context_size; @@ -4632,8 +5020,8 @@ public void onClick(View v) { } //mUtil.addDebugMsg(2, "I", "lv_height="+lv_height + " first_item_height="+first_item_height + " first_item_y_top="+first_item_y_top + " first_item_y_bottom="+first_item_y_bottom); - int lp=mGp.syncMessageView.getLastVisiblePosition(); - int fp=mGp.syncMessageView.getFirstVisiblePosition(); + //int lp=mGp.syncMessageView.getLastVisiblePosition(); + //int fp=mGp.syncMessageView.getFirstVisiblePosition(); mGp.syncMessageListAdapter.refresh(); mGp.syncMessageView.setSelectionFromTop(mGp.syncMessageView.getFirstVisiblePosition(), lv_height - y_offset); setMessageScrollButtonVisibility(); @@ -4652,7 +5040,7 @@ public void onClick(View v) { if (last_item_height > lv_height) { //item is more than one page: position to the top, the current bottom exat last visible position, minus 3 text lines - TextView listTextView = (TextView) mGp.syncMessageView.getChildAt(last_item_pos).findViewById(R.id.message_list_item_date); + TextView listTextView = mGp.syncMessageView.getChildAt(last_item_pos).findViewById(R.id.message_list_item_date); int text_context_size = 0; if (listTextView != null) text_context_size = (int)(listTextView.getTextSize() * 3); y_offset = -(lv_height - last_item_y_top - text_context_size); @@ -4747,7 +5135,7 @@ private void setMessageViewListener() { } private void clearMessageFilterSearchString() { - final EditText et_find_string=(EditText)mMessageView.findViewById(R.id.main_message_filter_string_value); + final EditText et_find_string= mMessageView.findViewById(R.id.main_message_filter_string_value); if (et_find_string.getText().length()>0) { et_find_string.setText(""); mGp.syncMessageListAdapter.setFilterString(""); @@ -4755,22 +5143,22 @@ private void clearMessageFilterSearchString() { } private void setMessageFilterListener() { - LinearLayout ll_filter_category=(LinearLayout) mMessageView.findViewById(R.id.main_message_filter_category_view); - LinearLayout ll_filter_string=(LinearLayout) mMessageView.findViewById(R.id.main_message_filter_string_view); + LinearLayout ll_filter_category= mMessageView.findViewById(R.id.main_message_filter_category_view); + LinearLayout ll_filter_string= mMessageView.findViewById(R.id.main_message_filter_string_view); if (mGp.themeColorList.theme_is_light) { ll_filter_category.setBackgroundColor(Color.LTGRAY); ll_filter_string.setBackgroundColor(Color.LTGRAY); } - final CheckBox cb_filter_info=(CheckBox)mMessageView.findViewById(R.id.main_message_filter_category_info); - final CheckBox cb_filter_warn=(CheckBox)mMessageView.findViewById(R.id.main_message_filter_category_warn); - final CheckBox cb_filter_error=(CheckBox)mMessageView.findViewById(R.id.main_message_filter_category_error); + final CheckBox cb_filter_info= mMessageView.findViewById(R.id.main_message_filter_category_info); + final CheckBox cb_filter_warn= mMessageView.findViewById(R.id.main_message_filter_category_warn); + final CheckBox cb_filter_error= mMessageView.findViewById(R.id.main_message_filter_category_error); - final EditText et_find_string=(EditText)mMessageView.findViewById(R.id.main_message_filter_string_value); - final Button btn_find=(Button)mMessageView.findViewById(R.id.main_message_filter_string_find); + final EditText et_find_string= mMessageView.findViewById(R.id.main_message_filter_string_value); + final Button btn_find= mMessageView.findViewById(R.id.main_message_filter_string_find); btn_find.setVisibility(Button.GONE); - final Button btn_reset=(Button)mMessageView.findViewById(R.id.main_message_filter_string_reset); - final CheckBox cb_filter_case_sensitive=(CheckBox) mMessageView.findViewById(R.id.main_message_filter_string_case_insensitive); + final Button btn_reset= mMessageView.findViewById(R.id.main_message_filter_string_reset); + final CheckBox cb_filter_case_sensitive= mMessageView.findViewById(R.id.main_message_filter_string_case_insensitive); cb_filter_info.setTextColor(mGp.themeColorList.text_color_primary); cb_filter_warn.setTextColor(mGp.themeColorList.text_color_warning); @@ -4897,19 +5285,19 @@ private void syncSpecificSyncTask(SyncTaskItem sti) { private void syncSelectedSyncTask() { final ArrayList t_list = new ArrayList(); SyncTaskItem item; - String sync_list_tmp = ""; + StringBuilder sync_list_tmp = new StringBuilder(); String sep = ""; boolean test_sync_task_found = false; for (int i = 0; i < mGp.syncTaskListAdapter.getCount(); i++) { item = mGp.syncTaskListAdapter.getItem(i); if (item.isChecked() && !item.isSyncFolderStatusError()) { t_list.add(item); - sync_list_tmp += sep + item.getSyncTaskName(); + sync_list_tmp.append(sep).append(item.getSyncTaskName()); sep = ","; if (item.isSyncTestMode()) test_sync_task_found = true; } } - final String sync_list = sync_list_tmp; + final String sync_list = sync_list_tmp.toString(); NotifyEvent ntfy_test_mode = new NotifyEvent(mContext); ntfy_test_mode.setListener(new NotifyEvent.NotifyEventListener() { @@ -4938,12 +5326,13 @@ public void negativeResponse(Context c, Object[] o) {} private void syncAutoSyncTask() { final ArrayList t_list = new ArrayList(); - String sync_list_tmp = "", sep = ""; + StringBuilder sync_list_tmp = new StringBuilder(); + String sep = ""; for (int i = 0; i < mGp.syncTaskListAdapter.getCount(); i++) { SyncTaskItem item = mGp.syncTaskListAdapter.getItem(i); if (item.isSyncTaskAuto() && !item.isSyncTestMode() && !item.isSyncFolderStatusError()) { t_list.add(item); - sync_list_tmp += sep + item.getSyncTaskName(); + sync_list_tmp.append(sep).append(item.getSyncTaskName()); sep = ","; } } @@ -4954,7 +5343,7 @@ private void syncAutoSyncTask() { } else { mUtil.addLogMsg("I", "", mContext.getString(R.string.msgs_main_sync_all_auto_tasks)); mUtil.addLogMsg("I", "", mContext.getString(R.string.msgs_main_sync_task_name_list) + sync_list_tmp); -// tabHost.setCurrentTabByTag(TAB_TAG_MSG); +// tabHost.setCurrentTabByTag(TAB_TAG_MSG); Toast.makeText(mContext, mContext.getString(R.string.msgs_main_sync_all_auto_tasks), Toast.LENGTH_SHORT).show(); startSyncTask(t_list); } @@ -5118,6 +5507,7 @@ private void syncThreadEnded() { // // }; + // not used private void applyMediaStatusChanged(String action) { mUiHandler.post(new Runnable() { @Override @@ -5128,10 +5518,10 @@ public void run() { if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) { ArrayList dup_list=SafManager3.getDuplicateUuid(mContext); if (dup_list.size()>0) { - String dup_info=""; - for(SafStorage3 item:dup_list) dup_info+="UUID="+item.uuid+" , Description="+item.description+"\n"; + StringBuilder dup_info= new StringBuilder(); + for(SafStorage3 item:dup_list) dup_info.append("UUID=").append(item.uuid).append(" , Description=").append(item.description).append("\n"); mUtil.showCommonDialog(false, "W", - mContext.getString(R.string.msgs_main_external_storage_uuid_duplicated), dup_info, null); + mContext.getString(R.string.msgs_main_external_storage_uuid_duplicated), dup_info.toString(), null); } } } @@ -5248,7 +5638,7 @@ public void onClick(View v) { mGp.confirmCancel.setOnClickListener(mGp.confirmCancelListener); } - static public void sendConfirmResponse(GlobalParameters gp, int response) { + public static void sendConfirmResponse(GlobalParameters gp, int response) { gp.confirmDialogShowed = false; synchronized (gp.syncThreadConfirm) { gp.syncThreadConfirm.setExtraDataInt(response); @@ -5272,86 +5662,55 @@ static public void sendConfirmResponse(GlobalParameters gp, int response) { } - final private boolean checkJcifsOptionChanged() { - boolean changed = false; - - String prevSmbLmCompatibility = mGp.settingsSmbLmCompatibility, - prevSmbUseExtendedSecurity = mGp.settingsSmbUseExtendedSecurity; - String p_response_timeout=mGp.settingsSmbClientResponseTimeout; - String p_disable_plain_text_passwords=mGp.settingsSmbDisablePlainTextPasswords; - - mGp.initJcifsOption(mContext); - - if (!mGp.settingsSmbLmCompatibility.equals(prevSmbLmCompatibility)) changed = true; - else if (!mGp.settingsSmbUseExtendedSecurity.equals(prevSmbUseExtendedSecurity)) changed = true; - else if (!mGp.settingsSmbClientResponseTimeout.equals(p_response_timeout)) changed = true; - else if (!mGp.settingsSmbDisablePlainTextPasswords.equals(p_disable_plain_text_passwords)) changed = true; - - if (changed) { - listSettingsOption(); - NotifyEvent ntfy=new NotifyEvent(mContext); - ntfy.setListener(new NotifyEvent.NotifyEventListener() { - @Override - public void positiveResponse(Context context, Object[] objects) { - mUtil.flushLog(); - mGp.settingExitClean=true; - finish(); - } - @Override - public void negativeResponse(Context context, Object[] objects) { - mGp.settingExitClean=true; - } - }); - mUtil.showCommonDialog(true, "W", - mContext.getString(R.string.msgs_smbsync_main_settings_restart_title), - mContext.getString(R.string.msgs_smbsync_main_settings_jcifs_changed_restart), ntfy); - } - - return changed; - } - + // not used private String printStackTraceElement(StackTraceElement[] ste) { - String st_msg = ""; - for (int i = 0; i < ste.length; i++) { - st_msg += "\n at " + ste[i].getClassName() + "." + - ste[i].getMethodName() + "(" + ste[i].getFileName() + - ":" + ste[i].getLineNumber() + ")"; + StringBuilder st_msg = new StringBuilder(); + for (StackTraceElement stack_element : ste) { + st_msg.append("\n at ").append(stack_element.getClassName()).append(".").append(stack_element.getMethodName()). + append("(").append(stack_element.getFileName()).append(":").append(stack_element.getLineNumber()).append(")"); } - return st_msg; + return st_msg.toString(); } + // not used method private void makeCacheDirectory() { // String packageName = mContext.getPackageName(); long b_time=System.currentTimeMillis(); File[] stg_array=mContext.getExternalFilesDirs(null); - for(File item:stg_array) { - if (item!=null) { - File cd=new File(item.getParentFile()+"/cache"); - if (!cd.exists()) { - boolean rc=cd.mkdirs(); -// mUtil.addDebugMsg(1, "I", "makeChachDirectory directory create result="+rc); + if (stg_array != null) { + for(File item:stg_array) { + if (item != null) { + File cd = new File(item.getParentFile()+"/cache"); + if (!cd.exists()) { + boolean rc = cd.mkdirs(); + mUtil.addDebugMsg(1, "I", "makeChachDirectory directory create result="+rc); + } } } + mUtil.addDebugMsg(1, "I", "makeCacheDirectory elapsed="+(System.currentTimeMillis()-b_time)); + } else { + mUtil.addDebugMsg(1, "I", "makeCacheDirectory error: no value from getExternalFilesDirs(null)"); } - mUtil.addDebugMsg(1, "I", "makeCacheDirectory elapsed="+(System.currentTimeMillis()-b_time)); } private void cleanupCacheFile() { long b_time=System.currentTimeMillis(); //Delete internal storage cache - File[] fl=mContext.getCacheDir().listFiles(); - for(File del_item:fl) { - deleteCacheFile(del_item); + File[] fl = mContext.getCacheDir().listFiles(); + if (fl != null && fl.length > 0) { + for(File del_item : fl) { + deleteCacheFile(del_item); + } } //Delete external storage cache fl=mContext.getExternalCacheDirs(); - if (fl!=null && fl.length>0) { - for(File cf:fl) { - if (cf!=null) { + if (fl != null && fl.length > 0) { + for(File cf : fl) { + if (cf != null) { File[] child_list=cf.listFiles(); - if (child_list!=null) { + if (child_list != null) { for(File ch_item:child_list) { if (ch_item!=null) { if (!deleteCacheFile(ch_item)) break; @@ -5369,22 +5728,24 @@ private void cleanupCacheFile() { private boolean deleteCacheFile(File del_item) { boolean result=true; if (del_item.isDirectory()) { - File[] child_list=del_item.listFiles(); - for(File child_item:child_list) { - if (child_item!=null) { - if (!deleteCacheFile(child_item)) { - result=false; - break; + File[] child_list = del_item.listFiles(); + if (child_list != null) { + for(File child_item : child_list) { + if (child_item != null) { + if (!deleteCacheFile(child_item)) { + result = false; + break; + } } } } if (result) { - result=del_item.delete(); - if (mUtil.getLogLevel()>=2 && result) mUtil.addDebugMsg(2, "I", "cache directory deleted, dir="+ del_item.getPath()); + result =del_item.delete(); + if (mUtil.getLogLevel() >= 2 && result) mUtil.addDebugMsg(2, "I", "cache directory deleted, dir="+ del_item.getPath()); } } else { - result=del_item.delete(); - if (mUtil.getLogLevel()>=2 && result) mUtil.addDebugMsg(2, "I", "cache file deleted, file="+ del_item.getPath()); + result = del_item.delete(); + if (mUtil.getLogLevel() >= 2 && result) mUtil.addDebugMsg(2, "I", "cache file deleted, file="+ del_item.getPath()); } return result; } @@ -5402,9 +5763,9 @@ private boolean deleteCacheFile(File del_item) { */ final static private int ANDROID_LONG_PRESS_TIMEOUT = 500; final static private int DEFAULT_LONG_PRESS_REPEAT_INTERVAL = 100; - private class RepeatListener implements View.OnTouchListener { + private static class RepeatListener implements View.OnTouchListener { - private Handler handler = new Handler(); + private final Handler handler = new Handler(); private final int mLongPressTimeout; private final int mRepeatInterval; @@ -5413,7 +5774,7 @@ private class RepeatListener implements View.OnTouchListener { private View mTouchedView; // private Rect mRect; // Variable to hold the bounds of the view rectangle - private Runnable handlerRunnable = new Runnable() { + private final Runnable handlerRunnable = new Runnable() { @Override public void run() { // mUtil.addDebugMsg(1, "I", "runnable enterd, enabled="+mTouchedView.isEnabled()); @@ -5473,6 +5834,7 @@ public boolean onTouch(View view, MotionEvent motionEvent) { case MotionEvent.ACTION_UP: // mUtil.addDebugMsg(1, "I", "runnable cancelled by Finger UP"); handler.removeCallbacks(handlerRunnable); + view.performClick(); // optional as click is enabled on ACTION_DOWN, just to suppress Lint warning mTouchedView.setPressed(false); mTouchedView = null; return mConsumeEvent; @@ -5510,7 +5872,7 @@ private void unsetMediaStatusListener() { final private class MediaStatusChangeReceiver extends BroadcastReceiver { @Override - final public void onReceive(Context c, Intent in) { + public void onReceive(Context c, Intent in) { String action = in.getAction(); mUtil.addDebugMsg(1, "I", "Media status change receiver, action=" + action); if (action.equals(Intent.ACTION_MEDIA_MOUNTED) || action.equals(Intent.ACTION_MEDIA_UNMOUNTED) diff --git a/app/src/main/java/com/sentaroh/android/SMBSync3/ActivityPasswordSettings.java b/app/src/main/java/com/sentaroh/android/SMBSync3/ActivityPasswordSettings.java index cbb71fce..70d36b48 100644 --- a/app/src/main/java/com/sentaroh/android/SMBSync3/ActivityPasswordSettings.java +++ b/app/src/main/java/com/sentaroh/android/SMBSync3/ActivityPasswordSettings.java @@ -66,20 +66,24 @@ public class ActivityPasswordSettings extends AppCompatActivity { @Override protected void attachBaseContext(Context base) { - super.attachBaseContext(GlobalParameters.setNewLocale(base)); + super.attachBaseContext(GlobalParameters.setLocaleAndMetrics(base)); } @Override protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); mActivity = ActivityPasswordSettings.this; mGp= GlobalWorkArea.getGlobalParameter(mActivity); setTheme(mGp.applicationTheme); + if (mGp.themeColorList == null) { mGp.themeColorList = ThemeUtil.getThemeColorList(mActivity); } + mGp.setDeviceOrientation(mActivity); + + super.onCreate(savedInstanceState); + //Remove notification bar // this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.preference_application_password_dlg); diff --git a/app/src/main/java/com/sentaroh/android/SMBSync3/ActivitySettings.java b/app/src/main/java/com/sentaroh/android/SMBSync3/ActivitySettings.java index c43fd4c2..42e2dec4 100644 --- a/app/src/main/java/com/sentaroh/android/SMBSync3/ActivitySettings.java +++ b/app/src/main/java/com/sentaroh/android/SMBSync3/ActivitySettings.java @@ -23,157 +23,236 @@ this software and associated documentation files (the "Software"), to deal */ +import android.Manifest; import android.app.Activity; -import android.app.FragmentManager; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; -import android.content.pm.ActivityInfo; -import android.content.res.Configuration; import android.media.MediaPlayer; import android.media.RingtoneManager; import android.net.Uri; +import android.os.Build; import android.os.Bundle; import android.os.SystemClock; -import android.preference.Preference; -import android.preference.PreferenceActivity; -import android.preference.PreferenceFragment; -import android.preference.PreferenceManager; -import android.util.DisplayMetrics; +import android.provider.Settings; +import android.view.MenuItem; + +import androidx.activity.result.ActivityResult; +import androidx.activity.result.ActivityResultCallback; +import androidx.activity.result.ActivityResultLauncher; +import androidx.activity.result.contract.ActivityResultContracts; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.appcompat.app.ActionBar; +import androidx.appcompat.app.AppCompatActivity; +import androidx.fragment.app.DialogFragment; +import androidx.fragment.app.Fragment; +import androidx.fragment.app.FragmentManager; +import androidx.fragment.app.FragmentManager.OnBackStackChangedListener; +import androidx.fragment.app.FragmentResultListener; +import androidx.preference.Preference; +import androidx.preference.PreferenceFragmentCompat; +import androidx.preference.PreferenceFragmentCompat.OnPreferenceStartFragmentCallback; +import androidx.preference.PreferenceManager; import com.sentaroh.android.Utilities3.Dialog.MessageDialogAppFragment; +import com.sentaroh.android.Utilities3.Preference.ListEditPreferenceDialogFragment; +import com.sentaroh.android.Utilities3.Preference.ListEditPreference; +import com.sentaroh.android.Utilities3.SafFile3; +import com.sentaroh.android.Utilities3.SafManager3; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.List; -import java.util.Locale; +import java.io.IOException; +import java.util.Objects; import static com.sentaroh.android.SMBSync3.Constants.*; import static com.sentaroh.android.SMBSync3.GlobalParameters.APPLICATION_LANGUAGE_SETTING_SYSTEM_DEFAULT; import static com.sentaroh.android.SMBSync3.GlobalParameters.SMB_CLIENT_RESPONSE_TIMEOUT_DEFAULT; import static com.sentaroh.android.SMBSync3.GlobalParameters.SMB_LM_COMPATIBILITY_DEFAULT; -public class ActivitySettings extends PreferenceActivity { - static final private Logger log= LoggerFactory.getLogger(ActivitySettings.class); +public class ActivitySettings extends AppCompatActivity implements OnPreferenceStartFragmentCallback { + static final private Logger log = LoggerFactory.getLogger(ActivitySettings.class); + private static final String TITLE_TAG = "ActivitySettings"; private static GlobalParameters mGp = null; - - private static Activity mActivity=null; - - private static String mCurrentScreenTheme=SCREEN_THEME_STANDARD; - + private AppCompatActivity mActivity = null; private CommonUtilities mUtil = null; - @Override - protected boolean isValidFragment(String fragmentName) { - // 使用できる Fragment か確認する - - return true; - } - @Override protected void attachBaseContext(Context base) { // log.info("attachBaseContext entered"); - super.attachBaseContext(GlobalParameters.setNewLocale(base)); + super.attachBaseContext(GlobalParameters.setLocaleAndMetrics(base)); } - @Override - public void onCreate(Bundle savedInstanceState) { - mActivity=ActivitySettings.this; - mGp= GlobalWorkArea.getGlobalParameter(ActivitySettings.this); - SharedPreferences shared_pref = CommonUtilities.getSharedPreference(ActivitySettings.this); - mCurrentScreenTheme=shared_pref.getString(getString(R.string.settings_screen_theme), SCREEN_THEME_STANDARD); - if (mCurrentScreenTheme.equals(SCREEN_THEME_STANDARD)) setTheme(R.style.Main); - else if (mCurrentScreenTheme.equals(SCREEN_THEME_LIGHT)) setTheme(R.style.MainLight); - else if (mCurrentScreenTheme.equals(SCREEN_THEME_BLACK)) setTheme(R.style.MainBlack); - GlobalParameters.setDisplayFontScale(ActivitySettings.this); - super.onCreate(savedInstanceState); + protected void onCreate(@Nullable Bundle savedInstanceState) { + mActivity = ActivitySettings.this; + mGp = GlobalWorkArea.getGlobalParameter(mActivity); + mUtil = new CommonUtilities(mActivity, "ActivitySettings", mGp, null); + //SharedPreferences shared_pref = CommonUtilities.getSharedPreference(ActivitySettings.this); - if (mUtil == null) mUtil = new CommonUtilities(this, "SettingsActivity", mGp, null); - mUtil.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName() + " entered"); - if (mGp.settingFixDeviceOrientationToPortrait) setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); - else setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); + // on Activity settings restart, apply new theme as it could have changed in settings + setTheme(GlobalParameters.getScreenTemeValue(mActivity)); + //GlobalParameters.setDisplayFontScale(ActivitySettings.this); - mCurrentScreenTheme=shared_pref.getString(getString(R.string.settings_screen_theme), SCREEN_THEME_STANDARD); - mCurrentLangaue =GlobalParameters.getLanguageCode(ActivitySettings.this); - } + mGp.setDeviceOrientation(mActivity); - @Override - public void onStart() { - super.onStart(); - mUtil.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName() + " entered"); - } + super.onCreate(savedInstanceState); - @Override - public void onResume() { - super.onResume(); mUtil.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName() + " entered"); - } - private List
mHeaderList=null; - public void refreshHeader(String fs) { - invalidateHeaders(); - } + setContentView(R.layout.settings_preference_main_layout); + + //Entering the settings menu from main activity + // Create the fragment only when the activity is created for the first time, not after orientation changes or back from another setting subscreen + if (savedInstanceState == null) { + getSupportFragmentManager().beginTransaction() + .replace(R.id.settings_preference_frame_layout, new ActivitySettings.SettingsFragment()) + .commit(); + mActivity.setTitle(R.string.settings_main_title); + } else { + //Returning to settings menu on configuration change (screen rotation...) + mActivity.setTitle(savedInstanceState.getCharSequence(TITLE_TAG)); + } + getSupportFragmentManager().addOnBackStackChangedListener(new OnBackStackChangedListener() { + public void onBackStackChanged() { + FragmentManager mFrag = getSupportFragmentManager(); + if (mFrag.getBackStackEntryCount() == 0) { + mActivity.setTitle(R.string.settings_main_title); + } + } + }); - @Override - public void onBuildHeaders(List
target) { - mUtil.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName() + " entered"); - mHeaderList=target; - loadHeadersFromResource(R.xml.settings_frag, target); - } + // Setup listeners to get results from a fragment + // Deprecates fragment.setTargetFragment(caller, 0); in onPreferenceStartFragment(...) +/* + // Test sample code + getSupportFragmentManager().setFragmentResultListener("SettingsSyncFragmentRequestKey", this, new FragmentResultListener() { + @Override + public void onFragmentResult(@NonNull String requestKey, @NonNull Bundle bundle) { + // We use a String here, but any type that can be put in a Bundle is supported + boolean result = bundle.getBoolean("restart_activity"); + String result_msg = bundle.getString("restart_message"); + // Do something with the result + mUtil.addDebugMsg(1, "I", "restart_activity="+result + " restart_message="+result_msg + " requestKey="+requestKey); + } + }); +*/ - @Override - public boolean onIsMultiPane() { - mGp= GlobalWorkArea.getGlobalParameter(ActivitySettings.this); - mUtil = new CommonUtilities(ActivitySettings.this, "SettingsActivity", mGp, null); - mUtil.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName() + " entered"); - return isTablet(this.getApplicationContext(), mUtil); + // Setup listener to reload SMB settings fragment: for some reason, PreferenceList is not refreshed after being modified by "Restore default values" button !! + getSupportFragmentManager().setFragmentResultListener("SettingsSmbFragmentRequestFragmentReload", this, new FragmentResultListener() { + @Override + public void onFragmentResult(@NonNull String requestKey, @NonNull Bundle bundle) { + boolean reload = bundle.getBoolean("restart_smb_fragment"); + mUtil.addDebugMsg(1, "I", "SettingsSmbFragmentRequestFragmentReload: " + "restart_smb_fragment=" + reload + " requestKey=" + requestKey); + + // First ensure we have the proper fragment to restart and that it is active + // Then, if result is reload==true: + // - restore previous fragment (root preferences menu) from back stack (simulating Back button) + // - replace current fragment (now root fragment) by a new instance of SettingsSmbFragment + // - add previous fragment (root fragment) to the back stack + // - properly set the title of new fragment (SettingsSmbFragment) + final Fragment fragmentInFrame = getSupportFragmentManager().findFragmentById(R.id.settings_preference_frame_layout); + if (fragmentInFrame instanceof SettingsSmbFragment) { + mUtil.addDebugMsg(3, "I", "setFragmentResultListener: found active fragment SettingsSmbFragment"); + if (reload) { + if (getSupportFragmentManager().popBackStackImmediate()) { + getSupportFragmentManager().beginTransaction() + .replace(R.id.settings_preference_frame_layout, new SettingsSmbFragment()) + .addToBackStack(null) + .commit(); + + mActivity.setTitle(R.string.settings_smb_title); + } + } + } else { + mUtil.addDebugMsg(1, "E", "setFragmentResultListener Exception: Active fragment was not SettingsSmbFragment"); + } + } + }); + setupActionBar(); } - public static boolean isTablet(Context context, CommonUtilities cu) { - float fs= GlobalParameters.getFontScaleFactorValue(context); - int multiPaneDP=500; - String lang_code=Locale.getDefault().getLanguage(); -// if (lang_code.equals("fr")) multiPaneDP=540; -// else if (lang_code.equals("ru")) multiPaneDP=800; - - multiPaneDP=(int)(((float)multiPaneDP)*fs); + private void setupActionBar() { + ActionBar actionBar = getSupportActionBar(); + if (actionBar != null) { + //actionBar.setTitle(R.string.title); //Will fix the window title for all Settings sub-menus - DisplayMetrics metrics = context.getResources().getDisplayMetrics(); - final float x_px = (float) Math.min(metrics.heightPixels, metrics.widthPixels); - final float y_px = (float) Math.max(metrics.heightPixels, metrics.widthPixels); - boolean portrait_mp = (x_px/metrics.density) >= multiPaneDP; - boolean land_mp = (y_px/metrics.density) >= multiPaneDP; + // Show the Up button in the action bar. + actionBar.setDisplayHomeAsUpEnabled(true); - int orientation = context.getResources().getConfiguration().orientation; - boolean sc_land_mp = (land_mp || mGp.settingForceDeviceTabletViewInLandscape) && orientation == Configuration.ORIENTATION_LANDSCAPE; //screen is in landscape orientation and either width size >= multiPaneDP or user forced MultiPanel view in landscape - return portrait_mp||sc_land_mp; //use MultiPane display in portrait if width >= multiPaneDP or in landscape if largest screen side >= multiPaneDP + // Show home button with icon in action bar + //actionBar.setIcon(R.drawable.ic_32_smbsync); + //actionBar.setDisplayShowHomeEnabled(true); + } } + @Override + protected void onSaveInstanceState(@NonNull Bundle outState) { + super.onSaveInstanceState(outState); + outState.putCharSequence(TITLE_TAG, mActivity.getTitle()); + } - private Context getActivityContext() { - return ActivitySettings.this; + @Override + public boolean onSupportNavigateUp() { + return getSupportFragmentManager().popBackStackImmediate() || super.onSupportNavigateUp(); } @Override - protected void onPause() { - super.onPause(); + public void onStart() { + super.onStart(); mUtil.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName() + " entered"); } @Override - final public void onStop() { - super.onStop(); + public void onResume() { + super.onResume(); mUtil.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName() + " entered"); } @Override - final public void onDestroy() { - super.onDestroy(); - mUtil.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName() + " entered"); + public void onBackPressed() { + // By default, super.onBackPressed() calls finish() but sets result to Activity.RESULT_CANCELED (val = 0) + // We set it to Activity.RESULT_OK (-1) + Intent resultInt = new Intent(); + resultInt.putExtra("Result", "Done"); + setResult(Activity.RESULT_OK, resultInt); + + super.onBackPressed(); + } + + // Return to main app when pressing Top action bar back button + @Override + public boolean onOptionsItemSelected(MenuItem item) { + int id = item.getItemId(); + if (id == android.R.id.home) { + onBackPressed(); + return true; + } + return super.onOptionsItemSelected(item); + } + + @Override + public boolean onPreferenceStartFragment(@NonNull PreferenceFragmentCompat caller, @NonNull Preference pref) { + // Instantiate the new Fragment + if (pref.getFragment() == null) return false; + + final Bundle args = pref.getExtras(); + final Fragment fragment = getSupportFragmentManager().getFragmentFactory().instantiate( + getClassLoader(), + pref.getFragment()); + fragment.setArguments(args); + + // Replace the existing Fragment with the new Fragment + getSupportFragmentManager().beginTransaction() + .replace(R.id.settings_preference_frame_layout, fragment) + .addToBackStack(null) + .commit(); + mActivity.setTitle(pref.getTitle()); + return true; } private static void playBackDefaultNotification(Context c, FragmentManager fm, int vol) { @@ -183,264 +262,363 @@ private static void playBackDefaultNotification(Context c, FragmentManager fm, i final MediaPlayer player = MediaPlayer.create(c, uri); if (player != null) { player.setVolume(volume, volume); - if (player != null) { - Thread th = new Thread() { - @Override - public void run() { - int dur = player.getDuration(); - player.start(); - SystemClock.sleep(dur + 10); - player.stop(); - player.reset(); - player.release(); - } - }; - th.setPriority(Thread.MAX_PRIORITY); - th.start(); - } + Thread th = new Thread() { + @Override + public void run() { + int dur = player.getDuration(); + player.start(); + SystemClock.sleep(dur + 10); + player.stop(); + player.reset(); + player.release(); + } + }; + th.setPriority(Thread.MAX_PRIORITY); + th.start(); } else { - MessageDialogAppFragment cd=MessageDialogAppFragment.newInstance( - false, "E", c.getString(R.string.settings_playback_ringtone_volume_disabled),""); + MessageDialogAppFragment cd = MessageDialogAppFragment.newInstance(false, "E", + c.getString(R.string.settings_playback_ringtone_volume_disabled), ""); cd.showDialog(fm, cd, null); } } } +/* + public static boolean isTablet(Context context, CommonUtilities cu) { + float fs = GlobalParameters.getFontScaleFactorValue(context); + int multiPaneDP = 500; + // String lang_code=Locale.getDefault().getLanguage(); + // if (lang_code.equals("fr")) multiPaneDP=540; + // else if (lang_code.equals("ru")) multiPaneDP=800; + multiPaneDP=(int)(((float)multiPaneDP)*fs); - public static class SettingsSync extends PreferenceFragment { - private SharedPreferences.OnSharedPreferenceChangeListener listenerAfterHc = - new SharedPreferences.OnSharedPreferenceChangeListener() { - public void onSharedPreferenceChanged(SharedPreferences shared_pref, String key_string) { - checkSettingValue(mUtil, shared_pref, key_string, getContext()); - } - }; + DisplayMetrics metrics = context.getResources().getDisplayMetrics(); + final float x_px = (float) Math.min(metrics.heightPixels, metrics.widthPixels); + final float y_px = (float) Math.max(metrics.heightPixels, metrics.widthPixels); + boolean portrait_mp = (x_px/metrics.density) >= multiPaneDP; + boolean land_mp = (y_px/metrics.density) >= multiPaneDP; + + int orientation = context.getResources().getConfiguration().orientation; + boolean sc_land_mp = (land_mp || mGp.settingForceDeviceTabletViewInLandscape) && orientation == Configuration.ORIENTATION_LANDSCAPE; + //screen is in landscape orientation and either width size >= multiPaneDP or user forced MultiPanel view in landscape + return portrait_mp || sc_land_mp; + //use MultiPane display in portrait if width >= multiPaneDP or in landscape if largest screen side >= multiPaneDP + } +*/ + public static final class SettingsFragment extends PreferenceFragmentCompat { + private AppCompatActivity mActivity = null; + private Context mContext = null; private CommonUtilities mUtil = null; @Override public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - mUtil = new CommonUtilities(getContext(), "SettingsSync", mGp, null); - mUtil.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName() + " entered"); - - addPreferencesFromResource(R.xml.settings_frag_sync); + mActivity = (ActivitySettings)getActivity(); + mContext = mActivity; + mUtil = new CommonUtilities(mContext, "SettingsFragment", mGp, null); - SharedPreferences shared_pref=CommonUtilities.getSharedPreference(getContext()); - - checkSettingValue(mUtil, shared_pref, getString(R.string.settings_wifi_lock), getContext()); - checkSettingValue(mUtil, shared_pref, getString(R.string.settings_sync_history_log), getContext()); - checkSettingValue(mUtil, shared_pref, getString(R.string.settings_force_screen_on_while_sync), getContext()); - checkSettingValue(mUtil, shared_pref, getString(R.string.settings_suppress_add_external_storage_notification), getContext()); - checkSettingValue(mUtil, shared_pref, getString(R.string.settings_suppress_start_sync_confirmation_message), getContext()); - checkSettingValue(mUtil, shared_pref, getString(R.string.settings_suppress_shortcut1_confirmation_message), getContext()); - checkSettingValue(mUtil, shared_pref, getString(R.string.settings_no_compress_file_type), getContext()); + super.onCreate(savedInstanceState);//calls onCreatePreferences() + mUtil.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName() + " entered"); } - private void checkSettingValue(CommonUtilities ut, SharedPreferences shared_pref, String key_string, Context c) { - Preference pref_key=findPreference(key_string); - if (key_string.equals(c.getString(R.string.settings_force_screen_on_while_sync))) { - } else if (key_string.equals(c.getString(R.string.settings_wifi_lock))) { - } else if (key_string.equals(c.getString(R.string.settings_sync_history_log))) { - } else if (key_string.equals(c.getString(R.string.settings_suppress_add_external_storage_notification))) { - } else if (key_string.equals(c.getString(R.string.settings_suppress_start_sync_confirmation_message))) { - } else if (key_string.equals(c.getString(R.string.settings_suppress_shortcut1_confirmation_message))) { - } else if (key_string.equals(c.getString(R.string.settings_no_compress_file_type))) { - if (shared_pref.getString(key_string, "").equals("")) { - shared_pref.edit().putString(key_string, DEFAULT_NOCOMPRESS_FILE_TYPE).commit(); - } - pref_key.setSummary(shared_pref.getString(key_string, DEFAULT_NOCOMPRESS_FILE_TYPE)); - } + @Override + public void onCreatePreferences(@Nullable Bundle savedInstanceState, @Nullable String rootKey) { + setPreferencesFromResource(R.xml.settings_frag, rootKey); } + // Tied to Activity.onStart of containing app, called when fragment gets visible to user @Override public void onStart() { super.onStart(); + mUtil.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName() + " entered"); - getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(listenerAfterHc); - mActivity.setTitle(R.string.settings_sync_title); } + // Tied to parent activity state, called when fragment is no longer visible @Override public void onStop() { - super.onStop(); mUtil.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName() + " entered"); - getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(listenerAfterHc); + + super.onStop(); } + // Cleaning up, called after onStop when view is detached + @Override + public void onDestroyView() { + super.onDestroyView(); + } } - public static class SettingsMisc extends PreferenceFragment { - private SharedPreferences.OnSharedPreferenceChangeListener listenerAfterHc = - new SharedPreferences.OnSharedPreferenceChangeListener() { - public void onSharedPreferenceChanged(SharedPreferences shared_pref, String key_string) { - checkSettingValue(mUtil, shared_pref, key_string, getContext()); - } - }; + public static final class SettingsSyncFragment extends PreferenceFragmentCompat implements SharedPreferences.OnSharedPreferenceChangeListener { + private AppCompatActivity mActivity = null; + private Context mContext = null; private CommonUtilities mUtil = null; @Override public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - mUtil = new CommonUtilities(getContext(), "SettingsMisc", mGp, null); + mActivity = (ActivitySettings)getActivity(); + mContext = mActivity; + mUtil = new CommonUtilities(mContext, "SettingsSyncFragment", mGp, null); + + super.onCreate(savedInstanceState);//calls onCreatePreferences() + mUtil.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName() + " entered"); + } - addPreferencesFromResource(R.xml.settings_frag_misc); + @Override + public void onCreatePreferences(@Nullable Bundle savedInstanceState, @Nullable String rootKey) { + setPreferencesFromResource(R.xml.settings_frag_sync, rootKey); - SharedPreferences shared_pref=CommonUtilities.getSharedPreference(getContext()); + //SharedPreferences shared_pref = PreferenceManager.getDefaultSharedPreferences(mContext); + SharedPreferences shared_pref = CommonUtilities.getSharedPreference(mContext); - shared_pref.edit().putBoolean(getString(R.string.settings_exit_clean), false).commit(); - findPreference(getString(R.string.settings_exit_clean).toString()).setEnabled(false); - checkSettingValue(mUtil, shared_pref, getString(R.string.settings_exit_clean), getContext()); + // Register listener to call onSharedPreferenceChanged() when a preference changes + //getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); + shared_pref.registerOnSharedPreferenceChangeListener(this); + + // Check all currrent preferences values and do any custom actions (enable/disable a setting...) on preferences screen creations + setCurrentValues(shared_pref); } - private void checkSettingValue(CommonUtilities ut, SharedPreferences shared_pref, String key_string, Context c) { + private static final String DIALOG_FRAGMENT_TAG = "ListEditPreferenceDialogFragment.DIALOG"; + //@SuppressWarnings("deprecation") + @Override + public void onDisplayPreferenceDialog(@NonNull Preference preference) { + // check if dialog is already showing + if (mActivity.getSupportFragmentManager().findFragmentByTag(DIALOG_FRAGMENT_TAG) != null) { + return; + } - if (key_string.equals(c.getString(R.string.settings_exit_clean))) { + // Try if the preference is one of our custom Preferences + final DialogFragment fragment; + if (preference instanceof ListEditPreference) { + // Create a new instance of ListEditPreferenceDialogFragment with the key of the related preference + String dialog_title = ""; + if (preference.getKey().equals(getString(R.string.settings_no_compress_file_type))) { + dialog_title = mContext.getString(R.string.settings_no_compress_file_type_dialog_title); + } + + fragment = ListEditPreferenceDialogFragment.newInstance(preference.getKey(), dialog_title); + } else { + fragment = null; + } + + if (fragment != null) { + // The dialog was created (it was one of our custom Preferences), show the dialog for it + /* + Deprecated setTargetFragment() must be implemented because source file PreferenceDialogFragmentCompat.java + implements @SuppressWarnings("deprecation") in onCreate() for deprecated getTargetFragment() method + Else, we get JavaExcption error "Target fragment must implement TargetFragment interface" + Until PreferenceDialogFragmentCompat.java adds an alternative, we're stuck to using setTargetFragment() deprecated method here + https://android.googlesource.com/platform/frameworks/support/+/refs/heads/androidx-preference-release/preference/preference/src/main/java/androidx/preference/PreferenceDialogFragmentCompat.java#78 + */ + fragment.setTargetFragment(this, 0); + fragment.show(mActivity.getSupportFragmentManager(), DIALOG_FRAGMENT_TAG); + } else { + // Dialog creation could not be handled here (another preference not instance of our custom ListEditPreference. + // Try with the super method to show regular preferences + super.onDisplayPreferenceDialog(preference); } } + /* + * Listener when the preferences change + * @param sharedPreferences that changed + * @param key that changed + */ + @Override + public void onSharedPreferenceChanged(SharedPreferences shared_pref, String key_string) { + checkSettingValue(mUtil, shared_pref, key_string, mContext); +/* + Preference preference = findPreference(key_string); + if (preference != null) { + if (!(preference instanceof CheckBoxPreference)){ + String value = shared_pref.getString(preference.getKey(), ""); + setPreferenceSummary(preference, value); + } + } +*/ + } + + // Tied to Activity.onStart of containing app, called when fragment gets visible to user @Override public void onStart() { super.onStart(); + mUtil.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName() + " entered"); - getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(listenerAfterHc); - mActivity.setTitle(R.string.settings_misc_title); } + // Tied to parent activity state, called when fragment is no longer visible @Override public void onStop() { - super.onStop(); mUtil.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName() + " entered"); - getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(listenerAfterHc); + + super.onStop(); + } + + // Cleaning up, called after onStop when view is detached + @Override + public void onDestroyView() { + super.onDestroyView(); + + //SharedPreferences shared_pref = PreferenceManager.getDefaultSharedPreferences(mContext); + SharedPreferences shared_pref = CommonUtilities.getSharedPreference(mContext); + + // Unregister listener to call onSharedPreferenceChanged() when a preference changes + //getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this); + shared_pref.unregisterOnSharedPreferenceChangeListener(this); + } +/* + // Test code to send results from current fragment to listening fragment + private void setResultCallback(boolean restart) { + Bundle result = new Bundle(); + result.putBoolean("restart_activity", restart); + result.putString("restart_message", restart ? "restart requiered":"no restart requiered"); + //requireActivity().getSupportFragmentManager().setFragmentResult("BasicPreferencesFragmentRequestKey", result); + //((AppCompatActivity)mActivity).getSupportFragmentManager().setFragmentResult("BasicPreferencesFragmentRequestKey", result); + mActivity.getSupportFragmentManager().setFragmentResult("SettingsSyncFragmentRequestKey", result); + } +*/ + private void setCurrentValues(SharedPreferences shared_pref) { + checkSettingValue(mUtil, shared_pref, getString(R.string.settings_wifi_lock), mContext); + checkSettingValue(mUtil, shared_pref, getString(R.string.settings_sync_history_log), mContext); + checkSettingValue(mUtil, shared_pref, getString(R.string.settings_force_screen_on_while_sync), mContext); + checkSettingValue(mUtil, shared_pref, getString(R.string.settings_suppress_add_external_storage_notification), mContext); + checkSettingValue(mUtil, shared_pref, getString(R.string.settings_suppress_start_sync_confirmation_message), mContext); + checkSettingValue(mUtil, shared_pref, getString(R.string.settings_suppress_shortcut1_confirmation_message), mContext); + checkSettingValue(mUtil, shared_pref, getString(R.string.settings_no_compress_file_type), mContext); } - ; + private void checkSettingValue(CommonUtilities ut, SharedPreferences shared_pref, String key_string, Context c) { + Preference pref_key = findPreference(key_string); + if (key_string.equals(c.getString(R.string.settings_force_screen_on_while_sync))) { + } else if (key_string.equals(c.getString(R.string.settings_wifi_lock))) { + } else if (key_string.equals(c.getString(R.string.settings_sync_history_log))) { + } else if (key_string.equals(c.getString(R.string.settings_suppress_add_external_storage_notification))) { + } else if (key_string.equals(c.getString(R.string.settings_suppress_start_sync_confirmation_message))) { + } else if (key_string.equals(c.getString(R.string.settings_suppress_shortcut1_confirmation_message))) { + } else if (key_string.equals(c.getString(R.string.settings_no_compress_file_type))) { + if (shared_pref.getString(key_string, "").equals("")) { + shared_pref.edit() + .putString(key_string, DEFAULT_NOCOMPRESS_FILE_TYPE) + .commit(); + } + Objects.requireNonNull(pref_key).setSummary(shared_pref.getString(key_string, DEFAULT_NOCOMPRESS_FILE_TYPE)); + } + } } - public static class SettingsSmb extends PreferenceFragment { - private SharedPreferences.OnSharedPreferenceChangeListener listenerAfterHc = - new SharedPreferences.OnSharedPreferenceChangeListener() { - public void onSharedPreferenceChanged(SharedPreferences shared_pref, String key_string) { - checkSettingValue(mUtil, shared_pref, key_string, getContext()); - } - }; + public static class SettingsUiFragment extends PreferenceFragmentCompat implements SharedPreferences.OnSharedPreferenceChangeListener { + private AppCompatActivity mActivity = null; + private Context mContext = null; private CommonUtilities mUtil = null; + private int mInitVolume = 100; + private String mCurrentLangaueSetting = null; + private String mCurrentThemeSetting = null; + private String mCurrentFontScaleSetting = null; + @Override public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - mUtil = new CommonUtilities(getContext(), "SettingsSmb", mGp, null); - mUtil.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName() + " entered"); + mActivity = (ActivitySettings)getActivity(); + mContext = mActivity; + mUtil = new CommonUtilities(mContext, "SettingsUiFragment", mGp, null); + + // Get current language, theme and font scale settings from Saved preferences (use global public method since we have one) + mCurrentLangaueSetting = GlobalParameters.getLanguageCode(mActivity); + mCurrentThemeSetting = GlobalParameters.getScreenTemeSetting(mActivity); + mCurrentFontScaleSetting = GlobalParameters.getFontScaleFactorSetting(mActivity); + + super.onCreate(savedInstanceState);//calls onCreatePreferences() - addPreferencesFromResource(R.xml.settings_frag_smb); + mUtil.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName() + " entered"); + } + @Override + public void onCreatePreferences(@Nullable Bundle savedInstanceState, @Nullable String rootKey) { + setPreferencesFromResource(R.xml.settings_frag_ui, rootKey); - SharedPreferences shared_pref=CommonUtilities.getSharedPreference(getContext()); + //SharedPreferences shared_pref = PreferenceManager.getDefaultSharedPreferences(mContext); + SharedPreferences shared_pref = CommonUtilities.getSharedPreference(mContext); - checkSettingValue(mUtil, shared_pref, getString(R.string.settings_smb_use_extended_security), getContext()); - checkSettingValue(mUtil, shared_pref, getString(R.string.settings_smb_lm_compatibility), getContext()); - checkSettingValue(mUtil, shared_pref, getString(R.string.settings_smb_client_response_timeout), getContext()); - checkSettingValue(mUtil, shared_pref, getString(R.string.settings_smb_disable_plain_text_passwords), getContext()); + // Register listener to call onSharedPreferenceChanged() when a preference changes + //getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); + shared_pref.registerOnSharedPreferenceChangeListener(this); - final Context c=getContext(); - Preference button = (Preference)getPreferenceManager().findPreference(getString(R.string.settings_smb_set_default_value_key)); - button.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { - @Override - public boolean onPreferenceClick(Preference preference) { - shared_pref.edit().putBoolean(c.getString(R.string.settings_smb_use_extended_security),true).commit(); - shared_pref.edit().putBoolean(c.getString(R.string.settings_smb_disable_plain_text_passwords),false).commit(); - shared_pref.edit().putString(c.getString(R.string.settings_smb_lm_compatibility),SMB_LM_COMPATIBILITY_DEFAULT).commit(); - shared_pref.edit().putString(c.getString(R.string.settings_smb_client_response_timeout),SMB_CLIENT_RESPONSE_TIMEOUT_DEFAULT).commit(); - return false; - } - }); + mInitVolume = shared_pref.getInt(getString(R.string.settings_playback_ringtone_volume), 100); + // Check all currrent preferences values and do any custom actions (enable/disable a setting...) on preferences screen creations + setCurrentValues(shared_pref); } - private void checkSettingValue(CommonUtilities ut, SharedPreferences shared_pref, String key_string, Context c) { - Preference pref_key=findPreference(key_string); - if (key_string.equals(c.getString(R.string.settings_smb_use_extended_security))) { - } else if (key_string.equals(c.getString(R.string.settings_smb_disable_plain_text_passwords))) { - } else if (key_string.equals(c.getString(R.string.settings_smb_lm_compatibility))) { - String lmc=shared_pref.getString(c.getString(R.string.settings_smb_lm_compatibility),SMB_LM_COMPATIBILITY_DEFAULT); - if (lmc.equals("3") || lmc.equals("4")) { - findPreference(c.getString(R.string.settings_smb_use_extended_security).toString()).setEnabled(false); - } else { - findPreference(c.getString(R.string.settings_smb_use_extended_security).toString()).setEnabled(true); + /* + * Listener when the preferences change + * @param sharedPreferences that changed + * @param key that changed + */ + @Override + public void onSharedPreferenceChanged(SharedPreferences shared_pref, String key_string) { + checkSettingValue(mUtil, shared_pref, key_string, mContext); +/* + Preference preference = findPreference(key_string); + if (preference != null) { + if (!(preference instanceof CheckBoxPreference)){ + String value = shared_pref.getString(preference.getKey(), ""); + setPreferenceSummary(preference, value); } - pref_key.setSummary(lmc); - } else if (key_string.equals(c.getString(R.string.settings_smb_client_response_timeout))) { - pref_key.setSummary(shared_pref.getString(key_string, SMB_CLIENT_RESPONSE_TIMEOUT_DEFAULT)+" Millis"); } +*/ } - + // Tied to Activity.onStart of containing app, called when fragment gets visible to user @Override public void onStart() { super.onStart(); + mUtil.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName() + " entered"); - getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(listenerAfterHc); - mActivity.setTitle(R.string.settings_smb_title); } + // Tied to parent activity state, called when fragment is no longer visible @Override public void onStop() { - super.onStop(); mUtil.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName() + " entered"); - getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(listenerAfterHc); - } - } - - private static String mCurrentLangaue =null; - - public static class SettingsUi extends PreferenceFragment { - private SharedPreferences.OnSharedPreferenceChangeListener listenerAfterHc = - new SharedPreferences.OnSharedPreferenceChangeListener() { - public void onSharedPreferenceChanged(SharedPreferences shared_pref, String key_string) { - checkSettingValue(mUtil, shared_pref, key_string, getContext()); - } - }; - private CommonUtilities mUtil = null; - private int mInitVolume = 100; - private String mCurrentFontScaleFactor=null; + super.onStop(); + } + // Cleaning up, called after onStop when view is detached @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - mUtil = new CommonUtilities(getContext(), "SettingsUi", mGp, null); - mUtil.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName() + " entered"); - - addPreferencesFromResource(R.xml.settings_frag_ui); + public void onDestroyView() { + super.onDestroyView(); - SharedPreferences shared_pref=CommonUtilities.getSharedPreference(getContext()); + //SharedPreferences shared_pref = PreferenceManager.getDefaultSharedPreferences(mContext); + SharedPreferences shared_pref = CommonUtilities.getSharedPreference(mContext); - mInitVolume = shared_pref.getInt(getString(R.string.settings_playback_ringtone_volume), 100); - - mCurrentFontScaleFactor=shared_pref.getString(getString(R.string.settings_display_font_scale_factor), GlobalParameters.FONT_SCALE_FACTOR_NORMAL); - - setCurrentValue(shared_pref); + // Unregister listener to call onSharedPreferenceChanged() when a preference changes + //getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this); + shared_pref.unregisterOnSharedPreferenceChangeListener(this); } - private void setCurrentValue(SharedPreferences shared_pref) { - checkSettingValue(mUtil, shared_pref, getString(R.string.settings_notification_message_when_sync_ended), getContext()); - checkSettingValue(mUtil, shared_pref, getString(R.string.settings_playback_ringtone_when_sync_ended), getContext()); - checkSettingValue(mUtil, shared_pref, getString(R.string.settings_playback_ringtone_volume), getContext()); - checkSettingValue(mUtil, shared_pref, getString(R.string.settings_vibrate_when_sync_ended), getContext()); - checkSettingValue(mUtil, shared_pref, getString(R.string.settings_screen_theme), getContext()); - checkSettingValue(mUtil, shared_pref, getString(R.string.settings_device_orientation_portrait), getContext()); - - checkSettingValue(mUtil, shared_pref, getString(R.string.settings_screen_theme_language), getContext()); - checkSettingValue(mUtil, shared_pref, getString(R.string.settings_display_font_scale_factor), getContext()); - checkSettingValue(mUtil, shared_pref, getString(R.string.settings_device_orientation_landscape_tablet), getContext()); - + private void setCurrentValues(SharedPreferences shared_pref) { + checkSettingValue(mUtil, shared_pref, getString(R.string.settings_notification_message_when_sync_ended), mContext); + checkSettingValue(mUtil, shared_pref, getString(R.string.settings_playback_ringtone_when_sync_ended), mContext); + checkSettingValue(mUtil, shared_pref, getString(R.string.settings_playback_ringtone_volume), mContext); + checkSettingValue(mUtil, shared_pref, getString(R.string.settings_vibrate_when_sync_ended), mContext); + checkSettingValue(mUtil, shared_pref, getString(R.string.settings_screen_theme), mContext); + checkSettingValue(mUtil, shared_pref, getString(R.string.settings_device_orientation_portrait), mContext); + + checkSettingValue(mUtil, shared_pref, getString(R.string.settings_screen_theme_language), mContext); + checkSettingValue(mUtil, shared_pref, getString(R.string.settings_display_font_scale_factor), mContext); + //checkSettingValue(mUtil, shared_pref, getString(R.string.settings_device_orientation_landscape_tablet), mContext); } private void checkSettingValue(CommonUtilities ut, SharedPreferences shared_pref, String key_string, Context c) { - Preference pref_key=findPreference(key_string); + Preference pref_key = findPreference(key_string); + Objects.requireNonNull(pref_key); if (key_string.equals(c.getString(R.string.settings_playback_ringtone_when_sync_ended))) { Preference rv = findPreference(c.getString(R.string.settings_playback_ringtone_volume)); - String kv=shared_pref.getString(key_string, NOTIFICATION_SOUND_WHEN_SYNC_ENDED_ALWAYS); + String kv = shared_pref.getString(key_string, NOTIFICATION_SOUND_WHEN_SYNC_ENDED_ALWAYS); + Objects.requireNonNull(rv); if (kv.equals(NOTIFICATION_SOUND_WHEN_SYNC_ENDED_ALWAYS)) { pref_key.setSummary(c.getString(R.string.settings_playback_ringtone_when_sync_ended_summary_always)); rv.setEnabled(true); @@ -455,7 +633,7 @@ private void checkSettingValue(CommonUtilities ut, SharedPreferences shared_pref rv.setEnabled(false); } } else if (key_string.equals(c.getString(R.string.settings_vibrate_when_sync_ended))) { - String kv=shared_pref.getString(key_string, NOTIFICATION_VIBRATE_WHEN_SYNC_ENDED_ALWAYS); + String kv = shared_pref.getString(key_string, NOTIFICATION_VIBRATE_WHEN_SYNC_ENDED_ALWAYS); if (kv.equals(NOTIFICATION_VIBRATE_WHEN_SYNC_ENDED_ALWAYS)) { pref_key.setSummary(c.getString(R.string.settings_vibrate_when_sync_ended_summary_always)); } else if (kv.equals(NOTIFICATION_VIBRATE_WHEN_SYNC_ENDED_ERROR)) { @@ -466,7 +644,7 @@ private void checkSettingValue(CommonUtilities ut, SharedPreferences shared_pref pref_key.setSummary(c.getString(R.string.settings_vibrate_when_sync_ended_summary_no)); } } else if (key_string.equals(c.getString(R.string.settings_notification_message_when_sync_ended))) { - String kv=shared_pref.getString(key_string, NOTIFICATION_MESSAGE_WHEN_SYNC_ENDED_ALWAYS); + String kv = shared_pref.getString(key_string, NOTIFICATION_MESSAGE_WHEN_SYNC_ENDED_ALWAYS); if (kv.equals(NOTIFICATION_MESSAGE_WHEN_SYNC_ENDED_ALWAYS)) { pref_key.setSummary(c.getString(R.string.settings_notification_message_when_sync_ended_summary_always)); } else if (kv.equals(NOTIFICATION_MESSAGE_WHEN_SYNC_ENDED_ERROR)) { @@ -480,169 +658,553 @@ private void checkSettingValue(CommonUtilities ut, SharedPreferences shared_pref int vol = shared_pref.getInt(key_string, 100); pref_key.setSummary( String.format(c.getString(R.string.settings_playback_ringtone_volume_summary), vol)); - if (mInitVolume != vol) playBackDefaultNotification(c, getFragmentManager(), vol); + if (mInitVolume != vol) playBackDefaultNotification(c, mActivity.getSupportFragmentManager(), vol); } else if (key_string.equals(c.getString(R.string.settings_screen_theme))) { - String tid=shared_pref.getString(key_string, SCREEN_THEME_STANDARD); + String tid = shared_pref.getString(key_string, SCREEN_THEME_DEFAULT); String[] wl_label = c.getResources().getStringArray(R.array.settings_screen_theme_list_entries); String sum_msg = wl_label[Integer.parseInt(tid)]; pref_key.setSummary(sum_msg); - if (!mCurrentScreenTheme.equals(tid)) { - if (tid.equals(SCREEN_THEME_STANDARD)) mActivity.setTheme(R.style.Main); - else if (tid.equals(SCREEN_THEME_LIGHT)) mActivity.setTheme(R.style.MainLight); - else if (tid.equals(SCREEN_THEME_BLACK)) mActivity.setTheme(R.style.MainBlack); - mCurrentScreenTheme=tid; + if (!mCurrentThemeSetting.equals(tid)) { + // Theme language changed, restart ActivitySettings for the changes to take effect. They will be applied by onCreate() of ActivitySettings + // App restart will be triggered on exiting Settings + //mCurrentThemeSetting = tid; //not needed because we restart activity immeadiately mActivity.finish(); Intent intent = new Intent(mActivity, ActivitySettings.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); mActivity.startActivity(intent); } } else if (key_string.equals(c.getString(R.string.settings_screen_theme_language))) { - String lang_value=shared_pref.getString(key_string, APPLICATION_LANGUAGE_SETTING_SYSTEM_DEFAULT); + String lang_value = shared_pref.getString(key_string, APPLICATION_LANGUAGE_SETTING_SYSTEM_DEFAULT); String[] lang_msgs = c.getResources().getStringArray(R.array.settings_screen_theme_language_list_entries); - String sum_msg=lang_msgs[0]; + String sum_msg = lang_msgs[0]; if (!lang_value.equals(APPLICATION_LANGUAGE_SETTING_SYSTEM_DEFAULT)) { - for(int i=0;i activityResultLaunchActivityPasswordSettings = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), + new ActivityResultCallback() { + @Override + public void onActivityResult(ActivityResult result) { + int resultCode = result.getResultCode(); + //Intent data = result.getData(); + if (resultCode == Activity.RESULT_OK) { + SharedPreferences shared_pref = PreferenceManager.getDefaultSharedPreferences(mContext); + checkSettingValue(mUtil, shared_pref, getString(R.string.settings_security_application_password), mContext); + } } } - } + ); @Override public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - mUtil = new CommonUtilities(getContext(), "SettingsSecurity", mGp, null); + mActivity = (ActivitySettings)getActivity(); + mContext = mActivity; + mUtil = new CommonUtilities(mContext, "SettingsSecurityFragment", mGp, null); + + super.onCreate(savedInstanceState);//calls onCreatePreferences() + mUtil.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName() + " entered"); + } - addPreferencesFromResource(R.xml.settings_frag_security); + @Override + public void onCreatePreferences(@Nullable Bundle savedInstanceState, @Nullable String rootKey) { + setPreferencesFromResource(R.xml.settings_frag_security, rootKey); - SharedPreferences shared_pref=CommonUtilities.getSharedPreference(getContext()); + //SharedPreferences shared_pref = PreferenceManager.getDefaultSharedPreferences(mContext); + SharedPreferences shared_pref = CommonUtilities.getSharedPreference(mContext); - checkSettingValue(mUtil, shared_pref, getString(R.string.settings_security_application_password), getContext()); + // Register listener to call onSharedPreferenceChanged() when a preference changes + //getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); + shared_pref.registerOnSharedPreferenceChangeListener(this); - Preference button = (Preference)getPreferenceManager().findPreference(getString(R.string.settings_security_application_password)); - button.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { + // Register listener to start password activity on preference click + Preference button = findPreference(getString(R.string.settings_security_application_password)); + Objects.requireNonNull(button).setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override - public boolean onPreferenceClick(Preference preference) { - Intent in=new Intent(getContext(), ActivityPasswordSettings.class); - startActivityForResult(in, 0); + public boolean onPreferenceClick(@NonNull Preference preference) { + Intent in = new Intent(mContext, ActivityPasswordSettings.class); + activityResultLaunchActivityPasswordSettings.launch(in); return false; } }); + + // Get current app settings directory preference value + mCurrentAppSettingsDirectory = GlobalParameters.getAppManagementDirSetting(mContext); + + // Check all currrent preferences values and do any custom actions (enable/disable a setting...) on preferences screen creations + setCurrentValues(shared_pref); + } + + /* + * Listener when the preferences change + * @param sharedPreferences that changed + * @param key that changed + */ + @Override + public void onSharedPreferenceChanged(SharedPreferences shared_pref, String key_string) { + checkSettingValue(mUtil, shared_pref, key_string, mContext); +/* + Preference preference = findPreference(key_string); + if (preference != null) { + if (!(preference instanceof CheckBoxPreference)){ + String value = shared_pref.getString(preference.getKey(), ""); + setPreferenceSummary(preference, value); + } + } +*/ + } + + // Tied to Activity.onStart of containing app, called when fragment gets visible to user + @Override + public void onStart() { + super.onStart(); + + mUtil.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName() + " entered"); + } + + // Tied to parent activity state, called when fragment is no longer visible + @Override + public void onStop() { + mUtil.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName() + " entered"); + + super.onStop(); + } + + // Cleaning up, called after onStop when view is detached + @Override + public void onDestroyView() { + super.onDestroyView(); + + //SharedPreferences shared_pref = PreferenceManager.getDefaultSharedPreferences(mContext); + SharedPreferences shared_pref = CommonUtilities.getSharedPreference(mContext); + + // Unregister listener to call onSharedPreferenceChanged() when a preference changes + //getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this); + shared_pref.unregisterOnSharedPreferenceChangeListener(this); + } + + private void setCurrentValues(SharedPreferences shared_pref) { + checkSettingValue(mUtil, shared_pref, getString(R.string.settings_security_application_password), mContext); + checkSettingValue(mUtil, shared_pref, getString(R.string.settings_security_app_settings_directory), mContext); } private void checkSettingValue(CommonUtilities ut, SharedPreferences shared_pref, String key_string, Context c) { - Preference pref_key=findPreference(key_string); - String hv= ApplicationPasswordUtils.getPasswordHashValue(shared_pref); + Preference pref_key = findPreference(key_string); + String hv = ApplicationPasswordUtils.getPasswordHashValue(shared_pref); + + // pref_key can be null if key_string equals settings_application_password_hash_value + // this is the case when We create, remove or change app password. + // the preference is edited in ApplicationPasswordUtils.class when we set the password + // This triggers onSharedPreferenceChanged() for the key settings_application_password_hash_value + // Since settings_application_password_hash_value is not present in our Security Preferences xml resource, it will return null + // One other alternative would be to add it as a hidden preference in xml +/* + +*/ + //Objects.requireNonNull(pref_key); + if (pref_key == null) { + mUtil.addDebugMsg(1, "I", "checkSettingValue: pref_key was null, key_string=" + key_string); + } if (key_string.equals(c.getString(R.string.settings_security_application_password))) { - String contents_string=""; + String contents_string; if (hv.equals("")) { contents_string=c.getString(R.string.settings_security_application_password_not_created); } else { - contents_string="-"+c.getString(R.string.settings_security_application_password_created); + contents_string = "-" + c.getString(R.string.settings_security_application_password_created); if (shared_pref.getBoolean(c.getString(R.string.settings_security_use_auth_timeout), true)) - contents_string+="\n-"+c.getString(R.string.settings_security_use_auth_timeout_title); + contents_string += "\n-" + c.getString(R.string.settings_security_use_auth_timeout_title); if (shared_pref.getBoolean(c.getString(R.string.settings_security_application_password_use_app_startup), false)) - contents_string+="\n-"+c.getString(R.string.settings_security_application_password_use_app_startup_title); + contents_string += "\n-" + c.getString(R.string.settings_security_application_password_use_app_startup_title); if (shared_pref.getBoolean(c.getString(R.string.settings_security_application_password_use_edit_task), false)) - contents_string+="\n-"+c.getString(R.string.settings_security_application_password_use_edit_task_title); + contents_string += "\n-" + c.getString(R.string.settings_security_application_password_use_edit_task_title); if (shared_pref.getBoolean(c.getString(R.string.settings_security_application_password_use_export_task), false)) - contents_string+="\n-"+c.getString(R.string.settings_security_application_password_use_export_task_title); + contents_string += "\n-" + c.getString(R.string.settings_security_application_password_use_export_task_title); if (shared_pref.getBoolean(c.getString(R.string.settings_security_init_smb_account_password), false)) - contents_string+="\n-"+c.getString(R.string.settings_security_init_smb_account_password_title); + contents_string += "\n-" + c.getString(R.string.settings_security_init_smb_account_password_title); if (shared_pref.getBoolean(c.getString(R.string.settings_security_init_zip_passowrd), false)) - contents_string+="\n-"+c.getString(R.string.settings_security_init_zip_passowrd_title); + contents_string += "\n-" + c.getString(R.string.settings_security_init_zip_passowrd_title); if (shared_pref.getBoolean(c.getString(R.string.settings_security_hide_show_smb_passowrd), false)) - contents_string+="\n-"+c.getString(R.string.settings_security_hide_show_smb_passowrd_title); + contents_string += "\n-" + c.getString(R.string.settings_security_hide_show_smb_passowrd_title); if (shared_pref.getBoolean(c.getString(R.string.settings_security_hide_show_zip_passowrd), false)) - contents_string+="\n-"+c.getString(R.string.settings_security_hide_show_zip_passowrd_title); + contents_string += "\n-" + c.getString(R.string.settings_security_hide_show_zip_passowrd_title); + } + Objects.requireNonNull(pref_key).setSummary(contents_string); + } else if (key_string.equals(c.getString(R.string.settings_security_app_settings_directory))) { + String kv = shared_pref.getString(key_string, APP_SETTINGS_DIRECTORY_ROOT); + String summary = ""; + if (kv.equals(APP_SETTINGS_DIRECTORY_ROOT)) { + // /data/data/APPLICATION_ID/files + try { + summary = c.getFilesDir().getCanonicalPath(); + } catch (IOException e) { + e.printStackTrace(); + summary = "/data/data/"+APPLICATION_ID+"/files"; + } + summary = String.format(c.getString(R.string.settings_security_app_settings_directory_summary_root), summary); + } else if (kv.equals(APP_SETTINGS_DIRECTORY_APP_SPECIFIC_INTERNAL)) { + // /storage/emulated/0/Android/data/APPLICATION_ID/files + summary = SafManager3.getAppSpecificDirectory(c, SafFile3.SAF_FILE_PRIMARY_UUID); + if (summary == null) { + summary = SafManager3.getPrimaryStoragePath() + "/Android/data/" + APPLICATION_ID + "/files"; + mUtil.addDebugMsg(1, "I", "checkSettingValue: SafManager3.getAppSpecificDirectory returns null on primary uid"); + } + summary = String.format(c.getString(R.string.settings_security_app_settings_directory_summary_app_specific), summary); + } else if (kv.equals(APP_SETTINGS_DIRECTORY_STORAGE)) { + // /storage/emulated/0/app_name + summary = String.format(c.getString(R.string.settings_security_app_settings_directory_summary_storage), mGp.externalStoragePrefix+"/"+APPLICATION_TAG); + } + Objects.requireNonNull(pref_key).setSummary(summary); + + if (!mCurrentAppSettingsDirectory.equals(kv)) { + //mCurrentAppSettingsDirectory = kv; //not needed because we restart activity immeadiately on Settings exit + // If the app dir setting is changed, an app restart is needed to properly display further messages and history + // App restart is triggered in reloadSettingParms() because it is useless here + // To properly preserve eventual log messages, we could setup a FragmentResultListener to restart app when returning to main Settings screen/fragment + //mActivity.finish(); + //Intent intent = new Intent(mActivity, ActivitySettings.class); + //intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); + //mActivity.startActivity(intent); + } + } + } + } + + public static class SettingsMiscFragment extends PreferenceFragmentCompat implements SharedPreferences.OnSharedPreferenceChangeListener { + private AppCompatActivity mActivity = null; + private Context mContext = null; + private CommonUtilities mUtil = null; + + ActivityResultLauncher requestPermissionLaunchLegacyStorage = registerForActivityResult(new ActivityResultContracts.RequestPermission(), + new ActivityResultCallback() { + @Override + public void onActivityResult(Boolean result) { + checkStoragePreferenceState(); + } + }); + + @Override + public void onCreate(Bundle savedInstanceState) { + mActivity = (ActivitySettings)getActivity(); + mContext = mActivity; + mUtil = new CommonUtilities(mContext, "SettingsMiscFragment", mGp, null); + + super.onCreate(savedInstanceState);//calls onCreatePreferences() + + mUtil.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName() + " entered"); + } + + @Override + public void onCreatePreferences(@Nullable Bundle savedInstanceState, @Nullable String rootKey) { + setPreferencesFromResource(R.xml.settings_frag_misc, rootKey); + + //SharedPreferences shared_pref = PreferenceManager.getDefaultSharedPreferences(mContext); + SharedPreferences shared_pref = CommonUtilities.getSharedPreference(mContext); + + // Register listener to call onSharedPreferenceChanged() when a preference changes + //getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); + shared_pref.registerOnSharedPreferenceChangeListener(this); + + // Register listener to start activity with system app permissions + Preference app_perms_pref = findPreference(getString(R.string.settings_app_permissions)); + Objects.requireNonNull(app_perms_pref).setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { + @Override + public boolean onPreferenceClick(@NonNull Preference preference) { + Intent intent = new Intent(); + intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); + Uri uri = Uri.fromParts("package", mActivity.getPackageName(), null); + intent.setData(uri); + mActivity.startActivity(intent); + + return false; + } + }); + + // Register listener to start activity with system app permissions + Preference storage_perms_pref = findPreference(getString(R.string.settings_storage_permission)); + Objects.requireNonNull(storage_perms_pref).setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { + @Override + public boolean onPreferenceClick(@NonNull Preference preference) { + if (Build.VERSION.SDK_INT >= 30) { + Intent intent = new Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION); + mActivity.startActivity(intent); + } else { + requestPermissionLaunchLegacyStorage.launch(Manifest.permission.WRITE_EXTERNAL_STORAGE); + } + + return false; + } + }); + + // Check all currrent preferences values and do any custom actions (enable/disable a setting...) on preferences screen creations + //setCurrentValues(shared_pref); + + shared_pref.edit().putBoolean(getString(R.string.settings_exit_clean), false).commit(); + Preference pref_key = findPreference(getString(R.string.settings_exit_clean)); + if (pref_key != null) pref_key.setEnabled(false); + + checkSettingValue(mUtil, shared_pref, getString(R.string.settings_exit_clean), mContext); + } + + /* + * Listener when the preferences change + * @param sharedPreferences that changed + * @param key that changed + */ + @Override + public void onSharedPreferenceChanged(SharedPreferences shared_pref, String key_string) { + checkSettingValue(mUtil, shared_pref, key_string, mContext); +/* + Preference preference = findPreference(key_string); + if (preference != null) { + if (!(preference instanceof CheckBoxPreference)){ + String value = shared_pref.getString(preference.getKey(), ""); + setPreferenceSummary(preference, value); } - pref_key.setSummary(contents_string); } +*/ } + // Tied to Activity.onStart of containing app, called when fragment gets visible to user @Override public void onStart() { super.onStart(); + mUtil.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName() + " entered"); - getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(listenerAfterHc); - mActivity.setTitle(R.string.settings_ui_title); } + // Tied to parent activity state, called when fragment is no longer visible @Override public void onStop() { - super.onStop(); mUtil.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName() + " entered"); - getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(listenerAfterHc); + + super.onStop(); } - } + // Cleaning up, called after onStop when view is detached + @Override + public void onDestroyView() { + super.onDestroyView(); + //SharedPreferences shared_pref = PreferenceManager.getDefaultSharedPreferences(mContext); + SharedPreferences shared_pref = CommonUtilities.getSharedPreference(mContext); + + // Unregister listener to call onSharedPreferenceChanged() when a preference changes + //getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this); + shared_pref.unregisterOnSharedPreferenceChangeListener(this); + } + + private void checkStoragePreferenceState() { + Preference pref_key = findPreference(getString(R.string.settings_storage_permission)); + Objects.requireNonNull(pref_key); + if (Build.VERSION.SDK_INT < 30) { + if (ActivityMain.isLegacyStorageAccessGranted(mActivity)) { + pref_key.setEnabled(false); + pref_key.setTitle(mContext.getString(R.string.settings_storage_permission_title_granted)); + } else { + pref_key.setEnabled(true); + pref_key.setTitle(mContext.getString(R.string.settings_storage_permission_title_denied)); + } + } else { + pref_key.setEnabled(true); + if (ActivityMain.isAllFileAccessPermissionGranted()) { + pref_key.setTitle(mContext.getString(R.string.settings_storage_permission_title_granted)); + } else { + pref_key.setTitle(mContext.getString(R.string.settings_storage_permission_title_denied)); + } + } + } + + private void checkSettingValue(CommonUtilities ut, SharedPreferences shared_pref, String key_string, Context c) { + checkStoragePreferenceState(); + + if (key_string.equals(c.getString(R.string.settings_exit_clean))) { + } + } + } } \ No newline at end of file diff --git a/app/src/main/java/com/sentaroh/android/SMBSync3/ActivityShortcut.java b/app/src/main/java/com/sentaroh/android/SMBSync3/ActivityShortcut.java index 54cb91c1..3b838031 100644 --- a/app/src/main/java/com/sentaroh/android/SMBSync3/ActivityShortcut.java +++ b/app/src/main/java/com/sentaroh/android/SMBSync3/ActivityShortcut.java @@ -69,7 +69,7 @@ final protected void onRestoreInstanceState(Bundle savedState) { @Override protected void attachBaseContext(Context base) { - super.attachBaseContext(GlobalParameters.setNewLocale(base)); + super.attachBaseContext(GlobalParameters.setLocaleAndMetrics(base)); } @Override @@ -80,7 +80,7 @@ public void onCreate(Bundle savedInstanceState) { mActivity= ActivityShortcut.this; mGp= GlobalWorkArea.getGlobalParameter(mActivity); - GlobalParameters.setDisplayFontScale(mActivity); + //GlobalParameters.setDisplayFontScale(mActivity); if (mGp.themeColorList == null) { mGp.themeColorList = ThemeUtil.getThemeColorList(mActivity); } diff --git a/app/src/main/java/com/sentaroh/android/SMBSync3/ApplicationPasswordUtils.java b/app/src/main/java/com/sentaroh/android/SMBSync3/ApplicationPasswordUtils.java index 5b16d84a..a10eac75 100644 --- a/app/src/main/java/com/sentaroh/android/SMBSync3/ApplicationPasswordUtils.java +++ b/app/src/main/java/com/sentaroh/android/SMBSync3/ApplicationPasswordUtils.java @@ -65,13 +65,15 @@ public class ApplicationPasswordUtils { final static private long APPLICATION_PASSWORD_VALIDITY_PERIOD =30*60*1000;//30 Min - private static final String APPLICATION_PASSWORD_HASH_VALUE = "settings_application_password_hash_value"; + private static final String APPLICATION_PASSWORD_HASH_PREFERENCE_KEY = "settings_application_password_hash_value"; + private static final String APPLICATION_PASSWORD_HASH_PREFERENCE_DEFAULT_VALUE = ""; + static public String getPasswordHashValue(SharedPreferences prefs) { - return prefs.getString(APPLICATION_PASSWORD_HASH_VALUE, ""); + return prefs.getString(APPLICATION_PASSWORD_HASH_PREFERENCE_KEY, APPLICATION_PASSWORD_HASH_PREFERENCE_DEFAULT_VALUE); } static public void savePasswordHashValue(GlobalParameters gp, SharedPreferences prefs, String hv) { - prefs.edit().putString(APPLICATION_PASSWORD_HASH_VALUE, hv).commit(); + prefs.edit().putString(APPLICATION_PASSWORD_HASH_PREFERENCE_KEY, hv).commit(); gp.settingSecurityApplicationPasswordHashValue=hv; } @@ -159,7 +161,7 @@ static public void authentication(final GlobalParameters gp, final Activity mAct tv_msg.setText(mActivity.getString(R.string.msgs_security_application_password_auth_specify_password)); final CheckedTextView ctv_prot=(CheckedTextView)dialog.findViewById(R.id.password_input_ctv_protect); ctv_prot.setVisibility(CheckedTextView.GONE); - final TextInputLayout ll_pswd1=(TextInputLayout)dialog.findViewById(R.id.password_input_password_view); + //final TextInputLayout ll_pswd1=(TextInputLayout)dialog.findViewById(R.id.password_input_password_view); final TextInputEditText et_pswd1=(TextInputEditText)dialog.findViewById(R.id.password_input_password); final TextInputLayout ll_pswd2=(TextInputLayout)dialog.findViewById(R.id.password_input_password_confirm_view); final TextInputEditText et_pswd2=(TextInputEditText)dialog.findViewById(R.id.password_input_password_confirm); diff --git a/app/src/main/java/com/sentaroh/android/SMBSync3/CommonUtilities.java b/app/src/main/java/com/sentaroh/android/SMBSync3/CommonUtilities.java index b6149606..32039876 100644 --- a/app/src/main/java/com/sentaroh/android/SMBSync3/CommonUtilities.java +++ b/app/src/main/java/com/sentaroh/android/SMBSync3/CommonUtilities.java @@ -40,14 +40,12 @@ this software and associated documentation files (the "Software"), to deal import android.location.LocationManager; import android.net.ConnectivityManager; import android.net.NetworkInfo; -import android.net.Uri; import android.net.wifi.WifiManager; import android.os.BatteryManager; import android.os.Build; import android.os.Environment; -import android.os.Handler; import android.os.PowerManager; -import android.preference.PreferenceManager; +import androidx.preference.PreferenceManager; import android.provider.Settings; import android.text.Editable; import android.text.Spannable; @@ -60,6 +58,7 @@ this software and associated documentation files (the "Software"), to deal import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; +import android.webkit.WebResourceRequest; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.CheckedTextView; @@ -69,6 +68,7 @@ this software and associated documentation files (the "Software"), to deal import android.widget.Spinner; import android.widget.TextView; +import androidx.core.content.ContextCompat; import androidx.fragment.app.FragmentManager; import com.sentaroh.android.JcifsFile2.JcifsUtil; @@ -80,7 +80,6 @@ this software and associated documentation files (the "Software"), to deal import com.sentaroh.android.Utilities3.Dialog.CommonDialog; import com.sentaroh.android.Utilities3.Dialog.MessageDialogFragment; import com.sentaroh.android.Utilities3.EncryptUtilV3; -import com.sentaroh.android.Utilities3.MiscUtil; import com.sentaroh.android.Utilities3.SafFile3; import com.sentaroh.android.Utilities3.ShellCommandUtil; import com.sentaroh.android.Utilities3.StringUtil; @@ -106,8 +105,8 @@ this software and associated documentation files (the "Software"), to deal import java.net.NetworkInterface; import java.net.SocketException; import java.net.UnknownHostException; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; -import java.util.Collections; import java.util.Comparator; import java.util.Enumeration; import java.util.Locale; @@ -117,7 +116,7 @@ this software and associated documentation files (the "Software"), to deal import static com.sentaroh.android.Utilities3.SafFile3.SAF_FILE_PRIMARY_UUID; public final class CommonUtilities { - private static Logger log= LoggerFactory.getLogger(CommonUtilities.class); + private static final Logger log= LoggerFactory.getLogger(CommonUtilities.class); private Context mContext = null; private LogUtil mLog = null; private GlobalParameters mGp = null; @@ -141,84 +140,89 @@ public LogUtil getLogUtil() { return mLog; } - static public void setViewEnabled(Activity a, View v, boolean enabled) { + public static void setViewEnabled(Activity a, View v, boolean enabled) { // Thread.dumpStack(); GlobalParameters gp=GlobalWorkArea.getGlobalParameter(a); CommonDialog.setViewEnabled(gp.themeColorList.theme_is_light, v, enabled); } - final public SharedPreferences getSharedPreference() { + public SharedPreferences getSharedPreference() { return getSharedPreference(mContext); } - final static public SharedPreferences getSharedPreference(Context c) { + public static SharedPreferences getSharedPreference(Context c) { return PreferenceManager.getDefaultSharedPreferences(c); } public static void setSpinnerBackground(Context c, Spinner spinner, boolean theme_is_light) { - if (theme_is_light) spinner.setBackground(c.getDrawable(R.drawable.spinner_color_background_light)); - else spinner.setBackground(c.getDrawable(R.drawable.spinner_color_background)); + if (theme_is_light) spinner.setBackground(ContextCompat.getDrawable(c, R.drawable.spinner_color_background_light)); + else spinner.setBackground(ContextCompat.getDrawable(c, R.drawable.spinner_color_background)); } public void showCommonDialog(final boolean negative, String type, String title, String msgtext, Object listener) { MessageDialogFragment cdf =MessageDialogFragment.newInstance(negative, type, title, msgtext); cdf.showDialog(mFragMgr,cdf, listener); - }; + } + public void showCommonDialogInfo(final boolean negative, String title, String msgtext, Object listener) { MessageDialogFragment cdf =MessageDialogFragment.newInstance(negative, MessageDialogFragment.CATEGORY_INFO, title, msgtext); cdf.showDialog(mFragMgr,cdf, listener); - }; + } + public void showCommonDialogWarn(final boolean negative, String title, String msgtext, Object listener) { MessageDialogFragment cdf =MessageDialogFragment.newInstance(negative, MessageDialogFragment.CATEGORY_WARN, title, msgtext); cdf.showDialog(mFragMgr,cdf, listener); - }; + } + public void showCommonDialogError(final boolean negative, String title, String msgtext, Object listener) { MessageDialogFragment cdf =MessageDialogFragment.newInstance(negative, MessageDialogFragment.CATEGORY_ERROR, title, msgtext); cdf.showDialog(mFragMgr,cdf, listener); - }; + } + + // not used public void showCommonDialogDanger(final boolean negative, String title, String msgtext, Object listener) { MessageDialogFragment cdf =MessageDialogFragment.newInstance(negative, MessageDialogFragment.CATEGORY_DANGER, title, msgtext); cdf.showDialog(mFragMgr,cdf, listener); - }; + } - static public void showCommonDialog(FragmentManager fm, final boolean negative, String type, String title, String msgtext, Object listener) { + public static void showCommonDialog(FragmentManager fm, final boolean negative, String type, String title, String msgtext, Object listener) { MessageDialogFragment cdf =MessageDialogFragment.newInstance(negative, type, title, msgtext); cdf.showDialog(fm, cdf, listener); - }; + } public void showCommonDialog(final boolean negative, String type, String title, Spannable msgtext, Object listener) { MessageDialogFragment cdf =MessageDialogFragment.newInstance(negative, type, title, ""); cdf.setMessageText(msgtext); cdf.showDialog(mFragMgr,cdf,listener); - }; + } public void showCommonDialog(final boolean negative, String type, String title, String msgtext, int text_color, Object listener) { MessageDialogFragment cdf =MessageDialogFragment.newInstance(negative, type, title, msgtext); cdf.setTextColor(text_color); cdf.showDialog(mFragMgr,cdf,listener); - }; + } public void showCommonDialog(final boolean negative, String type, String title, String msgtext, String ok_text, String cancel_text, Object listener) { MessageDialogFragment cdf =MessageDialogFragment.newInstance(negative, type, title, msgtext, ok_text, cancel_text); cdf.showDialog(mFragMgr,cdf,listener); - }; + } public void showCommonDialog(final boolean negative, String type, String title, String msgtext, String ok_text, String cancel_text, String extra_btn_label, Object listener, CallBackListener cbl, boolean max) { MessageDialogFragment cdf =MessageDialogFragment.newInstance(negative, type, title, msgtext, ok_text, cancel_text, extra_btn_label); cdf.showDialog(mFragMgr, cdf, listener, cbl, max); - }; + } public void showCommonDialogWarn(final boolean negative, String title, String msgtext, String ok_text, String cancel_text, Object listener) { MessageDialogFragment cdf =MessageDialogFragment.newInstance(negative, MessageDialogFragment.CATEGORY_WARN, title, msgtext, ok_text, cancel_text); cdf.showDialog(mFragMgr,cdf,listener); - }; + } public void showCommonDialogDanger(boolean negative, String title, String msgtext, String ok_text, String cancel_text, Object listener) { MessageDialogFragment cdf =MessageDialogFragment.newInstance(negative, MessageDialogFragment.CATEGORY_DANGER, title, msgtext, ok_text, cancel_text); cdf.showDialog(mFragMgr,cdf,listener); - }; + } public static String convertMakdownToHtml(Context c, String mark_down_fp) { // long b_time=System.currentTimeMillis(); @@ -238,10 +242,10 @@ public static String convertMakdownToHtml(Context c, String mark_down_fp) { public String getStringWithLangCode(Activity c, String lang_code, int res_id) { Configuration config = new Configuration(c.getResources().getConfiguration()); config.setLocale(new Locale(lang_code)); - String result = c.createConfigurationContext(config).getText(res_id).toString(); - return result; + return c.createConfigurationContext(config).getText(res_id).toString(); } + // not used public String getStringWithLangCode(Activity c, String lang_code, int res_id, Object... value) { String text = getStringWithLangCode(c, lang_code, res_id); String result=text; @@ -249,43 +253,46 @@ public String getStringWithLangCode(Activity c, String lang_code, int res_id, Ob return result; } - static public String getRootFilePath(String fp) { + // not used + public static String getRootFilePath(String fp) { String reform_fp=StringUtil.removeRedundantDirectorySeparator(fp); String is_pre=Environment.getExternalStorageDirectory().toString(); if (reform_fp.startsWith(is_pre)) return is_pre; else { String[] fp_parts=reform_fp.startsWith("/")?reform_fp.substring(1).split("/"):reform_fp.split("/"); - String rt_fp="/"+fp_parts[0]+"/"+fp_parts[1]; - return rt_fp; + return "/"+fp_parts[0]+"/"+fp_parts[1]; } } + // not used public static boolean isAllFileAccessAvailable() { return SafFile3.isAllFileAccessAvailable(); } - final public void setLogId(String li) { + // not used + public void setLogId(String li) { mLog.setLogId(li); } - final static public String getExecutedMethodName() { - String name = Thread.currentThread().getStackTrace()[3].getMethodName(); - return name; + public static String getExecutedMethodName() { + return Thread.currentThread().getStackTrace()[3].getMethodName(); } - final public void resetLogReceiver() { + // not used + public void resetLogReceiver() { mLog.resetLogReceiver(); } - final public void flushLog() { + public void flushLog() { mLog.flushLog(); } - final public void rotateLogFile() { + // not used + public void rotateLogFile() { mLog.rotateLogFile(); } - static public ArrayList listSystemInfo(Context c, GlobalParameters gp) { + public static ArrayList listSystemInfo(Context c, GlobalParameters gp) { ArrayList out=SystemInfo.listSystemInfo(c, gp.safMgr); @@ -335,7 +342,7 @@ static public ArrayList listSystemInfo(Context c, GlobalParameters gp) { if (activeNetwork!=null) { String network=activeNetwork.getExtraInfo(); - boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting(); + boolean isConnected = activeNetwork.isConnectedOrConnecting(); boolean isWiFi = activeNetwork.getType() == ConnectivityManager.TYPE_WIFI; out.add(" Network="+network+", isConnected="+isConnected+", isWiFi="+isWiFi); @@ -378,21 +385,22 @@ static public ArrayList listSystemInfo(Context c, GlobalParameters gp) { return out; } - final public static boolean isLocationServiceEnabled(Context c, GlobalParameters mGp) { - if (Build.VERSION.SDK_INT>=27) { - LocationManager lm= (LocationManager)c.getSystemService(Context.LOCATION_SERVICE); - if (Build.VERSION.SDK_INT==27) { - boolean gps=lm.isProviderEnabled(LocationManager.GPS_PROVIDER); - boolean nw=lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER); - return gps|nw; - } else { + public static boolean isLocationServiceEnabled(Context c, GlobalParameters mGp) { + if (Build.VERSION.SDK_INT >= 27) { + LocationManager lm = (LocationManager)c.getSystemService(Context.LOCATION_SERVICE); + if (Build.VERSION.SDK_INT == 27) { + boolean gps = lm.isProviderEnabled(LocationManager.GPS_PROVIDER); + boolean nw = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER); + return gps | nw; + } else if (Build.VERSION.SDK_INT >= 28) { return lm.isLocationEnabled(); } } return false; } - final public static boolean isNetworkConnected(Context context) { + // not used + public static boolean isNetworkConnected(Context context) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo ni = cm.getActiveNetworkInfo(); if (ni != null) { @@ -401,7 +409,8 @@ final public static boolean isNetworkConnected(Context context) { return false; } - final public void deleteLogFile() { + // not used + public void deleteLogFile() { mLog.deleteLogFile(); } @@ -409,7 +418,7 @@ public String buildPrintMsg(String cat, String... msg) { return mLog.buildPrintLogMsg(cat, msg); } - static public void setAboutFindListener(Activity a, LinearLayout ll, WebView wv) { + public static void setAboutFindListener(Activity a, LinearLayout ll, WebView wv) { final EditText et_find_string=(EditText)ll.findViewById(R.id.dlg_find_view_search_word); final ImageButton ib_find_next=(ImageButton) ll.findViewById(R.id.dlg_find_view_find_next); final ImageButton ib_find_prev=(ImageButton) ll.findViewById(R.id.dlg_find_view_find_prev); @@ -465,12 +474,13 @@ public boolean onLongClick(View v) { public void onFindResultReceived(int i, int i1, boolean b) { if (et_find_string.getText().length()>0) { if (i1>0) { - tv_find_count.setText((i+1)+"/"+i1); + String str = String.format("%d/%d", (i+1), i1); + tv_find_count.setText(str); tv_find_count.setTextColor(default_text_color); CommonUtilities.setViewEnabled(a, ib_find_next, true); CommonUtilities.setViewEnabled(a, ib_find_prev, true); } else { - tv_find_count.setText(0+"/"+0); + tv_find_count.setText("0/0"); tv_find_count.setTextColor(Color.RED); CommonUtilities.setViewEnabled(a, ib_find_next, false); CommonUtilities.setViewEnabled(a, ib_find_prev, false); @@ -504,7 +514,7 @@ public void afterTextChanged(Editable s) {} }); } - static public void setWebViewListener(GlobalParameters gp, WebView wv, int zf) { + public static void setWebViewListener(GlobalParameters gp, WebView wv, int zf) { // wv.setBackgroundColor(Color.LTGRAY); // if (Build.VERSION.SDK_INT>=29) { // if (!gp.themeColorList.theme_is_light) { @@ -527,7 +537,8 @@ static public void setWebViewListener(GlobalParameters gp, WebView wv, int zf) { // wv.getSettings().setBuiltInZoomControls(true); wv.setWebViewClient(new WebViewClient() { @Override - public boolean shouldOverrideUrlLoading (WebView view, String url) { + public boolean shouldOverrideUrlLoading (WebView view, WebResourceRequest request) { + // Returning false means we are going to load this url in the webView itself return false; } }); @@ -550,14 +561,14 @@ public boolean onKey(View v, int keyCode, KeyEvent event){ }); } - final static public String LIST_ITEM_DATA_SEPARATOR ="\u0000"; - final static public String LIST_ITEM_DUMMY_DATA ="\u0001"; - final static public String LIST_ITEM_ENCODE_CR_CHARACTER ="\u0003"; - final static public String LIST_ITEM_LINE_SEPARATOR="\n"; - synchronized static public void saveMessageList(Context c, GlobalParameters gp) { + final public static String LIST_ITEM_DATA_SEPARATOR ="\u0000"; + final public static String LIST_ITEM_DUMMY_DATA ="\u0001"; + final public static String LIST_ITEM_ENCODE_CR_CHARACTER ="\u0003"; + final public static String LIST_ITEM_LINE_SEPARATOR="\n"; + synchronized public static void saveMessageList(Context c, GlobalParameters gp) { // Thread.dumpStack(); - if (gp.syncMessageList == null || (gp.syncMessageList!=null && gp.syncMessageList.size()==0)) return; - long b_time= System.currentTimeMillis(); + if (gp.syncMessageList == null || gp.syncMessageList.size() == 0) return; + //long b_time= System.currentTimeMillis(); if (gp.syncMessageListChanged) { try { SafFile3 df =new SafFile3(c, gp.settingAppManagemsntDirectoryName); @@ -568,8 +579,8 @@ synchronized static public void saveMessageList(Context c, GlobalParameters gp) OutputStream fos=mf.getOutputStream(); BufferedOutputStream bos=new BufferedOutputStream(fos, GENERAL_IO_BUFFER_SIZE); PrintWriter pw=new PrintWriter(bos); - StringBuffer sb=new StringBuffer(1024*5); - synchronized (gp.syncMessageList) { + StringBuilder sb=new StringBuilder(1024*5); + synchronized (gp.mLockSyncMessageList) { for (MessageListAdapter.MessageListItem smi:gp.syncMessageList) { sb.setLength(0); sb.append(LIST_ITEM_DUMMY_DATA).append(smi.getCategory()).append(LIST_ITEM_DATA_SEPARATOR); //msgCat @@ -579,7 +590,7 @@ synchronized static public void saveMessageList(Context c, GlobalParameters gp) sb.append(LIST_ITEM_DUMMY_DATA).append(smi.getMessage().replaceAll("\n", LIST_ITEM_ENCODE_CR_CHARACTER)).append(LIST_ITEM_DATA_SEPARATOR); //msgBody sb.append(LIST_ITEM_DUMMY_DATA).append(smi.getPath()).append(LIST_ITEM_DATA_SEPARATOR); //msgPath sb.append(LIST_ITEM_DUMMY_DATA).append(smi.getType()).append(LIST_ITEM_DATA_SEPARATOR); //msgType - pw.println(sb.toString()); + pw.println(sb); } gp.syncMessageListChanged =false; } @@ -591,13 +602,13 @@ synchronized static public void saveMessageList(Context c, GlobalParameters gp) } } - static public ArrayList loadMessageList(Context c, GlobalParameters gp) { - long b_time= System.currentTimeMillis(); + public static ArrayList loadMessageList(Context c, GlobalParameters gp) { + //long b_time= System.currentTimeMillis(); ArrayList result=new ArrayList(GlobalParameters.MESSAGE_LIST_INITIAL_VALUE); try { SafFile3 mf =new SafFile3(c, gp.settingAppManagemsntDirectoryName + "/.messages"); if (mf!=null && mf.exists()) { - InputStreamReader isr = new InputStreamReader(mf.getInputStream(), "UTF-8"); + InputStreamReader isr = new InputStreamReader(mf.getInputStream(), StandardCharsets.UTF_8); BufferedReader bir=new BufferedReader(isr, GENERAL_IO_BUFFER_SIZE); String line=null; while((line=bir.readLine())!=null) { @@ -622,14 +633,12 @@ static public ArrayList loadMessageList(Cont return result; } - private final int MAX_MSG_COUNT = 5000; - - final public void addLogMsg(boolean ui_thread, boolean has_result_type, boolean has_path, boolean has_title, + public void addLogMsg(boolean ui_thread, boolean has_result_type, boolean has_path, boolean has_title, String cat, String title, String result_type, String path, String... msg) { // final SyncMessageItem mli=new SyncMessageItem(cat, "","", title, mLog.buildLogCatMsg("", cat, msg), path, type); String finalMsg = ""; StringBuilder log_msg = new StringBuilder(512); - for (int i = 0; i < msg.length; i++) log_msg.append(msg[i]); + for (String s : msg) log_msg.append(s); if (!log_msg.toString().equals("")) finalMsg = log_msg.toString(); if (!title.equals("")) { if (finalMsg.equals("")) mLog.addLogMsg(cat, title.concat(": ").concat(path).concat(result_type)); @@ -654,18 +663,21 @@ public void run() { } } - final public void addLogMsg(String cat, String task, String... msg) { + public void addLogMsg(String cat, String task, String... msg) { addLogMsg(false, false, false, false, cat, task, "", "", msg); } - final public void addLogMsgFromUI(String cat, String task, String... msg) { + // not used + public void addLogMsgFromUI(String cat, String task, String... msg) { addLogMsg(true, false, false, false, cat, task, "", "", msg); } private void putMsgListArray(MessageListAdapter.MessageListItem mli) { - synchronized (mGp.syncMessageList) { + final int MAX_MSG_COUNT = 5000; + synchronized (mGp.mLockSyncMessageList) { if (mGp.syncMessageList.size() > (MAX_MSG_COUNT + 200)) { - for (int i = 0; i < 200; i++) mGp.syncMessageList.remove(0); + mGp.syncMessageList.subList(0, 200).clear(); + //for (int i = 0; i < 200; i++) mGp.syncMessageList.remove(0); } mGp.syncMessageList.add(mli); mGp.syncMessageListChanged =true; @@ -678,18 +690,20 @@ private void putMsgListArray(MessageListAdapter.MessageListItem mli) { } } - final public void addDebugMsg(int lvl, String cat, String... msg) { + public void addDebugMsg(int lvl, String cat, String... msg) { mLog.addDebugMsg(lvl, cat, msg); } - final public boolean isLogFileExists() { + // not used + public boolean isLogFileExists() { boolean result = false; result = mLog.isLogFileExists(); if (mLog.getLogLevel() >= 3) addDebugMsg(3, "I", "Log file exists=" + result); return result; } - final public String getLogFilePath() { + // not used + public String getLogFilePath() { return mLog.getLogFilePath(); } @@ -701,11 +715,10 @@ public boolean isDebuggable() { } catch (NameNotFoundException e) { return false; } - if ((appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) == ApplicationInfo.FLAG_DEBUGGABLE) - return true; - return false; + return (appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) == ApplicationInfo.FLAG_DEBUGGABLE; } + // not used public boolean isWifiActive() { boolean ret = false; WifiManager mWifi = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE); @@ -723,11 +736,10 @@ public static String decryptUserData(Context c, EncryptUtilV3.CipherParms cp_int public static String encryptUserData(Context c, EncryptUtilV3.CipherParms cp_int, String user_data) { byte[] enc_byte = EncryptUtilV3.encrypt(user_data, cp_int); - String enc_str = Base64Compat.encodeToString(enc_byte, Base64Compat.NO_WRAP); - return enc_str; + return Base64Compat.encodeToString(enc_byte, Base64Compat.NO_WRAP); } - static public String buildSmbUrlAddressElement(String host, String port) { + public static String buildSmbUrlAddressElement(String host, String port) { String url_port=port.equals("")?"":":"+port; String url_address=""; if (CommonUtilities.isIpAddressV6(host)) { @@ -744,10 +756,8 @@ static public String buildSmbUrlAddressElement(String host, String port) { } public static boolean canSmbHostConnectable(String addr) { - boolean result = false; - if (JcifsUtil.canIpAddressAndPortConnectable(addr, 139, 3500) || - JcifsUtil.canIpAddressAndPortConnectable(addr, 445, 3500)) result = true; - return result; + return JcifsUtil.canIpAddressAndPortConnectable(addr, 139, 3500) || + JcifsUtil.canIpAddressAndPortConnectable(addr, 445, 3500); } public static boolean canSmbHostConnectable(String addr, String port) { @@ -762,11 +772,12 @@ public static boolean canSmbHostConnectable(String addr, int port) { return result; } - static public boolean isSmbHost(CommonUtilities cu, String address, String scan_port) { + // not used + public static boolean isSmbHost(CommonUtilities cu, String address, String scan_port) { return isSmbHost(cu, address, scan_port, 3500); } - static public boolean isSmbHost(CommonUtilities cu, String address, String scan_port, int time_out) { + public static boolean isSmbHost(CommonUtilities cu, String address, String scan_port, int time_out) { boolean smbhost = false; if (scan_port.equals("")) { if (!JcifsUtil.canIpAddressAndPortConnectable(address, 445, time_out)) { @@ -779,7 +790,7 @@ static public boolean isSmbHost(CommonUtilities cu, String address, String scan_ return smbhost; } - static public String getSmbHostName(CommonUtilities cu, String smb_level, String address) { + public static String getSmbHostName(CommonUtilities cu, String smb_level, String address) { String srv_name = JcifsUtil.getSmbHostNameByAddress(smb_level, address); cu.addDebugMsg(1, "I", "getSmbHostName Address=" + address + ", name=" + srv_name); return srv_name; @@ -828,10 +839,12 @@ public static InetAddress getInetAddress(String addr) { try { result= InetAddress.getByName(addr); } catch (Exception e) { + e.printStackTrace(); } return result; } + // not used public static boolean isIpAddressV4(String addr) { boolean result=false; InetAddress ia=getInetAddress(addr); @@ -888,6 +901,7 @@ public static String addScopeidToIpv6Address(String addr) { return addr; } + // not used public static String resolveHostName(GlobalParameters gp, CommonUtilities cu, String smb_level, String hn) { String resolve_addr = JcifsUtil.getSmbHostIpAddressByHostName(smb_level, hn); if (resolve_addr != null) {//list dns name resolve @@ -905,7 +919,8 @@ public static String resolveHostName(GlobalParameters gp, CommonUtilities cu, St return resolve_addr; } - static public boolean isIpV4PrivateAddress(String ip_v4_addr) { + // not used + public static boolean isIpV4PrivateAddress(String ip_v4_addr) { if (ip_v4_addr.startsWith("10.")) return true; else if (ip_v4_addr.startsWith("192.168.")) return true; else if (ip_v4_addr.startsWith("172.16.")) return true; @@ -927,7 +942,7 @@ static public boolean isIpV4PrivateAddress(String ip_v4_addr) { return false; } - static public boolean isPrivateAddress(String if_addr) { + public static boolean isPrivateAddress(String if_addr) { InetAddress ia=null; try { ia=InetAddress.getByName(if_addr); @@ -939,8 +954,9 @@ static public boolean isPrivateAddress(String if_addr) { return false; } + // not used public static String getIfHwAddress(String if_name) { - String result = ""; + StringBuilder result = new StringBuilder(); boolean exit = false; try { for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) { @@ -949,7 +965,7 @@ public static String getIfHwAddress(String if_name) { InetAddress inetAddress = enumIpAddr.nextElement(); if (inetAddress.isSiteLocalAddress() && (inetAddress instanceof Inet4Address)) { if (intf.getName().equals(if_name)) { - for(int i=0;i loadHistoryList() { - long b_time=System.currentTimeMillis(); + //long b_time=System.currentTimeMillis(); ArrayList hl = new ArrayList(GlobalParameters.HISTORY_LIST_INITIAL_VALUE); try { SafFile3 lf =new SafFile3(mContext, mGp.settingAppManagemsntDirectoryName + "/.history"); if (lf.exists()) { - InputStreamReader isr = new InputStreamReader(lf.getInputStream(), "UTF-8"); + InputStreamReader isr = new InputStreamReader(lf.getInputStream(), StandardCharsets.UTF_8); BufferedReader bir=new BufferedReader(isr, 1024*100); String line = ""; String[] l_array = null; @@ -1035,16 +1048,16 @@ public ArrayList loadHistoryList() { hli.sync_time = l_array[1]; hli.sync_elapsed_time = Long.parseLong(l_array[2]); hli.sync_task = l_array[3]; - hli.sync_status = Integer.valueOf(l_array[4]); - hli.sync_test_mode = l_array[5].equals("1") ? true : false; - hli.sync_result_no_of_copied = Integer.valueOf(l_array[6]); - hli.sync_result_no_of_deleted = Integer.valueOf(l_array[7]); - hli.sync_result_no_of_ignored = Integer.valueOf(l_array[8]); - hli.sync_result_no_of_moved = Integer.valueOf(l_array[9]); - hli.sync_result_no_of_replaced = Integer.valueOf(l_array[10]); + hli.sync_status = Integer.parseInt(l_array[4]); + hli.sync_test_mode = l_array[5].equals("1"); + hli.sync_result_no_of_copied = Integer.parseInt(l_array[6]); + hli.sync_result_no_of_deleted = Integer.parseInt(l_array[7]); + hli.sync_result_no_of_ignored = Integer.parseInt(l_array[8]); + hli.sync_result_no_of_moved = Integer.parseInt(l_array[9]); + hli.sync_result_no_of_replaced = Integer.parseInt(l_array[10]); hli.sync_req = l_array[11]; hli.sync_error_text = l_array[12].replaceAll(LIST_ITEM_ENCODE_CR_CHARACTER, "\n"); - hli.sync_result_no_of_retry = Integer.valueOf(l_array[13]); + hli.sync_result_no_of_retry = Integer.parseInt(l_array[13]); hli.sync_transfer_speed=l_array[14]; hli.sync_result_file_path = l_array[15]; hl.add(hli); @@ -1056,7 +1069,7 @@ public ArrayList loadHistoryList() { } bir.close(); if (hl.size() > 1) { - Collections.sort(hl, new Comparator() { + hl.sort(new Comparator() { @Override public int compare(HistoryListAdapter.HistoryListItem lhs, HistoryListAdapter.HistoryListItem rhs) { if (rhs.sync_date.equals(lhs.sync_date)) { @@ -1075,13 +1088,14 @@ public int compare(HistoryListAdapter.HistoryListItem lhs, HistoryListAdapter.Hi } public static String getStoragePathFromUuid(String uuid) { - if (uuid.equals(SAF_FILE_PRIMARY_UUID)) return Environment.getExternalStorageDirectory().getPath();//SafFile3.SAF_FILE_PRIMARY_STORAGE_PREFIX; + if (uuid.equals(SAF_FILE_PRIMARY_UUID)) return Environment.getExternalStorageDirectory().getPath();// /storage/emulated/0 else return SafFile3.SAF_FILE_EXTERNAL_STORAGE_PREFIX+uuid; } - final public void saveHistoryList(final ArrayList hl) { - if (hl == null || (hl!=null && hl.size()==0)) return; - synchronized (hl) { + public final Object mLockHistoryListAdapter = new Object(); + public void saveHistoryList(final ArrayList hl) { + if (hl == null || hl.size() == 0) return; + synchronized (mLockHistoryListAdapter) { try { SafFile3 df =new SafFile3(mContext, mGp.settingAppManagemsntDirectoryName); if (!df.exists()) df.mkdirs(); @@ -1096,7 +1110,7 @@ final public void saveHistoryList(final ArrayList del_list = new ArrayList(); + //final ArrayList del_list = new ArrayList(); for (int i = 0; i < hl.size(); i++) { if (!hl.get(i).sync_task.equals("")) { shli = hl.get(i); @@ -1104,7 +1118,7 @@ final public void saveHistoryList(final ArrayList syncRequestQueue = new ArrayBlockingQueue(1000); - public ThreadCtrl syncThreadConfirm = new ThreadCtrl(); + public final ThreadCtrl syncThreadConfirm = new ThreadCtrl(); public ThreadCtrl syncThreadCtrl = new ThreadCtrl(); public boolean activityRestartRequired = false; @@ -106,24 +107,27 @@ public class GlobalParameters { public boolean syncThreadActive = false; public boolean isSyncWorkerActive() {return syncWorkerIsActive;} - private boolean syncWorkerIsActive =false; + private boolean syncWorkerIsActive = false; public void setSyncWorkerActive(boolean active) {syncWorkerIsActive =active;} public boolean syncThreadConfirmWait = false; - public CallBackListener callbackShowDialogWindow =null; - public CallBackListener callbackHideDialogWindow =null; - public CallBackListener callbackShowConfirmDialog =null; - public CallBackListener callbackHideConfirmDialog =null; + public CallBackListener callbackShowDialogWindow = null; + public CallBackListener callbackHideDialogWindow = null; + public CallBackListener callbackShowConfirmDialog = null; + public CallBackListener callbackHideConfirmDialog = null; // public boolean themeIsLight = true; - public String settingScreenTheme = SCREEN_THEME_STANDARD; + public String settingScreenTheme = SCREEN_THEME_DEFAULT; public int applicationTheme = -1; public ThemeColorList themeColorList = null; - // Settings parameter + // Path where messages, history, logs and autosave files are stored + // App config on start is always stored in /data/data by android PreferencesManager // public String settingAppManagemsntDirectoryUuid ="primary"; -// public String settingAppManagemsntDirectoryName = SafFile3.SAF_FILE_PRIMARY_STORAGE_PREFIX+"/"+APPLICATION_TAG; - public String settingAppManagemsntDirectoryName = "/data/data/"+APPLICATION_ID+"/files/mgt_dir"; + //public String settingAppManagemsntDirectoryName = SafManager3.SAF_FILE_PRIMARY_STORAGE_PREFIX+"/"+APPLICATION_TAG; + public String settingAppManagemsntDirectoryName = null; //"/data/data/"+APPLICATION_ID+"/files"; // null, to ensure init on app start + + // currently unused public boolean settingExitClean = true; public boolean settingWriteSyncResultLog = true; @@ -186,13 +190,15 @@ public void setSupressShortcut3ConfirmationMessage(Context c, boolean suppress) settingSupressShortcut3ConfirmationMessage =suppress; } - final static private String PRIVACY_POLICY_AGGREEMENT_KEY="privacy_policy_aggreed"; - static public boolean isPrivacyPolicyAgreed(Context c) { + // not used + final private static String PRIVACY_POLICY_AGGREEMENT_KEY="privacy_policy_aggreed"; + public static boolean isPrivacyPolicyAgreed(Context c) { SharedPreferences prefs = CommonUtilities.getSharedPreference(c); - boolean aggree=prefs.getBoolean(PRIVACY_POLICY_AGGREEMENT_KEY, false); - return aggree; + return prefs.getBoolean(PRIVACY_POLICY_AGGREEMENT_KEY, false); } - static public void setPrivacyPolicyAgreed(Context c, boolean aggreed) { + + // not used + public static void setPrivacyPolicyAgreed(Context c, boolean aggreed) { SharedPreferences prefs = CommonUtilities.getSharedPreference(c); prefs.edit().putBoolean(PRIVACY_POLICY_AGGREEMENT_KEY, aggreed).commit(); } @@ -207,8 +213,10 @@ static public void setPrivacyPolicyAgreed(Context c, boolean aggreed) { public boolean settingSecurityHideShowSmbPasswordButton = false; public boolean settingSecurityHideShowZipPasswordButton = false; - public boolean appPasswordAuthValidated=false; - public long appPasswordAuthLastTime=0L; + public boolean appPasswordAuthValidated = false; + public long appPasswordAuthLastTime = 0L; + + public String settingSecurityAppSettingsDirectory = APP_SETTINGS_DIRECTORY_ROOT; public boolean settingPreventSyncStartDelay = false; // public boolean settingScreenOnIfScreenOnAtStartOfSync = false; @@ -221,11 +229,11 @@ static public void setPrivacyPolicyAgreed(Context c, boolean aggreed) { public int settingNotificationVolume = 100; - public boolean settingScheduleSyncEnabled=true; + public boolean settingScheduleSyncEnabled = true; public NotificationManager notificationManager = null; - final static public int notificationOngoingMessageID=1; - final static public int notificationNoticeMessageID=2; + final public static int notificationOngoingMessageID = 1; + final public static int notificationNoticeMessageID = 2; public boolean notificationEnabled = true; public int notificationSmallIcon = R.drawable.ic_48_smbsync_wait; public Notification notification = null; @@ -237,12 +245,13 @@ static public void setPrivacyPolicyAgreed(Context c, boolean aggreed) { public long notificationLastShowedWhen = 0; public String notificationAppName = ""; // public boolean notiifcationEnabled=false; - public long notificationNextShowedTime = 0; + //public long notificationNextShowedTime = 0; // public Bitmap notificationLargeIcon = null; public static final int MESSAGE_LIST_INITIAL_VALUE=5500; + public final Object mLockSyncMessageList = new Object(); public ArrayList syncMessageList = null; //new ArrayList(); - public boolean syncMessageListChanged =false; + public boolean syncMessageListChanged = false; public boolean freezeMessageViewScroll = false; public MessageListAdapter syncMessageListAdapter = null; public ListView syncMessageView = null; @@ -255,12 +264,12 @@ static public void setPrivacyPolicyAgreed(Context c, boolean aggreed) { public ArrayList syncScheduleList = new ArrayList(); public ScheduleListAdapter syncScheduleListAdapter = null; public ListView syncScheduleView = null; - public TextView syncScheduleMessage =null; + public TextView syncScheduleMessage = null; public ArrayList syncGroupList = new ArrayList(); public GroupListAdapter syncGroupListAdapter = null; public ListView syncGroupView = null; - public TextView syncGroupMessage =null; + public TextView syncGroupMessage = null; public ArrayList syncTaskList = new ArrayList(); public TaskListAdapter syncTaskListAdapter = null; @@ -299,20 +308,20 @@ static public void setPrivacyPolicyAgreed(Context c, boolean aggreed) { public Button confirmNoAll = null; public View.OnClickListener confirmNoAllListener = null; - public TextView confirmDialogConflictFilePathA=null; - public TextView confirmDialogConflictFileLengthA=null; - public TextView confirmDialogConflictFileLastModA=null; - public TextView confirmDialogConflictFilePathB=null; - public TextView confirmDialogConflictFileLengthB=null; - public TextView confirmDialogConflictFileLastModB=null; + public TextView confirmDialogConflictFilePathA = null; + public TextView confirmDialogConflictFileLengthA = null; + public TextView confirmDialogConflictFileLastModA = null; + public TextView confirmDialogConflictFilePathB = null; + public TextView confirmDialogConflictFileLengthB = null; + public TextView confirmDialogConflictFileLastModB = null; - public Button confirmDialogConflictButtonSelectA=null; + public Button confirmDialogConflictButtonSelectA = null; public View.OnClickListener confirmDialogConflictButtonSelectAListener = null; - public Button confirmDialogConflictButtonSelectB=null; + public Button confirmDialogConflictButtonSelectB = null; public View.OnClickListener confirmDialogConflictButtonSelectBListener = null; - public Button confirmDialogConflictButtonSyncIgnoreFile=null; + public Button confirmDialogConflictButtonSyncIgnoreFile = null; public View.OnClickListener confirmDialogConflictButtonSyncIgnoreFileListener = null; - public Button confirmDialogConflictButtonCancelSyncTask=null; + public Button confirmDialogConflictButtonCancelSyncTask = null; public View.OnClickListener confirmDialogConflictButtonCancelSyncTaskListener = null; public LinearLayout progressSpinView = null; @@ -323,8 +332,8 @@ static public void setPrivacyPolicyAgreed(Context c, boolean aggreed) { public SafManager3 safMgr = null; - private static LogStream logStream=null;//JCIFS logStream - private static Logger log = LoggerFactory.getLogger(GlobalParameters.class); + private static LogStream logStream = null;//JCIFS logStream + private static final Logger log = LoggerFactory.getLogger(GlobalParameters.class); public GlobalParameters() { } @@ -354,21 +363,37 @@ public void waitConfigurationLock() { } synchronized public void initGlobalParamter(Context c) { - if (Looper.myLooper()!=null) uiHandler = new Handler(); + if (Looper.myLooper() != null) uiHandler = new Handler(); debuggable = isDebuggable(c); +/* // Set app settings directory to /data/data/package_name/files + // Redundant as it is init in loadSettingsParms() try { settingAppManagemsntDirectoryName=c.getFilesDir().getCanonicalPath(); } catch (IOException e) { e.printStackTrace(); } - - externalStoragePrefix= Environment.getExternalStorageDirectory().getPath(); - - mDimWakeLock = ((PowerManager) c.getSystemService(Context.POWER_SERVICE)).newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "SMBSync3-thread-dim"); - forceDimScreenWakelock = ((PowerManager) c.getSystemService(Context.POWER_SERVICE)).newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "SMBSync3-thread-force-dim"); - mPartialWakeLock = ((PowerManager) c.getSystemService(Context.POWER_SERVICE)).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "SMBSync3-thread-partial"); +*/ + //externalStoragePrefix = Environment.getExternalStorageDirectory().getPath(); + externalStoragePrefix = SafManager3.getPrimaryStoragePath(); + + // If option "Force Screen On during sync" is enabled, screen is kept turned on and dimmed during sync + // The lock is released if a confirmation message pauses the sync (confirm delete, confirm overwrite...) + // - SCREEN_DIM_WAKE_LOCK: when acquired by acquireWakeLock() method, keep screen on and dimmed, if it was on, until lock is released by releaseWakeLock() method + // - ACQUIRE_CAUSES_WAKEUP: when SCREEN_DIM_WAKE_LOCK is acquired, turn on screen even if it was off when the lock was acquired + // SCREEN_DIM_WAKE_LOCK and ACQUIRE_CAUSES_WAKEUP are deprecated and only alternative is FLAG_KEEP_SCREEN_ON. + // New FLAG_KEEP_SCREEN_ON doesn't need a permission in manifest but must be added to an activity, not a service + // FLAG_KEEP_SCREEN_ON is bound to a window and keeps screen on while the window is active and visible + // FLAG_KEEP_SCREEN_ON keeps the screen on and at full brightness. + // So, for now, we keep the deprecated method. Else, SyncTask should be writtent as an activity and not a service, + // we would loose dim and screen cannot be kept awake without main activity in forground + // An alternative is to use PowerManager.PARTIAL_WAKE_LOCK, to only keep CPU active during background sync + // Another alternative is R.attr.turnScreenOn or Activity.setTurnScreenOn(boolean) in conjunction with R.attr.showWhenLocked + mDimWakeLock = ((PowerManager) c.getSystemService(Context.POWER_SERVICE)).newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "SMBSync3:thread-dim"); + forceDimScreenWakelock = ((PowerManager) c.getSystemService(Context.POWER_SERVICE)).newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "SMBSync3:thread-force-dim"); + + mPartialWakeLock = ((PowerManager) c.getSystemService(Context.POWER_SERVICE)).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "SMBSync3:thread-partial"); WifiManager wm = (WifiManager) c.getSystemService(Context.WIFI_SERVICE); mWifiLock = wm.createWifiLock(WifiManager.WIFI_MODE_FULL_HIGH_PERF, "SMBSync3-thread"); @@ -379,21 +404,21 @@ synchronized public void initGlobalParamter(Context c) { initSettingsParms(c); loadSettingsParms(c); - if (syncMessageList == null) syncMessageList =CommonUtilities.loadMessageList(c, this); + if (syncMessageList == null) syncMessageList = CommonUtilities.loadMessageList(c, this); initJcifsOption(c); } - public boolean configListLoaded=false; + public boolean configListLoaded = false; public void loadConfigList(Context c, CommonUtilities cu) { - if (cu.getLogLevel()>0) cu.addDebugMsg(1, "I", "config load started"); + if (cu.getLogLevel() > 0) cu.addDebugMsg(1, "I", "config load started"); acquireConfigurationLock(); if (!configListLoaded) { - configListLoaded=true; - ArrayListstl=new ArrayList(); - ArrayListsl=new ArrayList(); - ArrayListgl=new ArrayList(); + configListLoaded = true; + ArrayListstl = new ArrayList(); + ArrayListsl = new ArrayList(); + ArrayListgl = new ArrayList(); TaskListImportExport.loadTaskListFromAppDirectory(c, this, cu, stl, sl, null, gl); syncTaskList.addAll(stl); syncScheduleList.addAll(sl); @@ -407,34 +432,38 @@ private void initLogger(Context c) { final LogUtil jcifs_ng_lu = new LogUtil(c, "SLF4J"); final LogUtil jcifs_old_lu = new LogUtil(c, "JCIFS-V1"); - PrintStream smb1_ps= null; - OutputStream smb1_os=new OutputStream() { + PrintStream smb1_ps = null; + OutputStream smb1_os = new OutputStream() { @Override public void write(int b) throws IOException { byte[] buff = ByteBuffer.allocate(4).putInt(b).array(); + write(buff, 0, buff.length); +// Log.v("SMBSync3",StringUtil.getHexString(buff, 0, 4)); } @Override public void write(byte[] buff) throws IOException { - if (buff.length==1 && buff[0]!=0x0a) { + if (buff.length == 1 && buff[0] != 0x0a) { } else { - String msg=new String(buff,"UTF-8"); - if (!msg.equals("\n") && msg.replaceAll(" ","").length()>0) jcifs_old_lu.addDebugMsg(0,"I",msg); + String msg=new String(buff, StandardCharsets.UTF_8); + if (!msg.equals("\n") && msg.replaceAll(" ", "").length() > 0) jcifs_old_lu.addDebugMsg(0, "I", msg); +// Log.v("SMBSync3",StringUtil.getHexString(buff, 0, buff.length)); } } @Override public void write(byte[] buff, int buff_offset, int buff_length) throws IOException { - if (buff_length==1 && buff[buff_offset]!=0x0a) { + if (buff_length == 1 && buff[buff_offset] != 0x0a) { } else { - String msg=new String(buff,buff_offset,buff_length, "UTF-8"); - if (!msg.equals("\n") && msg.replaceAll(" ","").length()>0) jcifs_old_lu.addDebugMsg(0,"I",msg); + String msg = new String(buff,buff_offset,buff_length, StandardCharsets.UTF_8); + if (!msg.equals("\n") && msg.replaceAll(" ","").length() > 0) jcifs_old_lu.addDebugMsg(0, "I", msg); +// Log.v("SMBSync3",StringUtil.getHexString(buff, buff_offset, buff_length)); } } }; - smb1_ps=new PrintStream(smb1_os); + smb1_ps = new PrintStream(smb1_os); LogStream.setInstance(smb1_ps); - logStream= LogStream.getInstance();//Initial create JCIFS logStream object + logStream = LogStream.getInstance();//Initial create JCIFS logStream object - Slf4jLogWriter jcifs_ng_lw=new Slf4jLogWriter(jcifs_ng_lu); + Slf4jLogWriter jcifs_ng_lw = new Slf4jLogWriter(jcifs_ng_lu); log.setWriter(jcifs_ng_lw); } @@ -451,7 +480,7 @@ public void initStorageStatus(Context c) { public void refreshMediaDir(Context c) { if (safMgr == null) { - Thread th=new Thread(){ + Thread th = new Thread(){ @Override public void run() { safMgr = new SafManager3(c); @@ -477,14 +506,14 @@ public void initSettingsParms(Context c) { } if (!prefs.contains(c.getString(R.string.settings_screen_theme))) - pe.putString(c.getString(R.string.settings_screen_theme), SCREEN_THEME_STANDARD); + pe.putString(c.getString(R.string.settings_screen_theme), SCREEN_THEME_DEFAULT); if (!prefs.contains(c.getString(R.string.settings_notification_message_when_sync_ended))) pe.putString(c.getString(R.string.settings_notification_message_when_sync_ended),NOTIFICATION_MESSAGE_WHEN_SYNC_ENDED_ALWAYS); if (!prefs.contains(c.getString(R.string.settings_vibrate_when_sync_ended))) - pe.putString(c.getString(R.string.settings_vibrate_when_sync_ended),NOTIFICATION_VIBRATE_WHEN_SYNC_ENDED_ALWAYS); + pe.putString(c.getString(R.string.settings_vibrate_when_sync_ended), NOTIFICATION_VIBRATE_WHEN_SYNC_ENDED_ALWAYS); if (!prefs.contains(c.getString(R.string.settings_playback_ringtone_when_sync_ended))) - pe.putString(c.getString(R.string.settings_playback_ringtone_when_sync_ended),NOTIFICATION_SOUND_WHEN_SYNC_ENDED_ALWAYS); + pe.putString(c.getString(R.string.settings_playback_ringtone_when_sync_ended), NOTIFICATION_SOUND_WHEN_SYNC_ENDED_ALWAYS); if (!prefs.contains(c.getString(R.string.settings_playback_ringtone_volume))) pe.putInt(c.getString(R.string.settings_playback_ringtone_volume), 100); @@ -518,6 +547,9 @@ public void initSettingsParms(Context c) { if (!prefs.contains(c.getString(R.string.settings_security_hide_show_zip_passowrd))) pe.putBoolean(c.getString(R.string.settings_security_hide_show_zip_passowrd), false); + if (!prefs.contains(c.getString(R.string.settings_security_app_settings_directory))) + pe.putString(c.getString(R.string.settings_security_app_settings_directory), APP_SETTINGS_DIRECTORY_ROOT); + if (!prefs.contains(c.getString(R.string.settings_wifi_lock))) pe.putBoolean(c.getString(R.string.settings_wifi_lock), true); @@ -528,16 +560,15 @@ public void initSettingsParms(Context c) { pe.putString(c.getString(R.string.settings_screen_theme_language), APPLICATION_LANGUAGE_SETTING_SYSTEM_DEFAULT); if (!prefs.contains(c.getString(R.string.settings_display_font_scale_factor))) - pe.putString(c.getString(R.string.settings_display_font_scale_factor), FONT_SCALE_FACTOR_NORMAL); + pe.putString(c.getString(R.string.settings_display_font_scale_factor), FONT_SCALE_FACTOR_SETTING_DEFAULT); pe.commit(); - } public void loadSettingsParms(Context c) { SharedPreferences prefs = CommonUtilities.getSharedPreference(c); - settingExitClean=prefs.getBoolean(c.getString(R.string.settings_exit_clean), false); + settingExitClean = prefs.getBoolean(c.getString(R.string.settings_exit_clean), false); // settingErrorOption = prefs.getBoolean(c.getString(R.string.settings_error_option), false); settingWifiLockRequired = prefs.getBoolean(c.getString(R.string.settings_wifi_lock), true); @@ -554,12 +585,12 @@ public void loadSettingsParms(Context c) { settingNotificationVibrateWhenSyncEnded = prefs.getString(c.getString(R.string.settings_vibrate_when_sync_ended), NOTIFICATION_VIBRATE_WHEN_SYNC_ENDED_ALWAYS); settingExportedTaskEncryptRequired = prefs.getBoolean(c.getString(R.string.settings_exported_profile_encryption), true); - settingScreenTheme =prefs.getString(c.getString(R.string.settings_screen_theme), SCREEN_THEME_STANDARD); + settingScreenTheme = prefs.getString(c.getString(R.string.settings_screen_theme), SCREEN_THEME_DEFAULT); if (prefs.contains("settings_use_light_theme")) { boolean themeIsLight = prefs.getBoolean("settings_use_light_theme", false); if (themeIsLight) { prefs.edit().remove("settings_use_light_theme").commit(); - settingScreenTheme= SCREEN_THEME_LIGHT; + settingScreenTheme = SCREEN_THEME_LIGHT; prefs.edit().putString(c.getString(R.string.settings_screen_theme), SCREEN_THEME_LIGHT).commit(); } } @@ -568,9 +599,9 @@ public void loadSettingsParms(Context c) { else applicationTheme = R.style.Main; // loadLanguagePreference(c); - setDisplayFontScale(c); + //setDisplayFontScale(c); - settingForceDeviceTabletViewInLandscape = prefs.getBoolean(c.getString(R.string.settings_device_orientation_landscape_tablet), false); + //settingForceDeviceTabletViewInLandscape = prefs.getBoolean(c.getString(R.string.settings_device_orientation_landscape_tablet), false); settingFixDeviceOrientationToPortrait = prefs.getBoolean(c.getString(R.string.settings_device_orientation_portrait), false); @@ -578,7 +609,7 @@ public void loadSettingsParms(Context c) { settingWriteSyncResultLog = prefs.getBoolean(c.getString(R.string.settings_sync_history_log), true); - settingPreventSyncStartDelay =prefs.getBoolean(c.getString(R.string.settings_force_screen_on_while_sync), false); + settingPreventSyncStartDelay = prefs.getBoolean(c.getString(R.string.settings_force_screen_on_while_sync), false); settingSecurityApplicationPasswordHashValue = ApplicationPasswordUtils.getPasswordHashValue(prefs); settingSecurityApplicationPasswordUseAppStartup = prefs.getBoolean(c.getString(R.string.settings_security_application_password_use_app_startup), false); @@ -590,11 +621,32 @@ public void loadSettingsParms(Context c) { settingSecurityHideShowSmbPasswordButton = prefs.getBoolean(c.getString(R.string.settings_security_hide_show_smb_passowrd), false); settingSecurityHideShowZipPasswordButton = prefs.getBoolean(c.getString(R.string.settings_security_hide_show_zip_passowrd), false); - settingScheduleSyncEnabled=prefs.getBoolean(SCHEDULE_ENABLED_KEY, true); + settingSecurityAppSettingsDirectory = prefs.getString(c.getString(R.string.settings_security_app_settings_directory), APP_SETTINGS_DIRECTORY_ROOT); + if (settingSecurityAppSettingsDirectory.equals(APP_SETTINGS_DIRECTORY_ROOT)) { + // Set app settings directory to /data/data/APPLICATION_ID/files + try { + settingAppManagemsntDirectoryName = c.getFilesDir().getCanonicalPath(); + } catch (IOException e) { + e.printStackTrace(); + settingAppManagemsntDirectoryName = "/data/data/"+APPLICATION_ID+"/files"; + } + } else if (settingSecurityAppSettingsDirectory.equals(APP_SETTINGS_DIRECTORY_APP_SPECIFIC_INTERNAL)) { + // Set app settings directory to /storage/emulated/0/Android/data/APPLICATION_ID/files + settingAppManagemsntDirectoryName = SafManager3.getAppSpecificDirectory(c, SafFile3.SAF_FILE_PRIMARY_UUID); + if (settingAppManagemsntDirectoryName == null) { + settingAppManagemsntDirectoryName = SafManager3.getPrimaryStoragePath()+"/Android/data/"+APPLICATION_ID+"/files"; + if (log.isDebugEnabled()) log.debug("loadSettingsParms: SafManager3.getAppSpecificDirectory returns null on primary uid"); + } + } else if (settingSecurityAppSettingsDirectory.equals(APP_SETTINGS_DIRECTORY_STORAGE)) { + // Set app settings directory to /storage/emulated/0/app_name + settingAppManagemsntDirectoryName = SafManager3.getPrimaryStoragePath()+"/"+APPLICATION_TAG; + } + + settingScheduleSyncEnabled = prefs.getBoolean(SCHEDULE_ENABLED_KEY, true); - settingSupressAddExternalStorageNotification= + settingSupressAddExternalStorageNotification = prefs.getBoolean(c.getString(R.string.settings_suppress_add_external_storage_notification), false); - settingSupressStartSyncConfirmationMessage= + settingSupressStartSyncConfirmationMessage = prefs.getBoolean(c.getString(R.string.settings_suppress_start_sync_confirmation_message), false); settingSupressShortcut1ConfirmationMessage = prefs.getBoolean(c.getString(R.string.settings_suppress_shortcut1_confirmation_message), false); @@ -604,6 +656,11 @@ public void loadSettingsParms(Context c) { prefs.getBoolean(c.getString(R.string.settings_suppress_shortcut3_confirmation_message), false); } + public void setDeviceOrientation(final Activity a) { + if (settingFixDeviceOrientationToPortrait) a.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); + else a.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); + } + public void clearApplicationPasswordSetting(Context c) { settingSecurityApplicationPasswordUseAppStartup = false; settingSecurityApplicationPasswordUseEditTask = false; @@ -612,11 +669,11 @@ public void clearApplicationPasswordSetting(Context c) { settingSecurityHideShowSmbPasswordButton = false; settingSecurityHideShowZipPasswordButton = false; - settingSecurityReinitSmbAccountPasswordValue=false; - settingSecurityReinitZipPasswordValue=false; + settingSecurityReinitSmbAccountPasswordValue = false; + settingSecurityReinitZipPasswordValue = false; SharedPreferences prefs = CommonUtilities.getSharedPreference(c); - SharedPreferences.Editor editor=prefs.edit(); + SharedPreferences.Editor editor = prefs.edit(); editor.putBoolean(c.getString(R.string.settings_security_application_password_use_app_startup), settingSecurityApplicationPasswordUseAppStartup); editor.putBoolean(c.getString(R.string.settings_security_application_password_use_edit_task), settingSecurityApplicationPasswordUseEditTask); editor.putBoolean(c.getString(R.string.settings_security_application_password_use_export_task), settingSecurityApplicationPasswordUseExport); @@ -631,56 +688,60 @@ public void clearApplicationPasswordSetting(Context c) { public void setScheduleEnabled(Context c, boolean enabled) { SharedPreferences prefs = CommonUtilities.getSharedPreference(c); - settingScheduleSyncEnabled=enabled; + settingScheduleSyncEnabled = enabled; prefs.edit().putBoolean(SCHEDULE_ENABLED_KEY, enabled).commit(); } - public static final String FONT_SCALE_FACTOR_SMALL="0"; - public static final float FONT_SCALE_FACTOR_SMALL_VALUE=0.8f; - public static final String FONT_SCALE_FACTOR_NORMAL="1"; - public static final float FONT_SCALE_FACTOR_NORMAL_VALUE=1.0f; - public static final String FONT_SCALE_FACTOR_LARGE="2"; - public static final float FONT_SCALE_FACTOR_LARGE_VALUE=1.2f; - public static final String FONT_SCALE_FACTOR_LARGEST="3"; - public static final float FONT_SCALE_FACTOR_LARGEST_VALUE=1.6f; - static public String getFontScaleFactor(Context c) { + //Get current app settings directory value saved in Preferences + public static String getAppManagementDirSetting(Context c) { SharedPreferences prefs = CommonUtilities.getSharedPreference(c); - String fs=prefs.getString(c.getString(R.string.settings_display_font_scale_factor), FONT_SCALE_FACTOR_NORMAL); - return fs; - } - - static public float getFontScaleFactorValue(Context c) { - String fs=getFontScaleFactor(c); - float fs_value=getFontScaleFactorValue(c, fs); - return fs_value; + return prefs.getString(c.getString(R.string.settings_security_app_settings_directory), APP_SETTINGS_DIRECTORY_ROOT); + } + + public static final String FONT_SCALE_FACTOR_SMALL = "0"; + public static final float FONT_SCALE_FACTOR_SMALL_VALUE = 0.8f; + public static final String FONT_SCALE_FACTOR_NORMAL = "1"; + public static final float FONT_SCALE_FACTOR_NORMAL_VALUE = 1.0f; + public static final String FONT_SCALE_FACTOR_LARGE = "2"; + public static final float FONT_SCALE_FACTOR_LARGE_VALUE = 1.2f; + public static final String FONT_SCALE_FACTOR_LARGEST = "3"; + public static final float FONT_SCALE_FACTOR_LARGEST_VALUE = 1.6f; + public static final String FONT_SCALE_FACTOR_SETTING_DEFAULT = FONT_SCALE_FACTOR_NORMAL; + public static final float FONT_SCALE_FACTOR_DEFAULT_VALUE = FONT_SCALE_FACTOR_NORMAL_VALUE; + + //Get font scale saved settings from Preferences + public static String getFontScaleFactorSetting(Context c) { + SharedPreferences prefs = CommonUtilities.getSharedPreference(c); + return prefs.getString(c.getString(R.string.settings_display_font_scale_factor), FONT_SCALE_FACTOR_SETTING_DEFAULT); } - static public float getFontScaleFactorValue(Context c, String fs) { - float fs_value=1.0f; + // Get font scale float value from saved Preferences + public static float getFontScaleFactorValue(Context c) { + String fs=getFontScaleFactorSetting(c); + float fs_value = GlobalParameters.FONT_SCALE_FACTOR_DEFAULT_VALUE; if (fs.equals(GlobalParameters.FONT_SCALE_FACTOR_SMALL)) { - fs_value=FONT_SCALE_FACTOR_SMALL_VALUE; + fs_value = FONT_SCALE_FACTOR_SMALL_VALUE; } else if (fs.equals(GlobalParameters.FONT_SCALE_FACTOR_NORMAL)) { - fs_value=FONT_SCALE_FACTOR_NORMAL_VALUE; + fs_value = FONT_SCALE_FACTOR_NORMAL_VALUE; } else if (fs.equals(GlobalParameters.FONT_SCALE_FACTOR_LARGE)) { - fs_value=FONT_SCALE_FACTOR_LARGE_VALUE; + fs_value = FONT_SCALE_FACTOR_LARGE_VALUE; } else if (fs.equals(GlobalParameters.FONT_SCALE_FACTOR_LARGEST)) { - fs_value=FONT_SCALE_FACTOR_LARGEST_VALUE; + fs_value = FONT_SCALE_FACTOR_LARGEST_VALUE; } - return fs_value; - } - static public void setDisplayFontScale(Context c) { - SharedPreferences prefs = CommonUtilities.getSharedPreference(c); - String fs=prefs.getString(c.getString(R.string.settings_display_font_scale_factor), FONT_SCALE_FACTOR_NORMAL); - setDisplayFontScale(c, fs); + return fs_value; } - static public void setDisplayFontScale(Context c, String fs) { - float fs_value=getFontScaleFactorValue(c, fs); - setDisplayFontScale(c, fs_value); - } + // Return current config, updated with font scale factor from saved preferences + private static Configuration setDisplayFontScaleConfig(Context c) { + float fs = getFontScaleFactorValue(c); // get font scale from saved preferences + Resources res = c.getResources(); + Configuration config = new Configuration(res.getConfiguration()); + config.fontScale = fs; + return config; - static public void setDisplayFontScale(Context c, float scale) { + /* + // Deprecated API < 24 Configuration configuration=c.getResources().getConfiguration(); configuration.fontScale = scale; DisplayMetrics metrics = c.getResources().getDisplayMetrics(); @@ -689,42 +750,41 @@ static public void setDisplayFontScale(Context c, float scale) { wm.getDefaultDisplay().getMetrics(metrics); metrics.scaledDensity = configuration.fontScale * metrics.density; c.getResources().updateConfiguration(configuration, metrics); - + */ } - static public Context setNewLocale(Context c) { - String lc= getLanguageCode(c); + // Returns current context updated with locale from settings Preferences + public static Context setNewLocale(Context c) { + String lc = getLanguageCode(c); //get language code from saved preferences return updateLanguageResources(c, lc); } public static final String APPLICATION_LANGUAGE_SETTING_SYSTEM_DEFAULT = "system"; - - static public String getLanguageCode(Context c) { + // get language code from saved Preferences + public static String getLanguageCode(Context c) { SharedPreferences prefs = CommonUtilities.getSharedPreference(c); - String lc=prefs.getString(c.getString(R.string.settings_screen_theme_language), APPLICATION_LANGUAGE_SETTING_SYSTEM_DEFAULT); - return lc; + return prefs.getString(c.getString(R.string.settings_screen_theme_language), APPLICATION_LANGUAGE_SETTING_SYSTEM_DEFAULT); } // wrap language layout in the base context for all activities - static private Context updateLanguageResources(Context context, String language) { + private static Context updateLanguageResources(Context c, String language) { //if language is set to system default (defined as "0"), do not apply non existing language code "0" and return current context without wrapped language - if (!language.equals(APPLICATION_LANGUAGE_SETTING_SYSTEM_DEFAULT)) { - Locale locale = new Locale(language); - Locale.setDefault(locale); + if (language.equals(APPLICATION_LANGUAGE_SETTING_SYSTEM_DEFAULT)) return c; - Resources res = context.getResources(); - android.content.res.Configuration config = new android.content.res.Configuration(res.getConfiguration()); + Locale locale = new Locale(language); + Locale.setDefault(locale); - setLocaleForApi24(config, locale); - context = context.createConfigurationContext(config); - } - return context; + Resources res = c.getResources(); + Configuration config = new Configuration(res.getConfiguration()); //current config + Configuration newConfig = setLocaleConfigForApi24(config, locale); //apply new locale to current config + + return c.createConfigurationContext(newConfig); } - static private void setLocaleForApi24(android.content.res.Configuration config, Locale target) { + private static Configuration setLocaleConfigForApi24(Configuration config, Locale new_locale) { Set set = new LinkedHashSet<>(); - // bring the target locale to the front of the list - set.add(target); + // bring the new locale to the front of the list + set.add(new_locale); LocaleList all = LocaleList.getDefault(); for (int i = 0; i < all.size(); i++) { @@ -733,36 +793,69 @@ static private void setLocaleForApi24(android.content.res.Configuration config, } Locale[] locales = set.toArray(new Locale[0]); - config.setLocales(new LocaleList(locales)); + + config.setLocales(new LocaleList(locales)); //new config with locale + return config; } -// static public void loadLanguagePreference(Context c) { +// public static void loadLanguagePreference(Context c) { // SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c); // settingApplicationLanguage = prefs.getString(c.getString(R.string.settings_screen_theme_language), APPLICATION_LANGUAGE_SETTING_SYSTEM_DEFAULT); // } + // wrapper called only from attachBaseContext() + // - use as wrapper in attachBaseContext() for all activities and App or extend all App/Activities from a base Activity Class with attachBaseContext() + // - for App: implement also in onConfigurationChanged(), not needed in AppCompatActivity class + // To use updateConfiguration() deprecated method + // - no need to use wrapper in attachBaseContext() + // - all activities and App in AndroidManifest must have: android:configChanges="locale|orientation|screenSize|keyboardHidden|layoutDirection" + public static Context setLocaleAndMetrics(Context c) { + Context newContext = setNewLocale(c); // context with Locale from saved preferences + Configuration config = setDisplayFontScaleConfig(newContext); // config with locale and font scale factor from saved preferences + newContext = newContext.createConfigurationContext(config); // context with new config holding font scale and locale from saved preferences + + return newContext; + } + public boolean isScreenThemeIsLight() { - boolean result=false; - if (settingScreenTheme.equals(SCREEN_THEME_LIGHT)) result = true; - return result; + return settingScreenTheme.equals(SCREEN_THEME_LIGHT); } - final static public String SMB_LM_COMPATIBILITY_DEFAULT="3"; - final static public String SMB_CLIENT_RESPONSE_TIMEOUT_DEFAULT="30000"; - final static public String SMB_USE_EXTENDED_SECURITY_DEFAULT="true"; - final static public String SMB_USE_DISABLE_PLAIN_TEXT_PASSWORD_DEFAULT="false"; + // Get screen theme setting from saved setting Preferences + public static String getScreenTemeSetting(Context c) { + SharedPreferences prefs = CommonUtilities.getSharedPreference(c); + String theme_setting = prefs.getString(c.getString(R.string.settings_screen_theme), SCREEN_THEME_DEFAULT); + if (!theme_setting.equals(SCREEN_THEME_STANDARD) && !theme_setting.equals(SCREEN_THEME_LIGHT) && !theme_setting.equals(SCREEN_THEME_BLACK)) { + if (log.isDebugEnabled()) log.debug("getScreenTemeSetting Error: Invalid preference found: theme_setting=" + theme_setting); + return SCREEN_THEME_DEFAULT; + } + return theme_setting; + } + + // Get screen theme value from saved setting Preferences + public static int getScreenTemeValue(Context c) { + String theme_setting = getScreenTemeSetting(c); + if (theme_setting.equals(SCREEN_THEME_LIGHT)) return R.style.MainLight; + else if (theme_setting.equals(SCREEN_THEME_BLACK)) return R.style.MainBlack; + else return R.style.Main; + } + + final public static String SMB_LM_COMPATIBILITY_DEFAULT = "3"; + final public static String SMB_CLIENT_RESPONSE_TIMEOUT_DEFAULT = "30000"; + final public static String SMB_USE_EXTENDED_SECURITY_DEFAULT = "true"; + final public static String SMB_USE_DISABLE_PLAIN_TEXT_PASSWORD_DEFAULT = "false"; public String settingsSmbLmCompatibility = SMB_LM_COMPATIBILITY_DEFAULT, settingsSmbUseExtendedSecurity = SMB_USE_EXTENDED_SECURITY_DEFAULT, settingsSmbClientResponseTimeout = SMB_CLIENT_RESPONSE_TIMEOUT_DEFAULT, - settingsSmbDisablePlainTextPasswords=SMB_USE_DISABLE_PLAIN_TEXT_PASSWORD_DEFAULT; + settingsSmbDisablePlainTextPasswords = SMB_USE_DISABLE_PLAIN_TEXT_PASSWORD_DEFAULT; final public void initJcifsOption(Context c) { SharedPreferences prefs = CommonUtilities.getSharedPreference(c); settingsSmbLmCompatibility = prefs.getString(c.getString(R.string.settings_smb_lm_compatibility), SMB_LM_COMPATIBILITY_DEFAULT); boolean ues = prefs.getBoolean(c.getString(R.string.settings_smb_use_extended_security), true); - boolean dpp=prefs.getBoolean(c.getString(R.string.settings_smb_disable_plain_text_passwords),false); + boolean dpp = prefs.getBoolean(c.getString(R.string.settings_smb_disable_plain_text_passwords),false); settingsSmbClientResponseTimeout = prefs.getString(c.getString(R.string.settings_smb_client_response_timeout), SMB_CLIENT_RESPONSE_TIMEOUT_DEFAULT); if (settingsSmbLmCompatibility.equals("3") || settingsSmbLmCompatibility.equals("4")) { @@ -773,7 +866,7 @@ final public void initJcifsOption(Context c) { } settingsSmbUseExtendedSecurity = ues ? "true" : "false"; - settingsSmbDisablePlainTextPasswords=dpp ? "true" : "false"; + settingsSmbDisablePlainTextPasswords = dpp ? "true" : "false"; System.setProperty(JCIFS_OPTION_CLIENT_ATTR_EXPIRATION_PERIOD, "0"); System.setProperty(JCIFS_OPTION_NETBIOS_RETRY_TIMEOUT, "3000"); @@ -797,7 +890,7 @@ private boolean isDebuggable(Context c) { } catch (PackageManager.NameNotFoundException e) { result = false; } - if ((appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) == ApplicationInfo.FLAG_DEBUGGABLE) + if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) == ApplicationInfo.FLAG_DEBUGGABLE) result = true; // Log.v("","debuggable="+result); return result; @@ -836,7 +929,7 @@ public void acquireWakeLock(Context c, CommonUtilities util) { util.addDebugMsg(1, "I", "Wifilock acquired"); } } - isScreenOn(c,util); + if ((settingPreventSyncStartDelay)) {// && isScreenOn(c, util))) {// && !activityIsBackground) { if (!mDimWakeLock.isHeld()) { mDimWakeLock.acquire(); @@ -850,14 +943,15 @@ public void acquireWakeLock(Context c, CommonUtilities util) { } } - static public boolean isScreenOn(Context context, CommonUtilities util) { + // not used + public static boolean isScreenOn(Context context, CommonUtilities util) { PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); util.addDebugMsg(1, "I", "isDeviceIdleMode()=" + pm.isDeviceIdleMode() + ", isPowerSaveMode()=" + pm.isPowerSaveMode() + ", isInteractive()=" + pm.isInteractive()); return pm.isInteractive(); } - class Slf4jLogWriter extends LoggerWriter { + static class Slf4jLogWriter extends LoggerWriter { private LogUtil mLu =null; public Slf4jLogWriter(LogUtil lu) { mLu =lu; diff --git a/app/src/main/java/com/sentaroh/android/SMBSync3/GlobalWorkArea.java b/app/src/main/java/com/sentaroh/android/SMBSync3/GlobalWorkArea.java index 392fd085..a8690444 100644 --- a/app/src/main/java/com/sentaroh/android/SMBSync3/GlobalWorkArea.java +++ b/app/src/main/java/com/sentaroh/android/SMBSync3/GlobalWorkArea.java @@ -27,16 +27,16 @@ this software and associated documentation files (the "Software"), to deal import android.os.Looper; public class GlobalWorkArea { - static private GlobalParameters gp=null; - static public GlobalParameters getGlobalParameter(Context c) { - if (gp ==null) { - gp =new GlobalParameters(); + private static GlobalParameters gp = null; + public static GlobalParameters getGlobalParameter(Context c) { + if (gp == null) { + gp = new GlobalParameters(); gp.initGlobalParamter(c); } - if (Looper.myLooper()!=null && gp.uiHandler==null) gp.uiHandler = new Handler(Looper.getMainLooper()); + if (Looper.myLooper()!= null && gp.uiHandler == null) gp.uiHandler = new Handler(Looper.getMainLooper()); return gp; } - static public boolean isGlobalParameterCreated() { - return gp==null?false:true; + public static boolean isGlobalParameterCreated() { + return gp != null; } } diff --git a/app/src/main/java/com/sentaroh/android/SMBSync3/HistoryListAdapter.java b/app/src/main/java/com/sentaroh/android/SMBSync3/HistoryListAdapter.java index 84752920..518f1d76 100644 --- a/app/src/main/java/com/sentaroh/android/SMBSync3/HistoryListAdapter.java +++ b/app/src/main/java/com/sentaroh/android/SMBSync3/HistoryListAdapter.java @@ -212,7 +212,7 @@ public View getView(final int position, View convertView, ViewGroup parent) { if (o != null) { if (!o.sync_task.equals("")) { -// holder.ll_main.setBackgroundDrawable(ll_default); +// holder.ll_main.setBackground(ll_default); holder.tv_seq.setText(String.format("%1$3d", position + 1)); holder.tv_seq.setVisibility(TextView.VISIBLE); diff --git a/app/src/main/java/com/sentaroh/android/SMBSync3/ReadSmbFilelist.java b/app/src/main/java/com/sentaroh/android/SMBSync3/ReadSmbFilelist.java index 806ae0e5..b43650ca 100644 --- a/app/src/main/java/com/sentaroh/android/SMBSync3/ReadSmbFilelist.java +++ b/app/src/main/java/com/sentaroh/android/SMBSync3/ReadSmbFilelist.java @@ -305,6 +305,11 @@ private void readShareList() { JcifsFile remoteFile = new JcifsFile(smbUrl, auth); fl = remoteFile.listFiles(); + try { + remoteFile.close(); + } catch(Exception e) { + mUtil.addDebugMsg(1,"I","close() failed. Error=",e.getMessage()); + } } catch (JcifsException e) { e.printStackTrace(); String cause=""; diff --git a/app/src/main/java/com/sentaroh/android/SMBSync3/SeekBarPreference.java b/app/src/main/java/com/sentaroh/android/SMBSync3/SeekBarPreference.java deleted file mode 100644 index 79245175..00000000 --- a/app/src/main/java/com/sentaroh/android/SMBSync3/SeekBarPreference.java +++ /dev/null @@ -1,105 +0,0 @@ -package com.sentaroh.android.SMBSync3; - -/* -The MIT License (MIT) -Copyright (c) 2020 Sentaroh - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights to use, -copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, -and to permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or -substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, -INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR -PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -OTHER DEALINGS IN THE SOFTWARE. - -*/ - -import android.content.Context; -import android.content.res.TypedArray; -import android.preference.Preference; -import android.util.AttributeSet; -import android.view.View; -import android.widget.SeekBar; -import android.widget.SeekBar.OnSeekBarChangeListener; - -public class SeekBarPreference extends Preference implements OnSeekBarChangeListener { - - private static final int MAX_PROGRESS = 100; - private static final int DEFAULT_PROGRESS = 50; - private int currentProgress; - private int oldProgress; - - public SeekBarPreference(Context context, AttributeSet attrs) { - super(context, attrs); - setWidgetLayoutResource(R.layout.preference_widget_seekbar); - } - - /* - * Preference が 呼び出されるときにデフォルト値が読み込まれる必要がある - * 異なる Preference 型は異なる 値型 は持つはずなので、サブクラスはそれにあわせた型を返す必要がある - */ - @Override - protected Object onGetDefaultValue(TypedArray a, int index) { - return a.getInteger(index, DEFAULT_PROGRESS); - } - - /* - * Preference の初期値を設定する - * restorePersistedValue が true の場合、Preference 値を、SharedPreference からレストアすべき - * false の場合 Preference 値にデフォルト値をセット - * (SharedPreference の shouldPersist() が true の場合、可能ならSharedPreferenceに値を格納) - */ - @Override - protected void onSetInitialValue(boolean restorePersistedValue, Object defaultValue) { - if (restorePersistedValue) { - currentProgress = getPersistedInt(currentProgress); - } else { - currentProgress = (Integer) defaultValue; - persistInt(currentProgress); - } - oldProgress = currentProgress; - } - - /* - * Preference のために、ビューとデータをバインドする - * レイアウトからカスタムビューを参照しプロパティを設定するのに適する - * スーパークラスの実装の呼び出しを確実に行うこと - */ - @Override - protected void onBindView(View view) { - final SeekBar seekbar = (SeekBar) view.findViewById(R.id.pref_seekbar); - if (seekbar != null) { - seekbar.setProgress(currentProgress); - seekbar.setMax(MAX_PROGRESS); - seekbar.setOnSeekBarChangeListener(this); - } - super.onBindView(view); - } - - @Override - public void onStartTrackingTouch(SeekBar seekbar) { - } - - @Override - public void onProgressChanged(SeekBar seekbar, int progress, boolean fromUser) { - } - - @Override - public void onStopTrackingTouch(SeekBar seekbar) { - int progress = seekbar.getProgress(); - /* ユーザーが設定変更を行った後(内部的な値を設定する前)に呼び出す。 */ - currentProgress = (callChangeListener(progress)) ? progress : oldProgress; - - persistInt(currentProgress); - oldProgress = currentProgress; - } -} \ No newline at end of file diff --git a/app/src/main/java/com/sentaroh/android/SMBSync3/SmbServerScanner.java b/app/src/main/java/com/sentaroh/android/SMBSync3/SmbServerScanner.java index 76272336..f4ec2c8e 100644 --- a/app/src/main/java/com/sentaroh/android/SMBSync3/SmbServerScanner.java +++ b/app/src/main/java/com/sentaroh/android/SMBSync3/SmbServerScanner.java @@ -23,13 +23,18 @@ this software and associated documentation files (the "Software"), to deal */ +import static android.view.ViewTreeObserver.*; + import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; +import android.graphics.Rect; import android.os.Handler; import android.os.SystemClock; import android.text.Editable; +import android.text.TextUtils; import android.text.TextWatcher; +import android.text.method.PasswordTransformationMethod; import android.util.SparseBooleanArray; import android.view.LayoutInflater; import android.view.View; @@ -44,10 +49,19 @@ this software and associated documentation files (the "Software"), to deal import android.widget.ListView; import android.widget.RadioButton; import android.widget.RadioGroup; +import android.widget.ScrollView; +import android.widget.Spinner; import android.widget.TextView; -import static com.sentaroh.android.SMBSync3.SmbServerScanner.SmbServerScanResult.*; +import static com.sentaroh.android.SMBSync3.SmbServerScanner.SmbServerScanResult.SMB_STATUS_ACCESS_DENIED; +import static com.sentaroh.android.SMBSync3.SmbServerScanner.SmbServerScanResult.SMB_STATUS_INVALID_LOGON_TYPE; +import static com.sentaroh.android.SMBSync3.SmbServerScanner.SmbServerScanResult.SMB_STATUS_UNKNOWN_ACCOUNT; +import static com.sentaroh.android.SMBSync3.SmbServerScanner.SmbServerScanResult.SMB_STATUS_UNSUCCESSFULL; +import static com.sentaroh.android.SMBSync3.SmbServerScanner.SmbServerScanResult.SMB_STATUS_UNTESTED_LOGIN; + +//import androidx.constraintlayout.widget.ConstraintLayout; +import com.google.android.material.textfield.TextInputLayout; import com.sentaroh.android.JcifsFile2.JcifsAuth; import com.sentaroh.android.JcifsFile2.JcifsException; import com.sentaroh.android.JcifsFile2.JcifsFile; @@ -55,76 +69,129 @@ this software and associated documentation files (the "Software"), to deal import com.sentaroh.android.Utilities3.Dialog.DialogBackKeyListener; import com.sentaroh.android.Utilities3.NotifyEvent; import com.sentaroh.android.Utilities3.ThreadCtrl; +import com.sentaroh.android.Utilities3.Widget.CustomSpinnerAdapter; import java.net.MalformedURLException; import java.util.ArrayList; -import java.util.Collections; import java.util.Comparator; import java.util.Properties; - public class SmbServerScanner { private ActivityMain mActivity=null; private CommonUtilities mUtil=null; private GlobalParameters mGp=null; + // - scanner_smb_protocol: used to set the default smb protocol for the scanner based on an eventual configured server + // + sets library to get hostname (usually, SMB1 and SMB2 libs can detect SMB1/2/3 host names) + // + detects if SMB host is compatible with SMBv1, SMBv2/3 or both + // + leave empty to detect both SMB v1 and v2/3 compatible hosts + // - port_number: ports to scan. If left empty, will scan both default 445 and 139 ports public SmbServerScanner(ActivityMain a, GlobalParameters gp, CommonUtilities cu, final NotifyEvent p_ntfy, - String port_number, boolean scan_start, final String smb_protocol) { + final String port_number, final String scanner_smb_protocol, boolean scan_start) { mActivity=a; mUtil=cu; mGp=gp; - initDialog(p_ntfy, port_number, scan_start, smb_protocol); + initDialog(p_ntfy, port_number, scanner_smb_protocol, scan_start); } - private void initDialog(final NotifyEvent p_ntfy, String port_number, boolean scan_start, final String smb_protocol) { + private SmbServerScanAdapter mAdapter = null; + private final static String SYNC_FOLDER_SMB_PROTOCOL_SMB123 = SyncTaskItem.SYNC_FOLDER_SMB_PROTOCOL_SMB1 + " & " + SyncTaskItem.SYNC_FOLDER_SMB_PROTOCOL_SMB23; + + private void initDialog(final NotifyEvent p_ntfy, final String port_number, final String scanner_smb_protocol, boolean scan_start) { if (!SyncThread.isWifiOn(mActivity)) { mUtil.showCommonDialog(false, "W", mActivity.getString(R.string.msgs_scan_ip_address_select_title), mActivity.getString(R.string.msgs_scan_not_started_because_wifi_off), null); return; } + //カスタムダイアログの生成 final Dialog dialog = new Dialog(mActivity, mGp.applicationTheme); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setCanceledOnTouchOutside(false); dialog.setContentView(R.layout.scan_smb_server_scan_dlg); - LinearLayout ll_dlg_view = (LinearLayout) dialog.findViewById(R.id.scan_remote_ntwk_dlg_view); + //final ConstraintLayout ll_dlg_view = (ConstraintLayout) dialog.findViewById(R.id.scan_remote_ntwk_dlg_view); // ll_dlg_view.setBackgroundColor(mGp.themeColorList.dialog_msg_background_color); - final LinearLayout title_view = (LinearLayout) dialog.findViewById(R.id.scan_smb_server_scan_dlg_title_view); - final TextView title = (TextView) dialog.findViewById(R.id.scan_smb_server_scan_dlg_title); + final LinearLayout title_view = dialog.findViewById(R.id.scan_smb_server_scan_dlg_title_view); + final TextView title = dialog.findViewById(R.id.scan_smb_server_scan_dlg_title); title_view.setBackgroundColor(mGp.themeColorList.title_background_color); title.setTextColor(mGp.themeColorList.title_text_color); - final Button btn_scan = (Button) dialog.findViewById(R.id.scan_smb_server_scan_dlg_btn_ok); - final Button btn_cancel = (Button) dialog.findViewById(R.id.scan_smb_server_scan_dlg_btn_cancel); - final TextView tvmsg = (TextView) dialog.findViewById(R.id.scan_smb_server_scan_dlg_msg); - final TextView tv_result = (TextView) dialog.findViewById(R.id.scan_smb_server_scan_dlg_scan_result_title); + final ScrollView scan_settings_sv = dialog.findViewById(R.id.scan_smb_server_scan_dlg_settings_scroll_view); + scan_settings_sv.setScrollBarFadeDuration(0); + scan_settings_sv.setScrollbarFadingEnabled(false); + + final Button btn_scan = dialog.findViewById(R.id.scan_smb_server_scan_dlg_btn_ok); + final Button btn_cancel = dialog.findViewById(R.id.scan_smb_server_scan_dlg_btn_cancel); + final TextView tvmsg = dialog.findViewById(R.id.scan_smb_server_scan_dlg_msg); + //final TextView tv_result = (TextView) dialog.findViewById(R.id.scan_smb_server_scan_dlg_scan_result_title); tvmsg.setText(mActivity.getString(R.string.msgs_scan_ip_address_press_scan_btn)); - tv_result.setVisibility(TextView.GONE); + //tv_result.setVisibility(TextView.GONE); final String from = CommonUtilities.getIfIpAddress(mUtil).equals("")?"192.168.0.1":CommonUtilities.getIfIpAddress(mUtil); String subnet = from.substring(0, from.lastIndexOf(".")); String subnet_o1, subnet_o2, subnet_o3; subnet_o1 = subnet.substring(0, subnet.indexOf(".")); subnet_o2 = subnet.substring(subnet.indexOf(".") + 1, subnet.lastIndexOf(".")); - subnet_o3 = subnet.substring(subnet.lastIndexOf(".") + 1, subnet.length()); - final EditText baEt1 = (EditText) dialog.findViewById(R.id.scan_smb_server_scan_dlg_begin_address_o1); - final EditText baEt2 = (EditText) dialog.findViewById(R.id.scan_smb_server_scan_dlg_begin_address_o2); - final EditText baEt3 = (EditText) dialog.findViewById(R.id.scan_smb_server_scan_dlg_begin_address_o3); - final EditText baEt4 = (EditText) dialog.findViewById(R.id.scan_smb_server_scan_dlg_begin_address_o4); - final EditText eaEt5 = (EditText) dialog.findViewById(R.id.scan_smb_server_scan_dlg_end_address_o4); + subnet_o3 = subnet.substring(subnet.lastIndexOf(".") + 1); + final EditText baEt1 = dialog.findViewById(R.id.scan_smb_server_scan_dlg_begin_address_o1); + final EditText baEt2 = dialog.findViewById(R.id.scan_smb_server_scan_dlg_begin_address_o2); + final EditText baEt3 = dialog.findViewById(R.id.scan_smb_server_scan_dlg_begin_address_o3); + final EditText baEt4 = dialog.findViewById(R.id.scan_smb_server_scan_dlg_begin_address_o4); + final EditText eaEt5 = dialog.findViewById(R.id.scan_smb_server_scan_dlg_end_address_o4); + + // Debug to start scan on a fixed IP/range 192.168.1.50 -> 50 + //baEt1.setText("192"); + //baEt2.setText("168"); + //baEt3.setText("1"); + //baEt4.setText("50"); + //eaEt5.setText("50"); + baEt1.setText(subnet_o1); baEt2.setText(subnet_o2); baEt3.setText(subnet_o3); baEt4.setText("1"); - baEt4.setSelection(1); - eaEt5.setText("254"); + //baEt4.setSelection(1); baEt4.requestFocus(); + baEt4.setSelection(baEt4.getText().length()); + eaEt5.setText("254"); - final EditText et_port_number = (EditText) dialog.findViewById(R.id.scan_smb_server_scan_dlg_port_number); - + final Spinner dlg_scan_smb_protocol_spinner = dialog.findViewById(R.id.scan_smb_scanner_dlg_smb_protocol_spinner); + dlg_scan_smb_protocol_spinner.setOnItemSelectedListener(null); + CommonUtilities.setSpinnerBackground(mActivity, dlg_scan_smb_protocol_spinner, mGp.isScreenThemeIsLight()); + final CustomSpinnerAdapter smb_level_spinner_adapter = new CustomSpinnerAdapter(mActivity, android.R.layout.simple_spinner_item); + //smb_level_spinner_adapter.setDropDownTextWordwrapEnabled(true); + smb_level_spinner_adapter.setSpinner(dlg_scan_smb_protocol_spinner); + smb_level_spinner_adapter.setDropDownViewResource(android.R.layout.select_dialog_singlechoice); + dlg_scan_smb_protocol_spinner.setPrompt(mActivity.getString(R.string.msgs_scan_dlg_smb_level_spinner_dlg_title)); + dlg_scan_smb_protocol_spinner.setAdapter(smb_level_spinner_adapter); + + smb_level_spinner_adapter.add(SyncTaskItem.SYNC_FOLDER_SMB_PROTOCOL_SMB1); // 0 + smb_level_spinner_adapter.add(SyncTaskItem.SYNC_FOLDER_SMB_PROTOCOL_SMB23); // 1 + smb_level_spinner_adapter.add(SYNC_FOLDER_SMB_PROTOCOL_SMB123); // 2 + + if (scanner_smb_protocol.equals(SyncTaskItem.SYNC_FOLDER_SMB_PROTOCOL_SMB1)) dlg_scan_smb_protocol_spinner.setSelection(0); + else if (scanner_smb_protocol.equals(SyncTaskItem.SYNC_FOLDER_SMB_PROTOCOL_SMB23)) dlg_scan_smb_protocol_spinner.setSelection(1); + else dlg_scan_smb_protocol_spinner.setSelection(2); + + final EditText et_port_number = dialog.findViewById(R.id.scan_smb_server_scan_dlg_port_number); + if (port_number.isEmpty() || TextUtils.isDigitsOnly(port_number)) { + et_port_number.setText(port_number); + } else { + et_port_number.setText(""); + } +/* + et_port_number.addTextChangedListener(new TextWatcher() { + @Override + public void beforeTextChanged(CharSequence s, int start, int count, int after) {} + @Override + public void onTextChanged(CharSequence s, int start, int before, int count) {} + @Override + public void afterTextChanged(Editable s) {} + }); +*/ CommonDialog.setDlgBoxSizeLimit(dialog, true); final NotifyEvent ntfy_lv_click = new NotifyEvent(mActivity); @@ -147,11 +214,8 @@ public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {} @Override public void afterTextChanged(Editable editable) { - if (isValidScanAddress(dialog)) { - CommonUtilities.setViewEnabled(mActivity, btn_scan, true); - } else { - CommonUtilities.setViewEnabled(mActivity, btn_scan, false); - } + CommonUtilities.setViewEnabled(mActivity, btn_scan, isValidScanAddress(dialog)); + setDialogTitleOffscreenColor(title, tvmsg, scan_settings_sv, mGp.themeColorList.title_text_color, mGp.themeColorList.text_color_error); } }); @@ -162,11 +226,8 @@ public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {} @Override public void afterTextChanged(Editable editable) { - if (isValidScanAddress(dialog)) { - CommonUtilities.setViewEnabled(mActivity, btn_scan, true); - } else { - CommonUtilities.setViewEnabled(mActivity, btn_scan, false); - } + CommonUtilities.setViewEnabled(mActivity, btn_scan, isValidScanAddress(dialog)); + setDialogTitleOffscreenColor(title, tvmsg, scan_settings_sv, mGp.themeColorList.title_text_color, mGp.themeColorList.text_color_error); } }); @@ -177,11 +238,8 @@ public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {} @Override public void afterTextChanged(Editable editable) { - if (isValidScanAddress(dialog)) { - CommonUtilities.setViewEnabled(mActivity, btn_scan, true); - } else { - CommonUtilities.setViewEnabled(mActivity, btn_scan, false); - } + CommonUtilities.setViewEnabled(mActivity, btn_scan, isValidScanAddress(dialog)); + setDialogTitleOffscreenColor(title, tvmsg, scan_settings_sv, mGp.themeColorList.title_text_color, mGp.themeColorList.text_color_error); } }); @@ -192,11 +250,8 @@ public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {} @Override public void afterTextChanged(Editable editable) { - if (isValidScanAddress(dialog)) { - CommonUtilities.setViewEnabled(mActivity, btn_scan, true); - } else { - CommonUtilities.setViewEnabled(mActivity, btn_scan, false); - } + CommonUtilities.setViewEnabled(mActivity, btn_scan, isValidScanAddress(dialog)); + setDialogTitleOffscreenColor(title, tvmsg, scan_settings_sv, mGp.themeColorList.title_text_color, mGp.themeColorList.text_color_error); } }); @@ -207,23 +262,24 @@ public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {} @Override public void afterTextChanged(Editable editable) { - if (isValidScanAddress(dialog)) { - CommonUtilities.setViewEnabled(mActivity, btn_scan, true); - } else { - CommonUtilities.setViewEnabled(mActivity, btn_scan, false); - } + CommonUtilities.setViewEnabled(mActivity, btn_scan, isValidScanAddress(dialog)); + setDialogTitleOffscreenColor(title, tvmsg, scan_settings_sv, mGp.themeColorList.title_text_color, mGp.themeColorList.text_color_error); + } + }); + + scan_settings_sv.setOnScrollChangeListener(new View.OnScrollChangeListener() { + @Override + public void onScrollChange(View view, int i, int i1, int i2, int i3) { + setDialogTitleOffscreenColor(title, tvmsg, scan_settings_sv, mGp.themeColorList.title_text_color, mGp.themeColorList.text_color_error); } }); CommonUtilities.setViewEnabled(mActivity, btn_scan, true); - tvmsg.setText(""); - final ListView lv = (ListView) dialog.findViewById(R.id.scan_smb_server_scan_dlg_scan_result_list); - final SmbServerScanAdapter adap = new SmbServerScanAdapter - (mActivity, R.layout.scan_address_result_list_item, mScanResultList, ntfy_lv_click); - lv.setAdapter(adap); + final ListView lv = dialog.findViewById(R.id.scan_smb_server_scan_dlg_scan_result_list); lv.setScrollingCacheEnabled(false); - lv.setScrollbarFadingEnabled(false); + //lv.setScrollbarFadingEnabled(false); + lv.setScrollBarFadeDuration(0); lv.setEnabled(false); lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { @@ -239,22 +295,32 @@ public void onItemClick(AdapterView adapterView, View view, int i, long l) { public void onClick(View v) { tvmsg.setText(""); mScanResultList.clear(); + + // On next scan start, ensure we cannot click search results while scan is running, thus dismissing the dialog + // The scan thread would then continue to run in the background until it is completed + lv.setEnabled(false); + NotifyEvent ntfy = new NotifyEvent(mActivity); ntfy.setListener(new NotifyEvent.NotifyEventListener() { @Override public void positiveResponse(Context c, Object[] o) { + //mAdapter.notifyDataSetChanged(); + //mAdapter.sort(); lv.setEnabled(true); if (!mScanSmbErrorMessage.equals("")) { tvmsg.setText(mScanSmbErrorMessage); } else { if (mScanResultList.size() < 1) { tvmsg.setText(mActivity.getString(R.string.msgs_scan_ip_address_not_detected)); - tv_result.setVisibility(TextView.GONE); + //tv_result.setVisibility(TextView.GONE); } else { tvmsg.setText(mActivity.getString(R.string.msgs_scan_ip_address_select_detected_host)); - tv_result.setVisibility(TextView.VISIBLE); + //tv_result.setVisibility(TextView.VISIBLE); } } + moveScrollViewToTop(scan_settings_sv); + // Set color not needed since moveScrollViewToTop() triggers scan_settings_sv.setOnScrollChangeListener() + //setDialogTitleOffscreenColor(title, tvmsg, scan_settings_sv, mGp.themeColorList.title_text_color, mGp.themeColorList.text_color_error); } @Override @@ -262,7 +328,7 @@ public void negativeResponse(Context c, Object[] o) { } }); - tv_result.setVisibility(TextView.GONE); + //tv_result.setVisibility(TextView.GONE); String ba1 = baEt1.getText().toString(); String ba2 = baEt2.getText().toString(); String ba3 = baEt3.getText().toString(); @@ -271,7 +337,24 @@ public void negativeResponse(Context c, Object[] o) { String subnet = ba1 + "." + ba2 + "." + ba3; int begin_addr = Integer.parseInt(ba4); int end_addr = Integer.parseInt(ea5); - performSmbServerScan(dialog, lv, adap, subnet, begin_addr, end_addr, ntfy, smb_protocol); + + String scan_smb_level = getSmbSelectedProtocol(dlg_scan_smb_protocol_spinner); + boolean scan_smbv1 = false; + boolean scan_smbv23 = false; + if (scan_smb_level.equals(SyncTaskItem.SYNC_FOLDER_SMB_PROTOCOL_SMB1)) { + scan_smbv1 = true; + } else if (scan_smb_level.equals(SyncTaskItem.SYNC_FOLDER_SMB_PROTOCOL_SMB23)) { + scan_smbv23 = true; + } else { + // default scan for both protocols (not used currently during refresh shares, only radio buttons for SMBv1 and SMBv2/3 are provided) + scan_smbv1 = true; + scan_smbv23 = true; + } + + mAdapter = new SmbServerScanAdapter(mActivity, R.layout.scan_address_result_list_item, mScanResultList, ntfy_lv_click); + lv.setAdapter(mAdapter); + + performSmbServerScan(dialog, lv, subnet, begin_addr, end_addr, scan_smbv1, scan_smbv23, ntfy); } }); @@ -282,6 +365,7 @@ public void onClick(View v) { p_ntfy.notifyToListener(false, null); } }); + // Cancelリスナーの指定 dialog.setOnCancelListener(new Dialog.OnCancelListener() { @Override @@ -294,38 +378,48 @@ public void onCancel(DialogInterface arg0) { if (scan_start) btn_scan.performClick(); } - private void buildSmbServerParmsDlg(final SmbServerScanResult scan_result, final NotifyEvent p_ntfy) { + private ArrayAdaptermServerSharesListAdapter = null; + // called by initDialog() on server selected from scan results list view + private void buildSmbServerParmsDlg(SmbServerScanResult scan_result, final NotifyEvent p_ntfy) { final Dialog dialog=new Dialog(mActivity); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(R.layout.scan_smb_server_parm_dlg); - final LinearLayout ll_title=(LinearLayout) dialog.findViewById(R.id.scan_smb_server_parm_dlg_title_view); + final LinearLayout ll_title= dialog.findViewById(R.id.scan_smb_server_parm_dlg_title_view); ll_title.setBackgroundColor(mGp.themeColorList.title_background_color); - final TextView tv_title=(TextView)dialog.findViewById(R.id.scan_smb_server_parm_dlg_title); + final TextView tv_title= dialog.findViewById(R.id.scan_smb_server_parm_dlg_title); tv_title.setTextColor(mGp.themeColorList.title_text_color); - final TextView dlg_msg=(TextView)dialog.findViewById(R.id.scan_smb_server_parm_dlg_msg); - final RadioGroup dlg_smb_host_rg=(RadioGroup)dialog.findViewById(R.id.scan_smb_server_parm_dlg_smb_server_id_rg); - final RadioButton dlg_use_ip_addr=(RadioButton)dialog.findViewById(R.id.scan_smb_server_parm_dlg_smb_server_id_address); - final RadioButton dlg_use_host_name=(RadioButton)dialog.findViewById(R.id.scan_smb_server_parm_dlg_smb_server_id_hostname); - final TextView dlg_smb_host_selcted=(TextView)dialog.findViewById(R.id.scan_smb_server_parm_dlg_smb_server_selected); - final RadioButton dlg_use_smb1=(RadioButton)dialog.findViewById(R.id.scan_smb_server_parm_dlg_smb_server_smb_protocol_smb1); - final RadioButton dlg_use_smb23=(RadioButton)dialog.findViewById(R.id.scan_smb_server_parm_dlg_smb_server_smb_protocol_smb23); - final EditText dlg_smb_port_number=(EditText)dialog.findViewById(R.id.scan_smb_server_parm_dlg_smb_server_port_number); - final EditText dlg_smb_account_name=(EditText)dialog.findViewById(R.id.scan_smb_server_parm_dlg_smb_server_account_name); - final EditText dlg_smb_account_password=(EditText)dialog.findViewById(R.id.scan_smb_server_parm_dlg_smb_server_account_password); - final LinearLayout ll_dlg_smb_share_name=(LinearLayout) dialog.findViewById(R.id.scan_smb_server_parm_dlg_smb_server_share_view); - final ListView dlg_smb_share_name=(ListView)dialog.findViewById(R.id.scan_smb_server_parm_dlg_smb_server_share_name); - + final TextView dlg_msg= dialog.findViewById(R.id.scan_smb_server_parm_dlg_msg); + + final ScrollView server_settings_sv = dialog.findViewById(R.id.scan_smb_server_param_dlg_settings_scroll_view); + server_settings_sv.setScrollBarFadeDuration(0); + server_settings_sv.setScrollbarFadingEnabled(false); + + final RadioGroup dlg_smb_host_rg= dialog.findViewById(R.id.scan_smb_server_parm_dlg_smb_server_id_rg); + final RadioButton dlg_use_ip_addr= dialog.findViewById(R.id.scan_smb_server_parm_dlg_smb_server_id_address); + final RadioButton dlg_use_host_name= dialog.findViewById(R.id.scan_smb_server_parm_dlg_smb_server_id_hostname); + final TextView dlg_smb_host_selcted= dialog.findViewById(R.id.scan_smb_server_parm_dlg_smb_server_selected); + final RadioButton dlg_use_smb1= dialog.findViewById(R.id.scan_smb_server_parm_dlg_smb_server_smb_protocol_smb1); + final RadioButton dlg_use_smb23= dialog.findViewById(R.id.scan_smb_server_parm_dlg_smb_server_smb_protocol_smb23); + final EditText dlg_smb_port_number= dialog.findViewById(R.id.scan_smb_server_parm_dlg_smb_server_port_number); + final EditText dlg_smb_account_name= dialog.findViewById(R.id.scan_smb_server_parm_dlg_smb_server_account_name); + final EditText dlg_smb_account_password= dialog.findViewById(R.id.scan_smb_server_parm_dlg_smb_server_account_password); + //final LinearLayout ll_dlg_smb_share_name=(LinearLayout) dialog.findViewById(R.id.scan_smb_server_parm_dlg_smb_server_share_view); + + final ListView dlg_smb_shares_lv= dialog.findViewById(R.id.scan_smb_server_parm_dlg_smb_server_share_name); + //dlg_smb_shares_lv.setScrollbarFadingEnabled(false); + dlg_smb_shares_lv.setScrollBarFadeDuration(0); + final ArrayList share_name_list=new ArrayList(); - final ArrayAdaptershare_list_adapter=new ArrayAdapter(mActivity, android.R.layout.simple_list_item_single_choice, share_name_list); - dlg_smb_share_name.setChoiceMode(ListView.CHOICE_MODE_SINGLE); - dlg_smb_share_name.setAdapter(share_list_adapter); + mServerSharesListAdapter=new ArrayAdapter(mActivity, android.R.layout.simple_list_item_single_choice, share_name_list); + dlg_smb_shares_lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE); + dlg_smb_shares_lv.setAdapter(mServerSharesListAdapter); - final Button btn_refresh=(Button)dialog.findViewById(R.id.scan_smb_server_parm_dlg_btn_refresh_share_list); + final Button btn_refresh= dialog.findViewById(R.id.scan_smb_server_parm_dlg_btn_refresh_share_list); - final Button btn_ok=(Button)dialog.findViewById(R.id.scan_smb_server_parm_dlg_btn_ok); + final Button btn_ok= dialog.findViewById(R.id.scan_smb_server_parm_dlg_btn_ok); CommonUtilities.setViewEnabled(mActivity, btn_ok, false); - final Button btn_cancel=(Button)dialog.findViewById(R.id.scan_smb_server_parm_dlg_btn_cancel); + final Button btn_cancel= dialog.findViewById(R.id.scan_smb_server_parm_dlg_btn_cancel); CommonDialog.setDlgBoxSizeLimit(dialog,true); @@ -342,21 +436,21 @@ public void onCheckedChanged(RadioGroup radioGroup, int i) { } }); + // After scan result, enable the SMB Level radio button only for the available protocols found during scan + // Normally, if no SMB level protocol was found, the server cannot be selected and we should'nt have a situation + // where both SMB level radio buttons are unchecked and disabled. However, we account for this situation + dlg_use_smb23.setChecked(scan_result.smb23_available); + if (!scan_result.smb23_available) dlg_use_smb1.setChecked(scan_result.smb1_available); - if (scan_result.smb23_available) dlg_use_smb23.setChecked(true); - else { - if (scan_result.smb1_available) { - CommonUtilities.setViewEnabled(mActivity, dlg_use_smb1, true); - dlg_use_smb1.setChecked(true); - } - if (!scan_result.smb23_available) CommonUtilities.setViewEnabled(mActivity, dlg_use_smb23, false); - } - buildShareListSelectorView(dialog, scan_result, share_list_adapter); + dlg_smb_port_number.setText(scan_result.server_smb_port_number); + + buildShareListSelectorView(false, dialog, scan_result); CommonUtilities.setViewEnabled(mActivity, btn_ok, false); - dlg_smb_share_name.setOnItemClickListener(new AdapterView.OnItemClickListener() { + + dlg_smb_shares_lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView adapterView, View view, int i, long l) { - dlg_msg.setText(""); + buildShareListSelectorView(true, dialog, scan_result); CommonUtilities.setViewEnabled(mActivity, btn_ok, true); } }); @@ -365,8 +459,11 @@ public void onItemClick(AdapterView adapterView, View view, int i, long l) { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { dlg_use_smb23.setChecked(!b); + scan_result.share_item_list.clear(); + scan_result.smb1_nt_status_desc = SMB_STATUS_UNTESTED_LOGIN; + scan_result.smb23_nt_status_desc = SMB_STATUS_UNTESTED_LOGIN; + buildShareListSelectorView(false, dialog, scan_result); CommonUtilities.setViewEnabled(mActivity, btn_ok, false); - buildShareListSelectorView(dialog, scan_result, share_list_adapter); } }); @@ -374,8 +471,91 @@ public void onCheckedChanged(CompoundButton compoundButton, boolean b) { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { dlg_use_smb1.setChecked(!b); + scan_result.share_item_list.clear(); + scan_result.smb1_nt_status_desc = SMB_STATUS_UNTESTED_LOGIN; + scan_result.smb23_nt_status_desc = SMB_STATUS_UNTESTED_LOGIN; + buildShareListSelectorView(false, dialog, scan_result); CommonUtilities.setViewEnabled(mActivity, btn_ok, false); - buildShareListSelectorView(dialog, scan_result, share_list_adapter); + } + }); + + dlg_smb_port_number.addTextChangedListener(new TextWatcher() { + @Override + public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {} + + @Override + public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {} + + @Override + public void afterTextChanged(Editable s) { + scan_result.share_item_list.clear(); + scan_result.smb1_nt_status_desc = SMB_STATUS_UNTESTED_LOGIN; + scan_result.smb23_nt_status_desc = SMB_STATUS_UNTESTED_LOGIN; + buildShareListSelectorView(false, dialog, scan_result); + CommonUtilities.setViewEnabled(mActivity, btn_ok, false); + } + }); + + dlg_smb_account_name.addTextChangedListener(new TextWatcher() { + @Override + public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {} + + @Override + public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {} + + @Override + public void afterTextChanged(Editable s) { + scan_result.share_item_list.clear(); + scan_result.smb1_nt_status_desc = SMB_STATUS_UNTESTED_LOGIN; + scan_result.smb23_nt_status_desc = SMB_STATUS_UNTESTED_LOGIN; + buildShareListSelectorView(false, dialog, scan_result); + CommonUtilities.setViewEnabled(mActivity, btn_ok, false); + } + }); + + // Thread control to not trigger dlg_smb_account_password.addTextChangedListener.afterTextChanged() + // when we only click the end eye icon to show/hide password + final ThreadCtrl tc = new ThreadCtrl(); + tc.setDisabled(); // ThreadCtrl is enabled by default ! + dlg_smb_account_password.addTextChangedListener(new TextWatcher() { + @Override + public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {} + + @Override + public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {} + + @Override + public void afterTextChanged(Editable s) { + if (!tc.isEnabled()) { + scan_result.share_item_list.clear(); + scan_result.smb1_nt_status_desc = SMB_STATUS_UNTESTED_LOGIN; + scan_result.smb23_nt_status_desc = SMB_STATUS_UNTESTED_LOGIN; + buildShareListSelectorView(false, dialog, scan_result); + CommonUtilities.setViewEnabled(mActivity, btn_ok, false); + } + } + }); + + // override hide/show password onclick of end eye icon so that it doesn't trigger dlg_smb_account_password.addTextChangedListener.afterTextChanged() + final TextInputLayout til_smb_account_password = dialog.findViewById(R.id.scan_smb_server_parm_dlg_smb_server_account_password_view); + til_smb_account_password.setEndIconOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + tc.setEnabled(); + tc.setThreadResultSuccess(); + if (dlg_smb_account_password.getTransformationMethod()!=null) { + dlg_smb_account_password.setTransformationMethod(null); + } else { + dlg_smb_account_password.setTransformationMethod(new PasswordTransformationMethod()); + } + tc.setDisabled(); + } + }); + + server_settings_sv.setOnScrollChangeListener(new View.OnScrollChangeListener() { + @Override + public void onScrollChange(View view, int i, int i1, int i2, int i3) { + setDialogTitleOffscreenColor(tv_title, dlg_msg, server_settings_sv, mGp.themeColorList.title_text_color, mGp.themeColorList.text_color_error); } }); @@ -385,39 +565,32 @@ public void onClick(View view) { final NotifyEvent ntfy=new NotifyEvent(mActivity); ntfy.setListener(new NotifyEvent.NotifyEventListener() { @Override - public void positiveResponse(Context context, Object[] objects) { - buildShareListSelectorView(dialog, scan_result, share_list_adapter); - CommonUtilities.setViewEnabled(mActivity, btn_ok, false); - } - - @Override - public void negativeResponse(Context context, Object[] objects) { - - } - }); - final Handler hndl=new Handler(); - final String acct=dlg_smb_account_name.getText().toString().equals("")?null:dlg_smb_account_name.getText().toString(); - final String pswd=dlg_smb_account_password.getText().toString().equals("")?null:dlg_smb_account_password.getText().toString(); - Thread th=new Thread(){ - @Override - public void run() { - SmbServerScanResult result= createSmbServerShareInfo(null, acct, pswd, - scan_result.server_smb_ip_addr, scan_result.server_smb_name); + public void positiveResponse(Context context, Object[] arg1) { + SmbServerScanResult result = (SmbServerScanResult) arg1[0]; scan_result.smb1_nt_status_desc=result.smb1_nt_status_desc; scan_result.smb1_available=result.smb1_available; scan_result.smb23_nt_status_desc=result.smb23_nt_status_desc; scan_result.smb23_available=result.smb23_available; + // Port num did not change on return result + //scan_result.server_smb_port_number=result.server_smb_port_number; + //dlg_smb_port_number.setText(scan_result.server_smb_port_number); scan_result.share_item_list.clear(); scan_result.share_item_list.addAll(result.share_item_list); - hndl.post(new Runnable() { - @Override - public void run() { - ntfy.notifyToListener(true, null); - } - }); + + buildShareListSelectorView(false, dialog, scan_result); + CommonUtilities.setViewEnabled(mActivity, btn_ok, false); + + //moveScrollViewToTop(server_settings_sv); } - }; - th.start(); + + @Override + public void negativeResponse(Context context, Object[] objects) {} + }); + final String acct=dlg_smb_account_name.getText().toString().equals("")?null:dlg_smb_account_name.getText().toString(); + final String pswd=dlg_smb_account_password.getText().toString().equals("")?null:dlg_smb_account_password.getText().toString(); + final String port=dlg_smb_port_number.getText().toString(); + final String smb_level=dlg_use_smb1.isChecked()? SyncTaskItem.SYNC_FOLDER_SMB_PROTOCOL_SMB1:SyncTaskItem.SYNC_FOLDER_SMB_PROTOCOL_SMB23; + createSmbServerShareInfo(ntfy, smb_level, null, acct, pswd, scan_result.server_smb_ip_addr, scan_result.server_smb_name, port); } }); @@ -425,15 +598,15 @@ public void run() { @Override public void onClick(View view) { String smb_host=dlg_use_ip_addr.isChecked()?scan_result.server_smb_ip_addr:scan_result.server_smb_name; - String smb_level=dlg_use_smb1.isChecked()?SMB_LEVEL_SMB1: SmbServerScanResult.SMB_LEVEL_SMB23; + String smb_level=dlg_use_smb1.isChecked()? SyncTaskItem.SYNC_FOLDER_SMB_PROTOCOL_SMB1:SyncTaskItem.SYNC_FOLDER_SMB_PROTOCOL_SMB23; String smb_portnum=dlg_smb_port_number.getText().toString(); String smb_acct_name=dlg_smb_account_name.getText().toString(); String smb_acct_pswd=dlg_smb_account_password.getText().toString(); String smb_share_name=share_name_list.get(0); - SparseBooleanArray checked = dlg_smb_share_name.getCheckedItemPositions(); + SparseBooleanArray checked = dlg_smb_shares_lv.getCheckedItemPositions(); for (int i = 0; i <= share_name_list.size(); i++) { - if (checked.get(i) == true) { + if (checked.get(i)) { smb_share_name=share_name_list.get(i); break; } @@ -447,6 +620,7 @@ public void onClick(View view) { btn_cancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { + p_ntfy.notifyToListener(false, null); dialog.dismiss(); } }); @@ -454,6 +628,44 @@ public void onClick(View view) { dialog.show(); } + // If the warning message is out of the screen in ScrollView, set the dialog title color to red + private void setDialogTitleOffscreenColor(TextView tv_title, TextView dlg_msg, ScrollView sv, int color_msg_inscreen, int color_msg_offscreen) { + Rect rect = new Rect(); + sv.getHitRect(rect); + boolean msg_visible = dlg_msg.getLocalVisibleRect(rect); + if (dlg_msg.getText().length() != 0 && !msg_visible) { + tv_title.setTextColor(color_msg_offscreen); + } else { + tv_title.setTextColor(color_msg_inscreen); + } + } + + // ScrollView needs to be invalidated first to ensure it is not cached + // else, if view content did not change, it won't scroll + // A post delayed runnable is needed as even with the listener, can sometimes trigger before the ScrollView + // is completely drawn to screen and the scroll to top fails + private void moveScrollViewToTop(ScrollView sv) { + sv.invalidate(); + sv.requestLayout(); + sv.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() { + @Override + public void onGlobalLayout() { + // Ready, move up + final OnGlobalLayoutListener gl = this; + Handler hndl = new Handler(); + hndl.postDelayed(new Runnable() { + @Override + public void run() { + //sv.fullScroll(View.FOCUS_UP); + sv.smoothScrollTo(0,0); + //sv.scrollTo(0,0); + sv.getViewTreeObserver().removeOnGlobalLayoutListener(gl); + } + }, 100); + } + }); + } + // private void scanSmbServerEnableSmbScanSelectorOkButton(Dialog dialog) { // final TextView dlg_msg=(TextView)dialog.findViewById(R.id.scan_smb_server_parm_dlg_msg); // final Button btn_ok=(Button)dialog.findViewById(R.id.scan_smb_server_parm_dlg_btn_ok); @@ -462,96 +674,198 @@ public void onClick(View view) { // else CommonUtilities.setViewEnabled(mActivity, btn_ok, true); // } - private void buildShareListSelectorView(Dialog dialog, SmbServerScanResult scan_result, ArrayAdapter adapter) { - final TextView dlg_msg=(TextView)dialog.findViewById(R.id.scan_smb_server_parm_dlg_msg); - final RadioButton dlg_use_smb1=(RadioButton)dialog.findViewById(R.id.scan_smb_server_parm_dlg_smb_server_smb_protocol_smb1); - final RadioButton dlg_use_smb23=(RadioButton)dialog.findViewById(R.id.scan_smb_server_parm_dlg_smb_server_smb_protocol_smb23); - final LinearLayout ll_dlg_smb_share_name=(LinearLayout) dialog.findViewById(R.id.scan_smb_server_parm_dlg_smb_server_share_view); - final ListView dlg_smb_share_name=(ListView)dialog.findViewById(R.id.scan_smb_server_parm_dlg_smb_server_share_name); - adapter.clear(); - dlg_smb_share_name.setAdapter(null); - boolean share_added=false; + private void buildShareListSelectorView(final boolean select_share, Dialog dialog, SmbServerScanResult scan_result) { + final TextView tv_title= dialog.findViewById(R.id.scan_smb_server_parm_dlg_title); + final TextView dlg_msg= dialog.findViewById(R.id.scan_smb_server_parm_dlg_msg); + final ScrollView server_settings_sv = dialog.findViewById(R.id.scan_smb_server_param_dlg_settings_scroll_view); + final RadioButton dlg_use_ip_addr= dialog.findViewById(R.id.scan_smb_server_parm_dlg_smb_server_id_address); + final RadioButton dlg_use_host_name= dialog.findViewById(R.id.scan_smb_server_parm_dlg_smb_server_id_hostname); + final RadioButton dlg_use_smb1= dialog.findViewById(R.id.scan_smb_server_parm_dlg_smb_server_smb_protocol_smb1); + final RadioButton dlg_use_smb23= dialog.findViewById(R.id.scan_smb_server_parm_dlg_smb_server_smb_protocol_smb23); + final EditText dlg_smb_port_number= dialog.findViewById(R.id.scan_smb_server_parm_dlg_smb_server_port_number); + final EditText dlg_smb_account_name= dialog.findViewById(R.id.scan_smb_server_parm_dlg_smb_server_account_name); + final EditText dlg_smb_account_password= dialog.findViewById(R.id.scan_smb_server_parm_dlg_smb_server_account_password); + final TextInputLayout til_smb_account_password = dialog.findViewById(R.id.scan_smb_server_parm_dlg_smb_server_account_password_view); + final Button btn_refresh= dialog.findViewById(R.id.scan_smb_server_parm_dlg_btn_refresh_share_list); + final LinearLayout ll_dlg_smb_share_name= dialog.findViewById(R.id.scan_smb_server_parm_dlg_smb_server_share_view); + final ListView dlg_smb_shares_lv= dialog.findViewById(R.id.scan_smb_server_parm_dlg_smb_server_share_name); + final Button btn_ok= dialog.findViewById(R.id.scan_smb_server_parm_dlg_btn_ok); + + String original_info_msg = dlg_msg.getText().toString(); + + final String nt_status_desc; + String smb_level = ""; + CommonUtilities.setViewEnabled(mActivity, dlg_use_smb1, scan_result.smb1_available); + CommonUtilities.setViewEnabled(mActivity, dlg_use_smb23, scan_result.smb23_available); if (dlg_use_smb1.isChecked()) { - updateShareListSelectorAdapter(dialog, SMB_LEVEL_SMB1, dlg_msg, adapter, scan_result.smb1_nt_status_desc, scan_result.share_item_list); + nt_status_desc = scan_result.smb1_nt_status_desc; + smb_level = SyncTaskItem.SYNC_FOLDER_SMB_PROTOCOL_SMB1; + } else if (dlg_use_smb23.isChecked()) { + nt_status_desc = scan_result.smb23_nt_status_desc; + smb_level = SyncTaskItem.SYNC_FOLDER_SMB_PROTOCOL_SMB23; } else { - updateShareListSelectorAdapter(dialog, SMB_LEVEL_SMB23, dlg_msg, adapter, scan_result.smb23_nt_status_desc, scan_result.share_item_list); + // Normally, if no SMB level protocol was found, the server cannot be selected and we should'nt have a situation + // where both SMB level radio buttons are unchecked and disabled. However, we account for this situation + nt_status_desc = ""; + dlg_msg.setText(mActivity.getString(R.string.msgs_task_edit_sync_folder_dlg_edit_smb_server_parm_no_smb_level_error)); + + //server_settings_sv.setVisibility(ScrollView.GONE); + CommonUtilities.setViewEnabled(mActivity, server_settings_sv, false); + CommonUtilities.setViewEnabled(mActivity, dlg_use_ip_addr, false); + CommonUtilities.setViewEnabled(mActivity, dlg_use_host_name, false); + CommonUtilities.setViewEnabled(mActivity, dlg_use_smb1, false); + CommonUtilities.setViewEnabled(mActivity, dlg_use_smb23, false); + CommonUtilities.setViewEnabled(mActivity, dlg_smb_port_number, false); + CommonUtilities.setViewEnabled(mActivity, dlg_smb_account_name, false); + //CommonUtilities.setViewEnabled(mActivity, dlg_smb_account_password, false); + CommonUtilities.setViewEnabled(mActivity, til_smb_account_password, false); + CommonUtilities.setViewEnabled(mActivity, btn_refresh, false); + + ll_dlg_smb_share_name.setVisibility(LinearLayout.GONE); + + CommonUtilities.setViewEnabled(mActivity, btn_ok, false); + + mUtil.addDebugMsg(1, "E", "buildShareListSelectorView Exception: No SMB level enabled. address="+scan_result.server_smb_ip_addr + " , port="+scan_result.server_smb_port_number + + " , smb1_nt_status_desc="+scan_result.smb1_nt_status_desc + " , smb23_nt_status_desc"+scan_result.smb23_nt_status_desc); + return; } - if (adapter.getCount()>0) ll_dlg_smb_share_name.setVisibility(LinearLayout.VISIBLE); - else ll_dlg_smb_share_name.setVisibility(LinearLayout.GONE); -// scanSmbServerEnableSmbScanSelectorOkButton(dialog); + mUtil.addDebugMsg(1, "I", "buildShareListSelectorView: smb_level="+smb_level + " , nt_status_desc="+nt_status_desc); - if (dlg_msg.getText().length()==0 && adapter.getCount()>0) { - dlg_msg.setText(mActivity.getString(R.string.msgs_task_edit_sync_folder_dlg_edit_smb_server_parm_select_smb_share_name)); + if (!select_share) { + mServerSharesListAdapter.clear(); + //dlg_smb_shares_lv.setAdapter(null); //we need to setAdapter() again to reset all items to unchecked if adapter contents did not change + for(SmbServerScanShareInfo item : scan_result.share_item_list) { + if (item.smb_level.equals(smb_level)) { + mServerSharesListAdapter.add(item.share_name); + } + } + //dlg_smb_shares_lv.setAdapter(mServerSharesListAdapter); + mServerSharesListAdapter.notifyDataSetChanged(); + dlg_smb_shares_lv.clearChoices(); // alternative way instead of setAdapter(null) then setAdapter(mServerSharesListAdapter) + dlg_smb_shares_lv.smoothScrollToPosition(0); } - dlg_smb_share_name.setAdapter(adapter); - adapter.notifyDataSetChanged(); - } +// scanSmbServerEnableSmbScanSelectorOkButton(dialog); + + if (mServerSharesListAdapter.getCount() > 0) ll_dlg_smb_share_name.setVisibility(LinearLayout.VISIBLE); + else ll_dlg_smb_share_name.setVisibility(LinearLayout.GONE); - @SuppressWarnings("unchecked") - private void updateShareListSelectorAdapter(Dialog dialog, String smb_level, - TextView dlg_msg, ArrayAdapter adapter, String nt_status_desc, ArrayListsl) { + //mUtil.addDebugMsg(1, "I", "dlg_smb_shares_lv selected psition="+dlg_smb_shares_lv.getCheckedItemPosition()); + + String acct=dlg_smb_account_name.getText().toString(); + String pswd=dlg_smb_account_password.getText().toString(); if (nt_status_desc.equals(SMB_STATUS_ACCESS_DENIED)) { dlg_msg.setText(mActivity.getString(R.string.msgs_task_edit_sync_folder_dlg_edit_smb_server_parm_specify_correct_account)); } else if (nt_status_desc.equals(SMB_STATUS_INVALID_LOGON_TYPE)) { dlg_msg.setText(mActivity.getString(R.string.msgs_task_edit_sync_folder_dlg_edit_smb_server_parm_specify_enable_account)); } else if (nt_status_desc.equals(SMB_STATUS_UNKNOWN_ACCOUNT)) { - final EditText dlg_smb_account_name=(EditText)dialog.findViewById(R.id.scan_smb_server_parm_dlg_smb_server_account_name); - final EditText dlg_smb_account_password=(EditText)dialog.findViewById(R.id.scan_smb_server_parm_dlg_smb_server_account_password); - String acct=dlg_smb_account_name.getText().toString(); - String pswd=dlg_smb_account_password.getText().toString(); - if (acct.equals("") && pswd.equals("")) { + if (acct.equals("") || pswd.equals("")) { dlg_msg.setText(mActivity.getString(R.string.msgs_task_edit_sync_folder_dlg_edit_smb_server_parm_account_password_not_specified)); } else { dlg_msg.setText(mActivity.getString(R.string.msgs_task_edit_sync_folder_dlg_edit_smb_server_parm_specify_correct_account_password)); } - } else { + } else if (nt_status_desc.equals(SMB_STATUS_UNTESTED_LOGIN)) { + // On server selected from scan results: during scan for servers, no credentials are provided + // Also, on edit selected server settings (SMB level, port) + if (acct.equals("") || pswd.equals("")) { + dlg_msg.setText(mActivity.getString(R.string.msgs_task_edit_sync_folder_dlg_edit_smb_server_parm_account_password_empty)); + } else { + dlg_msg.setText(mActivity.getString(R.string.msgs_task_edit_sync_folder_dlg_edit_smb_server_parm_refresh_shares)); + } + } else if (nt_status_desc.equals(SMB_STATUS_UNSUCCESSFULL)) { + // on refresh shares, server cannot be reached because server params (port, SMB level) were edited in the dialog and differ now from what scan result returned + // also can happen if server when offline after the scan result. On refreshing shares, the server is not rechable + dlg_msg.setText(mActivity.getString(R.string.msgs_task_edit_sync_folder_dlg_edit_smb_server_parm_server_connection_error)); + } else if (mServerSharesListAdapter.getCount() <= 0) { + // On refresh shares, no shares were found + dlg_msg.setText(mActivity.getString(R.string.msgs_task_edit_sync_folder_dlg_edit_smb_server_parm_shares_list_empty)); + } else if (dlg_smb_shares_lv.getCheckedItemPosition() < 0) { + // on refresh shares, we have a list of shares without any share selected (unused: or on call of buildSmbServerParmsDlg() with a scan_result.share_item_list poupulated) + dlg_msg.setText(mActivity.getString(R.string.msgs_task_edit_sync_folder_dlg_edit_smb_server_parm_select_smb_share_name)); + } else if (select_share == true) { + // a share was selected in the available list of shares. dlg_msg.setText(""); + } else { + String exception = "Uknown exception, contact author with logs !"; + dlg_msg.setText(exception); + mUtil.addDebugMsg(1, "E", "buildShareListSelectorView Exception: adapter_count="+mServerSharesListAdapter.getCount() + + ", List selected pos="+dlg_smb_shares_lv.getCheckedItemPosition() + ", select_share="+select_share); } - for(SmbServerScanShareInfo item:sl) { - if (item.smb_level.equals(smb_level)) { - adapter.add(item.share_name); - } + + // Only possible cases below: refresh shares button failed to get shares (connection error, no shares) + // - after first view int, on server selected from scan results: SMB_STATUS_UNTESTED_LOGIN + // - after modifying server settings (port, SMB level): SMB_STATUS_UNTESTED_LOGIN + // - after refresh shares button successfull: mServerSharesListAdapter.getCount() > 0 + // - after selecting a server from the shares list: dlg_msg.getText().length == 0 + if (mServerSharesListAdapter.getCount() <= 0 && dlg_msg.getText().length() != 0 && !nt_status_desc.equals(SMB_STATUS_UNTESTED_LOGIN)) { + moveScrollViewToTop(server_settings_sv); } + setDialogTitleOffscreenColor(tv_title, dlg_msg, server_settings_sv, mGp.themeColorList.title_text_color, mGp.themeColorList.text_color_error); } +/* Scan thread: + - performSmbServerScan(): starts the first non UI thread startSmbServerScanThread() + + starts a scan for the first 100 IPs in the scan range + + waits for the first 100 Ips to complete for a maximum of 210*30= 6300 msecs + + starts a next 100 IPs scan... + - startSmbServerScanThread() scans for a single IP, called multiple times in multithreading + - mScanRequestedAddrList: each IP to scan is added to this list, once the IP scan thread completed, it is removed from the list + - mThreadScanResultList: ArrayList with all found SMB servers during scan, not bound to a GUI adapter + - mScanResultList: ArrayList with all found SMB servers during scan and bound to mAdapter + - mAdapter: the adapter bound to mScanResultList to display the servers found during scan + - During each scan result by startSmbServerScanThread(), if a server is found, it is first added to mThreadScanResultList + Then, in a Synchronized GUI post thread handler, mScanResultList is cleared and repopulated with all mThreadScanResultList contents + This makes it possible to start createSmbServerInfo() in multithreading and modify the results list bound to the GUI adapter in parallel + - startSmbServerScanThread() starts a first thread to test isSmbHost() + + if it finds an smb host, the first thread starts a second sub-thread th2 to launch createSmbServerInfo() in the background + + this way, first thread doesn't have to wait for createSmbServerInfo() to complete + + once th2 is completed, it handles the results in a handler.post GUI thread + + the GUI thread populates mScanResultList as explained above in a synchronized way and notifies the adapter + the GUI thread also updates the scan progress + - Scan progress is controlled by mLockScanProgress +*/ private int mScanCompleteCount = 0, mScanAddrCount = 0; - private ArrayList mScanRequestedAddrList = new ArrayList(); - private ArrayList mScanResultList = new ArrayList(); - private String mLockScanCompleteCount = ""; + // private int mStartedThreadsCount = 0, mTh2ResultEntered = 0, mTh2ResultOut = 0 //debug scanner multithreading + private final ArrayList mScanRequestedAddrList = new ArrayList(); + private final ArrayList mScanResultList = new ArrayList(); // UI adapter + private final ArrayList mThreadScanResultList = new ArrayList(); // non UI network scan threads + private static final Object mLockThreadsScanResultList = new Object(); //for mThreadScanResultList + private static final Object mLockScanProgress = new Object(); //for mScanRequestedAddrList and mScanCompleteCount + private static final Object mLockSmbServerScanAdapter = new Object(); //for mScanResultList and mAdapter private void performSmbServerScan( final Dialog dialog, final ListView lv_ipaddr, - final SmbServerScanAdapter adap, // final ArrayList ipAddressList, final String subnet, final int begin_addr, final int end_addr, - final NotifyEvent p_ntfy, final String smb_protcol) { + final boolean scan_smbv1, final boolean scan_smbv23, final NotifyEvent p_ntfy) { final Handler handler = new Handler(); final ThreadCtrl tc = new ThreadCtrl(); - final LinearLayout ll_addr = (LinearLayout) dialog.findViewById(R.id.scan_smb_server_scan_dlg_scan_address); - final LinearLayout ll_prog = (LinearLayout) dialog.findViewById(R.id.scan_smb_server_scan_dlg_progress); - final TextView tvmsg = (TextView) dialog.findViewById(R.id.scan_smb_server_scan_dlg_progress_msg); - final Button btn_scan = (Button) dialog.findViewById(R.id.scan_smb_server_scan_dlg_btn_ok); - final Button btn_cancel = (Button) dialog.findViewById(R.id.scan_smb_server_scan_dlg_btn_cancel); - final Button scan_cancel = (Button) dialog.findViewById(R.id.scan_smb_server_scan_dlg_progress_cancel); + final LinearLayout ll_addr = dialog.findViewById(R.id.scan_smb_server_scan_dlg_scan_address); + final LinearLayout ll_prog = dialog.findViewById(R.id.scan_smb_server_scan_dlg_progress); + final TextView tv_progress_percent_msg = dialog.findViewById(R.id.scan_smb_server_scan_dlg_progress_msg); + final Button btn_scan = dialog.findViewById(R.id.scan_smb_server_scan_dlg_btn_ok); + final Button btn_cancel = dialog.findViewById(R.id.scan_smb_server_scan_dlg_btn_cancel); + final Button scan_cancel = dialog.findViewById(R.id.scan_smb_server_scan_dlg_progress_cancel); // final CheckedTextView ctv_use_port_number = (CheckedTextView) dialog.findViewById(R.id.scan_remote_ntwk_ctv_use_port); - final EditText et_port_number = (EditText) dialog.findViewById(R.id.scan_smb_server_scan_dlg_port_number); + final EditText et_port_number = dialog.findViewById(R.id.scan_smb_server_scan_dlg_port_number); + final String scan_port = et_port_number.getText().toString(); - tvmsg.setText(""); + tv_progress_percent_msg.setText(""); scan_cancel.setText(R.string.msgs_scan_progress_spin_dlg_addr_cancel); ll_addr.setVisibility(LinearLayout.GONE); ll_prog.setVisibility(LinearLayout.VISIBLE); btn_scan.setVisibility(Button.GONE); btn_cancel.setVisibility(Button.GONE); - adap.setButtonEnabled(false); + mAdapter.setButtonEnabled(false); CommonUtilities.setViewEnabled(mActivity, scan_cancel, true); dialog.setOnKeyListener(new DialogBackKeyListener(mActivity)); dialog.setCancelable(false); mScanResultList.clear(); + mThreadScanResultList.clear(); // CANCELボタンの指定 scan_cancel.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { @@ -563,216 +877,347 @@ public void onClick(View v) { }); dialog.show(); + + final TextView tv_progress_ip_range = dialog.findViewById(R.id.scan_smb_server_scan_dlg_progress_msg_scan_range); + String scan_prog = mActivity.getString(R.string.msgs_ip_address_scan_progress_ip_range); + tv_progress_ip_range.setText(String.format(scan_prog, subnet, begin_addr, end_addr)); mUtil.addDebugMsg(1, "I", "Scan IP address ransge is " + subnet + "." + begin_addr + " - " + end_addr); - mScanRequestedAddrList.clear(); - - final String scan_prog = mActivity.getString(R.string.msgs_ip_address_scan_progress); + scan_prog = mActivity.getString(R.string.msgs_ip_address_scan_progress_percent); String p_txt = String.format(scan_prog, 0); - tvmsg.setText(p_txt); + tv_progress_percent_msg.setText(p_txt); - Thread th=new Thread(new Runnable() { + mScanRequestedAddrList.clear(); + Thread th = new Thread(new Runnable() { @Override public void run() {//non UI thread + //mStartedThreadsCount = 0; + //mTh2ResultEntered = 0; + //mTh2ResultOut = 0; mScanCompleteCount = 0; mScanAddrCount = end_addr - begin_addr + 1; - int scan_thread = 100; - String scan_port = ""; - if (et_port_number.getText().length()>0) scan_port = et_port_number.getText().toString(); - for (int i = begin_addr; i <= end_addr; i += scan_thread) { + int scan_threads = 100; + for (int i = begin_addr; i <= end_addr; i += scan_threads) { if (!tc.isEnabled()) break; boolean scan_end = false; - for (int j = i; j < (i + scan_thread); j++) { + for (int j = i; j < (i + scan_threads); j++) { if (!tc.isEnabled()) break; if (j <= end_addr) { - startSmbServerScanThread(handler, tc, dialog, p_ntfy, - lv_ipaddr, adap, tvmsg, subnet + "." + j, -// ipAddressList, - scan_port, smb_protcol); + startSmbServerScanThread(handler, tc, lv_ipaddr, tv_progress_percent_msg, subnet + "." + j, scan_port, scan_smbv1, scan_smbv23); } else { scan_end = true; + break; } } if (!scan_end) { for (int wc = 0; wc < 210; wc++) { if (!tc.isEnabled()) break; - synchronized (mScanRequestedAddrList) { + synchronized (mLockScanProgress) { if (mScanRequestedAddrList.size() == 0) break; } - SystemClock.sleep(30); + SystemClock.sleep(30); //msecs } + } else { + break; } } - if (!tc.isEnabled()) { - for (int i = 0; i < 1000; i++) { - SystemClock.sleep(100); - synchronized (mScanRequestedAddrList) { - if (mScanRequestedAddrList.size() == 0) break; - } + + // Wait for all threads to complete, up to max of 100 seconds + for (int i = 0; i < 1000; i++) { + SystemClock.sleep(100); + synchronized (mLockScanProgress) { + if (mScanRequestedAddrList.size() == 0) break; } - handler.post(new Runnable() {// UI thread - @Override - public void run() { - adap.sort(); - closeSmbServerScanProgressDlg(dialog, p_ntfy, lv_ipaddr, adap, tvmsg); - } - }); - } else { - for (int i = 0; i < 1000; i++) { - SystemClock.sleep(100); - synchronized (mScanRequestedAddrList) { - if (mScanRequestedAddrList.size() == 0) break; + } + handler.post(new Runnable() {//UI thread, all scan threads completed + @Override + public void run() { + synchronized (mLockSmbServerScanAdapter) { + mAdapter.notifyDataSetChanged(); + mAdapter.sort(); + //lv_ipaddr.setSelection(lv_ipaddr.getCount()); + closeSmbServerScanProgressDlg(dialog, p_ntfy); } } - handler.post(new Runnable() {// UI thread - @Override - public void run() { - synchronized (mLockScanCompleteCount) { - adap.sort(); - lv_ipaddr.setSelection(lv_ipaddr.getCount()); - adap.notifyDataSetChanged(); - closeSmbServerScanProgressDlg(dialog, p_ntfy, lv_ipaddr, adap, tvmsg); - } - } - }); - } + }); } }); th.setPriority(Thread.MIN_PRIORITY); th.start(); } - private void closeSmbServerScanProgressDlg( - final Dialog dialog, - final NotifyEvent p_ntfy, - final ListView lv_ipaddr, - final SmbServerScanAdapter adap, - final TextView tvmsg) { - final LinearLayout ll_addr = (LinearLayout) dialog.findViewById(R.id.scan_smb_server_scan_dlg_scan_address); - final LinearLayout ll_prog = (LinearLayout) dialog.findViewById(R.id.scan_smb_server_scan_dlg_progress); - final Button btn_scan = (Button) dialog.findViewById(R.id.scan_smb_server_scan_dlg_btn_ok); - final Button btn_cancel = (Button) dialog.findViewById(R.id.scan_smb_server_scan_dlg_btn_cancel); + private void closeSmbServerScanProgressDlg(final Dialog dialog, final NotifyEvent p_ntfy) { + final LinearLayout ll_addr = dialog.findViewById(R.id.scan_smb_server_scan_dlg_scan_address); + final LinearLayout ll_prog = dialog.findViewById(R.id.scan_smb_server_scan_dlg_progress); + final Button btn_scan = dialog.findViewById(R.id.scan_smb_server_scan_dlg_btn_ok); + final Button btn_cancel = dialog.findViewById(R.id.scan_smb_server_scan_dlg_btn_cancel); ll_addr.setVisibility(LinearLayout.VISIBLE); ll_prog.setVisibility(LinearLayout.GONE); btn_scan.setVisibility(Button.VISIBLE); btn_cancel.setVisibility(Button.VISIBLE); - adap.setButtonEnabled(true); + mAdapter.setButtonEnabled(true); dialog.setOnKeyListener(null); dialog.setCancelable(true); if (p_ntfy != null) p_ntfy.notifyToListener(true, null); - } private String mScanSmbErrorMessage=""; private void startSmbServerScanThread(final Handler handler, final ThreadCtrl tc, - final Dialog dialog, - final NotifyEvent p_ntfy, final ListView lv_ipaddr, - final SmbServerScanAdapter adap, - final TextView tvmsg, + final TextView tv_progress_percent_msg, final String addr, -// final ArrayList ipAddressList, - final String scan_port, final String smb_level) { - final String scan_prog = mActivity.getString(R.string.msgs_ip_address_scan_progress); + final String scan_port, + final boolean scan_smbv1, + final boolean scan_smbv23) { + final String scan_prog = mActivity.getString(R.string.msgs_ip_address_scan_progress_percent); if (!tc.isEnabled()) return; Thread th = new Thread(new Runnable() { @Override - public void run() {//non UI thread + public void run() {//non UI thread to start isSmbHost() for the given IP in the background and be able to scan more incoming IPs + //mStartedThreadsCount++; if (!tc.isEnabled()) return; // byte[] oo=new byte[Integer.MAX_VALUE]; - synchronized (mScanRequestedAddrList) { + synchronized (mLockScanProgress) { mScanRequestedAddrList.add(addr); } - if (CommonUtilities.isSmbHost(mUtil, addr, scan_port, 3500)) { - final String srv_name = CommonUtilities.getSmbHostName(mUtil, smb_level, addr); - mScanResultList.add(createSmbServerShareInfo(null, null, null, addr, srv_name)); + boolean found = false; + int i = -1; + String[] ports = { "445", "139" }; + if (scan_port != null && !scan_port.equals("")) { + ports = new String[] { scan_port }; + } + + for (String port : ports) { + i++; + found = CommonUtilities.isSmbHost(mUtil, addr, port, 3500); + if (found) break; + } + + final SmbServerInfo ssi = new SmbServerInfo(); + //ssi.serverHostName = addr; + //ssi.serverProtocol = scan_smbv1 ? SyncTaskItem.SYNC_FOLDER_SMB_PROTOCOL_SMB1 : SyncTaskItem.SYNC_FOLDER_SMB_PROTOCOL_SMB23; + ssi.serverPort = ports[i]; + + //if (true) {//debug to add all scanned servers + if (found) { + // start a new non UI background thread to scan for SMBv1 and SMBv2/3 protocols on the found server + // we don't have to lock around SmbServerScanResult and have to wait for createSmbServerInfo() to accept more threads for the next IPs + Thread th2 = new Thread(new Runnable() { + @Override + public void run() {//non UI thread + final SmbServerScanResult result = createSmbServerInfo(tc, scan_smbv1, scan_smbv23, null, null, null, addr, ssi.serverPort); + //final SmbServerScanResult result = createSmbServerInfo(tc, false, false, null, null, null, addr, port); //debug to add all scanned servers + //mTh2ResultOut++; //debug + + synchronized (mLockThreadsScanResultList) { + if (result != null) mThreadScanResultList.add(result); + } + handler.post(new Runnable() {//UI thread, createSmbServerInfo() thread completed, update the results ListView + // modify the results list and adapter with results + @Override + public void run() { + synchronized (mLockSmbServerScanAdapter) { + synchronized (mLockThreadsScanResultList) { + mScanResultList.clear(); // hacky way to not use AsyncTask. It also makes the ListView properly expand to bottom of screen if enough elements + mScanResultList.addAll(mThreadScanResultList); + } + + //mAdapter.sort(); // sorts the results dynamically. However, we won't see the last current added server as the list gets sorted each time + mAdapter.notifyDataSetChanged(); + lv_ipaddr.setSelection(lv_ipaddr.getCount()); // ensure the selection/listView is set to the last added server + } + synchronized (mLockScanProgress) { + mScanCompleteCount++; + mScanRequestedAddrList.remove(addr); + + //String p_txt = String.format(scan_prog+" mStarted="+mStartedThreadsCount +" Entered="+mTh2ResultEntered + " Out"+mTh2ResultOut, (mScanCompleteCount * 100) / mScanAddrCount); + String p_txt = String.format(scan_prog, (mScanCompleteCount * 100) / mScanAddrCount); + tv_progress_percent_msg.setText(p_txt); + } + } + }); + } + }); + th2.setPriority(Thread.MIN_PRIORITY); + th2.start(); + } else { + // server not found, update progress handler.post(new Runnable() {// UI thread @Override public void run() { - synchronized (mScanRequestedAddrList) { - mScanRequestedAddrList.remove(addr); - synchronized (adap) { -// adap.add(smb_server_item); - adap.sort(); - } - } - synchronized (mLockScanCompleteCount) { + //mTh2ResultOut++; + synchronized (mLockScanProgress) { mScanCompleteCount++; + mScanRequestedAddrList.remove(addr); + + //String p_txt = String.format(scan_prog+" mStarted="+mStartedThreadsCount +" Entered="+mTh2ResultEntered + " Out"+mTh2ResultOut, (mScanCompleteCount * 100) / mScanAddrCount); + String p_txt = String.format(scan_prog, (mScanCompleteCount * 100) / mScanAddrCount); + tv_progress_percent_msg.setText(p_txt); } } }); - } else { - synchronized (mScanRequestedAddrList) { - mScanRequestedAddrList.remove(addr); - } - synchronized (mLockScanCompleteCount) { - mScanCompleteCount++; - } } - handler.post(new Runnable() {// UI thread - @Override - public void run() { - synchronized (mLockScanCompleteCount) { - lv_ipaddr.setSelection(lv_ipaddr.getCount()); -// adap.notifyDataSetChanged(); - String p_txt = String.format(scan_prog, (mScanCompleteCount * 100) / mScanAddrCount); - tvmsg.setText(p_txt); - } - } - }); } }); th.setPriority(Thread.MIN_PRIORITY); th.start(); } - final private SmbServerScanResult createSmbServerShareInfo(String domain, String user, String pass, String address, String srv_name) { - SmbServerScanResult result=new SmbServerScanResult(); - result.server_smb_ip_addr=address; - result.server_smb_name=srv_name; - - try { - JcifsAuth auth=new JcifsAuth(JcifsAuth.JCIFS_FILE_SMB1, domain, user, pass); - result.smb1_nt_status_desc=isSmbServerAvailable(SMB_LEVEL_SMB1, auth, address); - if (!result.smb1_nt_status_desc.equals(SMB_STATUS_UNSUCCESSFULL)) { - result.smb1_available=true; - ArrayList sl=createSmbServerShareList(SMB_LEVEL_SMB1, auth, address); - result.share_item_list.addAll(sl); + // must be called from non UI background thread + private SmbServerScanResult createSmbServerInfo(final ThreadCtrl tc, boolean scan_smbv1, boolean scan_smbv23, String domain, String user, String pass, String address, String port) { + //mTh2ResultEntered++; + if (tc != null && !tc.isEnabled()) { + //p_ntfy.notifyToListener(false, null); + return null; + } + SmbServerScanResult result = new SmbServerScanResult(); + result.server_smb_ip_addr = address==null? "":address; + result.server_smb_port_number = port==null? "":port; + + String srv_name = null; + if (scan_smbv1) { + // Try to get server hostname by IP/addres + srv_name = CommonUtilities.getSmbHostName(mUtil, SyncTaskItem.SYNC_FOLDER_SMB_PROTOCOL_SMB1, result.server_smb_ip_addr); + result.server_smb_name = srv_name==null? "":srv_name; + try { + result.scan_for_smb1 = true; + JcifsAuth auth = new JcifsAuth(JcifsAuth.JCIFS_FILE_SMB1, domain, user, pass); + result.smb1_nt_status_desc = isSmbServerAvailable(auth, result.server_smb_ip_addr, result.server_smb_name, result.server_smb_port_number); + if (!result.smb1_nt_status_desc.equals(SMB_STATUS_UNSUCCESSFULL)) { + result.smb1_available = true; + result.smb1_nt_status_desc = SMB_STATUS_UNTESTED_LOGIN; + } else { + result.smb1_available = false; + } + } catch(JcifsException e) { + e.printStackTrace(); + mUtil.addDebugMsg(1, "I", "JcifsException occured, error=" + e.getMessage()); + mScanSmbErrorMessage=mActivity.getString(R.string.msgs_scan_smb_server_scan_dlg_scan_error); } - } catch(JcifsException e) { - e.printStackTrace(); - mUtil.addDebugMsg(1, "I", "JcifsException occured, error="+e.getMessage()); } - try { - Properties prop=new Properties(); - prop.setProperty("jcifs.smb.client.responseTimeout", mGp.settingsSmbClientResponseTimeout); - JcifsAuth auth=new JcifsAuth(JcifsAuth.JCIFS_FILE_SMB23, domain, user, pass, "SMB202", "SMB311", prop); - result.smb23_nt_status_desc =isSmbServerAvailable(SMB_LEVEL_SMB23, auth, address); - if (!result.smb23_nt_status_desc.equals(SMB_STATUS_UNSUCCESSFULL)) { - result.smb23_available =true; - ArrayList sl=createSmbServerShareList(SMB_LEVEL_SMB23, auth, address); - result.share_item_list.addAll(sl); + if (scan_smbv23) { + if (srv_name == null || srv_name.equals("")) { + srv_name = CommonUtilities.getSmbHostName(mUtil, SyncTaskItem.SYNC_FOLDER_SMB_PROTOCOL_SMB23, result.server_smb_ip_addr); + result.server_smb_name = srv_name==null? "":srv_name; + } + try { + result.scan_for_smb23 = true; + Properties prop = new Properties(); + prop.setProperty("jcifs.smb.client.responseTimeout", mGp.settingsSmbClientResponseTimeout); + JcifsAuth auth = new JcifsAuth(JcifsAuth.JCIFS_FILE_SMB23, domain, user, pass, JcifsAuth.SMB_CLIENT_MIN_VERSION, JcifsAuth.SMB_CLIENT_MAX_VERSION, prop); + result.smb23_nt_status_desc = isSmbServerAvailable(auth, result.server_smb_ip_addr, result.server_smb_name, result.server_smb_port_number); + if (!result.smb23_nt_status_desc.equals(SMB_STATUS_UNSUCCESSFULL)) { + result.smb23_available = true; + result.smb23_nt_status_desc = SMB_STATUS_UNTESTED_LOGIN; + } else { + result.smb23_available = false; + } + } catch(JcifsException e) { + e.printStackTrace(); + mUtil.addDebugMsg(1, "I", "JcifsException occured, error=" + e.getMessage()); + mScanSmbErrorMessage=mActivity.getString(R.string.msgs_scan_smb_server_scan_dlg_scan_error); } - } catch(JcifsException e) { - e.printStackTrace(); - mUtil.addDebugMsg(1, "I", "JcifsException occured, error="+e.getMessage()); } - return result; } - final private String isSmbServerAvailable(String smb_level, JcifsAuth auth, String address) { + private void createSmbServerShareInfo(final NotifyEvent p_ntfy, String smb_level, String domain, String user, String pass, String address, String srv_name, String port) { + SmbServerScanResult result = new SmbServerScanResult(); + result.server_smb_ip_addr = address==null? "":address; + result.server_smb_name = srv_name==null? "":srv_name; + result.server_smb_port_number = port==null? "":port; + + final Handler hndl=new Handler(); + final Dialog dialog=CommonDialog.showProgressSpinIndicator(mActivity); + dialog.show(); + Thread th=new Thread(){ + @Override + public void run() { + boolean scan_smbv1 = false; + boolean scan_smbv23 = false; + if (smb_level.equals(SyncTaskItem.SYNC_FOLDER_SMB_PROTOCOL_SMB1)) { + scan_smbv1 = true; + } else if (smb_level.equals(SyncTaskItem.SYNC_FOLDER_SMB_PROTOCOL_SMB23)) { + scan_smbv23 = true; + } else { + // default scan for both protocols (not used currently during refresh shares, only radio buttons for SMBv1 and SMBv2/3 are provided) + scan_smbv1 = true; + scan_smbv23 = true; + } + + if (scan_smbv1) { + try { + JcifsAuth auth = new JcifsAuth(JcifsAuth.JCIFS_FILE_SMB1, domain, user, pass); + result.smb1_nt_status_desc = isSmbServerAvailable(auth, result.server_smb_ip_addr, result.server_smb_name, result.server_smb_port_number); + if (!result.smb1_nt_status_desc.equals(SMB_STATUS_UNSUCCESSFULL)) { + result.smb1_available = true; + ArrayList sl = createSmbServerShareList(SyncTaskItem.SYNC_FOLDER_SMB_PROTOCOL_SMB1, auth, result.server_smb_ip_addr, result.server_smb_name, result.server_smb_port_number); + result.share_item_list.addAll(sl); + } else { + result.smb1_available = false; + } + } catch(JcifsException e) { + e.printStackTrace(); + mUtil.addDebugMsg(1, "I", "JcifsException occured, error=" + e.getMessage()); + } + } + + if (scan_smbv23) { + try { + Properties prop = new Properties(); + prop.setProperty("jcifs.smb.client.responseTimeout", "3000"); + JcifsAuth auth = new JcifsAuth(JcifsAuth.JCIFS_FILE_SMB23, domain, user, pass, JcifsAuth.SMB_CLIENT_MIN_VERSION, JcifsAuth.SMB_CLIENT_MAX_VERSION, prop); + result.smb23_nt_status_desc = isSmbServerAvailable(auth, result.server_smb_ip_addr, result.server_smb_name, result.server_smb_port_number); + if (!result.smb23_nt_status_desc.equals(SMB_STATUS_UNSUCCESSFULL)) { + result.smb23_available = true; + ArrayList sl = createSmbServerShareList(SyncTaskItem.SYNC_FOLDER_SMB_PROTOCOL_SMB23, auth, result.server_smb_ip_addr, result.server_smb_name, result.server_smb_port_number); + result.share_item_list.addAll(sl); + } else { + result.smb23_available = false; + } + } catch(JcifsException e) { + e.printStackTrace(); + mUtil.addDebugMsg(1, "I", "JcifsException occured, error=" + e.getMessage()); + } + } + + hndl.post(new Runnable() { + @Override + public void run() { + p_ntfy.notifyToListener(true, new Object[]{result}); + dialog.dismiss(); + } + }); + } + }; + th.start(); + } + + private String isSmbServerAvailable(JcifsAuth auth, String address, String srv_name, String port) { boolean result=false; - JcifsFile[] share_file_list=null; + String smb_ip_addr = address==null? "":address; + String smb_hostname = srv_name==null? "":srv_name; + String port_number = port==null? "":port; + + String host = smb_ip_addr; + if (host.equals("")) host = smb_hostname; + + String url_prefix=CommonUtilities.buildSmbUrlAddressElement(host, port_number); + url_prefix = "smb://" + url_prefix; + mUtil.addDebugMsg(1, "I", "buildRemoteUrl url_prefix="+url_prefix); + String server_status=""; try { - JcifsFile sf = new JcifsFile("smb://"+address, auth); - share_file_list=sf.listFiles(); + // we just try to connect to the server without credentials + //JcifsFile[] share_file_list=null; + //JcifsFile sf = new JcifsFile(url_prefix, auth); + //share_file_list=sf.listFiles(); + JcifsFile sf = new JcifsFile(url_prefix, auth); + sf.listFiles(); server_status=""; - mUtil.addDebugMsg(1,"I","isSmbServerAvailable level="+smb_level+", address="+address+", result="+server_status); result=true; try { sf.close(); @@ -780,29 +1225,43 @@ final private String isSmbServerAvailable(String smb_level, JcifsAuth auth, Stri mUtil.addDebugMsg(1,"I","close() failed. Error=",e.getMessage()); } } catch (JcifsException e) { -// e.printStackTrace(); + //e.printStackTrace(); if (e.getNtStatus()==0xc0000001) server_status=SMB_STATUS_UNSUCCESSFULL; // else if (e.getNtStatus()==0xc0000022) server_status=SMB_STATUS_ACCESS_DENIED; // else if (e.getNtStatus()==0xc000015b) server_status=SMB_STATUS_INVALID_LOGON_TYPE; // else if (e.getNtStatus()==0xc000006d) server_status=SMB_STATUS_UNKNOWN_ACCOUNT; // - mUtil.addDebugMsg(1,"I","isSmbServerAvailable level="+smb_level+", address="+address+ - ", statue="+server_status+ String.format(", status=0x%8h",e.getNtStatus())+", result="+result); - + else server_status=Integer.toHexString(e.getNtStatus()); + mUtil.addDebugMsg(1,"I","isSmbServerAvailable smb_level="+auth.getSmbLevel() + ", url_prefix="+url_prefix+ + ", status="+server_status+ String.format(", status=0x%8h",e.getNtStatus())+", result="+result); } catch (MalformedURLException e) { -// log.info("Test logon failed." , e); + //log.info("Test logon failed." , e); + //e.printStackTrace(); } + mUtil.addDebugMsg(1, "I", "isSmbServerAvailable smb_level="+auth.getSmbLevel() + ", smb_ip_addr="+smb_ip_addr + ", smb_hostname="+smb_hostname + ", url_prefix="+url_prefix + ", result="+server_status); return server_status; } + + private ArrayList createSmbServerShareList(String smb_level, JcifsAuth auth, String address, String srv_name, String port) { + String smb_ip_addr = address==null? "":address; + String smb_hostname = srv_name==null? "":srv_name; + String port_number = port==null? "":port; + + String host = smb_ip_addr; + if (host.equals("")) host = smb_hostname; + + String url_prefix=CommonUtilities.buildSmbUrlAddressElement(host, port_number); + url_prefix = "smb://" + url_prefix; + //mUtil.addDebugMsg(1, "I", "buildRemoteUrl url_prefix="+url_prefix); + + mUtil.addDebugMsg(1, "I", "createSmbServerShareList level="+smb_level + ", smb_ip_addr="+smb_ip_addr + ", smb_hostname="+smb_hostname + ", url_prefix="+url_prefix); - final private ArrayList createSmbServerShareList(String smb_level, JcifsAuth auth, String address) { ArrayList result=new ArrayList(); JcifsFile[] share_file_list=null; try { - JcifsFile sf = new JcifsFile("smb://"+address, auth); + JcifsFile sf = new JcifsFile(url_prefix, auth); share_file_list=sf.listFiles(); - mUtil.addDebugMsg(1,"I","createSmbServerShareList level="+smb_level+", address="+address); for(JcifsFile item:share_file_list) { - mUtil.addDebugMsg(1,"I"," Share="+item.getName()); + mUtil.addDebugMsg(1, "I", " Share="+item.getName()); SmbServerScanShareInfo share_item=new SmbServerScanShareInfo(); share_item.smb_level=smb_level; share_item.share_name=item.getName().substring(0, item.getName().length()-1); @@ -816,7 +1275,7 @@ final private ArrayList createSmbServerShareList(String mUtil.addDebugMsg(1,"I","close() failed. Error=",e.getMessage()); } } catch (JcifsException e) { - mUtil.addDebugMsg(1,"I","createSmbServerShareList level="+smb_level+", address="+address+ + mUtil.addDebugMsg(1,"I","createSmbServerShareList level="+smb_level + ", url_prefix="+url_prefix + String.format(", status=0x%8h",e.getNtStatus())); } catch (MalformedURLException e) { @@ -827,12 +1286,13 @@ final private ArrayList createSmbServerShareList(String private boolean isValidScanAddress(Dialog dialog) { boolean result = false; - final EditText baEt1 = (EditText) dialog.findViewById(R.id.scan_smb_server_scan_dlg_begin_address_o1); - final EditText baEt2 = (EditText) dialog.findViewById(R.id.scan_smb_server_scan_dlg_begin_address_o2); - final EditText baEt3 = (EditText) dialog.findViewById(R.id.scan_smb_server_scan_dlg_begin_address_o3); - final EditText baEt4 = (EditText) dialog.findViewById(R.id.scan_smb_server_scan_dlg_begin_address_o4); - final EditText eaEt5 = (EditText) dialog.findViewById(R.id.scan_smb_server_scan_dlg_end_address_o4); - final TextView tvmsg = (TextView) dialog.findViewById(R.id.scan_smb_server_scan_dlg_msg); + + final EditText baEt1 = dialog.findViewById(R.id.scan_smb_server_scan_dlg_begin_address_o1); + final EditText baEt2 = dialog.findViewById(R.id.scan_smb_server_scan_dlg_begin_address_o2); + final EditText baEt3 = dialog.findViewById(R.id.scan_smb_server_scan_dlg_begin_address_o3); + final EditText baEt4 = dialog.findViewById(R.id.scan_smb_server_scan_dlg_begin_address_o4); + final EditText eaEt5 = dialog.findViewById(R.id.scan_smb_server_scan_dlg_end_address_o4); + final TextView tvmsg = dialog.findViewById(R.id.scan_smb_server_scan_dlg_msg); String ba1 = baEt1.getText().toString(); String ba2 = baEt2.getText().toString(); @@ -862,6 +1322,7 @@ private boolean isValidScanAddress(Dialog dialog) { eaEt5.requestFocus(); return false; } + int iba1=0, iba2=0, iba3=0, iba4=0, iea5=0; try { iba1 = Integer.parseInt(ba1); @@ -959,9 +1420,17 @@ private boolean isValidScanAddress(Dialog dialog) { return result; } - static public class SmbServerInfo { + private String getSmbSelectedProtocol(Spinner spinner) { + if (spinner.getSelectedItem()==null) { + return SyncTaskItem.SYNC_FOLDER_SMB_PROTOCOL_DEFAULT; + } + return (String)spinner.getSelectedItem(); + } + + public static class SmbServerInfo { public String serverHostIpAddress =""; public String serverHostName =""; + //public String serverHostNameOrIP = ""; public String serverProtocol=""; public String serverPort=""; public String serverShareName=""; @@ -971,34 +1440,40 @@ static public class SmbServerInfo { public String serverAccountPassword=""; } - public class SmbServerScanResult { - public static final String SMB_LEVEL_SMB1="SMB1"; - public static final String SMB_LEVEL_SMB23 ="SMB23"; + public static class SmbServerScanResult { public static final String SMB_STATUS_UNSUCCESSFULL="Unsuccessfull"; public static final String SMB_STATUS_ACCESS_DENIED="Access denied"; public static final String SMB_STATUS_INVALID_LOGON_TYPE="Invalid login type"; public static final String SMB_STATUS_UNKNOWN_ACCOUNT="Unknown account or invalid password"; - // public String server_smb_level= "SMB1"; + public static final String SMB_STATUS_UNTESTED_LOGIN="Login failed because no user or password were provided"; // during scan for servers, SMB_STATUS_UNKNOWN_ACCOUNT + + // True if the scan query that listed the server was started with the corresponding SMB level selected (SMBv1, SMBv23 or "SMBv1 & SMBv23") + public boolean scan_for_smb1=false; + public boolean scan_for_smb23=false; + + // true if the found server supports the corresponding SMB level public boolean smb1_available=false; - public String smb1_nt_status_desc=""; public boolean smb23_available =false; + + public String smb1_nt_status_desc=""; public String smb23_nt_status_desc =""; public String server_smb_name= ""; public String server_smb_ip_addr= ""; - public String server_smb_port_number= "139"; + public String server_smb_port_number= "445"; public ArrayList share_item_list=new ArrayList(); } - public class SmbServerScanShareInfo { - public String smb_level= "SMB1"; + private static class SmbServerScanShareInfo { + public String smb_level= SyncTaskItem.SYNC_FOLDER_SMB_PROTOCOL_DEFAULT; public String share_name=""; } private static class SmbServerScanAdapter extends ArrayAdapter { private ArrayList mResultList = null; + private static final Object mLockResultList = new Object(); //for mResultList private int mResourceId = 0; - private Context mActivity; + private final Context mActivity; private NotifyEvent mNtfyEvent = null; private boolean mButtonEnabled = true; @@ -1018,15 +1493,15 @@ public void setButtonEnabled(boolean p) { @Override public void add(SmbServerScanResult item) { - synchronized (mResultList) { + synchronized (mLockResultList) { mResultList.add(item); notifyDataSetChanged(); } } public void sort() { - synchronized (mResultList) { - Collections.sort(mResultList, new Comparator() { + synchronized (mLockResultList) { + mResultList.sort(new Comparator() { @Override public int compare(SmbServerScanResult lhs, SmbServerScanResult rhs) { String r_o4 = rhs.server_smb_ip_addr.substring(rhs.server_smb_ip_addr.lastIndexOf(".") + 1); @@ -1049,28 +1524,94 @@ public View getView(final int position, View convertView, final ViewGroup parent LayoutInflater vi = (LayoutInflater) mActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); v = vi.inflate(mResourceId, null); holder = new ViewHolder(); - holder.tv_name = (TextView) v.findViewById(R.id.scan_result_list_item_server_name); - holder.tv_addr = (TextView) v.findViewById(R.id.scan_result_list_item_server_addr); + holder.tv_name = v.findViewById(R.id.scan_result_list_item_server_name); + holder.tv_addr = v.findViewById(R.id.scan_result_list_item_server_addr); v.setTag(holder); } else { holder = (ViewHolder) v.getTag(); } if (o != null) { - String smb_level=""; - if (o.smb1_available) smb_level+="SMB1 "; - if (o.smb23_available) smb_level+="SMB2/3 "; - holder.tv_name.setText(o.server_smb_name+"\n"+smb_level); + String smb_level = ""; + String sep = ""; + if (o.smb1_available) { + smb_level += SyncTaskItem.SYNC_FOLDER_SMB_PROTOCOL_SMB1; + sep = " "; + } + if (o.smb23_available) { + smb_level += sep; + smb_level += SyncTaskItem.SYNC_FOLDER_SMB_PROTOCOL_SMB23; + } + + sep = "\n"; + if (o.server_smb_name.equals("")) { + sep = ""; + } + String smb_name_txt = o.server_smb_name + sep + smb_level; + holder.tv_name.setText(smb_name_txt); holder.tv_addr.setText(o.server_smb_ip_addr); - if (o.server_smb_name.equals("")) holder.tv_name.setEnabled(false); - else holder.tv_name.setEnabled(true); + //if (o.server_smb_name.equals("")) holder.tv_name.setEnabled(false); + //else holder.tv_name.setEnabled(true); + + // Grey-out invalid entries, we disable selecting them in isEnabled() method + if (!o.smb1_available && !o.smb23_available) { + // Server responds to be SMB compatible but doesn't provide a compatible SMB v1/2/3 level support + // Exp: scanning uses port 135 while SMB server is listening on a different port + holder.tv_name.setEnabled(false); + holder.tv_addr.setEnabled(false); + } + if (o.scan_for_smb1 && !o.scan_for_smb23) { + // SMB v1 only scan, servers with only SMB v2/3 are greyed + if (o.smb1_available) { + holder.tv_name.setEnabled(true); + holder.tv_addr.setEnabled(true); + } else { + holder.tv_name.setEnabled(false); + holder.tv_addr.setEnabled(false); + } + } + if (o.scan_for_smb23 && !o.scan_for_smb1) { + // SMB v2/3 only scan, servers with only SMB v1 are greyed + if (o.smb23_available) { + holder.tv_name.setEnabled(true); + holder.tv_addr.setEnabled(true); + } else { + holder.tv_name.setEnabled(false); + holder.tv_addr.setEnabled(false); + } + } } return v; } - class ViewHolder { - TextView tv_name, tv_addr; + // the method returns true if all the list items can be selected + @Override + public boolean areAllItemsEnabled() { + return false; } + // The method returns true for a particular list item position so that the list item at that position can be selected + // On scan result, if we select SMBv1 and results have an SMBv2 only server, do not allow the server to be selectable + // Same if we select SMBv23 and results have an SMBv1 only server, do not allow the server to be selectable + @Override + public boolean isEnabled(int position) { + final SmbServerScanResult o = getItem(position); + boolean is_selectable = o.smb1_available || o.smb23_available; + // Server responds to be SMB compatible but doesn't provide a compatible SMB v1/2/3 level support + // Exp: scanning uses port 135 while SMB server is listening on a different port -> Server cannot be selected in results + if (o.scan_for_smb1 && !o.scan_for_smb23) { + // SMB v1 only scan, servers with only SMB v2/3 cannot be selected + if (!o.smb1_available) is_selectable = false; + } + if (o.scan_for_smb23 && !o.scan_for_smb1) { + // SMB v2/3 only scan, servers with only SMB v1 cannot be selected + if (!o.smb23_available) is_selectable = false; + } + return is_selectable; + } + + static class ViewHolder { + TextView tv_name, tv_addr; + } } } diff --git a/app/src/main/java/com/sentaroh/android/SMBSync3/SyncConfiguration.java b/app/src/main/java/com/sentaroh/android/SMBSync3/SyncConfiguration.java index b9c31f0a..d0fb3232 100644 --- a/app/src/main/java/com/sentaroh/android/SMBSync3/SyncConfiguration.java +++ b/app/src/main/java/com/sentaroh/android/SMBSync3/SyncConfiguration.java @@ -543,7 +543,7 @@ private static Element createXmlSettingsElement(Context c, GlobalParameters gp, setting_tag.appendChild(createXmlSettingDataItemString(c, gp, cu, main_document, c.getString(R.string.settings_vibrate_when_sync_ended), NOTIFICATION_VIBRATE_WHEN_SYNC_ENDED_ALWAYS));//gp.settingNotificationVibrateWhenSyncEnded); setting_tag.appendChild(createXmlSettingDataItemBoolean(c, gp, cu, main_document, c.getString(R.string.settings_device_orientation_portrait), false));//gp.settingFixDeviceOrientationToPortrait?"true":"false"); - setting_tag.appendChild(createXmlSettingDataItemString(c, gp, cu, main_document, c.getString(R.string.settings_screen_theme), SCREEN_THEME_STANDARD));//gp.settingScreenTheme); + setting_tag.appendChild(createXmlSettingDataItemString(c, gp, cu, main_document, c.getString(R.string.settings_screen_theme), SCREEN_THEME_DEFAULT));//gp.settingScreenTheme); setting_tag.appendChild(createXmlSettingDataItemString(c, gp, cu, main_document, c.getString(R.string.settings_screen_theme_language), GlobalParameters.APPLICATION_LANGUAGE_SETTING_SYSTEM_DEFAULT)); setting_tag.appendChild(createXmlSettingDataItemString(c, gp, cu, main_document, c.getString(R.string.settings_display_font_scale_factor), GlobalParameters.FONT_SCALE_FACTOR_NORMAL)); diff --git a/app/src/main/java/com/sentaroh/android/SMBSync3/SyncTaskItem.java b/app/src/main/java/com/sentaroh/android/SMBSync3/SyncTaskItem.java index ddc7b9ec..077cbf0f 100644 --- a/app/src/main/java/com/sentaroh/android/SMBSync3/SyncTaskItem.java +++ b/app/src/main/java/com/sentaroh/android/SMBSync3/SyncTaskItem.java @@ -23,6 +23,8 @@ this software and associated documentation files (the "Software"), to deal */ +import androidx.annotation.NonNull; + import com.sentaroh.android.JcifsFile2.JcifsAuth; import com.sentaroh.android.Utilities3.SafManager3; @@ -38,12 +40,13 @@ this software and associated documentation files (the "Software"), to deal import java.util.ArrayList; import java.util.TimeZone; +//class SyncTaskItem implements Serializable { class SyncTaskItem implements Serializable, Cloneable { private static final long serialVersionUID = 1L; - private static Logger log= LoggerFactory.getLogger(SyncTaskItem.class); + private static final Logger log= LoggerFactory.getLogger(SyncTaskItem.class); public SyncTaskItem(String stn, boolean pfa, boolean ic) { - syncTaskName = stn; + syncTaskName = stn; syncTaskEnabled = pfa; isChecked = ic; initOffsetOfDst(); @@ -59,9 +62,9 @@ private void initOffsetOfDst() { } public static final int SYNC_TASK_NAME_MAX_LENGTH=64; - private String syncTaskName = ""; - public String getSyncTaskName() {return syncTaskName;} - public void setSyncTaskName(String p) {syncTaskName = p;} + private String syncTaskName = ""; + public String getSyncTaskName() {return syncTaskName;} + public void setSyncTaskName(String p) {syncTaskName = p;} public final static String SYNC_TASK_TYPE_MIRROR = "M"; // index 0 (Indexes position from SYNC_TASK_TYPE_LIST not used for now) public final static String SYNC_TASK_TYPE_COPY = "C"; // index 1 @@ -152,7 +155,7 @@ public void setSyncTaskType(String p) { public String getSyncFilterFileSizeType() {return syncFilterFileSizeType;} public void setSyncFilterFileSizeType(String p) {syncFilterFileSizeType = p;} static final public String[] syncFilterFileSizeTypeValueArray=new String[]{FILTER_FILE_SIZE_TYPE_NONE, FILTER_FILE_SIZE_TYPE_LESS_THAN, FILTER_FILE_SIZE_TYPE_GREATER_THAN}; - static public String getSyncFilterFileSizeTypeByIndex(int index) { + public static String getSyncFilterFileSizeTypeByIndex(int index) { if (index>=0 && index<=2) return syncFilterFileSizeTypeValueArray[index]; else return FILTER_FILE_SIZE_TYPE_NONE; } @@ -166,7 +169,7 @@ static public String getSyncFilterFileSizeTypeByIndex(int index) { public String getSyncFilterFileSizeUnit() {return syncFilterFileSizeUnit;} public void setSyncFilterFileSizeUnit(String p) {syncFilterFileSizeUnit = p;} static final public String[] syncFilterFileSizeUnitValueArray=new String[]{FILTER_FILE_SIZE_UNIT_BYTE, FILTER_FILE_SIZE_UNIT_KIB, FILTER_FILE_SIZE_UNIT_MIB, FILTER_FILE_SIZE_UNIT_GIB}; - static public String getSyncFilterFileSizeUnitByIndex(int index) { + public static String getSyncFilterFileSizeUnitByIndex(int index) { if (index>=0 && index<=3) return syncFilterFileSizeUnitValueArray[index]; else return FILTER_FILE_SIZE_TYPE_NONE; } @@ -185,7 +188,7 @@ static public String getSyncFilterFileSizeUnitByIndex(int index) { public String getSyncFilterFileDateType() {return syncFilterFileDateType;} public void setSyncFilterFileDateType(String p) {syncFilterFileDateType = p;} static final public String[] syncFilterFileDateTypeValueArray=new String[]{FILTER_FILE_DATE_TYPE_NONE, FILTER_FILE_DATE_TYPE_OLDER_THAN, FILTER_FILE_DATE_TYPE_NEWER_THAN, FILTER_FILE_DATE_TYPE_AFTER_SYNC_BEGIN_DAY}; - static public String getSyncFilterFileDateTypeByIndex(int index) { + public static String getSyncFilterFileDateTypeByIndex(int index) { if (index>=0 && index<=3) return syncFilterFileDateTypeValueArray[index]; else return FILTER_FILE_SIZE_TYPE_NONE; } @@ -260,7 +263,7 @@ static public String getSyncFilterFileDateTypeByIndex(int index) { WIFI_STATUS_WIFI_HAS_PRIVATE_IP_ADDRESS, WIFI_STATUS_WIFI_IP_ADDRESS_LIST}; private String syncOptionWifiStatus = WIFI_STATUS_WIFI_DEFAULT; public String getSyncOptionWifiStatusOption() {return syncOptionWifiStatus;} - static public String getSyncOptionWifiStatusOptionValueByIndex(int index) { + public static String getSyncOptionWifiStatusOptionValueByIndex(int index) { if (index>=0 && index<=3) return WIFI_STATUS_WIFI_LIST[index]; return WIFI_STATUS_WIFI_LIST[0]; } @@ -332,16 +335,16 @@ public void setSyncOptionSyncAllowAllIpAddress(boolean p) { public boolean isSyncOptionMoveOnlyRemoveSourceDirectoryIfEmpty() {return syncOptionMoveOnlyRemoveSourceDirectoryIfEmpty;} public void setSyncOptionMoveOnlyRemoveSourceDirectoryIfEmpty(boolean p) {syncOptionMoveOnlyRemoveSourceDirectoryIfEmpty = p;} - final static public String SYNC_TASK_OPTION_ERROR_OPTION_STOP ="STOP"; - final static public int SYNC_TASK_OPTION_ERROR_OPTION_INDEX_STOP =0; - final static public String SYNC_TASK_OPTION_ERROR_OPTION_SKIP_UNCOND ="SKIP_UNCOND"; - final static public int SYNC_TASK_OPTION_ERROR_OPTION_INDEX_UNCOND =1; - final static public String SYNC_TASK_OPTION_ERROR_OPTION_SKIP_NETWORK ="SKIP_NETWORK"; - final static public int SYNC_TASK_OPTION_ERROR_OPTION_INDEX_NETWORK =2; - final static private String[] SYNC_OPTION_TASK_ERROR_VALUES=new String[]{SYNC_TASK_OPTION_ERROR_OPTION_STOP, SYNC_TASK_OPTION_ERROR_OPTION_SKIP_UNCOND, SYNC_TASK_OPTION_ERROR_OPTION_SKIP_NETWORK}; + final public static String SYNC_TASK_OPTION_ERROR_OPTION_STOP ="STOP"; + final public static int SYNC_TASK_OPTION_ERROR_OPTION_INDEX_STOP =0; + final public static String SYNC_TASK_OPTION_ERROR_OPTION_SKIP_UNCOND ="SKIP_UNCOND"; + final public static int SYNC_TASK_OPTION_ERROR_OPTION_INDEX_UNCOND =1; + final public static String SYNC_TASK_OPTION_ERROR_OPTION_SKIP_NETWORK ="SKIP_NETWORK"; + final public static int SYNC_TASK_OPTION_ERROR_OPTION_INDEX_NETWORK =2; + final private static String[] SYNC_OPTION_TASK_ERROR_VALUES=new String[]{SYNC_TASK_OPTION_ERROR_OPTION_STOP, SYNC_TASK_OPTION_ERROR_OPTION_SKIP_UNCOND, SYNC_TASK_OPTION_ERROR_OPTION_SKIP_NETWORK}; private String syncOptionTaskErrorOption= SYNC_TASK_OPTION_ERROR_OPTION_STOP; public String getSyncTaskErrorOption() {return syncOptionTaskErrorOption;} - static public String getSyncTaskErrorOptionValueByIndex(int index) { + public static String getSyncTaskErrorOptionValueByIndex(int index) { if (index>=0 && index<=2) return SYNC_OPTION_TASK_ERROR_VALUES[index]; else return SYNC_OPTION_TASK_ERROR_VALUES[0]; } @@ -373,7 +376,12 @@ public int getSyncTaskErrorOptionIndex() { public final static String SYNC_FOLDER_SMB_PROTOCOL_SMB23 = JcifsAuth.JCIFS_FILE_SMB23; public final static String SYNC_FOLDER_SMB_PROTOCOL_DEFAULT = SYNC_FOLDER_SMB_PROTOCOL_SMB23; public final static String SYNC_FOLDER_SMB_PROTOCOL_DEFAULT_DESCRIPTION = SYNC_FOLDER_SMB_PROTOCOL_DEFAULT; - public final static String[] SYNC_FOLDER_SMB_PROTOCOL_LIST=new String[]{SYNC_FOLDER_SMB_PROTOCOL_SMB1, SYNC_FOLDER_SMB_PROTOCOL_SMB23}; + public final static int SYNC_FOLDER_SMB_PROTOCOL_SMB1_INDEX = 0; + public final static int SYNC_FOLDER_SMB_PROTOCOL_SMB23_INDEX = 1; + public final static int SYNC_FOLDER_SMB_PROTOCOL_DEFAULT_INDEX = SYNC_FOLDER_SMB_PROTOCOL_SMB23_INDEX; + public final static String[] SYNC_FOLDER_SMB_PROTOCOL_LIST=new String[] { + SYNC_FOLDER_SMB_PROTOCOL_SMB1, // 0 + SYNC_FOLDER_SMB_PROTOCOL_SMB23}; // 1 private String syncTaskSourceFolderSmbProtocol = SYNC_FOLDER_SMB_PROTOCOL_DEFAULT; public String getSourceSmbProtocol() {return syncTaskSourceFolderSmbProtocol;} public void setSourceSmbProtocol(String proto) {syncTaskSourceFolderSmbProtocol=proto;} @@ -657,32 +665,32 @@ public void setSyncFilterArchiveRetentionPeriod(int period) { public boolean isSyncTaskRunning() {return syncTaskIsRunning;} private int syncLastSyncResult = 0; - static public final int SYNC_RESULT_STATUS_SUCCESS = HistoryListAdapter.HistoryListItem.SYNC_RESULT_STATUS_SUCCESS; - static public final int SYNC_RESULT_STATUS_CANCEL = HistoryListAdapter.HistoryListItem.SYNC_RESULT_STATUS_CANCEL; - static public final int SYNC_RESULT_STATUS_ERROR = HistoryListAdapter.HistoryListItem.SYNC_RESULT_STATUS_ERROR; - static public final int SYNC_RESULT_STATUS_WARNING = HistoryListAdapter.HistoryListItem.SYNC_RESULT_STATUS_WARNING; - static public final int SYNC_RESULT_STATUS_SKIP = HistoryListAdapter.HistoryListItem.SYNC_RESULT_STATUS_SKIP; - static public final int SYNC_RESULT_STATUS_DEFAULT = SYNC_RESULT_STATUS_SUCCESS; - static public final String SYNC_RESULT_STATUS_DEFAULT_DESCRIPTION = "SUCCESS"; + public static final int SYNC_RESULT_STATUS_SUCCESS = HistoryListAdapter.HistoryListItem.SYNC_RESULT_STATUS_SUCCESS; + public static final int SYNC_RESULT_STATUS_CANCEL = HistoryListAdapter.HistoryListItem.SYNC_RESULT_STATUS_CANCEL; + public static final int SYNC_RESULT_STATUS_ERROR = HistoryListAdapter.HistoryListItem.SYNC_RESULT_STATUS_ERROR; + public static final int SYNC_RESULT_STATUS_WARNING = HistoryListAdapter.HistoryListItem.SYNC_RESULT_STATUS_WARNING; + public static final int SYNC_RESULT_STATUS_SKIP = HistoryListAdapter.HistoryListItem.SYNC_RESULT_STATUS_SKIP; + public static final int SYNC_RESULT_STATUS_DEFAULT = SYNC_RESULT_STATUS_SUCCESS; + public static final String SYNC_RESULT_STATUS_DEFAULT_DESCRIPTION = "SUCCESS"; public final static int[] SYNC_RESULT_STATUS_LIST = new int[]{SYNC_RESULT_STATUS_SUCCESS, SYNC_RESULT_STATUS_CANCEL, SYNC_RESULT_STATUS_ERROR, SYNC_RESULT_STATUS_WARNING}; public int getLastSyncResult() {return syncLastSyncResult;} public void setLastSyncResult(int p) {syncLastSyncResult = p;} private int syncTaskStatusErrorCode =0; - static public final int SYNC_TASK_STATUS_ERROR_NO_ERROR =0; - static public final int SYNC_TASK_STATUS_ERROR_PRESET_FILTER_AUDIO =1; - static public final int SYNC_TASK_STATUS_ERROR_PRESET_FILTER_IMAGE =2; - static public final int SYNC_TASK_STATUS_ERROR_PRESET_FILTER_VIDEO =4; -// static public final int SYNC_TASK_ERROR_DIRECTORY_FILTER=1; + public static final int SYNC_TASK_STATUS_ERROR_NO_ERROR =0; + public static final int SYNC_TASK_STATUS_ERROR_PRESET_FILTER_AUDIO =1; + public static final int SYNC_TASK_STATUS_ERROR_PRESET_FILTER_IMAGE =2; + public static final int SYNC_TASK_STATUS_ERROR_PRESET_FILTER_VIDEO =4; +// public static final int SYNC_TASK_ERROR_DIRECTORY_FILTER=1; public boolean isSyncTaskError() {return !(syncTaskStatusErrorCode == SYNC_TASK_STATUS_ERROR_NO_ERROR);} public int getSyncTaskStatusErrorCode() {return syncTaskStatusErrorCode;} public void setSyncTaskStatusErrorCode(int error) { syncTaskStatusErrorCode =error;} - static public final int SYNC_FOLDER_STATUS_ERROR_NO_ERROR =0; - static public final int SYNC_FOLDER_STATUS_ERROR_ACCOUNT_NAME =1; - static public final int SYNC_FOLDER_STATUS_ERROR_ACCOUNT_PASSWORD =2; - static public final int SYNC_FOLDER_STATUS_ERROR_ZIP_PASSWORD =4; + public static final int SYNC_FOLDER_STATUS_ERROR_NO_ERROR =0; + public static final int SYNC_FOLDER_STATUS_ERROR_ACCOUNT_NAME =1; + public static final int SYNC_FOLDER_STATUS_ERROR_ACCOUNT_PASSWORD =2; + public static final int SYNC_FOLDER_STATUS_ERROR_ZIP_PASSWORD =4; private int syncSourceFolderStatusError = SyncTaskItem.SYNC_FOLDER_STATUS_ERROR_NO_ERROR; public boolean isSyncFolderStatusError() {return (syncSourceFolderStatusError + syncDestinationFolderStatusError)!= SYNC_FOLDER_STATUS_ERROR_NO_ERROR;} public int getSourceFolderStatusError() {return syncSourceFolderStatusError;} @@ -697,9 +705,23 @@ public void setDestinationFolderStatusError(int error_code) { public boolean isChanged() {return isChanged;} public void setChanged(boolean changed) {isChanged=changed;} - @SuppressWarnings("unchecked") + // Clone using java Cloneable clone() + // not used + @NonNull @Override public SyncTaskItem clone() { + SyncTaskItem npfli = null; + try { + npfli = (SyncTaskItem) super.clone(); + } catch (CloneNotSupportedException e) { + e.printStackTrace(); + } + assert npfli != null; + return npfli; + } + + // Custom clone using Serialization/Deserialization + public SyncTaskItem cloneSerial() { SyncTaskItem npfli = null; try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); @@ -719,9 +741,7 @@ public SyncTaskItem clone() { npfli = (SyncTaskItem) ois.readObject(); ois.close(); bais.close(); - } catch (IOException e) { - e.printStackTrace(); - } catch (ClassNotFoundException e) { + } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } @@ -730,7 +750,7 @@ public SyncTaskItem clone() { public boolean isSame(SyncTaskItem sti) { boolean result = false; - if (syncTaskName.equals(sti.getSyncTaskName()) && + if (syncTaskName.equals(sti.getSyncTaskName()) && (isChanged==sti.isChanged()) && (syncTaskGroup.equals(sti.getSyncTaskGroup())) && (syncTaskEnabled==sti.isSyncTaskAuto()) && @@ -831,34 +851,34 @@ public boolean isSame(SyncTaskItem sti) { (syncOptionSyncOnlyCharging==sti.isSyncOptionSyncWhenCharging())) { - String ff_cmp1 = ""; - for (FilterListAdapter.FilterListItem item : syncFileNameFilter) ff_cmp1 += item.toString()+" "; + StringBuilder ff_cmp1 = new StringBuilder(); + for (FilterListAdapter.FilterListItem item : syncFileNameFilter) ff_cmp1.append(item.toString()).append(" "); - String ff_cmp2 = ""; - for (FilterListAdapter.FilterListItem item : sti.getFileNameFilter()) ff_cmp2 += item.toString()+" "; + StringBuilder ff_cmp2 = new StringBuilder(); + for (FilterListAdapter.FilterListItem item : sti.getFileNameFilter()) ff_cmp2.append(item.toString()).append(" "); - String df_cmp1 = ""; - for (FilterListAdapter.FilterListItem item : syncDirectoryFilter) df_cmp1 += item.toString()+" "; + StringBuilder df_cmp1 = new StringBuilder(); + for (FilterListAdapter.FilterListItem item : syncDirectoryFilter) df_cmp1.append(item.toString()).append(" "); - String df_cmp2 = ""; - for (FilterListAdapter.FilterListItem item : sti.getDirectoryFilter()) df_cmp2 += item.toString()+" "; + StringBuilder df_cmp2 = new StringBuilder(); + for (FilterListAdapter.FilterListItem item : sti.getDirectoryFilter()) df_cmp2.append(item.toString()).append(" "); - String wap_cmp1 = ""; - for (FilterListAdapter.FilterListItem item : syncOptionWifiAccessPointGrantList) wap_cmp1 += item.toString()+" "; + StringBuilder wap_cmp1 = new StringBuilder(); + for (FilterListAdapter.FilterListItem item : syncOptionWifiAccessPointGrantList) wap_cmp1.append(item.toString()).append(" "); - String wap_cmp2 = ""; - for (FilterListAdapter.FilterListItem item : sti.getSyncOptionWifiAccessPointGrantList()) wap_cmp2 += item.toString()+" "; + StringBuilder wap_cmp2 = new StringBuilder(); + for (FilterListAdapter.FilterListItem item : sti.getSyncOptionWifiAccessPointGrantList()) wap_cmp2.append(item.toString()).append(" "); - String wad_cmp1 = ""; - for (FilterListAdapter.FilterListItem item : syncOptionWifiIPAddressGrantList) wad_cmp1 += item.toString()+" "; + StringBuilder wad_cmp1 = new StringBuilder(); + for (FilterListAdapter.FilterListItem item : syncOptionWifiIPAddressGrantList) wad_cmp1.append(item.toString()).append(" "); - String wad_cmp2 = ""; - for (FilterListAdapter.FilterListItem item : sti.getSyncOptionWifiIPAddressGrantList()) wad_cmp2 += item.toString()+" "; + StringBuilder wad_cmp2 = new StringBuilder(); + for (FilterListAdapter.FilterListItem item : sti.getSyncOptionWifiIPAddressGrantList()) wad_cmp2.append(item.toString()).append(" "); - if ((ff_cmp1.equals(ff_cmp2)) && - (df_cmp1.equals(df_cmp2)) && - (wap_cmp1.equals(wap_cmp2)) && - (wad_cmp1.equals(wad_cmp2)) + if ((ff_cmp1.toString().equals(ff_cmp2.toString())) && + (df_cmp1.toString().equals(df_cmp2.toString())) && + (wap_cmp1.toString().equals(wap_cmp2.toString())) && + (wad_cmp1.toString().equals(wad_cmp2.toString())) ) { result = true; } diff --git a/app/src/main/java/com/sentaroh/android/SMBSync3/SyncThread.java b/app/src/main/java/com/sentaroh/android/SMBSync3/SyncThread.java index cc56bcd1..2c12665d 100644 --- a/app/src/main/java/com/sentaroh/android/SMBSync3/SyncThread.java +++ b/app/src/main/java/com/sentaroh/android/SMBSync3/SyncThread.java @@ -710,10 +710,9 @@ private int checkSmbAccess(SyncTaskItem sti) { } } mStwa.util.addDebugMsg(1,"I","Source SMB Address reachable="+reachable+", addr="+sti.getSourceSmbHost()); + // Mod: Source is SMB: fix SMB sync error message displaying url:port:port error instead of url:port if (!reachable) { - String msg=""; - if (sti.getSourceSmbPort().equals("")) msg=mStwa.appContext.getString(R.string.msgs_mirror_smb_addr_not_connected, mStwa.sourceSmbHost); - else msg=mStwa.appContext.getString(R.string.msgs_mirror_smb_addr_not_connected, mStwa.sourceSmbHost +":"+sti.getSourceSmbPort()); + String msg=mStwa.appContext.getString(R.string.msgs_mirror_smb_addr_not_connected, mStwa.sourceSmbHost); showMsg(mStwa, true, mStwa.currentSTI.getSyncTaskName(), "E", "", "", msg); mGp.syncThreadCtrl.setThreadMessage(msg); sync_result = SyncTaskItem.SYNC_RESULT_STATUS_ERROR; @@ -739,22 +738,22 @@ private int checkSmbAccess(SyncTaskItem sti) { } mStwa.destinationSmbHost =CommonUtilities.buildSmbUrlAddressElement(sti.getDestinationSmbHost(), sti.getDestinationSmbPort()); boolean reachable=false; + // Mod: fix SMB sync unable to connect when setting a custom port in target if (sti.getDestinationSmbPort().equals("")) { - reachable=CommonUtilities.canSmbHostConnectable(mStwa.destinationSmbHost); + reachable=CommonUtilities.canSmbHostConnectable(sti.getDestinationSmbHost()); } else { try { int port_no=Integer.valueOf(sti.getDestinationSmbPort()); - reachable=CommonUtilities.canSmbHostConnectable(mStwa.destinationSmbHost, port_no); + reachable=CommonUtilities.canSmbHostConnectable(sti.getDestinationSmbHost(), port_no); } catch(Exception e) { mStwa.util.addDebugMsg(1,"I","Invalid Destination SMB port number="+sti.getDestinationSmbPort()); - reachable=CommonUtilities.canSmbHostConnectable(mStwa.destinationSmbHost); + reachable=CommonUtilities.canSmbHostConnectable(sti.getDestinationSmbHost()); } } mStwa.util.addDebugMsg(1,"I","Destination SMB Address reachable="+reachable+", addr="+mStwa.destinationSmbHost); if (!reachable) { - String msg=""; - if (sti.getDestinationSmbPort().equals("")) msg=mStwa.appContext.getString(R.string.msgs_mirror_smb_addr_not_connected, mStwa.destinationSmbHost); - else msg=mStwa.appContext.getString(R.string.msgs_mirror_smb_addr_not_connected, mStwa.destinationSmbHost +":"+sti.getDestinationSmbPort()); + // Mod: Target is SMB: fix SMB sync error message displaying url:port:port error instead of url:port + String msg=mStwa.appContext.getString(R.string.msgs_mirror_smb_addr_not_connected, mStwa.destinationSmbHost); showMsg(mStwa, true, mStwa.currentSTI.getSyncTaskName(), "E", "", "", msg); mGp.syncThreadCtrl.setThreadMessage(msg); sync_result = SyncTaskItem.SYNC_RESULT_STATUS_ERROR; @@ -1289,14 +1288,14 @@ public static boolean isValidFileDirectoryName(SyncThreadWorkArea stwa, SyncTask return true; } -// static public boolean canAccessLocalDirectory(String path) { +// static public boolean canAccessLocalDirectory(String path, GlobalParameters gp) { // boolean result=true; // if (path.endsWith(".android_secure")) result=false; // else { // if (Build.VERSION.SDK_INT>=30) { // String[] fp_array=path.split("/"); -// if (path.startsWith("/storage/emulated/0")) { -// String abs_dir=path.replace("/storage/emulated/0", ""); +// if (path.startsWith(gp.externalStoragePrefix)) { +// String abs_dir=path.replace(gp.externalStoragePrefix, ""); // if (!abs_dir.equals("")) { // if (abs_dir.startsWith("/Android/data") || abs_dir.startsWith("/Android/obb")) { // result=false; diff --git a/app/src/main/java/com/sentaroh/android/SMBSync3/SyncThreadSyncZip.java b/app/src/main/java/com/sentaroh/android/SMBSync3/SyncThreadSyncZip.java index 7d2a809e..0de1cc60 100644 --- a/app/src/main/java/com/sentaroh/android/SMBSync3/SyncThreadSyncZip.java +++ b/app/src/main/java/com/sentaroh/android/SMBSync3/SyncThreadSyncZip.java @@ -70,17 +70,17 @@ static private void setZipEnvironment(SyncThreadWorkArea stwa, SyncTaskItem sti, if (sti.getDestinationZipEncryptMethod().equals(SyncTaskItem.ZIP_OPTION_ENCRYPT_STANDARD)) { zp.setEncryptionMethod(EncryptionMethod.ZIP_STANDARD); zp.setEncryptFiles(true); - zp.setPassword(sti.getDestinationZipPassword()); + //zp.setPassword(sti.getDestinationZipPassword()); } else if (sti.getDestinationZipEncryptMethod().equals(SyncTaskItem.ZIP_OPTION_ENCRYPT_AES128)) { zp.setEncryptionMethod(EncryptionMethod.AES); zp.setAesKeyStrength(AesKeyStrength.KEY_STRENGTH_128); zp.setEncryptFiles(true); - zp.setPassword(sti.getDestinationZipPassword()); + //zp.setPassword(sti.getDestinationZipPassword()); } else if (sti.getDestinationZipEncryptMethod().equals(SyncTaskItem.ZIP_OPTION_ENCRYPT_AES256)) { zp.setEncryptionMethod(EncryptionMethod.AES); zp.setAesKeyStrength(AesKeyStrength.KEY_STRENGTH_256); zp.setEncryptFiles(true); - zp.setPassword(sti.getDestinationZipPassword()); + //zp.setPassword(sti.getDestinationZipPassword()); } } @@ -100,7 +100,7 @@ static public int syncMirrorLocalToLocalZip(SyncThreadWorkArea stwa, SyncTaskIte } String out_temp_path=dest_file_path+".tmp"; try { - BufferedZipFile3 bzf = new BufferedZipFile3(stwa.appContext, dest_file_path, out_temp_path, sti.getDestinationZipFileNameEncoding()); + BufferedZipFile3 bzf = new BufferedZipFile3(stwa.appContext, dest_file_path, out_temp_path, sti.getDestinationZipFileNameEncoding(), sti.getDestinationZipPassword()); if (bzf != null) { bzf.setNoCompressExtentionList(stwa.gp.settingNoCompressFileType); // bzf.setPassword(sti.getDestinationZipPassword()); @@ -197,7 +197,7 @@ static public int syncCopyLocalToLocalZip(SyncThreadWorkArea stwa, SyncTaskItem } String out_temp_path=dest_file_path+".tmp"; try { - BufferedZipFile3 bzf = new BufferedZipFile3(stwa.appContext, dest_file_path, out_temp_path, sti.getDestinationZipFileNameEncoding()); + BufferedZipFile3 bzf = new BufferedZipFile3(stwa.appContext, dest_file_path, out_temp_path, sti.getDestinationZipFileNameEncoding(), sti.getDestinationZipPassword()); if (bzf != null) { bzf.setNoCompressExtentionList(stwa.gp.settingNoCompressFileType); // bzf.setPassword(sti.getDestinationZipPassword()); @@ -279,7 +279,7 @@ static public int syncMoveLocalToLocalZip(SyncThreadWorkArea stwa, SyncTaskItem } String out_temp_path=dest_file_path+".tmp"; try { - BufferedZipFile3 bzf = new BufferedZipFile3(stwa.appContext, dest_file_path, out_temp_path, sti.getDestinationZipFileNameEncoding()); + BufferedZipFile3 bzf = new BufferedZipFile3(stwa.appContext, dest_file_path, out_temp_path, sti.getDestinationZipFileNameEncoding(), sti.getDestinationZipPassword()); if (bzf != null) { bzf.setNoCompressExtentionList(stwa.gp.settingNoCompressFileType); // bzf.setPassword(sti.getDestinationZipPassword()); diff --git a/app/src/main/java/com/sentaroh/android/SMBSync3/TaskEditor.java b/app/src/main/java/com/sentaroh/android/SMBSync3/TaskEditor.java index 6c579499..a8748878 100644 --- a/app/src/main/java/com/sentaroh/android/SMBSync3/TaskEditor.java +++ b/app/src/main/java/com/sentaroh/android/SMBSync3/TaskEditor.java @@ -27,34 +27,24 @@ this software and associated documentation files (the "Software"), to deal import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; -import android.content.Intent; -import android.content.res.ColorStateList; import android.content.res.Configuration; -import android.graphics.Color; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Build; import android.os.Bundle; -import android.os.Environment; import android.os.Handler; -import android.os.storage.StorageManager; import android.text.Editable; import android.text.TextWatcher; -import android.text.method.HideReturnsTransformationMethod; import android.text.method.PasswordTransformationMethod; import android.util.Base64; -import android.view.ActionMode; import android.view.KeyEvent; import android.view.LayoutInflater; -import android.view.Menu; -import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.webkit.WebView; -import android.webkit.WebViewClient; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.Button; @@ -67,16 +57,16 @@ this software and associated documentation files (the "Software"), to deal import android.widget.Spinner; import android.widget.TextView; +import androidx.annotation.NonNull; +import androidx.core.content.ContextCompat; import androidx.fragment.app.DialogFragment; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentTransaction; -import com.google.android.material.textfield.TextInputEditText; import com.google.android.material.textfield.TextInputLayout; import com.sentaroh.android.SMBSync3.LocalStorageSelectorAdapter.LocalStorageSelectorItem; -import com.sentaroh.android.Utilities3.CallBackListener; import com.sentaroh.android.Utilities3.Dialog.CommonDialog; import com.sentaroh.android.Utilities3.Dialog.CommonFileSelector2; import com.sentaroh.android.Utilities3.MiscUtil; @@ -93,14 +83,22 @@ this software and associated documentation files (the "Software"), to deal import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; import java.util.ArrayList; +import java.util.Calendar; import java.util.Date; +import java.util.Locale; +import java.util.Objects; import java.util.regex.Matcher; import java.util.regex.Pattern; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import static android.view.KeyEvent.KEYCODE_BACK; import static com.sentaroh.android.SMBSync3.Constants.*; -import static com.sentaroh.android.SMBSync3.SmbServerScanner.SmbServerScanResult.SMB_LEVEL_SMB1; import static com.sentaroh.android.SMBSync3.SyncTaskItem.TEMPLATE_ORIGINAL_NAME; import static com.sentaroh.android.SMBSync3.SyncTaskItem.ARCHIVE_SUFFIX_DIGIT_DEFAULT; import static com.sentaroh.android.Utilities3.SafFile3.SAF_FILE_PRIMARY_UUID; @@ -116,6 +114,8 @@ public class TaskEditor extends DialogFragment { private TaskListUtils mTaskUtil = null; private CommonUtilities mUtil = null; + private static final Logger log= LoggerFactory.getLogger(TaskEditor.class); + private FragmentManager mFragMgr = null; public static TaskEditor newInstance() { @@ -129,13 +129,13 @@ public TaskEditor() { } @Override - public void onSaveInstanceState(Bundle outState) { + public void onSaveInstanceState(@NonNull Bundle outState) { super.onSaveInstanceState(outState); mUtil.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName() + " entered"); } @Override - public void onConfigurationChanged(final Configuration newConfig) { + public void onConfigurationChanged(@NonNull final Configuration newConfig) { // Ignore orientation change to keep activity from restarting super.onConfigurationChanged(newConfig); mUtil.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName() + " entered"); @@ -144,7 +144,7 @@ public void onConfigurationChanged(final Configuration newConfig) { } @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mUtil.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName() + " entered"); View view = super.onCreateView(inflater, container, savedInstanceState); CommonDialog.setDlgBoxSizeLimit(mDialog, true); @@ -154,12 +154,12 @@ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle sa @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - setRetainInstance(true); + //setRetainInstance(true); if (mActivity == null) mActivity = (ActivityMain)getActivity(); mFragment = this; - mFragMgr = this.getFragmentManager(); + if (mFragMgr == null) mFragMgr = Objects.requireNonNull(mActivity).getSupportFragmentManager(); if (mGp==null) mGp=GlobalWorkArea.getGlobalParameter(mActivity); - if (mUtil == null) mUtil = new CommonUtilities(mActivity, "TaskEditor", mGp, getFragmentManager()); + if (mUtil == null) mUtil = new CommonUtilities(mActivity, "TaskEditor", mGp, mFragMgr); mUtil.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName() + " entered"); if (mTerminateRequired) { this.dismiss(); @@ -170,18 +170,28 @@ private void initFragment() { } +/* + //Deprecated @Override final public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mUtil.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName() + " entered"); } +*/ + //Called before onCreate() @Override - final public void onAttach(Activity activity) { - super.onAttach(activity); - if (mActivity == null) mActivity = (ActivityMain)getActivity(); - if (mGp==null) mGp=GlobalWorkArea.getGlobalParameter(mActivity); - if (mUtil == null) mUtil = new CommonUtilities(mActivity, "TaskEditor", mGp, getFragmentManager()); + final public void onAttach(@NonNull Context context) { + super.onAttach(context); + if (context instanceof Activity){ + mActivity = (ActivityMain) context; + } + + //if (mActivity == null) mActivity = (ActivityMain)getActivity(); + //if (mActivity == null) log.debug("TaskEditor onAttach mActivity is null"); + if (mFragMgr == null) mFragMgr = mActivity.getSupportFragmentManager(); + if (mGp == null) mGp=GlobalWorkArea.getGlobalParameter(mActivity); + if (mUtil == null) mUtil = new CommonUtilities(mActivity, "TaskEditor", mGp, mFragMgr); mUtil.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName() + " entered"); } @@ -208,16 +218,17 @@ final public void onStop() { @Override public void onDestroyView() { mUtil.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName() + " entered"); - if (getDialog() != null && getRetainInstance()) + //if (getDialog() != null && getRetainInstance()) + if (getDialog() != null) getDialog().setDismissMessage(null); super.onDestroyView(); } @Override - public void onCancel(DialogInterface di) { + public void onCancel(@NonNull DialogInterface di) { mUtil.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName() + " entered"); if (!mTerminateRequired) { - final Button btnCancel = (Button) mDialog.findViewById(R.id.edit_profile_sync_dlg_btn_cancel); + final Button btnCancel = mDialog.findViewById(R.id.edit_profile_sync_dlg_btn_cancel); btnCancel.performClick(); } mFragment.dismiss(); @@ -225,11 +236,12 @@ public void onCancel(DialogInterface di) { } @Override - public void onDismiss(DialogInterface di) { + public void onDismiss(@NonNull DialogInterface di) { mUtil.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName() + " entered"); super.onDismiss(di); } + @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { mUtil.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName() + " entered"); @@ -246,7 +258,7 @@ public Dialog onCreateDialog(Bundle savedInstanceState) { return mDialog; } - class SavedViewContents { + static class SavedViewContents { public CharSequence prof_name_et; public int prof_name_et_spos; public int prof_name_et_epos; @@ -310,63 +322,63 @@ class SavedViewContents { private SavedViewContents saveViewContents() { SavedViewContents sv = new SavedViewContents(); - final EditText et_sync_main_task_name = (EditText) mDialog.findViewById(R.id.edit_sync_task_task_name); - final CheckedTextView ctv_auto = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_ctv_auto); - final Spinner spinnerSyncOption = (Spinner) mDialog.findViewById(R.id.edit_sync_task_sync_type); + final EditText et_sync_main_task_name = mDialog.findViewById(R.id.edit_sync_task_task_name); + final CheckedTextView ctv_auto = mDialog.findViewById(R.id.edit_sync_task_ctv_auto); + final Spinner spinnerSyncOption = mDialog.findViewById(R.id.edit_sync_task_sync_type); - final Button swap_source_destination = (Button)mDialog.findViewById(R.id.edit_sync_task_swap_source_and_destination_btn); - final Button source_folder_info = (Button) mDialog.findViewById(R.id.edit_sync_task_source_folder_info_btn); - final Button destination_folder_info = (Button) mDialog.findViewById(R.id.edit_sync_task_destination_folder_info_btn); + final Button swap_source_destination = mDialog.findViewById(R.id.edit_sync_task_swap_source_and_destination_btn); + final Button source_folder_info = mDialog.findViewById(R.id.edit_sync_task_source_folder_info_btn); + final Button destination_folder_info = mDialog.findViewById(R.id.edit_sync_task_destination_folder_info_btn); - final Button sync_task_edit_btn_ok = (Button) mDialog.findViewById(R.id.edit_profile_sync_dlg_btn_ok); + final Button sync_task_edit_btn_ok = mDialog.findViewById(R.id.edit_profile_sync_dlg_btn_ok); - final Button dir_filter_btn = (Button) mDialog.findViewById(R.id.sync_filter_edit_dir_filter_btn); - final Button file_filter_btn = (Button) mDialog.findViewById(R.id.sync_filter_edit_file_filter_btn); + final Button dir_filter_btn = mDialog.findViewById(R.id.sync_filter_edit_dir_filter_btn); + final Button file_filter_btn = mDialog.findViewById(R.id.sync_filter_edit_file_filter_btn); // final TextView dlg_file_filter=(TextView) mDialog.findViewById(R.id.sync_filter_summary_file_filter); // final TextView dlg_dir_filter=(TextView) mDialog.findViewById(R.id.sync_filter_summary_dir_filter); - final LinearLayout ll_special_option_view = (LinearLayout) mDialog.findViewById(R.id.edit_sync_task_option_special_option_view); - - final CheckedTextView ctvTestMode = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_test_mode); - - final LinearLayout ll_specific_file_type_view = (LinearLayout) mDialog.findViewById(R.id.sync_filter_file_type_detail_view); - - final CheckedTextView ctv_task_sync_when_cahrging =(CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_start_when_charging); - final CheckedTextView ctvProcessRootDirFile = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_source_root_dir_file); - final CheckedTextView ctvConfirmOverride = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_confirm_override_delete_file); - final Spinner spinnerSyncWifiStatus = (Spinner) mDialog.findViewById(R.id.edit_sync_task_option_spinner_wifi_status); - final CheckedTextView ctv_sync_allow_global_ip_addr =(CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_sync_allow_all_ip_address); - final CheckedTextView ctvShowSpecialOption = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_show_special_option); - final CheckedTextView ctvSyncSubDir = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_sub_dir); - final CheckedTextView ctvSyncEmptyDir = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_empty_directory); - final CheckedTextView ctvSyncHiddenDir = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_hidden_directory); - final CheckedTextView ctvSyncHiddenFile = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_hidden_file); - final CheckedTextView ctvProcessOverride = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_process_override_delete_file); - final CheckedTextView ctvDeleteFirst = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_delete_first_when_mirror); - - final CheckedTextView ctvIgnoreFilterRemoveDirFileDesNotExistsInSource = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_remove_dir_file_excluded_by_filter); - - final CheckedTextView ctvRetry = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_retry_if_error_occured); - final CheckedTextView ctvSyncUseRemoteSmallIoArea = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_use_remote_small_io_area); - final CheckedTextView ctvDoNotResetRemoteFile = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_do_mot_reset_file_last_mod_time); - final CheckedTextView ctvDiffUseFileSize = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_diff_use_file_size); - final CheckedTextView ctvDeterminChangedFileSizeGtDestination = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_diff_file_size_greater_than_destination); - final CheckedTextView ctDeterminChangedFileByTime = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_diff_use_last_mod_time); - final Spinner spinnerSyncDiffTimeValue = (Spinner) mDialog.findViewById(R.id.edit_sync_task_option_spinner_diff_file_determin_time_value); - final CheckedTextView ctv_never_overwrite_destination_file_newer_than_the_source_file =(CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_never_overwrite_destination_file_if_it_is_newer_than_the_source_file); - final CheckedTextView ctv_ignore_dst_difference =(CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_diff_ignore_dst_difference); - final Spinner spinnerSyncDstOffsetValue =(Spinner) mDialog.findViewById(R.id.edit_sync_task_option_spinner_offset_daylight_saving_time_value); - final CheckedTextView ctv_edit_sync_task_option_ignore_unusable_character_used_directory_file_name =(CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ignore_unusable_character_used_directory_file_name); - final CheckedTextView ctv_sync_remove_source_if_empty =(CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_remove_directory_if_empty_when_move); - - final Spinner sp_file_size_type=(Spinner)mDialog.findViewById(R.id.sync_filter_file_size_type_spinner); - final EditText et_file_size_value=(EditText)mDialog.findViewById(R.id.sync_filter_file_size_value); - final Spinner sp_file_size_unit=(Spinner)mDialog.findViewById(R.id.sync_filter_file_size_unit_spinner); - - final CheckedTextView ctvIgnore_0_byte_file=(CheckedTextView)mDialog.findViewById(R.id.edit_sync_task_option_ignore_file_size_0_bytes_file); - - final Spinner sp_file_date_type=(Spinner)mDialog.findViewById(R.id.sync_filter_file_date_type_spinner); - final EditText et_file_date_value=(EditText)mDialog.findViewById(R.id.sync_filter_file_date_value); + final LinearLayout ll_special_option_view = mDialog.findViewById(R.id.edit_sync_task_option_special_option_view); + + final CheckedTextView ctvTestMode = mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_test_mode); + + final LinearLayout ll_specific_file_type_view = mDialog.findViewById(R.id.sync_filter_file_type_detail_view); + + final CheckedTextView ctv_task_sync_when_cahrging = mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_start_when_charging); + final CheckedTextView ctvProcessRootDirFile = mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_source_root_dir_file); + final CheckedTextView ctvConfirmOverride = mDialog.findViewById(R.id.edit_sync_task_option_ctv_confirm_override_delete_file); + final Spinner spinnerSyncWifiStatus = mDialog.findViewById(R.id.edit_sync_task_option_spinner_wifi_status); + final CheckedTextView ctv_sync_allow_global_ip_addr = mDialog.findViewById(R.id.edit_sync_task_option_sync_allow_all_ip_address); + final CheckedTextView ctvShowSpecialOption = mDialog.findViewById(R.id.edit_sync_task_option_ctv_show_special_option); + final CheckedTextView ctvSyncSubDir = mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_sub_dir); + final CheckedTextView ctvSyncEmptyDir = mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_empty_directory); + final CheckedTextView ctvSyncHiddenDir = mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_hidden_directory); + final CheckedTextView ctvSyncHiddenFile = mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_hidden_file); + final CheckedTextView ctvProcessOverride = mDialog.findViewById(R.id.edit_sync_task_option_ctv_process_override_delete_file); + final CheckedTextView ctvDeleteFirst = mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_delete_first_when_mirror); + + final CheckedTextView ctvIgnoreFilterRemoveDirFileDesNotExistsInSource = mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_remove_dir_file_excluded_by_filter); + + final CheckedTextView ctvRetry = mDialog.findViewById(R.id.edit_sync_task_option_ctv_retry_if_error_occured); + final CheckedTextView ctvSyncUseRemoteSmallIoArea = mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_use_remote_small_io_area); + final CheckedTextView ctvDoNotResetRemoteFile = mDialog.findViewById(R.id.edit_sync_task_option_ctv_do_mot_reset_file_last_mod_time); + final CheckedTextView ctvDiffUseFileSize = mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_diff_use_file_size); + final CheckedTextView ctvDeterminChangedFileSizeGtDestination = mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_diff_file_size_greater_than_destination); + final CheckedTextView ctDeterminChangedFileByTime = mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_diff_use_last_mod_time); + final Spinner spinnerSyncDiffTimeValue = mDialog.findViewById(R.id.edit_sync_task_option_spinner_diff_file_determin_time_value); + final CheckedTextView ctv_never_overwrite_destination_file_newer_than_the_source_file = mDialog.findViewById(R.id.edit_sync_task_option_never_overwrite_destination_file_if_it_is_newer_than_the_source_file); + final CheckedTextView ctv_ignore_dst_difference = mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_diff_ignore_dst_difference); + final Spinner spinnerSyncDstOffsetValue = mDialog.findViewById(R.id.edit_sync_task_option_spinner_offset_daylight_saving_time_value); + final CheckedTextView ctv_edit_sync_task_option_ignore_unusable_character_used_directory_file_name = mDialog.findViewById(R.id.edit_sync_task_option_ignore_unusable_character_used_directory_file_name); + final CheckedTextView ctv_sync_remove_source_if_empty = mDialog.findViewById(R.id.edit_sync_task_option_ctv_remove_directory_if_empty_when_move); + + final Spinner sp_file_size_type= mDialog.findViewById(R.id.sync_filter_file_size_type_spinner); + final EditText et_file_size_value= mDialog.findViewById(R.id.sync_filter_file_size_value); + final Spinner sp_file_size_unit= mDialog.findViewById(R.id.sync_filter_file_size_unit_spinner); + + final CheckedTextView ctvIgnore_0_byte_file= mDialog.findViewById(R.id.edit_sync_task_option_ignore_file_size_0_bytes_file); + + final Spinner sp_file_date_type= mDialog.findViewById(R.id.sync_filter_file_date_type_spinner); + final EditText et_file_date_value= mDialog.findViewById(R.id.sync_filter_file_date_value); sv.prof_name_et = et_sync_main_task_name.getText(); sv.prof_name_et_spos = et_sync_main_task_name.getSelectionStart(); @@ -433,69 +445,69 @@ private void performClickNoSound(View v) { } private void restoreViewContents(final SavedViewContents sv) { - final EditText et_sync_main_task_name = (EditText) mDialog.findViewById(R.id.edit_sync_task_task_name); - final CheckedTextView ctv_auto = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_ctv_auto); - final Spinner spinnerSyncOption = (Spinner) mDialog.findViewById(R.id.edit_sync_task_sync_type); + final EditText et_sync_main_task_name = mDialog.findViewById(R.id.edit_sync_task_task_name); + final CheckedTextView ctv_auto = mDialog.findViewById(R.id.edit_sync_task_ctv_auto); + final Spinner spinnerSyncOption = mDialog.findViewById(R.id.edit_sync_task_sync_type); - final Button swap_source_destination = (Button)mDialog.findViewById(R.id.edit_sync_task_swap_source_and_destination_btn); - final Button source_folder_info = (Button) mDialog.findViewById(R.id.edit_sync_task_source_folder_info_btn); - final Button destination_folder_info = (Button) mDialog.findViewById(R.id.edit_sync_task_destination_folder_info_btn); + final Button swap_source_destination = mDialog.findViewById(R.id.edit_sync_task_swap_source_and_destination_btn); + final Button source_folder_info = mDialog.findViewById(R.id.edit_sync_task_source_folder_info_btn); + final Button destination_folder_info = mDialog.findViewById(R.id.edit_sync_task_destination_folder_info_btn); - final Button edit_sync_task_ok_btn = (Button) mDialog.findViewById(R.id.edit_profile_sync_dlg_btn_ok); + final Button edit_sync_task_ok_btn = mDialog.findViewById(R.id.edit_profile_sync_dlg_btn_ok); - final Button dir_filter_btn = (Button) mDialog.findViewById(R.id.sync_filter_edit_dir_filter_btn); - final Button file_filter_btn = (Button) mDialog.findViewById(R.id.sync_filter_edit_file_filter_btn); + final Button dir_filter_btn = mDialog.findViewById(R.id.sync_filter_edit_dir_filter_btn); + final Button file_filter_btn = mDialog.findViewById(R.id.sync_filter_edit_file_filter_btn); - final LinearLayout ll_special_option_view = (LinearLayout) mDialog.findViewById(R.id.edit_sync_task_option_special_option_view); + final LinearLayout ll_special_option_view = mDialog.findViewById(R.id.edit_sync_task_option_special_option_view); - final CheckedTextView ctvTestMode = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_test_mode); + final CheckedTextView ctvTestMode = mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_test_mode); - final LinearLayout ll_specific_file_type_view = (LinearLayout) mDialog.findViewById(R.id.sync_filter_file_type_detail_view); + final LinearLayout ll_specific_file_type_view = mDialog.findViewById(R.id.sync_filter_file_type_detail_view); - final LinearLayout ll_specific_directory_view = (LinearLayout) mDialog.findViewById(R.id.sync_filter_sub_directory_detail_view); + final LinearLayout ll_specific_directory_view = mDialog.findViewById(R.id.sync_filter_sub_directory_detail_view); - final CheckedTextView ctv_task_sync_when_cahrging =(CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_start_when_charging); - final CheckedTextView ctvProcessRootDirFile = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_source_root_dir_file); - final CheckedTextView ctvConfirmOverride = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_confirm_override_delete_file); - final Spinner spinnerSyncWifiStatus = (Spinner) mDialog.findViewById(R.id.edit_sync_task_option_spinner_wifi_status); - final CheckedTextView ctv_sync_allow_global_ip_addr =(CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_sync_allow_all_ip_address); - final CheckedTextView ctvShowSpecialOption = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_show_special_option); - final CheckedTextView ctvSyncSubDir = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_sub_dir); - final CheckedTextView ctvSyncEmptyDir = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_empty_directory); - final CheckedTextView ctvSyncHiddenDir = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_hidden_directory); - final CheckedTextView ctvSyncHiddenFile = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_hidden_file); - final CheckedTextView ctvProcessOverride = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_process_override_delete_file); - final CheckedTextView ctvDeleteFirst = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_delete_first_when_mirror); + final CheckedTextView ctv_task_sync_when_cahrging = mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_start_when_charging); + final CheckedTextView ctvProcessRootDirFile = mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_source_root_dir_file); + final CheckedTextView ctvConfirmOverride = mDialog.findViewById(R.id.edit_sync_task_option_ctv_confirm_override_delete_file); + final Spinner spinnerSyncWifiStatus = mDialog.findViewById(R.id.edit_sync_task_option_spinner_wifi_status); + final CheckedTextView ctv_sync_allow_global_ip_addr = mDialog.findViewById(R.id.edit_sync_task_option_sync_allow_all_ip_address); + final CheckedTextView ctvShowSpecialOption = mDialog.findViewById(R.id.edit_sync_task_option_ctv_show_special_option); + final CheckedTextView ctvSyncSubDir = mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_sub_dir); + final CheckedTextView ctvSyncEmptyDir = mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_empty_directory); + final CheckedTextView ctvSyncHiddenDir = mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_hidden_directory); + final CheckedTextView ctvSyncHiddenFile = mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_hidden_file); + final CheckedTextView ctvProcessOverride = mDialog.findViewById(R.id.edit_sync_task_option_ctv_process_override_delete_file); + final CheckedTextView ctvDeleteFirst = mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_delete_first_when_mirror); - final CheckedTextView ctvIgnoreFilterRemoveDirFileDesNotExistsInSource = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_remove_dir_file_excluded_by_filter); + final CheckedTextView ctvIgnoreFilterRemoveDirFileDesNotExistsInSource = mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_remove_dir_file_excluded_by_filter); - final CheckedTextView ctvRetry = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_retry_if_error_occured); - final CheckedTextView ctvSyncUseRemoteSmallIoArea = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_use_remote_small_io_area); - final CheckedTextView ctvDoNotResetRemoteFile = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_do_mot_reset_file_last_mod_time); - final CheckedTextView ctvDiffUseFileSize = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_diff_use_file_size); - final CheckedTextView ctvDeterminChangedFileSizeGtDestination = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_diff_file_size_greater_than_destination); - final CheckedTextView ctDeterminChangedFileByTime = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_diff_use_last_mod_time); - final Spinner spinnerSyncDiffTimeValue = (Spinner) mDialog.findViewById(R.id.edit_sync_task_option_spinner_diff_file_determin_time_value); - final CheckedTextView ctv_never_overwrite_destination_file_newer_than_the_source_file =(CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_never_overwrite_destination_file_if_it_is_newer_than_the_source_file); - final CheckedTextView ctv_ignore_dst_difference =(CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_diff_ignore_dst_difference); - final Spinner spinnerSyncDstOffsetValue =(Spinner) mDialog.findViewById(R.id.edit_sync_task_option_spinner_offset_daylight_saving_time_value); - final CheckedTextView ctv_edit_sync_task_option_ignore_unusable_character_used_directory_file_name =(CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ignore_unusable_character_used_directory_file_name); - final CheckedTextView ctv_sync_remove_source_if_empty =(CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_remove_directory_if_empty_when_move); + final CheckedTextView ctvRetry = mDialog.findViewById(R.id.edit_sync_task_option_ctv_retry_if_error_occured); + final CheckedTextView ctvSyncUseRemoteSmallIoArea = mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_use_remote_small_io_area); + final CheckedTextView ctvDoNotResetRemoteFile = mDialog.findViewById(R.id.edit_sync_task_option_ctv_do_mot_reset_file_last_mod_time); + final CheckedTextView ctvDiffUseFileSize = mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_diff_use_file_size); + final CheckedTextView ctvDeterminChangedFileSizeGtDestination = mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_diff_file_size_greater_than_destination); + final CheckedTextView ctDeterminChangedFileByTime = mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_diff_use_last_mod_time); + final Spinner spinnerSyncDiffTimeValue = mDialog.findViewById(R.id.edit_sync_task_option_spinner_diff_file_determin_time_value); + final CheckedTextView ctv_never_overwrite_destination_file_newer_than_the_source_file = mDialog.findViewById(R.id.edit_sync_task_option_never_overwrite_destination_file_if_it_is_newer_than_the_source_file); + final CheckedTextView ctv_ignore_dst_difference = mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_diff_ignore_dst_difference); + final Spinner spinnerSyncDstOffsetValue = mDialog.findViewById(R.id.edit_sync_task_option_spinner_offset_daylight_saving_time_value); + final CheckedTextView ctv_edit_sync_task_option_ignore_unusable_character_used_directory_file_name = mDialog.findViewById(R.id.edit_sync_task_option_ignore_unusable_character_used_directory_file_name); + final CheckedTextView ctv_sync_remove_source_if_empty = mDialog.findViewById(R.id.edit_sync_task_option_ctv_remove_directory_if_empty_when_move); - final Spinner sp_file_size_type=(Spinner)mDialog.findViewById(R.id.sync_filter_file_size_type_spinner); - final EditText et_file_size_value=(EditText)mDialog.findViewById(R.id.sync_filter_file_size_value); - final Spinner sp_file_size_unit=(Spinner)mDialog.findViewById(R.id.sync_filter_file_size_unit_spinner); + final Spinner sp_file_size_type= mDialog.findViewById(R.id.sync_filter_file_size_type_spinner); + final EditText et_file_size_value= mDialog.findViewById(R.id.sync_filter_file_size_value); + final Spinner sp_file_size_unit= mDialog.findViewById(R.id.sync_filter_file_size_unit_spinner); - final CheckedTextView ctvIgnore_0_byte_file=(CheckedTextView)mDialog.findViewById(R.id.edit_sync_task_option_ignore_file_size_0_bytes_file); + final CheckedTextView ctvIgnore_0_byte_file= mDialog.findViewById(R.id.edit_sync_task_option_ignore_file_size_0_bytes_file); - final Spinner sp_file_date_type=(Spinner)mDialog.findViewById(R.id.sync_filter_file_date_type_spinner); - final EditText et_file_date_value=(EditText)mDialog.findViewById(R.id.sync_filter_file_date_value); + final Spinner sp_file_date_type= mDialog.findViewById(R.id.sync_filter_file_date_type_spinner); + final EditText et_file_date_value= mDialog.findViewById(R.id.sync_filter_file_date_value); et_sync_main_task_name.setText(sv.prof_name_et); ctvTestMode.setChecked(sv.sync_test_mode); if (sv.sync_test_mode) CommonUtilities.setViewEnabled(mActivity, ctv_auto, false); ctv_auto.setChecked(sv.cb_active); - CommonUtilities.setViewEnabled(mActivity, spinnerSyncOption, false); + //CommonUtilities.setViewEnabled(mActivity, spinnerSyncOption, false); spinnerSyncOption.setSelection(sv.sync_opt); CommonUtilities.setViewEnabled(mActivity, swap_source_destination, sv.sync_task_swap_source_destination_button_enabled); @@ -522,7 +534,7 @@ private void restoreViewContents(final SavedViewContents sv) { ctvConfirmOverride.setChecked(sv.sync_conf_required); ctvDeleteFirst.setChecked(sv.sync_delete_first); - CommonUtilities.setViewEnabled(mActivity, spinnerSyncWifiStatus, false); + //CommonUtilities.setViewEnabled(mActivity, spinnerSyncWifiStatus, false); int wifi_opt_sel=0; if (sv.sync_wifi_option.equals(SyncTaskItem.WIFI_STATUS_WIFI_CONNECT_ANY_AP)) wifi_opt_sel=1; @@ -543,7 +555,7 @@ private void restoreViewContents(final SavedViewContents sv) { ctvDeterminChangedFileSizeGtDestination.setChecked(sv.sync_diff_file_size_gt_destination); ctDeterminChangedFileByTime.setChecked(sv.sync_diff_use_last_mod); - CommonUtilities.setViewEnabled(mActivity, spinnerSyncDiffTimeValue, false); + //CommonUtilities.setViewEnabled(mActivity, spinnerSyncDiffTimeValue, false); spinnerSyncDiffTimeValue.setSelection(sv.sync_diff_last_mod_value); ctv_task_sync_when_cahrging.setChecked(sv.sync_when_cahrging); @@ -585,7 +597,7 @@ public void reInitViewWidget() { private void restoreEditSyncFolderContents() { if (mEditFolderDialog!=null) { - SyncFolderEditValue new_sfev=buildSyncFolderEditValue(mEditFolderDialog, mEditFolderSfev); + SyncFolderEditValue new_sfev=buildSyncFolderEditValue(mEditFolderDialog, mEditFolderSfev, false); editSyncFolder(true, mEditFolderSti, new_sfev, mEditFolderNotify); } } @@ -632,6 +644,7 @@ private void setDialogMsg(final TextView tv, final String msg) { } } + // not used private static String removeInvalidCharForDirectoryName(String in_str) { String out = in_str .replaceAll(":", "") @@ -663,6 +676,7 @@ static private String removeInvalidCharForDirectoryName(Editable s) { return null; } + // not used private static String removeInvalidCharForFileName(String in_str) { String out = in_str .replaceAll(":", "") @@ -722,89 +736,108 @@ static private String removeInvalidCharForShareName(Editable s) { } private void setSyncFolderSmbListener(final Dialog dialog, final SyncTaskItem sti, final SyncFolderEditValue sfev, final SyncFolderEditValue org_sfev, final NotifyEvent ntfy) { - final TextView dlg_msg = (TextView) dialog.findViewById(R.id.edit_sync_folder_dlg_msg); + final TextView dlg_msg = dialog.findViewById(R.id.edit_sync_folder_dlg_msg); dlg_msg.setVisibility(TextView.VISIBLE); - final CheckedTextView ctv_sync_folder_edit_smb_detail = (CheckedTextView) dialog.findViewById(R.id.edit_sync_folder_dlg_ctv_edit_smb_server_detail); - final Spinner sp_sync_folder_type = (Spinner) dialog.findViewById(R.id.edit_sync_folder_dlg_folder_type); - final Spinner sp_sync_folder_smb_proto = (Spinner) dialog.findViewById(R.id.edit_sync_folder_dlg_smb_protocol); - - final Button btn_search_host = (Button) dialog.findViewById(R.id.edit_sync_folder_dlg_search_remote_host); - final Button btn_sync_folder_smb_list_dir = (Button) dialog.findViewById(R.id.edit_sync_folder_dlg_list_smb_directory_btn); - final EditText et_sync_folder_dir_name = (EditText) dialog.findViewById(R.id.edit_sync_folder_dlg_smb_directory_name); - final EditText et_remote_host = (EditText) dialog.findViewById(R.id.edit_sync_folder_dlg_remote_server); + final CheckedTextView ctv_sync_folder_edit_smb_detail = dialog.findViewById(R.id.edit_sync_folder_dlg_ctv_edit_smb_server_detail); + final Spinner sp_sync_folder_type = dialog.findViewById(R.id.edit_sync_folder_dlg_folder_type); + final Spinner sp_sync_folder_smb_proto = dialog.findViewById(R.id.edit_sync_folder_dlg_smb_protocol); + + final Button btn_search_host = dialog.findViewById(R.id.edit_sync_folder_dlg_search_remote_host); + final Button btn_sync_folder_smb_list_dir = dialog.findViewById(R.id.edit_sync_folder_dlg_list_smb_directory_btn); + final EditText et_sync_folder_dir_name = dialog.findViewById(R.id.edit_sync_folder_dlg_smb_directory_name); + final EditText et_remote_host = dialog.findViewById(R.id.edit_sync_folder_dlg_remote_server); // final LinearLayout ll_sync_folder_port = (LinearLayout)dialog.findViewById(R.id.edit_sync_folder_dlg_port_option_view); - final CheckedTextView ctv_sync_folder_use_port = (CheckedTextView) dialog.findViewById(R.id.edit_sync_folder_dlg_ctv_use_remote_port_number); - final EditText et_sync_folder_port = (EditText) dialog.findViewById(R.id.edit_sync_folder_dlg_remote_port); - final LinearLayout ll_dir_view = (LinearLayout) dialog.findViewById(R.id.edit_sync_folder_dlg_smb_directory_view); - final CheckedTextView ctv_sync_folder_use_pswd = (CheckedTextView) dialog.findViewById(R.id.edit_sync_folder_dlg_ctv_use_user_pass); - final EditText et_sync_folder_domain = (EditText) dialog.findViewById(R.id.edit_sync_folder_dlg_remote_domain); - final EditText et_sync_folder_user = (EditText) dialog.findViewById(R.id.edit_sync_folder_dlg_remote_user); - final TextInputEditText et_sync_folder_pswd = (TextInputEditText ) dialog.findViewById(R.id.edit_sync_folder_dlg_remote_pass); - final TextInputLayout ll_sync_folder_pswd_view = (TextInputLayout) dialog.findViewById(R.id.edit_sync_folder_dlg_remote_pass_view); + final CheckedTextView ctv_sync_folder_use_port = dialog.findViewById(R.id.edit_sync_folder_dlg_ctv_use_remote_port_number); + final EditText et_sync_folder_port = dialog.findViewById(R.id.edit_sync_folder_dlg_remote_port); + final LinearLayout ll_dir_view = dialog.findViewById(R.id.edit_sync_folder_dlg_smb_directory_view); + final CheckedTextView ctv_sync_folder_use_pswd = dialog.findViewById(R.id.edit_sync_folder_dlg_ctv_use_user_pass); + final EditText et_sync_folder_domain = dialog.findViewById(R.id.edit_sync_folder_dlg_remote_domain); + final EditText et_sync_folder_user = dialog.findViewById(R.id.edit_sync_folder_dlg_remote_user); + final EditText et_sync_folder_pswd = dialog.findViewById(R.id.edit_sync_folder_dlg_remote_pass); + final TextInputLayout ll_sync_folder_pswd_view = dialog.findViewById(R.id.edit_sync_folder_dlg_remote_pass_view); // final CheckedTextView ctv_show_password = (CheckedTextView) dialog.findViewById(R.id.edit_sync_folder_dlg_ctv_show_smb_account_password); - final Button btn_sync_folder_list_share = (Button) dialog.findViewById(R.id.edit_sync_folder_dlg_list_share_btn); - final EditText et_sync_folder_share_name = (EditText) dialog.findViewById(R.id.edit_sync_folder_dlg_share_name); - final Button btn_sync_folder_ok = (Button) dialog.findViewById(R.id.edit_profile_remote_btn_ok); + final Button btn_sync_folder_list_share = dialog.findViewById(R.id.edit_sync_folder_dlg_list_share_btn); + final EditText et_sync_folder_share_name = dialog.findViewById(R.id.edit_sync_folder_dlg_share_name); + final Button btn_sync_folder_ok = dialog.findViewById(R.id.edit_profile_remote_btn_ok); sp_sync_folder_smb_proto.setOnItemSelectedListener(null); setSpinnerSyncFolderSmbProto(sti, sp_sync_folder_smb_proto, sfev.folder_smb_protocol); et_remote_host.setText(sfev.folder_smb_host); - CommonUtilities.setCheckedTextViewListener(ctv_sync_folder_use_port); - if (!sfev.folder_smb_port.equals("")) { - ctv_sync_folder_use_port.setChecked(true); - CommonUtilities.setViewEnabled(mActivity, et_sync_folder_port, true); - et_sync_folder_port.setText(sfev.folder_smb_port); - } else { - if (sfev.folder_smb_use_port_number) ctv_sync_folder_use_port.setChecked(true); - else ctv_sync_folder_use_port.setChecked(false); - CommonUtilities.setViewEnabled(mActivity, et_sync_folder_port, false); - } + ctv_sync_folder_use_port.setChecked(sfev.folder_smb_use_port); + et_sync_folder_port.setText(sfev.folder_smb_port); + CommonUtilities.setViewEnabled(mActivity, et_sync_folder_port, ctv_sync_folder_use_port.isChecked()); + + //CommonUtilities.setCheckedTextViewListener(ctv_sync_folder_use_port); ctv_sync_folder_use_port.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { boolean isChecked = !ctv_sync_folder_use_port.isChecked(); ctv_sync_folder_use_port.setChecked(isChecked); CommonUtilities.setViewEnabled(mActivity, et_sync_folder_port, isChecked); - checkSyncFolderValidation(dialog, sti, sfev); + checkSyncFolderValidation(dialog, sti, sfev, org_sfev); + //setSyncFolderOkButtonEnabledIfFolderChanged(dialog, org_sfev); } }); et_sync_folder_domain.setVisibility(EditText.GONE); - if (!sfev.folder_smb_account.equals("") || !sfev.folder_smb_password.equals("") || sfev.folder_error_code!= SyncTaskItem.SYNC_FOLDER_STATUS_ERROR_NO_ERROR) { - ctv_sync_folder_use_pswd.setChecked(true); + + ctv_sync_folder_use_pswd.setChecked(sfev.folder_smb_use_pswd); + et_sync_folder_user.setText(sfev.folder_smb_account); + et_sync_folder_pswd.setText(sfev.folder_smb_password); + if (ctv_sync_folder_use_pswd.isChecked() || (sfev.folder_error_code != SyncTaskItem.SYNC_FOLDER_STATUS_ERROR_NO_ERROR)) { CommonUtilities.setViewEnabled(mActivity, et_sync_folder_user, true); - et_sync_folder_user.setText(sfev.folder_smb_account); CommonUtilities.setViewEnabled(mActivity, et_sync_folder_pswd, true); - et_sync_folder_pswd.setText(sfev.folder_smb_password); } else { - if (sfev.folder_smb_use_account_name_password) ctv_sync_folder_use_pswd.setChecked(true); - else ctv_sync_folder_use_pswd.setChecked(false); CommonUtilities.setViewEnabled(mActivity, et_sync_folder_user, false); CommonUtilities.setViewEnabled(mActivity, et_sync_folder_pswd, false); } + // if (mGp.settingSecurityReinitSmbAccountPasswordValue && !mGp.settingSecurityApplicationPasswordHashValue.equals("")) { // et_sync_folder_user.setText(""); // et_sync_folder_pswd.setText(""); // } - sfev.folder_smb_use_pswd =ctv_sync_folder_use_pswd.isChecked(); + ctv_sync_folder_use_pswd.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { boolean isChecked = !ctv_sync_folder_use_pswd.isChecked(); ctv_sync_folder_use_pswd.setChecked(isChecked); + + if (mGp.settingSecurityHideShowSmbPasswordButton) { + //ll_sync_folder_pswd_view.setPasswordVisibilityToggleEnabled(false); + ll_sync_folder_pswd_view.setEndIconMode(TextInputLayout.END_ICON_NONE); + } else { + //ll_sync_folder_pswd_view.setPasswordVisibilityToggleEnabled(isChecked); + ll_sync_folder_pswd_view.setEndIconMode(TextInputLayout.END_ICON_PASSWORD_TOGGLE); + } + + //Toggle SMB password Layout view on use password check/uncheck + CommonUtilities.setViewEnabled(mActivity, ll_sync_folder_pswd_view, isChecked); + CommonUtilities.setViewEnabled(mActivity, et_sync_folder_user, isChecked); CommonUtilities.setViewEnabled(mActivity, et_sync_folder_pswd, isChecked); -// ll_sync_folder_pswd_view.setPasswordVisibilityToggleEnabled(isChecked); - if (mGp.settingSecurityHideShowSmbPasswordButton) ll_sync_folder_pswd_view.setPasswordVisibilityToggleEnabled(false); - else ll_sync_folder_pswd_view.setPasswordVisibilityToggleEnabled(isChecked); - checkSyncFolderValidation(dialog, sti, sfev); + //ll_sync_folder_pswd_view.setPasswordVisibilityToggleEnabled(isChecked); + + checkSyncFolderValidation(dialog, sti, sfev, org_sfev); + //setSyncFolderOkButtonEnabledIfFolderChanged(dialog, org_sfev); } }); - if (mGp.settingSecurityHideShowSmbPasswordButton) ll_sync_folder_pswd_view.setPasswordVisibilityToggleEnabled(false); - else ll_sync_folder_pswd_view.setPasswordVisibilityToggleEnabled(true); + if (mGp.settingSecurityHideShowSmbPasswordButton) { + //ll_sync_folder_pswd_view.setPasswordVisibilityToggleEnabled(false); + ll_sync_folder_pswd_view.setEndIconMode(TextInputLayout.END_ICON_NONE); + } else { + //ll_sync_folder_pswd_view.setPasswordVisibilityToggleEnabled(true); + ll_sync_folder_pswd_view.setEndIconMode(TextInputLayout.END_ICON_PASSWORD_TOGGLE); + + // Mod 1/2: Preserve SMB password masked/unmasked state on screen rotation + if (sfev.show_smb_passowrd) et_sync_folder_pswd.setTransformationMethod(null); + else et_sync_folder_pswd.setTransformationMethod(new PasswordTransformationMethod()); + } + +/* // Mod: Allow copy/paste in smb password field when it is unmasked ll_sync_folder_pswd_view.setEndIconOnClickListener(new OnClickListener() { @Override public void onClick(View v) { @@ -834,11 +867,9 @@ public void onDestroyActionMode(ActionMode mode) { } else { et_sync_folder_pswd.setTransformationMethod(new PasswordTransformationMethod()); } - } }); -// if (sfev.show_smb_passowrd) et_sync_folder_pswd.setTransformationMethod(new PasswordTransformationMethod()); -// else et_sync_folder_pswd.setTransformationMethod(null); +*/ et_sync_folder_share_name.setText(sfev.folder_smb_share); @@ -849,7 +880,8 @@ public void beforeTextChanged(CharSequence s, int start, int count, int after) { public void onTextChanged(CharSequence s, int start, int before, int count) {} @Override public void afterTextChanged(Editable s) { - checkSyncFolderValidation(dialog, sti, sfev); + checkSyncFolderValidation(dialog, sti, sfev, org_sfev); + //setSyncFolderOkButtonEnabledIfFolderChanged(dialog, org_sfev); } }); et_sync_folder_port.addTextChangedListener(new TextWatcher() { @@ -859,7 +891,8 @@ public void beforeTextChanged(CharSequence s, int start, int count, int after) { public void onTextChanged(CharSequence s, int start, int before, int count) {} @Override public void afterTextChanged(Editable s) { - checkSyncFolderValidation(dialog, sti, sfev); + checkSyncFolderValidation(dialog, sti, sfev, org_sfev); + //setSyncFolderOkButtonEnabledIfFolderChanged(dialog, org_sfev); } }); @@ -870,7 +903,8 @@ public void beforeTextChanged(CharSequence s, int start, int count, int after) { public void onTextChanged(CharSequence s, int start, int before, int count) {} @Override public void afterTextChanged(Editable s) { - checkSyncFolderValidation(dialog, sti, sfev); + checkSyncFolderValidation(dialog, sti, sfev, org_sfev); + //setSyncFolderOkButtonEnabledIfFolderChanged(dialog, org_sfev); } }); et_sync_folder_pswd.addTextChangedListener(new TextWatcher() { @@ -880,7 +914,8 @@ public void beforeTextChanged(CharSequence s, int start, int count, int after) { public void onTextChanged(CharSequence s, int start, int before, int count) {} @Override public void afterTextChanged(Editable s) { - checkSyncFolderValidation(dialog, sti, sfev); + checkSyncFolderValidation(dialog, sti, sfev, org_sfev); + //setSyncFolderOkButtonEnabledIfFolderChanged(dialog, org_sfev); } }); et_sync_folder_share_name.addTextChangedListener(new TextWatcher() { @@ -894,14 +929,18 @@ public void afterTextChanged(Editable s) { if (remove_char!=null) { mUtil.showCommonDialogWarn(false, mActivity.getString(R.string.msgs_task_sync_task_dlg_share_name_has_invalid_char), "", null); } - checkSyncFolderValidation(dialog, sti, sfev); + checkSyncFolderValidation(dialog, sti, sfev, org_sfev); + //setSyncFolderOkButtonEnabledIfFolderChanged(dialog, org_sfev); } }); sp_sync_folder_smb_proto.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { - setSyncFolderViewVisibility(dialog, sti, sfev.is_source_folder, sfev); + setSyncFolderViewVisibility(dialog, sti, sfev.is_source_folder, sfev, org_sfev); + + //checkSyncFolderValidation(dialog, sti, sfev, org_sfev); + setSyncFolderOkButtonEnabledIfFolderChanged(dialog, org_sfev); } @Override public void onNothingSelected(AdapterView parent) { @@ -924,6 +963,17 @@ public void positiveResponse(Context arg0, Object[] o) { String smb_share_name=result[5]; mUtil.addDebugMsg(1,"I", "editSyncFolder(SMB) selected value, host="+smb_host+", protocol="+smb_level+", port="+smb_portnum+ ", account="+smb_acct_name+", share="+smb_share_name); + +/// + final EditText et_remote_host = dialog.findViewById(R.id.edit_sync_folder_dlg_remote_server); + final EditText et_sync_folder_port = dialog.findViewById(R.id.edit_sync_folder_dlg_remote_port); + final CheckedTextView ctv_sync_folder_use_port = dialog.findViewById(R.id.edit_sync_folder_dlg_ctv_use_remote_port_number); + final EditText et_sync_folder_user = dialog.findViewById(R.id.edit_sync_folder_dlg_remote_user); + final CheckedTextView ctv_sync_folder_use_pswd = dialog.findViewById(R.id.edit_sync_folder_dlg_ctv_use_user_pass); + final EditText et_sync_folder_pswd = dialog.findViewById(R.id.edit_sync_folder_dlg_remote_pass); + final EditText et_sync_folder_share_name = dialog.findViewById(R.id.edit_sync_folder_dlg_share_name); + final Spinner sp_sync_folder_smb_proto = dialog.findViewById(R.id.edit_sync_folder_dlg_smb_protocol); +/// et_remote_host.setText(smb_host); et_sync_folder_port.setText(smb_portnum); ctv_sync_folder_use_port.setChecked(!smb_portnum.equals("")); @@ -931,8 +981,9 @@ public void positiveResponse(Context arg0, Object[] o) { ctv_sync_folder_use_pswd.setChecked(!smb_acct_name.equals("") || !smb_acct_pswd.equals("")); et_sync_folder_pswd.setText(smb_acct_pswd); et_sync_folder_share_name.setText(smb_share_name); - if (smb_level.equals(SMB_LEVEL_SMB1)) sp_sync_folder_smb_proto.setSelection(0); - else sp_sync_folder_smb_proto.setSelection(1); + if (smb_level.equals(SyncTaskItem.SYNC_FOLDER_SMB_PROTOCOL_SMB1)) sp_sync_folder_smb_proto.setSelection(SyncTaskItem.SYNC_FOLDER_SMB_PROTOCOL_SMB1_INDEX); + else if (smb_level.equals(SyncTaskItem.SYNC_FOLDER_SMB_PROTOCOL_SMB23)) sp_sync_folder_smb_proto.setSelection(SyncTaskItem.SYNC_FOLDER_SMB_PROTOCOL_SMB23_INDEX); + else sp_sync_folder_smb_proto.setSelection(SyncTaskItem.SYNC_FOLDER_SMB_PROTOCOL_DEFAULT_INDEX); } @Override @@ -940,17 +991,51 @@ public void negativeResponse(Context arg0, Object[] arg1) { } }); - String port_num = ""; - if (ctv_sync_folder_use_port.isChecked()) port_num = et_sync_folder_port.getText().toString(); - final Spinner sp_sync_folder_smb_proto = (Spinner) dialog.findViewById(R.id.edit_sync_folder_dlg_smb_protocol); - SmbServerScanner ss=new SmbServerScanner(mActivity, mGp, mUtil, ntfy_search_result, port_num, true, (String)sp_sync_folder_smb_proto.getSelectedItem()); + //String smb_scan_protocol = (String) sp_sync_folder_smb_proto.getSelectedItem(); + //String port_num = ""; + //if (ctv_sync_folder_use_port.isChecked()) port_num = et_sync_folder_port.getText().toString(); + SmbServerScanner ss=new SmbServerScanner(mActivity, mGp, mUtil, ntfy_search_result, "", "", true); + + checkSyncFolderValidation(dialog, sti, sfev, org_sfev); + //setSyncFolderOkButtonEnabledIfFolderChanged(dialog, org_sfev); } }); btn_sync_folder_list_share.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { - mTaskUtil.invokeSelectSmbShareDlg(dialog); + NotifyEvent ntfy_list_shares=new NotifyEvent(mActivity); + ntfy_list_shares.setListener(new NotifyEvent.NotifyEventListener() { + @Override + public void positiveResponse(Context context, Object[] objects) { + String[] result=(String[])objects[0]; + + // query the dialog again as it could have been destroyed on screen rotation during invokeSelectSmbShareDlg() thread + final EditText et_sync_folder_share_name = dialog.findViewById(R.id.edit_sync_folder_dlg_share_name); + et_sync_folder_share_name.setText(result[0]); + } + + @Override + public void negativeResponse(Context context, Object[] objects) {} + }); + String remote_host="", smb_proto = "", remote_port = "", remote_user = "", remote_pass = "", share_name = ""; + remote_host=et_remote_host.getText().toString().trim(); + smb_proto=(String)sp_sync_folder_smb_proto.getSelectedItem(); + if (ctv_sync_folder_use_port.isChecked()) { + remote_port = et_sync_folder_port.getText().toString(); + } + if (ctv_sync_folder_use_pswd.isChecked()) { + remote_user = et_sync_folder_user.getText().toString().trim(); + remote_pass = et_sync_folder_pswd.getText().toString(); + } + share_name = et_sync_folder_share_name.getText().toString(); + //boolean ipc_enforced=ctv_sync_folder_smb_ipc_enforced.isChecked(); + //boolean smb2_negotiation=ctv_sync_folder_smb_use_smb2_negotiation.isChecked(); + + mTaskUtil.invokeSelectSmbShareDlg(remote_host, smb_proto, remote_port, remote_user, remote_pass, share_name, ntfy_list_shares); + + checkSyncFolderValidation(dialog, sti, sfev, org_sfev); + //setSyncFolderOkButtonEnabledIfFolderChanged(dialog, org_sfev); } }); @@ -960,14 +1045,27 @@ public void onClick(View v) { public void onClick(View view) { boolean isChecked=!((CheckedTextView)view).isChecked(); ((CheckedTextView)view).setChecked(isChecked); + + // Mod: Mask SMB password when edit SMB parameters option is unchecked + if (!isChecked || mGp.settingSecurityHideShowSmbPasswordButton) { + //ll_sync_folder_pswd_view.setPasswordVisibilityToggleEnabled(false); + ll_sync_folder_pswd_view.setEndIconMode(TextInputLayout.END_ICON_NONE); + } else { + //ll_sync_folder_pswd_view.setPasswordVisibilityToggleEnabled(true); + ll_sync_folder_pswd_view.setEndIconMode(TextInputLayout.END_ICON_PASSWORD_TOGGLE); + } + setSyncFolderSmbDetailView(dialog, isChecked); - setSyncFolderViewVisibility(dialog, sti, sfev.is_source_folder, sfev); + + setSyncFolderViewVisibility(dialog, sti, sfev.is_source_folder, sfev, org_sfev); + checkSyncFolderValidation(dialog, sti, sfev, org_sfev); + //setSyncFolderOkButtonEnabledIfFolderChanged(dialog, org_sfev); } }); ctv_sync_folder_edit_smb_detail.setChecked(sfev.show_smb_detail_settings); setSyncFolderSmbDetailView(dialog, sfev.show_smb_detail_settings); - final Button btn_sync_folder_edit_dir_rule = (Button) dialog.findViewById(R.id.edit_sync_folder_dlg_edit_smb_dir_keyword); + final Button btn_sync_folder_edit_dir_rule = dialog.findViewById(R.id.edit_sync_folder_dlg_edit_smb_dir_keyword); // if (sfev.is_source_folder) btn_sync_folder_edit_dir_rule.setVisibility(Button.GONE); btn_sync_folder_edit_dir_rule.setOnClickListener(new OnClickListener() { @Override @@ -976,18 +1074,22 @@ public void onClick(View v) { ntfy.setListener(new NotifyEvent.NotifyEventListener() { @Override public void positiveResponse(Context context, Object[] objects) { - boolean changed=(boolean)objects[0]; - final Button btn_sync_folder_ok = (Button) dialog.findViewById(R.id.edit_profile_remote_btn_ok); - if (changed) setSyncFolderOkButtonEnabled(btn_sync_folder_ok, true); - else setSyncFolderOkButtonEnabled(btn_sync_folder_ok, false); + final String edited_name = (String)objects[0]; + final EditText et_sync_folder_dir_name = dialog.findViewById(R.id.edit_sync_folder_dlg_smb_directory_name); + et_sync_folder_dir_name.setText(edited_name); + + final Button btn_sync_folder_ok = dialog.findViewById(R.id.edit_profile_remote_btn_ok); + checkSyncFolderValidation(dialog, sti, sfev, org_sfev); } @Override public void negativeResponse(Context context, Object[] objects) {} }); - boolean disable_taken_date=false; - if (sfev.task_type.equals(SyncTaskItem.SYNC_TASK_TYPE_MIRROR)) disable_taken_date=true; + boolean disable_taken_date= sfev.task_type.equals(SyncTaskItem.SYNC_TASK_TYPE_MIRROR); editDirectoryFileNameRule(true, disable_taken_date, sti, sfev, et_sync_folder_dir_name, mActivity.getString(R.string.msgs_task_sync_task_edit_directory_name_keyword), ntfy); + + checkSyncFolderValidation(dialog, sti, sfev, org_sfev); + //setSyncFolderOkButtonEnabledIfFolderChanged(dialog, org_sfev); } }); @@ -1027,7 +1129,7 @@ public void afterTextChanged(Editable s) { } else { dlg_msg.setText(""); } - if (e_msg.equals("")) setSyncFolderOkButtonEnabledIfFolderChanged(dialog, org_sfev); + if (e_msg.equals("")) checkSyncFolderValidation(dialog, sti, sfev, org_sfev); //setSyncFolderOkButtonEnabledIfFolderChanged(dialog, org_sfev); } }); @@ -1036,33 +1138,35 @@ public void afterTextChanged(Editable s) { public void onClick(View v) { String sel = sp_sync_folder_type.getSelectedItem().toString(); mTaskUtil.selectRemoteDirectoryDlg(dialog, !sfev.is_source_folder); - setSyncFolderOkButtonEnabledIfFolderChanged(dialog, org_sfev); + + checkSyncFolderValidation(dialog, sti, sfev, org_sfev); + //setSyncFolderOkButtonEnabledIfFolderChanged(dialog, org_sfev); } }); } private void setSyncFolderSmbDetailView(Dialog dialog, boolean enabled) { - final CheckedTextView ctv_sync_folder_edit_smb_detail = (CheckedTextView) dialog.findViewById(R.id.edit_sync_folder_dlg_ctv_edit_smb_server_detail); - final Spinner sp_sync_folder_type = (Spinner) dialog.findViewById(R.id.edit_sync_folder_dlg_folder_type); - final Spinner sp_sync_folder_smb_proto = (Spinner) dialog.findViewById(R.id.edit_sync_folder_dlg_smb_protocol); - - final Button btn_search_host = (Button) dialog.findViewById(R.id.edit_sync_folder_dlg_search_remote_host); - final Button btn_sync_folder_smb_list_dir = (Button) dialog.findViewById(R.id.edit_sync_folder_dlg_list_smb_directory_btn); - final EditText et_sync_folder_dir_name = (EditText) dialog.findViewById(R.id.edit_sync_folder_dlg_smb_directory_name); - final EditText et_remote_host = (EditText) dialog.findViewById(R.id.edit_sync_folder_dlg_remote_server); + final CheckedTextView ctv_sync_folder_edit_smb_detail = dialog.findViewById(R.id.edit_sync_folder_dlg_ctv_edit_smb_server_detail); + final Spinner sp_sync_folder_type = dialog.findViewById(R.id.edit_sync_folder_dlg_folder_type); + final Spinner sp_sync_folder_smb_proto = dialog.findViewById(R.id.edit_sync_folder_dlg_smb_protocol); + + final Button btn_search_host = dialog.findViewById(R.id.edit_sync_folder_dlg_search_remote_host); + final Button btn_sync_folder_smb_list_dir = dialog.findViewById(R.id.edit_sync_folder_dlg_list_smb_directory_btn); + final EditText et_sync_folder_dir_name = dialog.findViewById(R.id.edit_sync_folder_dlg_smb_directory_name); + final EditText et_remote_host = dialog.findViewById(R.id.edit_sync_folder_dlg_remote_server); // final LinearLayout ll_sync_folder_port = (LinearLayout)dialog.findViewById(R.id.edit_sync_folder_dlg_port_option_view); - final CheckedTextView ctv_sync_folder_use_port = (CheckedTextView) dialog.findViewById(R.id.edit_sync_folder_dlg_ctv_use_remote_port_number); - final EditText et_sync_folder_port = (EditText) dialog.findViewById(R.id.edit_sync_folder_dlg_remote_port); - final LinearLayout ll_dir_view = (LinearLayout) dialog.findViewById(R.id.edit_sync_folder_dlg_smb_directory_view); - final CheckedTextView ctv_sync_folder_use_pswd = (CheckedTextView) dialog.findViewById(R.id.edit_sync_folder_dlg_ctv_use_user_pass); - final EditText et_sync_folder_domain = (EditText) dialog.findViewById(R.id.edit_sync_folder_dlg_remote_domain); - final EditText et_sync_folder_user = (EditText) dialog.findViewById(R.id.edit_sync_folder_dlg_remote_user); - final TextInputEditText et_sync_folder_pswd = (TextInputEditText ) dialog.findViewById(R.id.edit_sync_folder_dlg_remote_pass); - final TextInputLayout ll_sync_folder_pswd_view = (TextInputLayout) dialog.findViewById(R.id.edit_sync_folder_dlg_remote_pass_view); - final Button btn_sync_folder_list_share = (Button) dialog.findViewById(R.id.edit_sync_folder_dlg_list_share_btn); - final EditText et_sync_folder_share_name = (EditText) dialog.findViewById(R.id.edit_sync_folder_dlg_share_name); - - final TextView tv_hdr_smb_protocol=(TextView)dialog.findViewById(R.id.edit_sync_folder_dlg_hdr_smb_protocol); + final CheckedTextView ctv_sync_folder_use_port = dialog.findViewById(R.id.edit_sync_folder_dlg_ctv_use_remote_port_number); + final EditText et_sync_folder_port = dialog.findViewById(R.id.edit_sync_folder_dlg_remote_port); + final LinearLayout ll_dir_view = dialog.findViewById(R.id.edit_sync_folder_dlg_smb_directory_view); + final CheckedTextView ctv_sync_folder_use_pswd = dialog.findViewById(R.id.edit_sync_folder_dlg_ctv_use_user_pass); + final EditText et_sync_folder_domain = dialog.findViewById(R.id.edit_sync_folder_dlg_remote_domain); + final EditText et_sync_folder_user = dialog.findViewById(R.id.edit_sync_folder_dlg_remote_user); + final EditText et_sync_folder_pswd = dialog.findViewById(R.id.edit_sync_folder_dlg_remote_pass); + final TextInputLayout ll_sync_folder_pswd_view = dialog.findViewById(R.id.edit_sync_folder_dlg_remote_pass_view); + final Button btn_sync_folder_list_share = dialog.findViewById(R.id.edit_sync_folder_dlg_list_share_btn); + final EditText et_sync_folder_share_name = dialog.findViewById(R.id.edit_sync_folder_dlg_share_name); + + final TextView tv_hdr_smb_protocol= dialog.findViewById(R.id.edit_sync_folder_dlg_hdr_smb_protocol); CommonUtilities.setViewEnabled(mActivity, btn_search_host, !ctv_sync_folder_edit_smb_detail.isChecked()); CommonUtilities.setViewEnabled(mActivity, tv_hdr_smb_protocol, enabled); @@ -1075,6 +1179,7 @@ private void setSyncFolderSmbDetailView(Dialog dialog, boolean enabled) { } else { CommonUtilities.setViewEnabled(mActivity, et_sync_folder_port, false); } + CommonUtilities.setViewEnabled(mActivity, ctv_sync_folder_use_pswd, enabled); if (enabled) { if (ctv_sync_folder_use_pswd.isChecked()) { @@ -1091,6 +1196,7 @@ private void setSyncFolderSmbDetailView(Dialog dialog, boolean enabled) { CommonUtilities.setViewEnabled(mActivity, et_sync_folder_user, false); CommonUtilities.setViewEnabled(mActivity, ll_sync_folder_pswd_view, false); } + CommonUtilities.setViewEnabled(mActivity, btn_sync_folder_list_share, enabled); CommonUtilities.setViewEnabled(mActivity, et_sync_folder_share_name, enabled); @@ -1098,23 +1204,23 @@ private void setSyncFolderSmbDetailView(Dialog dialog, boolean enabled) { private void setSyncFolderLocalListener(final Dialog dialog, final SyncTaskItem sti, final SyncFolderEditValue sfev, final SyncFolderEditValue org_sfev,final NotifyEvent ntfy) { - final TextView dlg_msg = (TextView) dialog.findViewById(R.id.edit_sync_folder_dlg_msg); - final Spinner sp_sync_folder_type = (Spinner) dialog.findViewById(R.id.edit_sync_folder_dlg_folder_type); - final Button btn_sync_folder_ok = (Button) dialog.findViewById(R.id.edit_profile_remote_btn_ok); + final TextView dlg_msg = dialog.findViewById(R.id.edit_sync_folder_dlg_msg); + final Spinner sp_sync_folder_type = dialog.findViewById(R.id.edit_sync_folder_dlg_folder_type); + final Button btn_sync_folder_ok = dialog.findViewById(R.id.edit_profile_remote_btn_ok); - final LinearLayout ll_sync_folder_local_storage = (LinearLayout) dialog.findViewById(R.id.edit_sync_folder_dlg_internal_storage_selector_view); - final Spinner sp_sync_folder_local_storage_selector = (Spinner) dialog.findViewById(R.id.edit_sync_folder_dlg_local_storage_selector); + final LinearLayout ll_sync_folder_local_storage = dialog.findViewById(R.id.edit_sync_folder_dlg_internal_storage_selector_view); + final Spinner sp_sync_folder_local_storage_selector = dialog.findViewById(R.id.edit_sync_folder_dlg_local_storage_selector); sp_sync_folder_local_storage_selector.setOnItemSelectedListener(null); setSpinnerSyncFolderStorageSelector(sti, sp_sync_folder_local_storage_selector, sfev.folder_storage_uuid); - final Button btn_sync_folder_permission = (Button) dialog.findViewById(R.id.edit_sync_folder_dlg_local_storage_request_permission); + final Button btn_sync_folder_permission = dialog.findViewById(R.id.edit_sync_folder_dlg_local_storage_request_permission); - final Button btn_sync_folder_local_list_dir = (Button) dialog.findViewById(R.id.edit_sync_folder_dlg_list_internal_directory_btn); + final Button btn_sync_folder_local_list_dir = dialog.findViewById(R.id.edit_sync_folder_dlg_list_internal_directory_btn); - final EditText et_sync_folder_dir_name = (EditText) dialog.findViewById(R.id.edit_sync_folder_dlg_internal_directory_name); - final EditText et_file_template = (EditText) dialog.findViewById(R.id.edit_sync_folder_dlg_archive_file_name_template); + final EditText et_sync_folder_dir_name = dialog.findViewById(R.id.edit_sync_folder_dlg_internal_directory_name); + final EditText et_file_template = dialog.findViewById(R.id.edit_sync_folder_dlg_archive_file_name_template); et_sync_folder_dir_name.setText(sfev.folder_directory.startsWith("/")?sfev.folder_directory:"/"+sfev.folder_directory); - final LinearLayout ll_dir_view = (LinearLayout) dialog.findViewById(R.id.edit_sync_folder_dlg_internal_directory_view); + final LinearLayout ll_dir_view = dialog.findViewById(R.id.edit_sync_folder_dlg_internal_directory_view); et_sync_folder_dir_name.addTextChangedListener(new TextWatcher() { @Override @@ -1155,15 +1261,16 @@ public void afterTextChanged(Editable s) { setSyncFolderArchiveFileImage(dialog, sti, s.toString(), true); } - if (e_msg.equals("")) setSyncFolderOkButtonEnabledIfFolderChanged(dialog, org_sfev); + if (e_msg.equals("")) checkSyncFolderValidation(dialog, sti, sfev, org_sfev); //setSyncFolderOkButtonEnabledIfFolderChanged(dialog, org_sfev); } }); sp_sync_folder_local_storage_selector.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView adapterView, View view, int i, long l) { - checkSyncFolderValidation(dialog, sti, sfev); - setSyncFolderOkButtonEnabledIfFolderChanged(dialog, org_sfev); + checkSyncFolderValidation(dialog, sti, sfev, org_sfev); + //setSyncFolderOkButtonEnabledIfFolderChanged(dialog, org_sfev); + LocalStorageSelectorItem sl=(LocalStorageSelectorItem)sp_sync_folder_local_storage_selector.getSelectedItem(); mUtil.addDebugMsg(1,"I","isExfatFileSystem="+CommonUtilities.isExfatFileSystem(sl.uuid)); } @@ -1188,11 +1295,11 @@ public void positiveResponse(Context context, Object[] objects) { @Override public void negativeResponse(Context context, Object[] objects) {} }); - requestLocalStoragePermission(mActivity, mGp, mUtil, ntfy); + mActivity.requestLocalStoragePermission(mActivity, mGp, mUtil, ntfy); } }); - final Button btn_sync_folder_edit_internal_dir_rule = (Button) dialog.findViewById(R.id.edit_sync_folder_dlg_edit_internal_dir_keyword); + final Button btn_sync_folder_edit_internal_dir_rule = dialog.findViewById(R.id.edit_sync_folder_dlg_edit_internal_dir_keyword); // if (sfev.is_source_folder) btn_sync_folder_edit_internal_dir_rule.setVisibility(Button.GONE); btn_sync_folder_edit_internal_dir_rule.setOnClickListener(new OnClickListener() { @Override @@ -1201,15 +1308,16 @@ public void onClick(View v) { ntfy.setListener(new NotifyEvent.NotifyEventListener() { @Override public void positiveResponse(Context context, Object[] objects) { - boolean changed=(boolean)objects[0]; - if (changed) setSyncFolderOkButtonEnabled(btn_sync_folder_ok, true); - else setSyncFolderOkButtonEnabled(btn_sync_folder_ok, false); + final String edited_name = (String)objects[0]; + final EditText et_sync_folder_dir_name = dialog.findViewById(R.id.edit_sync_folder_dlg_internal_directory_name); + et_sync_folder_dir_name.setText(edited_name); + + checkSyncFolderValidation(dialog, sti, sfev, org_sfev); } @Override public void negativeResponse(Context context, Object[] objects) {} }); - boolean disable_taken_date=false; - if (sfev.task_type.equals(SyncTaskItem.SYNC_TASK_TYPE_MIRROR)) disable_taken_date=true; + boolean disable_taken_date= sfev.task_type.equals(SyncTaskItem.SYNC_TASK_TYPE_MIRROR); editDirectoryFileNameRule(true, disable_taken_date, sti, sfev, et_sync_folder_dir_name, mActivity.getString(R.string.msgs_task_sync_task_edit_directory_name_keyword), ntfy); } @@ -1225,7 +1333,7 @@ public void onClick(View v) { ntfy.setListener(new NotifyEvent.NotifyEventListener() { @Override public void positiveResponse(Context arg0, Object[] arg1) { - EditText et_sync_folder_dir_name = (EditText) dialog.findViewById(R.id.edit_sync_folder_dlg_internal_directory_name); + EditText et_sync_folder_dir_name = dialog.findViewById(R.id.edit_sync_folder_dlg_internal_directory_name); LocalStorageSelectorItem sel_item=(LocalStorageSelectorItem)sp_sync_folder_local_storage_selector.getSelectedItem(); // Uri zip_uri = (Uri) arg1[0]; String fp=((String)arg1[1]).replace(sel_item.root_path, ""); @@ -1245,128 +1353,15 @@ public void negativeResponse(Context arg0, Object[] arg1) { true, true, sel_item.uuid, "", "", mActivity.getString(R.string.msgs_select_local_dir)); fsdf.showDialog(false, mActivity.getSupportFragmentManager(), fsdf, ntfy); - setSyncFolderOkButtonEnabledIfFolderChanged(dialog, org_sfev); + checkSyncFolderValidation(dialog, sti, sfev, org_sfev); + //setSyncFolderOkButtonEnabledIfFolderChanged(dialog, org_sfev); } }); } - static public void requestLocalStoragePermission(final ActivityMain activity, - final GlobalParameters gp, final CommonUtilities ut, final NotifyEvent p_ntfy) { -// final Spinner sp_sync_folder_local_storage_selector = (Spinner) dialog.findViewById(R.id.edit_sync_folder_dlg_local_storage_selector); - NotifyEvent ntfy=new NotifyEvent(activity); - ntfy.setListener(new NotifyEvent.NotifyEventListener() { - @SuppressWarnings("unchecked") - @Override - public void positiveResponse(Context context, Object[] objects) { - ArrayListuuid_list=(ArrayList)objects[0]; - final NotifyEvent ntfy_response=new NotifyEvent(context); - ntfy_response.setListener(new NotifyEvent.NotifyEventListener() { - @Override - public void positiveResponse(Context context, Object[] objects) { - final int resultCode=(Integer)objects[0]; - final Intent data=(Intent)objects[1]; - final String uuid=(String)objects[2]; - - if (resultCode == Activity.RESULT_OK) { - if (data==null || data.getDataString()==null) { - String msg=activity.getString(R.string.msgs_storage_permission_msg_grant_permission_failed_null); - ut.showCommonDialogWarn(false, msg, "", null); - ut.addLogMsg("E", "", msg, ""); - return; - } - ut.addDebugMsg(1, "I", "Intent=" + data.getData().toString()); - if (!gp.safMgr.isRootTreeUri(data.getData())) { - ut.addDebugMsg(1, "I", "Selected UUID="+ SafManager3.getUuidFromUri(data.getData().toString())); - String em=gp.safMgr.getLastErrorMessage(); - if (em.length()>0) ut.addDebugMsg(1, "I", "SafMessage="+em); - - NotifyEvent ntfy_retry = new NotifyEvent(context); - ntfy_retry.setListener(new NotifyEvent.NotifyEventListener() { - @Override - public void positiveResponse(Context c, Object[] o) { - requestStoragePermissionByUuid(activity, ut, uuid, ntfy_response); - } - - @Override - public void negativeResponse(Context c, Object[] o) {} - }); - ut.showCommonDialogWarn(true, context.getString(R.string.msgs_main_external_storage_select_retry_select_msg), - data.getData().getPath(), ntfy_retry); - } else { - ut.addDebugMsg(1, "I", "Selected UUID="+SafManager3.getUuidFromUri(data.getData().toString())); - String em=gp.safMgr.getLastErrorMessage(); - if (em.length()>0) ut.addDebugMsg(1, "I", "SafMessage="+em); - boolean rc=gp.safMgr.addUuid(data.getData()); - if (!rc) { - String msg=activity.getString(R.string.msgs_storage_permission_msg_add_uuid_failed); - String saf_msg=gp.safMgr.getLastErrorMessage(); - ut.showCommonDialogWarn(false, msg, saf_msg, null); - ut.addLogMsg("E", "", msg, "\n", saf_msg); - } - if (p_ntfy!=null) p_ntfy.notifyToListener(true, null); - } - } else { - ut.showCommonDialogWarn(false, - context.getString(R.string.msgs_main_external_storage_request_permission), - context.getString(R.string.msgs_main_external_storage_select_required_cancel_msg), null); - - } - } - - @Override - public void negativeResponse(Context context, Object[] objects) {} - }); - for(String uuid:uuid_list) { - requestStoragePermissionByUuid(activity, ut, uuid, ntfy_response); - } - } - - @Override - public void negativeResponse(Context context, Object[] objects) {} - }); - StoragePermission sp=new StoragePermission(activity, ntfy); - sp.showDialog(); - - } - - static public void requestStoragePermissionByUuid(final ActivityMain a, final CommonUtilities cu, final String uuid, final NotifyEvent ntfy) { - cu.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName()+" enterd"); - Intent intent = null; - StorageManager sm = (StorageManager) a.getSystemService(Context.STORAGE_SERVICE); - ArrayListvol_list=SafManager3.getStorageVolumeInfo(a); - for(SafManager3.StorageVolumeInfo svi:vol_list) { - if (svi.uuid.equals(uuid)) { - if (Build.VERSION.SDK_INT>=29) { - if (!svi.uuid.equals(SAF_FILE_PRIMARY_UUID)) { - intent=svi.volume.createOpenDocumentTreeIntent(); - } - } else { - if (!svi.uuid.equals(SAF_FILE_PRIMARY_UUID)) { - intent=svi.volume.createAccessIntent(null); - } - } - if (intent!=null) { - try { - a.launchActivityResult(a, "UUID", intent, new CallBackListener() { - @Override - public void onCallBack(Context context, boolean positive, Object[] objects) { - ntfy.notifyToListener(true, new Object[]{positive?0:-1, objects[0], uuid}); - } - }); - } catch(Exception e) { - String st= MiscUtil.getStackTraceString(e); - cu.showCommonDialog(false, "E", - a.getString(R.string.msgs_storage_permission_msg_saf_error_occured), e.getMessage()+"\n"+st, null); - } - break; - } - } - } - } - private void setSyncFolderArchiveListener(final Dialog dialog, final SyncTaskItem n_sti, final SyncFolderEditValue sfev, final SyncFolderEditValue org_sfev,final NotifyEvent ntfy) { - final LinearLayout archive_option_view = (LinearLayout) dialog.findViewById(R.id.edit_sync_folder_dlg_archive_view); + final LinearLayout archive_option_view = dialog.findViewById(R.id.edit_sync_folder_dlg_archive_view); if (n_sti.getSyncTaskType().equals(SyncTaskItem.SYNC_TASK_TYPE_ARCHIVE)) { if (sfev.is_source_folder) archive_option_view.setVisibility(LinearLayout.GONE); @@ -1375,26 +1370,28 @@ private void setSyncFolderArchiveListener(final Dialog dialog, final SyncTaskIte archive_option_view.setVisibility(LinearLayout.GONE); } - final Spinner sp_sync_suffix_option = (Spinner) dialog.findViewById(R.id.edit_sync_folder_dlg_archive_suffix_seqno); + final Spinner sp_sync_suffix_option = dialog.findViewById(R.id.edit_sync_folder_dlg_archive_suffix_seqno); sp_sync_suffix_option.setOnItemSelectedListener(null); setSpinnerSyncTaskArchiveSuffixSeq(sp_sync_suffix_option, sfev.archive_file_append_suffix_digit); - final CheckedTextView ctv_ignore_source_directory_hierarchy=(CheckedTextView)dialog.findViewById(R.id.edit_sync_folder_dlg_archive_ignore_source_directory_hierarchy); + final CheckedTextView ctv_ignore_source_directory_hierarchy= dialog.findViewById(R.id.edit_sync_folder_dlg_archive_ignore_source_directory_hierarchy); ctv_ignore_source_directory_hierarchy.setChecked(sfev.archive_ignore_source_directory_hiearachy); ctv_ignore_source_directory_hierarchy.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { boolean isChecked=!ctv_ignore_source_directory_hierarchy.isChecked(); ctv_ignore_source_directory_hierarchy.setChecked(isChecked); + + //checkSyncFolderValidation(dialog, n_sti, sfev, org_sfev); setSyncFolderOkButtonEnabledIfFolderChanged(dialog, org_sfev); } }); - final LinearLayout template_view = (LinearLayout) dialog.findViewById(R.id.edit_sync_folder_dlg_archive_template_view); - final EditText et_file_template = (EditText) dialog.findViewById(R.id.edit_sync_folder_dlg_archive_file_name_template); + final LinearLayout template_view = dialog.findViewById(R.id.edit_sync_folder_dlg_archive_template_view); + final EditText et_file_template = dialog.findViewById(R.id.edit_sync_folder_dlg_archive_file_name_template); et_file_template.setTextColor(mGp.themeColorList.text_color_primary); - final Button btn_sync_folder_edit_file_rule = (Button) dialog.findViewById(R.id.edit_sync_folder_dlg_archive_file_name_keyword); + final Button btn_sync_folder_edit_file_rule = dialog.findViewById(R.id.edit_sync_folder_dlg_archive_file_name_keyword); if (sfev.is_source_folder) btn_sync_folder_edit_file_rule.setVisibility(Button.GONE); btn_sync_folder_edit_file_rule.setOnClickListener(new OnClickListener() { @Override @@ -1403,9 +1400,12 @@ public void onClick(View v) { ntfy.setListener(new NotifyEvent.NotifyEventListener() { @Override public void positiveResponse(Context context, Object[] objects) { - boolean changed=(boolean)objects[0]; -// if (changed) setSyncFolderOkButtonEnabled(btn_sync_folder_ok, true); -// else setSyncFolderOkButtonEnabled(btn_sync_folder_ok, false); + final String edited_name = (String)objects[0]; + final EditText et_file_template = dialog.findViewById(R.id.edit_sync_folder_dlg_archive_file_name_template); + et_file_template.setText(edited_name); + + // not needed, change will trigger et_file_template.addTextChangedListener() which will call checkArchiveOkButtonEnabled() + //checkArchiveOkButtonEnabled(sfev, n_sti, dialog); } @Override public void negativeResponse(Context context, Object[] objects) {} @@ -1415,7 +1415,7 @@ public void negativeResponse(Context context, Object[] objects) {} } }); - final TextView tv_template = (TextView) dialog.findViewById(R.id.edit_sync_folder_dlg_archive_new_name); + final TextView tv_template = dialog.findViewById(R.id.edit_sync_folder_dlg_archive_new_name); sp_sync_suffix_option.setOnItemSelectedListener(new OnItemSelectedListener() { @Override @@ -1467,34 +1467,33 @@ public void afterTextChanged(Editable s) { }); tv_template.setText(getSyncTaskArchiveTemplateNewName(sp_sync_suffix_option.getSelectedItemPosition(), et_file_template.getText().toString(), sfev.folder_directory, n_sti)); - } private void setSyncFolderArchiveFileImage(final Dialog dialog, SyncTaskItem n_sti, final String destination_dir, boolean create_directory) { - final Spinner sp_sync_retain_period = (Spinner) dialog.findViewById(R.id.edit_sync_filter_archive_retention_period); + final Spinner sp_sync_retain_period = dialog.findViewById(R.id.edit_sync_filter_archive_retention_period); - final LinearLayout template_view = (LinearLayout) dialog.findViewById(R.id.edit_sync_folder_dlg_archive_template_view); - final EditText et_file_template = (EditText) dialog.findViewById(R.id.edit_sync_folder_dlg_archive_file_name_template); - final TextView tv_template = (TextView) dialog.findViewById(R.id.edit_sync_folder_dlg_archive_new_name); + final LinearLayout template_view = dialog.findViewById(R.id.edit_sync_folder_dlg_archive_template_view); + final EditText et_file_template = dialog.findViewById(R.id.edit_sync_folder_dlg_archive_file_name_template); + final TextView tv_template = dialog.findViewById(R.id.edit_sync_folder_dlg_archive_new_name); } private void setSyncFolderZipListener(final Dialog dialog, final SyncTaskItem sti, final SyncFolderEditValue sfev, final SyncFolderEditValue org_sfev,final NotifyEvent ntfy) { - final TextView dlg_msg = (TextView) dialog.findViewById(R.id.edit_sync_folder_dlg_msg); - final Spinner sp_sync_folder_type = (Spinner) dialog.findViewById(R.id.edit_sync_folder_dlg_folder_type); - final Button btn_sync_folder_ok = (Button) dialog.findViewById(R.id.edit_profile_remote_btn_ok); + final TextView dlg_msg = dialog.findViewById(R.id.edit_sync_folder_dlg_msg); + final Spinner sp_sync_folder_type = dialog.findViewById(R.id.edit_sync_folder_dlg_folder_type); + final Button btn_sync_folder_ok = dialog.findViewById(R.id.edit_profile_remote_btn_ok); // final CheckedTextView ctv_sync_folder_show_zip_password = (CheckedTextView) dialog.findViewById(R.id.edit_sync_folder_dlg_ctv_show_zip_password); - final Spinner sp_sync_folder_zip_storage_selector = (Spinner) dialog.findViewById(R.id.edit_sync_folder_dlg_zip_storage_selector); + final Spinner sp_sync_folder_zip_storage_selector = dialog.findViewById(R.id.edit_sync_folder_dlg_zip_storage_selector); sp_sync_folder_zip_storage_selector.setOnItemSelectedListener(null); setSpinnerSyncFolderStorageSelector(sti, sp_sync_folder_zip_storage_selector, sfev.folder_storage_uuid); - final Button btn_sync_folder_permission = (Button) dialog.findViewById(R.id.edit_sync_folder_dlg_zip_local_storage_request_permission); + final Button btn_sync_folder_permission = dialog.findViewById(R.id.edit_sync_folder_dlg_zip_local_storage_request_permission); sp_sync_folder_zip_storage_selector.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView adapterView, View view, int i, long l) { - checkSyncFolderValidation(dialog, sti, sfev); - setSyncFolderOkButtonEnabledIfFolderChanged(dialog, org_sfev); + checkSyncFolderValidation(dialog, sti, sfev, org_sfev); + //setSyncFolderOkButtonEnabledIfFolderChanged(dialog, org_sfev); } @Override public void onNothingSelected(AdapterView adapterView) {} @@ -1517,15 +1516,15 @@ public void positiveResponse(Context context, Object[] objects) { @Override public void negativeResponse(Context context, Object[] objects) {} }); - requestLocalStoragePermission(mActivity, mGp, mUtil, ntfy); + mActivity.requestLocalStoragePermission(mActivity, mGp, mUtil, ntfy); } }); - final LinearLayout ll_zip_view = (LinearLayout) dialog.findViewById(R.id.edit_sync_folder_dlg_zip_view); + final LinearLayout ll_zip_view = dialog.findViewById(R.id.edit_sync_folder_dlg_zip_view); - final Button btn_zip_filelist = (Button) dialog.findViewById(R.id.edit_sync_folder_dlg_zip_filelist_btn); - final EditText et_zip_file = (EditText) dialog.findViewById(R.id.edit_sync_folder_dlg_zip_file_name); - final TextView tv_zip_dir = (TextView) dialog.findViewById(R.id.edit_sync_folder_dlg_zip_dir_name); + final Button btn_zip_filelist = dialog.findViewById(R.id.edit_sync_folder_dlg_zip_filelist_btn); + final EditText et_zip_file = dialog.findViewById(R.id.edit_sync_folder_dlg_zip_file_name); + final TextView tv_zip_dir = dialog.findViewById(R.id.edit_sync_folder_dlg_zip_dir_name); String zip_dir="", zip_file=""; if (sfev.zip_file_name.lastIndexOf("/")>1) { @@ -1539,7 +1538,7 @@ public void negativeResponse(Context context, Object[] objects) {} tv_zip_dir.setText(zip_dir); et_zip_file.setText(zip_file); - final Button btn_sync_folder_edit_zip_dir_rule = (Button) dialog.findViewById(R.id.edit_sync_folder_dlg_edit_zip_dir_keyword); + final Button btn_sync_folder_edit_zip_dir_rule = dialog.findViewById(R.id.edit_sync_folder_dlg_edit_zip_dir_keyword); if (sfev.is_source_folder) btn_sync_folder_edit_zip_dir_rule.setVisibility(Button.GONE); btn_sync_folder_edit_zip_dir_rule.setOnClickListener(new OnClickListener() { @Override @@ -1548,80 +1547,89 @@ public void onClick(View v) { ntfy.setListener(new NotifyEvent.NotifyEventListener() { @Override public void positiveResponse(Context context, Object[] objects) { - boolean changed=(boolean)objects[0]; - if (changed) setSyncFolderOkButtonEnabled(btn_sync_folder_ok, true); - else setSyncFolderOkButtonEnabled(btn_sync_folder_ok, false); + final String edited_name = (String)objects[0]; + final EditText et_zip_file = dialog.findViewById(R.id.edit_sync_folder_dlg_zip_file_name); + et_zip_file.setText(edited_name); + + // Called in et_zip_file.addTextChangedListener + //checkSyncFolderValidation(dialog, sti, sfev, org_sfev); } @Override public void negativeResponse(Context context, Object[] objects) {} }); - boolean disable_taken_date=false; - if (sfev.task_type.equals(SyncTaskItem.SYNC_TASK_TYPE_MIRROR)) disable_taken_date=true; + boolean disable_taken_date= sfev.task_type.equals(SyncTaskItem.SYNC_TASK_TYPE_MIRROR); editDirectoryFileNameRule(false, disable_taken_date, sti, sfev, et_zip_file, mActivity.getString(R.string.msgs_task_sync_task_edit_file_name_keyword), ntfy); } }); - final Spinner sp_comp_level = (Spinner) dialog.findViewById(R.id.edit_sync_folder_dlg_zip_comp_level); + final Spinner sp_comp_level = dialog.findViewById(R.id.edit_sync_folder_dlg_zip_comp_level); sp_comp_level.setOnItemSelectedListener(null); setSpinnerSyncFolderZipCompressionLevel(sp_comp_level, sfev.zip_comp_level); - final Spinner sp_zip_enc_method=(Spinner) dialog.findViewById(R.id.edit_sync_folder_dlg_zip_enc_method); + final Spinner sp_zip_enc_method= dialog.findViewById(R.id.edit_sync_folder_dlg_zip_enc_method); sp_zip_enc_method.setOnItemSelectedListener(null); setSpinnerSyncFolderZipEncryptMethod(sp_zip_enc_method, sfev.zip_enc_method); - final LinearLayout ll_password_view=(LinearLayout)dialog.findViewById(R.id.edit_sync_folder_dlg_zip_enc_password_view_all); - final TextInputLayout ll_zip_pswd_view=(TextInputLayout)dialog.findViewById(R.id.edit_sync_folder_dlg_zip_enc_password_view); - final EditText et_zip_pswd = (EditText) dialog.findViewById(R.id.edit_sync_folder_dlg_zip_enc_password); - final TextInputLayout ll_zip_conf_pswd_view=(TextInputLayout)dialog.findViewById(R.id.edit_sync_folder_dlg_zip_enc_confirm_view); - final EditText et_zip_conf_pswd = (EditText) dialog.findViewById(R.id.edit_sync_folder_dlg_zip_enc_confirm); + final LinearLayout ll_password_view= dialog.findViewById(R.id.edit_sync_folder_dlg_zip_enc_password_view_all); + final TextInputLayout ll_zip_pswd_view= dialog.findViewById(R.id.edit_sync_folder_dlg_zip_enc_password_view); + final EditText et_zip_pswd = dialog.findViewById(R.id.edit_sync_folder_dlg_zip_enc_password); + final TextInputLayout ll_zip_conf_pswd_view= dialog.findViewById(R.id.edit_sync_folder_dlg_zip_enc_confirm_view); + final EditText et_zip_conf_pswd = dialog.findViewById(R.id.edit_sync_folder_dlg_zip_enc_confirm); // final Button btn_zip_select_sdcard = (Button) dialog.findViewById(R.id.edit_sync_folder_dlg_zip_select_document_tree); -// final LinearLayout ll_conf_pswd_view=(LinearLayout)dialog.findViewById(R.id.edit_sync_folder_dlg_zip_enc_confirm_view); - - ll_zip_pswd_view.setPasswordVisibilityToggleEnabled(false); -// if (mGp.settingSecurityHideShowZipPasswordButton) ll_zip_pswd_view.setPasswordVisibilityToggleEnabled(false); -// else { -// ll_zip_pswd_view.setPasswordVisibilityToggleEnabled(true); -// if (sfev.show_zip_passowrd) { -// et_zip_pswd.setTransformationMethod(null); -// ll_zip_conf_pswd_view.setVisibility(TextInputLayout.GONE); -// } else { -// et_zip_pswd.setTransformationMethod(new PasswordTransformationMethod()); -// ll_zip_conf_pswd_view.setVisibility(TextInputLayout.VISIBLE); -// } -// } -// -// ll_zip_pswd_view.setEndIconOnClickListener(new View.OnClickListener() { -// @Override -// public void onClick(View v) { -// if (et_zip_pswd.getTransformationMethod()!=null) { -// et_zip_pswd.setTransformationMethod(null); -// ll_zip_conf_pswd_view.setVisibility(TextInputLayout.GONE); -// et_zip_pswd.setCustomSelectionActionModeCallback(new ActionMode.Callback() { -// @Override -// public boolean onCreateActionMode(ActionMode mode, Menu menu) { -// return true; -// } -// @Override -// public boolean onPrepareActionMode(ActionMode mode, Menu menu) { -// menu.removeItem(android.R.id.cut); -// menu.removeItem(android.R.id.copy); -// menu.removeItem(android.R.id.shareText); -// return true; -// } -// @Override -// public boolean onActionItemClicked(ActionMode mode, MenuItem item) { -// return false; -// } -// @Override -// public void onDestroyActionMode(ActionMode mode) { -// } -// }); -// } else { -// et_zip_pswd.setTransformationMethod(new PasswordTransformationMethod()); -// ll_zip_conf_pswd_view.setVisibility(TextInputLayout.VISIBLE); -// } -// } -// }); + // Mod: Fix Zip password could not be set because confirmation password is not clickable + ll_zip_conf_pswd_view.setVisibility(TextInputLayout.VISIBLE); + if (mGp.settingSecurityHideShowZipPasswordButton) { + //ll_zip_pswd_view.setPasswordVisibilityToggleEnabled(false); + ll_zip_pswd_view.setEndIconMode(TextInputLayout.END_ICON_NONE); + } else { + //ll_zip_pswd_view.setPasswordVisibilityToggleEnabled(true); + ll_zip_pswd_view.setEndIconMode(TextInputLayout.END_ICON_PASSWORD_TOGGLE); + if (sfev.show_zip_passowrd) { + et_zip_pswd.setTransformationMethod(null); + ll_zip_conf_pswd_view.setVisibility(TextInputLayout.GONE); + } else { + et_zip_pswd.setTransformationMethod(new PasswordTransformationMethod()); + ll_zip_conf_pswd_view.setVisibility(TextInputLayout.VISIBLE); + } + } + + ll_zip_pswd_view.setEndIconOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (et_zip_pswd.getTransformationMethod()!=null) { + et_zip_pswd.setTransformationMethod(null); + ll_zip_conf_pswd_view.setVisibility(TextInputLayout.GONE); +/* + et_zip_pswd.setCustomSelectionActionModeCallback(new ActionMode.Callback() { + @Override + public boolean onCreateActionMode(ActionMode mode, Menu menu) { + return true; + } + @Override + public boolean onPrepareActionMode(ActionMode mode, Menu menu) { + menu.removeItem(android.R.id.cut); + menu.removeItem(android.R.id.copy); + menu.removeItem(android.R.id.shareText); + return true; + } + @Override + public boolean onActionItemClicked(ActionMode mode, MenuItem item) { + return false; + } + @Override + public void onDestroyActionMode(ActionMode mode) { + } + }); +*/ + } else { + et_zip_pswd.setTransformationMethod(new PasswordTransformationMethod()); + ll_zip_conf_pswd_view.setVisibility(TextInputLayout.VISIBLE); + } + } + }); + + et_zip_pswd.setText(sfev.zip_file_password); + et_zip_conf_pswd.setText(sfev.zip_file_confirm_password); if (sfev.zip_enc_method.equals(SyncTaskItem.ZIP_OPTION_ENCRYPT_NONE)) { ll_password_view.setVisibility(LinearLayout.GONE); } else { @@ -1637,8 +1645,9 @@ public void onItemSelected(AdapterView parent, View view, int position, long } else { ll_password_view.setVisibility(LinearLayout.GONE); } - setSyncFolderOkButtonEnabledIfFolderChanged(dialog, org_sfev); - checkSyncFolderValidation(dialog, sti, sfev); + + checkSyncFolderValidation(dialog, sti, sfev, org_sfev); + //setSyncFolderOkButtonEnabledIfFolderChanged(dialog, org_sfev); } @Override @@ -1648,6 +1657,7 @@ public void onNothingSelected(AdapterView parent) {} sp_comp_level.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { + //checkSyncFolderValidation(dialog, sti, sfev, org_sfev); setSyncFolderOkButtonEnabledIfFolderChanged(dialog, org_sfev); } @Override @@ -1665,11 +1675,13 @@ public void positiveResponse(Context c, Object[] o) { Uri zip_uri = (Uri) o[0]; String fd=((String)o[2]).replace(sel_item.root_path, ""); String fn=(String)o[3]; - EditText et_zip_file = (EditText) dialog.findViewById(R.id.edit_sync_folder_dlg_zip_file_name); - TextView tv_zip_dir = (TextView) dialog.findViewById(R.id.edit_sync_folder_dlg_zip_dir_name); + EditText et_zip_file = dialog.findViewById(R.id.edit_sync_folder_dlg_zip_file_name); + TextView tv_zip_dir = dialog.findViewById(R.id.edit_sync_folder_dlg_zip_dir_name); et_zip_file.setText(fn); tv_zip_dir.setText(fd.equals("")?"/":fd); - setSyncFolderOkButtonEnabledIfFolderChanged(dialog, org_sfev); + + checkSyncFolderValidation(dialog, sti, sfev, org_sfev); + //setSyncFolderOkButtonEnabledIfFolderChanged(dialog, org_sfev); } @Override @@ -1681,10 +1693,11 @@ public void negativeResponse(Context c, Object[] o) { String title = mActivity.getString(R.string.msgs_task_edit_sync_folder_dlg_zip_select_file_title); CommonFileSelector2 fsdf= - CommonFileSelector2.newInstance(true, true, true, CommonFileSelector2.DIALOG_SELECT_CATEGORY_FILE, true, uuid, "", "", title); + CommonFileSelector2.newInstance(true, true, true, CommonFileSelector2.DIALOG_SELECT_CATEGORY_FILE, true, uuid, "", et_zip_file.getText().toString(), title); fsdf.showDialog(false, mActivity.getSupportFragmentManager(), fsdf, ntfy); } }); + et_zip_file.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {} @@ -1697,7 +1710,9 @@ public void afterTextChanged(Editable s) { for(int i = s.length()-1; i >= 0; i--){ if (s.charAt(i) == '\n'){ s.delete(i, i + 1); - checkSyncFolderValidation(dialog, sti, sfev); + + checkSyncFolderValidation(dialog, sti, sfev, org_sfev); + //setSyncFolderOkButtonEnabledIfFolderChanged(dialog, org_sfev); return; } } @@ -1705,11 +1720,12 @@ public void afterTextChanged(Editable s) { if (remove_char!=null) { mUtil.showCommonDialogWarn(false, mActivity.getString(R.string.msgs_task_sync_task_dlg_file_name_has_invalid_char), "", null); } - checkSyncFolderValidation(dialog, sti, sfev); + + checkSyncFolderValidation(dialog, sti, sfev, org_sfev); + //setSyncFolderOkButtonEnabledIfFolderChanged(dialog, org_sfev); } }); - et_zip_pswd.setText(sfev.zip_file_password); - et_zip_conf_pswd.setText(sfev.zip_file_confirm_password); + et_zip_pswd.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {} @@ -1717,14 +1733,17 @@ public void beforeTextChanged(CharSequence s, int start, int count, int after) { public void onTextChanged(CharSequence s, int start, int before, int count) {} @Override public void afterTextChanged(Editable s) { - checkSyncFolderValidation(dialog, sti, sfev); + + checkSyncFolderValidation(dialog, sti, sfev, org_sfev); + //setSyncFolderOkButtonEnabledIfFolderChanged(dialog, org_sfev); } }); - if (et_zip_pswd.getText().length() > 0) CommonUtilities.setViewEnabled(mActivity, et_zip_conf_pswd, true); - else CommonUtilities.setViewEnabled(mActivity, et_zip_conf_pswd, false); + // Hide Confirmation password if no password is entered + //if (et_zip_pswd.getText().length() > 0) CommonUtilities.setViewEnabled(mActivity, et_zip_conf_pswd, true); + //else CommonUtilities.setViewEnabled(mActivity, et_zip_conf_pswd, false); - CommonUtilities.setEditTextPasteCopyEnabled(et_zip_conf_pswd, false); + //CommonUtilities.setEditTextPasteCopyEnabled(et_zip_conf_pswd, false); et_zip_conf_pswd.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {} @@ -1732,7 +1751,8 @@ public void beforeTextChanged(CharSequence s, int start, int count, int after) { public void onTextChanged(CharSequence s, int start, int before, int count) {} @Override public void afterTextChanged(Editable s) { - checkSyncFolderValidation(dialog, sti, sfev); + checkSyncFolderValidation(dialog, sti, sfev, org_sfev); + //setSyncFolderOkButtonEnabledIfFolderChanged(dialog, org_sfev); } }); } @@ -1751,7 +1771,7 @@ private void editSyncFolder(boolean rebuild, SyncTaskItem sti, final SyncFolderE } else { t_dialog = new Dialog(this.mActivity, mGp.applicationTheme); mEditFolderDialog=t_dialog; - mEditFolderSfev=sfev.clone(); + mEditFolderSfev=sfev.cloneSerial(); mEditFolderSti=sti; mEditFolderNotify=ntfy; t_dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); @@ -1760,22 +1780,22 @@ private void editSyncFolder(boolean rebuild, SyncTaskItem sti, final SyncFolderE } final Dialog dialog = t_dialog; - final TextView dlg_msg = (TextView) dialog.findViewById(R.id.edit_sync_folder_dlg_msg); + final TextView dlg_msg = dialog.findViewById(R.id.edit_sync_folder_dlg_msg); - final Spinner spinnerSyncType = (Spinner) mDialog.findViewById(R.id.edit_sync_task_sync_type); + //final Spinner spinnerSyncType = (Spinner) mDialog.findViewById(R.id.edit_sync_task_sync_type); - LinearLayout ll_dlg_view = (LinearLayout) dialog.findViewById(R.id.edit_sync_folder_dlg_view); + LinearLayout ll_dlg_view = dialog.findViewById(R.id.edit_sync_folder_dlg_view); // ll_dlg_view.setBackgroundColor(mGp.themeColorList.dialog_msg_background_color); - LinearLayout title_view = (LinearLayout) dialog.findViewById(R.id.edit_sync_folder_dlg_title_view); + LinearLayout title_view = dialog.findViewById(R.id.edit_sync_folder_dlg_title_view); title_view.setBackgroundColor(mGp.themeColorList.title_background_color); - TextView dlg_title = (TextView) dialog.findViewById(R.id.edit_sync_folder_dlg_title); + TextView dlg_title = dialog.findViewById(R.id.edit_sync_folder_dlg_title); dlg_title.setBackgroundColor(mGp.themeColorList.title_background_color); dlg_title.setTextColor(mGp.themeColorList.title_text_color); dlg_title.setText(sfev.folder_title); - final Spinner sp_sync_folder_type = (Spinner) dialog.findViewById(R.id.edit_sync_folder_dlg_folder_type); + final Spinner sp_sync_folder_type = dialog.findViewById(R.id.edit_sync_folder_dlg_folder_type); sp_sync_folder_type.setOnItemSelectedListener(null); setSpinnerSyncFolderType(sti, sp_sync_folder_type, sfev.folder_type, sfev.is_source_folder); @@ -1793,15 +1813,15 @@ private void editSyncFolder(boolean rebuild, SyncTaskItem sti, final SyncFolderE setSyncFolderFieldHelpListener(dialog, sfev.folder_type); - final Button btn_sync_folder_cancel = (Button) dialog.findViewById(R.id.edit_profile_remote_btn_cancel); - final Button btn_sync_folder_ok = (Button) dialog.findViewById(R.id.edit_profile_remote_btn_ok); + final Button btn_sync_folder_cancel = dialog.findViewById(R.id.edit_profile_remote_btn_cancel); + final Button btn_sync_folder_ok = dialog.findViewById(R.id.edit_profile_remote_btn_ok); - setSyncFolderViewVisibility(dialog, sti, sfev.is_source_folder, sfev); + setSyncFolderViewVisibility(dialog, sti, sfev.is_source_folder, sfev, mEditFolderSfev); sp_sync_folder_type.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { - setSyncFolderViewVisibility(dialog, sti, sfev.is_source_folder, sfev); + setSyncFolderViewVisibility(dialog, sti, sfev.is_source_folder, sfev, mEditFolderSfev); } @Override public void onNothingSelected(AdapterView parent) {} @@ -1812,9 +1832,9 @@ public void onNothingSelected(AdapterView parent) {} btn_sync_folder_ok.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { - SyncFolderEditValue nsfev = buildSyncFolderEditValue(dialog, sfev); - final TextView tv_template = (TextView) dialog.findViewById(R.id.edit_sync_folder_dlg_archive_new_name); - nsfev.folder_error_code= SyncTaskItem.SYNC_FOLDER_STATUS_ERROR_NO_ERROR; + SyncFolderEditValue nsfev = buildSyncFolderEditValue(dialog, sfev, true); + final TextView tv_template = dialog.findViewById(R.id.edit_sync_folder_dlg_archive_new_name); + nsfev.folder_error_code = SyncTaskItem.SYNC_FOLDER_STATUS_ERROR_NO_ERROR; ntfy.notifyToListener(true, new Object[]{nsfev}); dialog.dismiss(); mEditFolderDialog=null; @@ -1875,71 +1895,71 @@ private void editDirectoryFileNameRule(boolean edit_directory_rule, boolean disa dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); dialog.setContentView(R.layout.edit_sync_folder_edit_keywor_dlg); - final TextView dlg_msg = (TextView) dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_msg); + final TextView dlg_msg = dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_msg); dlg_msg.setVisibility(TextView.GONE); - LinearLayout ll_dlg_view = (LinearLayout) dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_view); + LinearLayout ll_dlg_view = dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_view); // ll_dlg_view.setBackgroundColor(mGp.themeColorList.dialog_msg_background_color); - LinearLayout title_view = (LinearLayout) dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_title_view); + LinearLayout title_view = dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_title_view); title_view.setBackgroundColor(mGp.themeColorList.title_background_color); - TextView dlg_title = (TextView) dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_title); + TextView dlg_title = dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_title); dlg_title.setBackgroundColor(mGp.themeColorList.title_background_color); dlg_title.setTextColor(mGp.themeColorList.title_text_color); dlg_title.setText(title_text); - ImageButton ib_help=(ImageButton)dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_help); + ImageButton ib_help= dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_help); setSyncFolderKeywordHelpListener(dialog, !disable_taken_date); - final Button dlg_ok = (Button) dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_ok); + final Button dlg_ok = dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_ok); CommonUtilities.setViewEnabled(mActivity, dlg_ok,false); - final Button dlg_cancel = (Button) dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_cancel); + final Button dlg_cancel = dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_cancel); - final NonWordwrapTextView dlg_image = (NonWordwrapTextView) dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_image); + final NonWordwrapTextView dlg_image = dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_image); - final NonWordwrapTextView dlg_taken_title=(NonWordwrapTextView)dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_taken_title); - final NonWordwrapTextView dlg_exec_title=(NonWordwrapTextView)dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_exec_title); + final NonWordwrapTextView dlg_taken_title= dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_taken_title); + final NonWordwrapTextView dlg_exec_title= dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_exec_title); dlg_taken_title.setText(mActivity.getString(R.string.msgs_sync_folder_archive_add_taken_date_button)); // dlg_taken_title.setWordWrapEnabled(true); dlg_exec_title.setText(mActivity.getString(R.string.msgs_sync_folder_archive_add_sync_begin_date_button)); // dlg_exec_title.setWordWrapEnabled(true); - final LinearLayout dlg_ll_taken = (LinearLayout) dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_taken_view); - final Button dlg_taken_date = (Button) dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_taken_date); - final Button dlg_taken_time = (Button) dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_taken_time); - final Button dlg_taken_day_of_year = (Button) dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_taken_day_of_year); - final Button dlg_taken_yyyy = (Button) dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_taken_yyyy); - final Button dlg_taken_yy = (Button) dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_taken_yy); - final Button dlg_taken_mm = (Button) dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_taken_mm); - final Button dlg_taken_dd = (Button) dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_taken_dd); - final Button dlg_taken_hh = (Button) dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_taken_hh); - final Button dlg_taken_min = (Button) dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_taken_min); - final Button dlg_taken_sec = (Button) dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_taken_sec); - final Button dlg_taken_week_number = (Button) dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_taken_week_number); - final Button dlg_taken_week_day = (Button) dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_taken_week_day); - final Button dlg_taken_week_day_long = (Button) dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_taken_week_day_long); + final LinearLayout dlg_ll_taken = dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_taken_view); + final Button dlg_taken_date = dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_taken_date); + final Button dlg_taken_time = dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_taken_time); + final Button dlg_taken_day_of_year = dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_taken_day_of_year); + final Button dlg_taken_yyyy = dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_taken_yyyy); + final Button dlg_taken_yy = dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_taken_yy); + final Button dlg_taken_mm = dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_taken_mm); + final Button dlg_taken_dd = dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_taken_dd); + final Button dlg_taken_hh = dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_taken_hh); + final Button dlg_taken_min = dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_taken_min); + final Button dlg_taken_sec = dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_taken_sec); + final Button dlg_taken_week_number = dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_taken_week_number); + final Button dlg_taken_week_day = dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_taken_week_day); + final Button dlg_taken_week_day_long = dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_taken_week_day_long); if (disable_taken_date) dlg_ll_taken.setVisibility(LinearLayout.GONE); - final Button dlg_exec_date = (Button) dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_exec_date); - final Button dlg_exec_time = (Button) dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_exec_time); - final Button dlg_exec_day_of_year = (Button) dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_exec_day_of_year); - final Button dlg_exec_yyyy = (Button) dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_exec_yyyy); - final Button dlg_exec_yy = (Button) dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_exec_yy); - final Button dlg_exec_mm = (Button) dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_exec_mm); - final Button dlg_exec_dd = (Button) dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_exec_dd); - final Button dlg_exec_hh = (Button) dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_exec_hh); - final Button dlg_exec_min = (Button) dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_exec_min); - final Button dlg_exec_sec = (Button) dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_exec_sec); - final Button dlg_exec_week_number = (Button) dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_exec_week_number); - final Button dlg_exec_week_day = (Button) dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_exec_week_day); - final Button dlg_exec_week_day_long = (Button) dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_exec_week_day_long); - - final LinearLayout ll_dlg_file_name = (LinearLayout) dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_file_name_view); - final Button dlg_org_name = (Button) dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_org_name); - - final Button dlg_const_minus = (Button) dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_const_minus); - final Button dlg_const_slash = (Button) dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_const_slash); - final Button dlg_const_underbar = (Button) dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_const_underbar); - - final EditText dlg_keyword = (EditText) dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_keyword); + final Button dlg_exec_date = dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_exec_date); + final Button dlg_exec_time = dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_exec_time); + final Button dlg_exec_day_of_year = dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_exec_day_of_year); + final Button dlg_exec_yyyy = dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_exec_yyyy); + final Button dlg_exec_yy = dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_exec_yy); + final Button dlg_exec_mm = dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_exec_mm); + final Button dlg_exec_dd = dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_exec_dd); + final Button dlg_exec_hh = dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_exec_hh); + final Button dlg_exec_min = dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_exec_min); + final Button dlg_exec_sec = dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_exec_sec); + final Button dlg_exec_week_number = dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_exec_week_number); + final Button dlg_exec_week_day = dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_exec_week_day); + final Button dlg_exec_week_day_long = dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_exec_week_day_long); + + final LinearLayout ll_dlg_file_name = dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_file_name_view); + final Button dlg_org_name = dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_org_name); + + final Button dlg_const_minus = dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_const_minus); + final Button dlg_const_slash = dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_const_slash); + final Button dlg_const_underbar = dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_const_underbar); + + final EditText dlg_keyword = dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_keyword); CommonDialog.setDlgBoxSizeCompact(dialog); @@ -1987,7 +2007,7 @@ public void afterTextChanged(Editable s) { boolean loop_exit=false; while(!loop_exit) { String name_str=s.toString(); - if (name_str.indexOf("//")>=0) { + if (name_str.contains("//")) { int sp=name_str.indexOf("//"); s.delete(sp, sp+1); loop_exit=true; @@ -1997,16 +2017,15 @@ public void afterTextChanged(Editable s) { } } - String cv=getConvertedDirectoryFileName(s.toString(), System.currentTimeMillis(), "DSC-001"); dlg_image.setText(cv); - if (etInput.getText().toString().equals(dlg_keyword.getText().toString())) CommonUtilities.setViewEnabled(mActivity, dlg_ok, false); - else CommonUtilities.setViewEnabled(mActivity, dlg_ok, true); + CommonUtilities.setViewEnabled(mActivity, dlg_ok, !etInput.getText().toString().equals(dlg_keyword.getText().toString())); } else { CommonUtilities.setViewEnabled(mActivity, dlg_ok, false); } } }); + String cv=getConvertedDirectoryFileName(dlg_keyword.getText().toString(), System.currentTimeMillis(), "DSC-001"); dlg_image.setText(cv); @@ -2061,7 +2080,8 @@ public void afterTextChanged(Editable s) { dlg_ok.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { - etInput.setText(dlg_keyword.getText()); + //etInput.setText(dlg_keyword.getText()); + p_ntfy.notifyToListener(true, new Object[]{dlg_keyword.getText().toString()}); dialog.dismiss(); } }); @@ -2091,8 +2111,27 @@ public void negativeResponse(Context context, Object[] objects) {} } private void setWeekDayButtonLabel(Button short_button, Button long_button, String short_label, String long_label) { - Date date_sunday=new Date("2020/07/26"); - Date date_monday=new Date("2020/07/27"); + //for Current Date: date = new Date(); + //for default Date: date = new Date(0); + Date date_sunday = null; + Date date_monday = null; + try { + String date_sun_format = "2022/07/24"; //a sunday day of the year + String date_mon_format = "2022/07/25"; //a monday day of the year + DateFormat format = new SimpleDateFormat("yyyy/MM/dd", Locale.getDefault()); //Locale.getDefault() is lang set in app, not system wide, as we alter locale in mGp.setLocaleConfigForApi24() + date_sunday = format.parse(date_sun_format); + date_monday = format.parse(date_mon_format); + } catch (ParseException pe) { + mUtil.addDebugMsg(1, "E", "setWeekDayButtonLabel: parse data format exception"); + } + + if (date_sunday == null || date_monday == null) { + date_sunday = new Date(); //today + Calendar cal = Calendar.getInstance(); + cal.setTime(date_sunday); + cal.add(Calendar.DATE, 1); //tomorrow, aka next day relative to date_sunday + date_monday = cal.getTime(); + } String s_sunday=SyncThread.getWeekday(date_sunday.getTime()); String s_monday=SyncThread.getWeekday(date_monday.getTime()); String l_sunday=SyncThread.getWeekdayLong(date_sunday.getTime()); @@ -2106,8 +2145,8 @@ private void setWeekDayButtonLabel(Button short_button, Button long_button, Stri } private void setSyncFolderKeywordButtonListener(final Dialog dialog, final Button btn, final EditText et, final String key_word, String original_string) { - final NonWordwrapTextView dlg_image = (NonWordwrapTextView) dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_image); - final Button dlg_ok = (Button) dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_ok); + final NonWordwrapTextView dlg_image = dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_image); + final Button dlg_ok = dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_btn_ok); btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { @@ -2115,61 +2154,60 @@ public void onClick(View v) { else et.getText().replace(et.getSelectionStart(), et.getSelectionEnd(), key_word); String cv=getConvertedDirectoryFileName(et.getText().toString(), System.currentTimeMillis(), "DSC-001"); dlg_image.setText(cv); - if (et.getText().toString().equals(original_string.toString())) CommonUtilities.setViewEnabled(mActivity, dlg_ok, false); - else CommonUtilities.setViewEnabled(mActivity, dlg_ok, true); + CommonUtilities.setViewEnabled(mActivity, dlg_ok, !et.getText().toString().equals(original_string)); } }); } - private SyncFolderEditValue buildSyncFolderEditValue(Dialog dialog, SyncFolderEditValue org_sfev) { - final Spinner sp_sync_folder_type = (Spinner) dialog.findViewById(R.id.edit_sync_folder_dlg_folder_type); - final Spinner sp_sync_folder_smb_proto = (Spinner) dialog.findViewById(R.id.edit_sync_folder_dlg_smb_protocol); - final LinearLayout ll_sync_folder_local_storage = (LinearLayout) dialog.findViewById(R.id.edit_sync_folder_dlg_internal_storage_selector_view); - final Spinner sp_sync_folder_local_storage_selector = (Spinner) dialog.findViewById(R.id.edit_sync_folder_dlg_local_storage_selector); - final Spinner sp_sync_folder_zip_storage_selector = (Spinner) dialog.findViewById(R.id.edit_sync_folder_dlg_zip_storage_selector); + private SyncFolderEditValue buildSyncFolderEditValue(Dialog dialog, SyncFolderEditValue org_sfev, boolean is_save_btn) { + final Spinner sp_sync_folder_type = dialog.findViewById(R.id.edit_sync_folder_dlg_folder_type); + final Spinner sp_sync_folder_smb_proto = dialog.findViewById(R.id.edit_sync_folder_dlg_smb_protocol); + final LinearLayout ll_sync_folder_local_storage = dialog.findViewById(R.id.edit_sync_folder_dlg_internal_storage_selector_view); + final Spinner sp_sync_folder_local_storage_selector = dialog.findViewById(R.id.edit_sync_folder_dlg_local_storage_selector); + final Spinner sp_sync_folder_zip_storage_selector = dialog.findViewById(R.id.edit_sync_folder_dlg_zip_storage_selector); - final EditText et_remote_host = (EditText) dialog.findViewById(R.id.edit_sync_folder_dlg_remote_server); + final EditText et_remote_host = dialog.findViewById(R.id.edit_sync_folder_dlg_remote_server); // final CheckedTextView ctv_sync_folder_smb_ipc_enforced = (CheckedTextView) dialog.findViewById(R.id.edit_sync_folder_dlg_ctv_smb_ipc_signing_enforced); // final CheckedTextView ctv_sync_folder_smb_use_smb2_negotiation = (CheckedTextView) dialog.findViewById(R.id.edit_sync_folder_dlg_ctv_smb_use_smb2_negotiation); - final CheckedTextView ctv_sync_folder_use_port = (CheckedTextView) dialog.findViewById(R.id.edit_sync_folder_dlg_ctv_use_remote_port_number); - final EditText et_sync_folder_port = (EditText) dialog.findViewById(R.id.edit_sync_folder_dlg_remote_port); - final CheckedTextView ctv_sync_folder_use_pswd = (CheckedTextView) dialog.findViewById(R.id.edit_sync_folder_dlg_ctv_use_user_pass); - final EditText et_sync_folder_domain = (EditText) dialog.findViewById(R.id.edit_sync_folder_dlg_remote_domain); - final EditText et_sync_folder_user = (EditText) dialog.findViewById(R.id.edit_sync_folder_dlg_remote_user); - final EditText et_sync_folder_pswd = (EditText) dialog.findViewById(R.id.edit_sync_folder_dlg_remote_pass); - - final Button btn_sync_folder_list_share = (Button) dialog.findViewById(R.id.edit_sync_folder_dlg_list_share_btn); - final EditText et_sync_folder_share_name = (EditText) dialog.findViewById(R.id.edit_sync_folder_dlg_share_name); - final Button btn_sync_folder_local_list_dir = (Button) dialog.findViewById(R.id.edit_sync_folder_dlg_list_internal_directory_btn); - final Button btn_sync_folder_smb_list_dir = (Button) dialog.findViewById(R.id.edit_sync_folder_dlg_list_smb_directory_btn); - final TextInputLayout ll_sync_folder_pswd_view = (TextInputLayout) dialog.findViewById(R.id.edit_sync_folder_dlg_remote_pass_view); + final CheckedTextView ctv_sync_folder_use_port = dialog.findViewById(R.id.edit_sync_folder_dlg_ctv_use_remote_port_number); + final EditText et_sync_folder_port = dialog.findViewById(R.id.edit_sync_folder_dlg_remote_port); + final CheckedTextView ctv_sync_folder_use_pswd = dialog.findViewById(R.id.edit_sync_folder_dlg_ctv_use_user_pass); + final EditText et_sync_folder_domain = dialog.findViewById(R.id.edit_sync_folder_dlg_remote_domain); + final EditText et_sync_folder_user = dialog.findViewById(R.id.edit_sync_folder_dlg_remote_user); + final EditText et_sync_folder_pswd = dialog.findViewById(R.id.edit_sync_folder_dlg_remote_pass); + + final Button btn_sync_folder_list_share = dialog.findViewById(R.id.edit_sync_folder_dlg_list_share_btn); + final EditText et_sync_folder_share_name = dialog.findViewById(R.id.edit_sync_folder_dlg_share_name); + final Button btn_sync_folder_local_list_dir = dialog.findViewById(R.id.edit_sync_folder_dlg_list_internal_directory_btn); + final Button btn_sync_folder_smb_list_dir = dialog.findViewById(R.id.edit_sync_folder_dlg_list_smb_directory_btn); +// final TextInputLayout ll_sync_folder_pswd_view = (TextInputLayout) dialog.findViewById(R.id.edit_sync_folder_dlg_remote_pass_view); // final CheckedTextView ctv_sync_folder_show_smb_password = (CheckedTextView) dialog.findViewById(R.id.edit_sync_folder_dlg_ctv_show_smb_account_password); - final EditText et_sync_folder_internal_dir_name = (EditText) dialog.findViewById(R.id.edit_sync_folder_dlg_internal_directory_name); - final EditText et_sync_folder_smb_dir_name = (EditText) dialog.findViewById(R.id.edit_sync_folder_dlg_smb_directory_name); + final EditText et_sync_folder_internal_dir_name = dialog.findViewById(R.id.edit_sync_folder_dlg_internal_directory_name); + final EditText et_sync_folder_smb_dir_name = dialog.findViewById(R.id.edit_sync_folder_dlg_smb_directory_name); - final CheckedTextView ctv_sync_folder_edit_smb_detail = (CheckedTextView) dialog.findViewById(R.id.edit_sync_folder_dlg_ctv_edit_smb_server_detail); + final CheckedTextView ctv_sync_folder_edit_smb_detail = dialog.findViewById(R.id.edit_sync_folder_dlg_ctv_edit_smb_server_detail); - final LinearLayout ll_dir_view = (LinearLayout) dialog.findViewById(R.id.edit_sync_folder_dlg_internal_directory_view); - final LinearLayout ll_zip_view = (LinearLayout) dialog.findViewById(R.id.edit_sync_folder_dlg_zip_view); + final LinearLayout ll_dir_view = dialog.findViewById(R.id.edit_sync_folder_dlg_internal_directory_view); + final LinearLayout ll_zip_view = dialog.findViewById(R.id.edit_sync_folder_dlg_zip_view); - final TextView tv_zip_dir = (TextView) dialog.findViewById(R.id.edit_sync_folder_dlg_zip_dir_name); - final EditText et_zip_file = (EditText) dialog.findViewById(R.id.edit_sync_folder_dlg_zip_file_name); - final Spinner sp_comp_level = (Spinner) dialog.findViewById(R.id.edit_sync_folder_dlg_zip_comp_level); - final Spinner sp_zip_enc_method=(Spinner) dialog.findViewById(R.id.edit_sync_folder_dlg_zip_enc_method); - final TextInputEditText et_zip_pswd = (TextInputEditText) dialog.findViewById(R.id.edit_sync_folder_dlg_zip_enc_password); - final EditText et_zip_conf_pswd = (EditText) dialog.findViewById(R.id.edit_sync_folder_dlg_zip_enc_confirm); - final LinearLayout ll_conf_pswd_view=(LinearLayout)dialog.findViewById(R.id.edit_sync_folder_dlg_zip_enc_confirm_view); + final TextView tv_zip_dir = dialog.findViewById(R.id.edit_sync_folder_dlg_zip_dir_name); + final EditText et_zip_file = dialog.findViewById(R.id.edit_sync_folder_dlg_zip_file_name); + final Spinner sp_comp_level = dialog.findViewById(R.id.edit_sync_folder_dlg_zip_comp_level); + final Spinner sp_zip_enc_method= dialog.findViewById(R.id.edit_sync_folder_dlg_zip_enc_method); + final EditText et_zip_pswd = dialog.findViewById(R.id.edit_sync_folder_dlg_zip_enc_password); + final EditText et_zip_conf_pswd = dialog.findViewById(R.id.edit_sync_folder_dlg_zip_enc_confirm); + final LinearLayout ll_conf_pswd_view= dialog.findViewById(R.id.edit_sync_folder_dlg_zip_enc_confirm_view); // final CheckedTextView ctv_sync_folder_show_zip_password = (CheckedTextView) dialog.findViewById(R.id.edit_sync_folder_dlg_ctv_show_zip_password); - final Spinner sp_sync_retain_period = (Spinner) dialog.findViewById(R.id.edit_sync_filter_archive_retention_period); - final Spinner sp_sync_suffix_option = (Spinner) dialog.findViewById(R.id.edit_sync_folder_dlg_archive_suffix_seqno); - final EditText et_file_template = (EditText) dialog.findViewById(R.id.edit_sync_folder_dlg_archive_file_name_template); + final Spinner sp_sync_retain_period = dialog.findViewById(R.id.edit_sync_filter_archive_retention_period); + final Spinner sp_sync_suffix_option = dialog.findViewById(R.id.edit_sync_folder_dlg_archive_suffix_seqno); + final EditText et_file_template = dialog.findViewById(R.id.edit_sync_folder_dlg_archive_file_name_template); - final CheckedTextView ctv_ignore_source_directory_hierarchy=(CheckedTextView)dialog.findViewById(R.id.edit_sync_folder_dlg_archive_ignore_source_directory_hierarchy); + final CheckedTextView ctv_ignore_source_directory_hierarchy= dialog.findViewById(R.id.edit_sync_folder_dlg_archive_ignore_source_directory_hierarchy); - SyncFolderEditValue nsfev = org_sfev.clone(); + SyncFolderEditValue nsfev = org_sfev.cloneSerial(); String sel = sp_sync_folder_type.getSelectedItem().toString(); if (sel.equals(mActivity.getString(R.string.msgs_main_sync_profile_dlg_sync_folder_type_local))) {//Internal @@ -2210,21 +2248,20 @@ private SyncFolderEditValue buildSyncFolderEditValue(Dialog dialog, SyncFolderEd else if (zip_enc_method.equals(mActivity.getString(R.string.msgs_task_edit_sync_folder_dlg_zip_encrypt_zip_crypto))) nsfev.zip_enc_method = SyncTaskItem.ZIP_OPTION_ENCRYPT_STANDARD; else if (zip_enc_method.equals(mActivity.getString(R.string.msgs_task_edit_sync_folder_dlg_zip_encrypt_aes128))) nsfev.zip_enc_method = SyncTaskItem.ZIP_OPTION_ENCRYPT_AES128; else if (zip_enc_method.equals(mActivity.getString(R.string.msgs_task_edit_sync_folder_dlg_zip_encrypt_aes256))) nsfev.zip_enc_method = SyncTaskItem.ZIP_OPTION_ENCRYPT_AES256; - - if (tv_zip_dir.getText().toString().trim().equals("/")) nsfev.zip_file_name=et_zip_file.getText().toString().trim(); - else nsfev.zip_file_name=tv_zip_dir.getText().toString().trim().substring(1)+"/"+et_zip_file.getText().toString().trim(); - - if (!nsfev.zip_enc_method.equals(SyncTaskItem.ZIP_OPTION_ENCRYPT_NONE)) { - nsfev.zip_file_password = et_zip_pswd.getText().toString(); - nsfev.zip_file_confirm_password = et_zip_conf_pswd.getText().toString(); - } else { + if (is_save_btn && nsfev.zip_enc_method.equals(SyncTaskItem.ZIP_OPTION_ENCRYPT_NONE)) { nsfev.zip_file_password = ""; nsfev.zip_file_confirm_password=""; + } else { + nsfev.zip_file_password = et_zip_pswd.getText().toString(); + nsfev.zip_file_confirm_password = et_zip_conf_pswd.getText().toString(); } + if (tv_zip_dir.getText().toString().trim().equals("/")) nsfev.zip_file_name=et_zip_file.getText().toString().trim(); + else nsfev.zip_file_name=tv_zip_dir.getText().toString().trim().substring(1)+"/"+et_zip_file.getText().toString().trim(); + if (mGp.settingSecurityReinitZipPasswordValue && et_zip_pswd.getText().toString().length()>0) nsfev.isChanged=true; - nsfev.show_zip_passowrd=et_zip_pswd.getTransformationMethod()==null?true:false; + nsfev.show_zip_passowrd = et_zip_pswd.getTransformationMethod() == null; nsfev.folder_type = SyncTaskItem.SYNC_FOLDER_TYPE_ZIP; } else if (sel.equals(mActivity.getString(R.string.msgs_main_sync_profile_dlg_sync_folder_type_smb))) {//smb @@ -2235,24 +2272,30 @@ private SyncFolderEditValue buildSyncFolderEditValue(Dialog dialog, SyncFolderEd while(nsfev.folder_directory.endsWith("/")) { nsfev.folder_directory=nsfev.folder_directory.substring(0, nsfev.folder_directory.length()-1); } + nsfev.folder_type = SyncTaskItem.SYNC_FOLDER_TYPE_SMB; nsfev.folder_smb_host =et_remote_host.getText().toString(); nsfev.folder_smb_domain = et_sync_folder_domain.getText().toString().trim(); - if (ctv_sync_folder_use_port.isChecked()) - nsfev.folder_smb_port = et_sync_folder_port.getText().toString(); - else nsfev.folder_smb_port = ""; - if (ctv_sync_folder_use_pswd.isChecked()) { - nsfev.folder_smb_account = et_sync_folder_user.getText().toString().trim(); - nsfev.folder_smb_password = et_sync_folder_pswd.getText().toString(); + + nsfev.folder_smb_use_port =ctv_sync_folder_use_port.isChecked(); + if (is_save_btn && !ctv_sync_folder_use_port.isChecked()) { + nsfev.folder_smb_port = ""; } else { + nsfev.folder_smb_port = et_sync_folder_port.getText().toString(); + } + + nsfev.folder_smb_use_pswd =ctv_sync_folder_use_pswd.isChecked(); + if (is_save_btn && !ctv_sync_folder_use_pswd.isChecked()) { nsfev.folder_smb_account = ""; nsfev.folder_smb_password = ""; + } else { + nsfev.folder_smb_account = et_sync_folder_user.getText().toString().trim(); + nsfev.folder_smb_password = et_sync_folder_pswd.getText().toString(); } if (mGp.settingSecurityReinitSmbAccountPasswordValue && (et_sync_folder_user.getText().toString().length()>0 || et_sync_folder_pswd.getText().toString().length()>0) ) nsfev.isChanged=true; - nsfev.folder_smb_use_pswd =ctv_sync_folder_use_pswd.isChecked(); nsfev.folder_smb_share = et_sync_folder_share_name.getText().toString().trim(); nsfev.folder_smb_protocol=getSmbSelectedProtocol(sp_sync_folder_smb_proto); if (nsfev.task_type.equals(SyncTaskItem.SYNC_TASK_TYPE_ARCHIVE)) { @@ -2263,7 +2306,9 @@ private SyncFolderEditValue buildSyncFolderEditValue(Dialog dialog, SyncFolderEd } nsfev.show_smb_detail_settings=ctv_sync_folder_edit_smb_detail.isChecked(); - nsfev.show_smb_passowrd=et_sync_folder_pswd.getTransformationMethod()==null?false:true; + + // Mod 2/2: Preserve SMB password masked/unmasked state on screen rotation + nsfev.show_smb_passowrd = nsfev.show_smb_detail_settings && et_sync_folder_pswd.getTransformationMethod() == null; } return nsfev; } @@ -2273,28 +2318,28 @@ private void setSyncFolderOkButtonEnabled(Button ok_btn, boolean enabled) { } private void setSyncFolderSmbListDirectoryButtonEnabled(Dialog dialog, boolean enabled) { - final Button btn_sync_folder_smb_list_dir = (Button) dialog.findViewById(R.id.edit_sync_folder_dlg_list_smb_directory_btn); + final Button btn_sync_folder_smb_list_dir = dialog.findViewById(R.id.edit_sync_folder_dlg_list_smb_directory_btn); CommonUtilities.setViewEnabled(mActivity, btn_sync_folder_smb_list_dir, enabled); } - private void setSyncFolderViewVisibility(final Dialog dialog, SyncTaskItem sti, final boolean source, SyncFolderEditValue org_sfev) { - final TextView dlg_msg = (TextView) dialog.findViewById(R.id.edit_sync_folder_dlg_msg); - final Spinner sp_sync_folder_type = (Spinner) dialog.findViewById(R.id.edit_sync_folder_dlg_folder_type); - final LinearLayout ll_sync_folder_local_storage = (LinearLayout) dialog.findViewById(R.id.edit_sync_folder_dlg_internal_storage_selector_view); - final Spinner sp_sync_folder_local_storage_selector = (Spinner) dialog.findViewById(R.id.edit_sync_folder_dlg_local_storage_selector); - final Spinner sp_sync_folder_smb_proto = (Spinner) dialog.findViewById(R.id.edit_sync_folder_dlg_smb_protocol); + private void setSyncFolderViewVisibility(final Dialog dialog, SyncTaskItem sti, final boolean source, SyncFolderEditValue sfev, SyncFolderEditValue org_sfev) { + final TextView dlg_msg = dialog.findViewById(R.id.edit_sync_folder_dlg_msg); + final Spinner sp_sync_folder_type = dialog.findViewById(R.id.edit_sync_folder_dlg_folder_type); + final LinearLayout ll_sync_folder_local_storage = dialog.findViewById(R.id.edit_sync_folder_dlg_internal_storage_selector_view); + final Spinner sp_sync_folder_local_storage_selector = dialog.findViewById(R.id.edit_sync_folder_dlg_local_storage_selector); + final Spinner sp_sync_folder_smb_proto = dialog.findViewById(R.id.edit_sync_folder_dlg_smb_protocol); // final CheckedTextView ctv_sync_folder_smb_ipc_enforced = (CheckedTextView) dialog.findViewById(R.id.edit_sync_folder_dlg_ctv_smb_ipc_signing_enforced); // final CheckedTextView ctv_sync_folder_smb_use_smb2_negotiation = (CheckedTextView) dialog.findViewById(R.id.edit_sync_folder_dlg_ctv_smb_use_smb2_negotiation); - final LinearLayout ll_sync_folder_smb_view = (LinearLayout) dialog.findViewById(R.id.edit_sync_folder_dlg_smb_view); - final LinearLayout ll_sync_folder_internal_view = (LinearLayout) dialog.findViewById(R.id.edit_sync_folder_dlg_internal_view); - final LinearLayout ll_sync_folder_zip_view = (LinearLayout) dialog.findViewById(R.id.edit_sync_folder_dlg_zip_view); + final LinearLayout ll_sync_folder_smb_view = dialog.findViewById(R.id.edit_sync_folder_dlg_smb_view); + final LinearLayout ll_sync_folder_internal_view = dialog.findViewById(R.id.edit_sync_folder_dlg_internal_view); + final LinearLayout ll_sync_folder_zip_view = dialog.findViewById(R.id.edit_sync_folder_dlg_zip_view); - final Button btn_sync_folder_local_list_dir = (Button) dialog.findViewById(R.id.edit_sync_folder_dlg_list_internal_directory_btn); - final Button btn_sync_folder_smb_list_dir = (Button) dialog.findViewById(R.id.edit_sync_folder_dlg_list_smb_directory_btn); - final Button btn_sync_folder_edit_dir_rule = (Button) dialog.findViewById(R.id.edit_sync_folder_dlg_edit_smb_dir_keyword); + final Button btn_sync_folder_local_list_dir = dialog.findViewById(R.id.edit_sync_folder_dlg_list_internal_directory_btn); + final Button btn_sync_folder_smb_list_dir = dialog.findViewById(R.id.edit_sync_folder_dlg_list_smb_directory_btn); + final Button btn_sync_folder_edit_dir_rule = dialog.findViewById(R.id.edit_sync_folder_dlg_edit_smb_dir_keyword); - final LinearLayout ll_internal_keyword_view = (LinearLayout) ll_sync_folder_internal_view.findViewById(R.id.edit_sync_folder_dlg_internal_dir_keyword_view); - final LinearLayout ll_smb_keyword_view = (LinearLayout) ll_sync_folder_smb_view.findViewById(R.id.edit_sync_folder_dlg_smb_dir_keyword_view); + final LinearLayout ll_internal_keyword_view = ll_sync_folder_internal_view.findViewById(R.id.edit_sync_folder_dlg_internal_dir_keyword_view); + final LinearLayout ll_smb_keyword_view = ll_sync_folder_smb_view.findViewById(R.id.edit_sync_folder_dlg_smb_dir_keyword_view); setSyncFolderSmbListDirectoryButtonEnabled(dialog, true); String sel = sp_sync_folder_type.getSelectedItem().toString(); @@ -2310,54 +2355,54 @@ private void setSyncFolderViewVisibility(final Dialog dialog, SyncTaskItem sti, ll_sync_folder_internal_view.setVisibility(LinearLayout.GONE); ll_sync_folder_smb_view.setVisibility(LinearLayout.VISIBLE); ll_sync_folder_zip_view.setVisibility(LinearLayout.GONE); - checkSyncFolderValidation(dialog, sti, org_sfev); + checkSyncFolderValidation(dialog, sti, sfev, org_sfev); setSyncFolderFieldHelpListener(dialog, SyncTaskItem.SYNC_FOLDER_TYPE_SMB); } else if (sel.equals(mActivity.getString(R.string.msgs_main_sync_profile_dlg_sync_folder_type_local))) { ll_sync_folder_internal_view.setVisibility(LinearLayout.VISIBLE); ll_sync_folder_smb_view.setVisibility(LinearLayout.GONE); ll_sync_folder_zip_view.setVisibility(LinearLayout.GONE); - checkSyncFolderValidation(dialog, sti, org_sfev); + checkSyncFolderValidation(dialog, sti, sfev, org_sfev); setSyncFolderFieldHelpListener(dialog, SyncTaskItem.SYNC_FOLDER_TYPE_LOCAL); } else if (sel.equals(mActivity.getString(R.string.msgs_main_sync_profile_dlg_sync_folder_type_zip))) { ll_sync_folder_internal_view.setVisibility(LinearLayout.GONE); ll_sync_folder_smb_view.setVisibility(LinearLayout.GONE); ll_sync_folder_zip_view.setVisibility(LinearLayout.VISIBLE); - checkSyncFolderValidation(dialog, sti, org_sfev); + checkSyncFolderValidation(dialog, sti, sfev, org_sfev); setSyncFolderFieldHelpListener(dialog, SyncTaskItem.SYNC_FOLDER_TYPE_ZIP); } } - private boolean checkSyncFolderValidation(Dialog dialog, SyncTaskItem sti, SyncFolderEditValue org_sfev) { + private boolean checkSyncFolderValidation(Dialog dialog, SyncTaskItem sti, SyncFolderEditValue sfev, SyncFolderEditValue org_sfev) { boolean result = true; - final TextView dlg_msg = (TextView) dialog.findViewById(R.id.edit_sync_folder_dlg_msg); + final TextView dlg_msg = dialog.findViewById(R.id.edit_sync_folder_dlg_msg); setDialogMsg(dlg_msg, ""); - final Spinner sp_sync_folder_type = (Spinner) dialog.findViewById(R.id.edit_sync_folder_dlg_folder_type); - final CheckedTextView ctv_sync_folder_edit_smb_detail = (CheckedTextView) dialog.findViewById(R.id.edit_sync_folder_dlg_ctv_edit_smb_server_detail); - final Spinner sp_sync_folder_local_storage_selector = (Spinner) dialog.findViewById(R.id.edit_sync_folder_dlg_local_storage_selector); - final Spinner sp_sync_folder_zip_storage_selector = (Spinner) dialog.findViewById(R.id.edit_sync_folder_dlg_zip_storage_selector); - final Button btn_sync_folder_permission = (Button) dialog.findViewById(R.id.edit_sync_folder_dlg_local_storage_request_permission); + final Spinner sp_sync_folder_type = dialog.findViewById(R.id.edit_sync_folder_dlg_folder_type); + final CheckedTextView ctv_sync_folder_edit_smb_detail = dialog.findViewById(R.id.edit_sync_folder_dlg_ctv_edit_smb_server_detail); + final Spinner sp_sync_folder_local_storage_selector = dialog.findViewById(R.id.edit_sync_folder_dlg_local_storage_selector); + final Spinner sp_sync_folder_zip_storage_selector = dialog.findViewById(R.id.edit_sync_folder_dlg_zip_storage_selector); + final Button btn_sync_folder_permission = dialog.findViewById(R.id.edit_sync_folder_dlg_local_storage_request_permission); - final Button btn_sync_folder_local_list_dir = (Button) dialog.findViewById(R.id.edit_sync_folder_dlg_list_internal_directory_btn); + final Button btn_sync_folder_local_list_dir = dialog.findViewById(R.id.edit_sync_folder_dlg_list_internal_directory_btn); - final EditText et_remote_host = (EditText) dialog.findViewById(R.id.edit_sync_folder_dlg_remote_server); - final CheckedTextView ctv_sync_folder_use_port = (CheckedTextView) dialog.findViewById(R.id.edit_sync_folder_dlg_ctv_use_remote_port_number); - final EditText et_sync_folder_port = (EditText) dialog.findViewById(R.id.edit_sync_folder_dlg_remote_port); + final EditText et_remote_host = dialog.findViewById(R.id.edit_sync_folder_dlg_remote_server); + final CheckedTextView ctv_sync_folder_use_port = dialog.findViewById(R.id.edit_sync_folder_dlg_ctv_use_remote_port_number); + final EditText et_sync_folder_port = dialog.findViewById(R.id.edit_sync_folder_dlg_remote_port); - final CheckedTextView ctv_sync_folder_use_pswd = (CheckedTextView) dialog.findViewById(R.id.edit_sync_folder_dlg_ctv_use_user_pass); - final EditText et_sync_folder_user = (EditText) dialog.findViewById(R.id.edit_sync_folder_dlg_remote_user); - final EditText et_sync_folder_pswd = (EditText) dialog.findViewById(R.id.edit_sync_folder_dlg_remote_pass); + final CheckedTextView ctv_sync_folder_use_pswd = dialog.findViewById(R.id.edit_sync_folder_dlg_ctv_use_user_pass); + final EditText et_sync_folder_user = dialog.findViewById(R.id.edit_sync_folder_dlg_remote_user); + final EditText et_sync_folder_pswd = dialog.findViewById(R.id.edit_sync_folder_dlg_remote_pass); - final EditText et_sync_folder_share_name = (EditText) dialog.findViewById(R.id.edit_sync_folder_dlg_share_name); + final EditText et_sync_folder_share_name = dialog.findViewById(R.id.edit_sync_folder_dlg_share_name); - final Button btn_sync_folder_ok = (Button) dialog.findViewById(R.id.edit_profile_remote_btn_ok); + final Button btn_sync_folder_ok = dialog.findViewById(R.id.edit_profile_remote_btn_ok); // final LinearLayout ll_sync_folder_smb_view = (LinearLayout)dialog.findViewById(R.id.edit_sync_folder_dlg_smb_host_view); // final Button btn_search_host = (Button)dialog.findViewById(R.id.edit_sync_folder_dlg_search_remote_host); // final EditText et_sync_folder_domain = (EditText)dialog.findViewById(R.id.edit_sync_folder_dlg_remote_domain); - final Button btn_sync_folder_smb_list_share = (Button) dialog.findViewById(R.id.edit_sync_folder_dlg_list_share_btn); - final Button btn_sync_folder_smb_list_dir = (Button) dialog.findViewById(R.id.edit_sync_folder_dlg_list_smb_directory_btn); - final Button btn_sync_folder_edit_smb_dir_rule = (Button) dialog.findViewById(R.id.edit_sync_folder_dlg_edit_smb_dir_keyword); + final Button btn_sync_folder_smb_list_share = dialog.findViewById(R.id.edit_sync_folder_dlg_list_share_btn); + final Button btn_sync_folder_smb_list_dir = dialog.findViewById(R.id.edit_sync_folder_dlg_list_smb_directory_btn); + final Button btn_sync_folder_edit_smb_dir_rule = dialog.findViewById(R.id.edit_sync_folder_dlg_edit_smb_dir_keyword); // final EditText et_sync_folder_dir_name = (EditText)dialog.findViewById(R.id.edit_sync_folder_dlg_directory_name); // final Button btn_sdcard_select_sdcard = (Button)dialog.findViewById(R.id.edit_sync_folder_dlg_show_select_document_tree); // final CheckedTextView ctv_sync_folder_use_usb_folder = (CheckedTextView)dialog.findViewById(R.id.edit_sync_folder_dlg_ctv_use_usb_folder); @@ -2367,13 +2412,13 @@ private boolean checkSyncFolderValidation(Dialog dialog, SyncTaskItem sti, SyncF // final LinearLayout ll_zip_view = (LinearLayout)dialog.findViewById(R.id.edit_sync_folder_dlg_zip_view); // final CheckedTextView ctv_sync_folder_zip_file_name_time_stamp = (CheckedTextView)dialog.findViewById(R.id.edit_sync_folder_dlg_zip_file_time_stamp); - final Button btn_zip_filelist = (Button) dialog.findViewById(R.id.edit_sync_folder_dlg_zip_filelist_btn); - final EditText et_sync_folder_zip_file_name = (EditText) dialog.findViewById(R.id.edit_sync_folder_dlg_zip_file_name); - final Spinner sp_zip_enc_method=(Spinner) dialog.findViewById(R.id.edit_sync_folder_dlg_zip_enc_method); - final TextInputEditText et_zip_pswd = (TextInputEditText) dialog.findViewById(R.id.edit_sync_folder_dlg_zip_enc_password); - final EditText et_zip_conf_pswd = (EditText) dialog.findViewById(R.id.edit_sync_folder_dlg_zip_enc_confirm); - final EditText et_sync_folder_dir_name = (EditText) dialog.findViewById(R.id.edit_sync_folder_dlg_internal_directory_name); - final EditText et_file_template = (EditText) dialog.findViewById(R.id.edit_sync_folder_dlg_archive_file_name_template); + final Button btn_zip_filelist = dialog.findViewById(R.id.edit_sync_folder_dlg_zip_filelist_btn); + final EditText et_sync_folder_zip_file_name = dialog.findViewById(R.id.edit_sync_folder_dlg_zip_file_name); + final Spinner sp_zip_enc_method= dialog.findViewById(R.id.edit_sync_folder_dlg_zip_enc_method); + final EditText et_zip_pswd = dialog.findViewById(R.id.edit_sync_folder_dlg_zip_enc_password); + final EditText et_zip_conf_pswd = dialog.findViewById(R.id.edit_sync_folder_dlg_zip_enc_confirm); + final EditText et_sync_folder_dir_name = dialog.findViewById(R.id.edit_sync_folder_dlg_internal_directory_name); + final EditText et_file_template = dialog.findViewById(R.id.edit_sync_folder_dlg_archive_file_name_template); String sel_type = sp_sync_folder_type.getSelectedItem().toString(); if (sel_type.equals(mActivity.getString(R.string.msgs_main_sync_profile_dlg_sync_folder_type_local))) { @@ -2410,8 +2455,8 @@ private boolean checkSyncFolderValidation(Dialog dialog, SyncTaskItem sti, SyncF CommonUtilities.setViewEnabled(mActivity, btn_sync_folder_local_list_dir, false); } } - if (result && !org_sfev.is_source_folder) { - if (org_sfev.task_type.equals(SyncTaskItem.SYNC_TASK_TYPE_MIRROR)) { + if (result && !sfev.is_source_folder) { + if (sfev.task_type.equals(SyncTaskItem.SYNC_TASK_TYPE_MIRROR)) { String e_msg=checkTakenDateParameterUsed(et_sync_folder_dir_name.getText().toString()); if (!e_msg.equals("")) { result = false; @@ -2455,16 +2500,16 @@ private boolean checkSyncFolderValidation(Dialog dialog, SyncTaskItem sti, SyncF setDialogMsg(dlg_msg, mActivity.getString(R.string.msgs_main_sync_profile_dlg_specify_host_userid_pswd)); } } - if (result && folder_share_name.equals("")) { + if (result && folder_share_name.equals("")) { //result always true ! setDialogMsg(dlg_msg, mActivity.getString(R.string.msgs_main_sync_profile_dlg_specify_host_share_name)); CommonUtilities.setViewEnabled(mActivity, btn_sync_folder_smb_list_share, ctv_sync_folder_edit_smb_detail.isChecked()); CommonUtilities.setViewEnabled(mActivity, btn_sync_folder_smb_list_dir, false); CommonUtilities.setViewEnabled(mActivity, btn_sync_folder_edit_smb_dir_rule, false); result = false; } else { - if (result) { - if (result && !org_sfev.is_source_folder) { - if (org_sfev.task_type.equals(SyncTaskItem.SYNC_TASK_TYPE_MIRROR)) { + if (result) { //result always true ! + if (result && !sfev.is_source_folder) { //result always true ! + if (sfev.task_type.equals(SyncTaskItem.SYNC_TASK_TYPE_MIRROR)) { String e_msg=checkTakenDateParameterUsed(et_sync_folder_dir_name.getText().toString()); if (!e_msg.equals("")) { result = false; @@ -2537,11 +2582,10 @@ private String checkTakenDateParameterUsed(String dir_name) { } private void setSyncFolderOkButtonEnabledIfFolderChanged(Dialog dialog, SyncFolderEditValue org_sfev) { - final Button btn_sync_folder_ok = (Button) dialog.findViewById(R.id.edit_profile_remote_btn_ok); - SyncFolderEditValue nsfev = buildSyncFolderEditValue(dialog, org_sfev); - boolean same = nsfev.isSame(org_sfev); - if (!same) setSyncFolderOkButtonEnabled(btn_sync_folder_ok, true); - else setSyncFolderOkButtonEnabled(btn_sync_folder_ok, false); + final Button btn_sync_folder_ok = dialog.findViewById(R.id.edit_profile_remote_btn_ok); + SyncFolderEditValue nsfev = buildSyncFolderEditValue(dialog, org_sfev, false); + boolean same = nsfev.isSame(org_sfev, mUtil); + setSyncFolderOkButtonEnabled(btn_sync_folder_ok, !same); } static public Dialog showDialogWithHideOption(final Activity activity, final GlobalParameters gp, CommonUtilities cu, @@ -2553,28 +2597,28 @@ static public Dialog showDialogWithHideOption(final Activity activity, final Glo dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(R.layout.show_warning_message_dlg); - final LinearLayout dlg_view = (LinearLayout) dialog.findViewById(R.id.confirm_app_specific_dlg_view); + final LinearLayout dlg_view = dialog.findViewById(R.id.confirm_app_specific_dlg_view); // dlg_view.setBackgroundColor(gp.themeColorList.text_background_color); - final LinearLayout title_view = (LinearLayout) dialog.findViewById(R.id.show_warning_message_dlg_title_view); - final ScrollView msg_view = (ScrollView) dialog.findViewById(R.id.show_warning_message_dlg_msg_view); + final LinearLayout title_view = dialog.findViewById(R.id.show_warning_message_dlg_title_view); + final ScrollView msg_view = dialog.findViewById(R.id.show_warning_message_dlg_msg_view); // msg_view.setBackgroundColor(Color.DKGRAY); - final LinearLayout btn_view = (LinearLayout) dialog.findViewById(R.id.show_warning_message_dlg_btn_view); + final LinearLayout btn_view = dialog.findViewById(R.id.show_warning_message_dlg_btn_view); // btn_view.setBackgroundColor(Color.DKGRAY); - final TextView title = (TextView) dialog.findViewById(R.id.show_warning_message_dlg_title); + final TextView title = dialog.findViewById(R.id.show_warning_message_dlg_title); title_view.setBackgroundColor(gp.themeColorList.title_background_color); title.setText(title_text); title.setTextColor(gp.themeColorList.title_text_color); - TextView dlg_msg=((TextView) dialog.findViewById(R.id.show_warning_message_dlg_msg)); + TextView dlg_msg= dialog.findViewById(R.id.show_warning_message_dlg_msg); dlg_msg.setText(msg_text); - final Button btnOk = (Button) dialog.findViewById(R.id.show_warning_message_dlg_close); + final Button btnOk = dialog.findViewById(R.id.show_warning_message_dlg_close); btnOk.setText(ok_label); btnOk.setVisibility(ok_visible?Button.VISIBLE:Button.GONE); - final Button btnCancel = (Button) dialog.findViewById(R.id.show_warning_message_dlg_cancel); + final Button btnCancel = dialog.findViewById(R.id.show_warning_message_dlg_cancel); btnCancel.setText(cancel_label); btnCancel.setVisibility(cancel_visible?Button.VISIBLE:Button.GONE); - final CheckedTextView ctvSuppr = (CheckedTextView) dialog.findViewById(R.id.show_warning_message_dlg_ctv_suppress); + final CheckedTextView ctvSuppr = dialog.findViewById(R.id.show_warning_message_dlg_ctv_suppress); CommonUtilities.setCheckedTextViewListener(ctvSuppr); ctvSuppr.setText(suppress_text); @@ -2606,7 +2650,7 @@ public void onCancel(DialogInterface arg0) { } private void invokeEditDirFilterDlg(final Dialog dialog, final SyncTaskItem n_sti, final String type, final TextView dlg_msg) { - final TextView dlg_dir_filter = (TextView) dialog.findViewById(R.id.sync_filter_edit_dir_filter_btn); + final TextView dlg_dir_filter = dialog.findViewById(R.id.sync_filter_edit_dir_filter_btn); NotifyEvent ntfy = new NotifyEvent(mActivity); //Listen setRemoteShare response ntfy.setListener(new NotifyEvent.NotifyEventListener() { @@ -2626,7 +2670,7 @@ public void negativeResponse(Context arg0, Object[] arg1) { } private void invokeEditFileFilterDlg(Dialog dialog, final SyncTaskItem n_sti, final String type, final TextView dlg_msg) { - final TextView dlg_file_filter = (TextView) dialog.findViewById(R.id.sync_filter_edit_file_filter_btn); + final TextView dlg_file_filter = dialog.findViewById(R.id.sync_filter_edit_file_filter_btn); NotifyEvent ntfy = new NotifyEvent(mActivity); //Listen setRemoteShare response ntfy.setListener(new NotifyEvent.NotifyEventListener() { @@ -2660,7 +2704,7 @@ private String buildSourceSyncFolderInfo(SyncTaskItem sti, Button info_btn, Imag if (SafManager3.isUuidRegistered(mActivity, sti.getSourceStorageUuid())) img_res=R.drawable.ic_32_external_media; else img_res=R.drawable.ic_32_external_media_bad; } - info_icon.setImageDrawable(mActivity.getResources().getDrawable(img_res, null)); + info_icon.setImageDrawable(ContextCompat.getDrawable(mActivity, img_res)); } else if (sti.getSourceFolderType().equals(SyncTaskItem.SYNC_FOLDER_TYPE_SMB)) { String host = sti.getSourceSmbHost(); String share = sti.getSourceSmbShareName(); @@ -2670,7 +2714,7 @@ private String buildSourceSyncFolderInfo(SyncTaskItem sti, Button info_btn, Imag if (dir.startsWith("/")) info = "smb://" + host + "/" + share + dir; else info = "smb://" + host + "/" + share + "/" + dir; } - info_icon.setImageDrawable(mActivity.getResources().getDrawable(R.drawable.ic_32_server, null)); + info_icon.setImageDrawable(ContextCompat.getDrawable(mActivity, R.drawable.ic_32_server)); } return info; } @@ -2690,7 +2734,7 @@ private String buildDestinationSyncFolderInfo(SyncTaskItem sti, Button info_btn, if (SafManager3.isUuidRegistered(mActivity, sti.getDestinationStorageUuid())) img_res=R.drawable.ic_32_external_media; else img_res=R.drawable.ic_32_external_media_bad; } - info_icon.setImageDrawable(mActivity.getResources().getDrawable(img_res, null)); + info_icon.setImageDrawable(ContextCompat.getDrawable(mActivity, img_res)); } else if (sti.getDestinationFolderType().equals(SyncTaskItem.SYNC_FOLDER_TYPE_ZIP)) { info = CommonUtilities.getStoragePathFromUuid(sti.getDestinationStorageUuid())+"/"+ sti.getDestinationZipOutputFileName(); int img_res=0; @@ -2702,7 +2746,7 @@ private String buildDestinationSyncFolderInfo(SyncTaskItem sti, Button info_btn, img_res=R.drawable.ic_32_archive_bad; } } - info_icon.setImageDrawable(mActivity.getResources().getDrawable(img_res, null)); + info_icon.setImageDrawable(ContextCompat.getDrawable(mActivity, img_res)); } else if (sti.getDestinationFolderType().equals(SyncTaskItem.SYNC_FOLDER_TYPE_SMB)) { String host = sti.getDestinationSmbHost(); String share = sti.getDestinationSmbShareName(); @@ -2712,7 +2756,7 @@ private String buildDestinationSyncFolderInfo(SyncTaskItem sti, Button info_btn, if (dir.startsWith("/")) info = "smb://" + host + "/" + share + dir; else info = "smb://" + host + "/" + share + "/" + dir; } - info_icon.setImageDrawable(mActivity.getResources().getDrawable(R.drawable.ic_32_server, null)); + info_icon.setImageDrawable(ContextCompat.getDrawable(mActivity, R.drawable.ic_32_server)); } return info; } @@ -2825,7 +2869,7 @@ private void setSpinnerSyncFolderStorageSelector(SyncTaskItem sti, Spinner spinn private String getSmbSelectedProtocol(Spinner spinner) { if (spinner.getSelectedItem()==null) { - return SyncTaskItem.SYNC_FOLDER_SMB_PROTOCOL_SMB23; + return SyncTaskItem.SYNC_FOLDER_SMB_PROTOCOL_DEFAULT; } return (String)spinner.getSelectedItem(); } @@ -2843,9 +2887,9 @@ private void setSpinnerSyncFolderSmbProto(SyncTaskItem sti, Spinner spinner, Str adapter.add(SyncTaskItem.SYNC_FOLDER_SMB_PROTOCOL_SMB1); adapter.add(SyncTaskItem.SYNC_FOLDER_SMB_PROTOCOL_SMB23); - if (cv.equals(SyncTaskItem.SYNC_FOLDER_SMB_PROTOCOL_SMB1)) spinner.setSelection(0); - else if (cv.equals(SyncTaskItem.SYNC_FOLDER_SMB_PROTOCOL_SMB23)) spinner.setSelection(1); - else spinner.setSelection(1); + if (cv.equals(SyncTaskItem.SYNC_FOLDER_SMB_PROTOCOL_SMB1)) spinner.setSelection(SyncTaskItem.SYNC_FOLDER_SMB_PROTOCOL_SMB1_INDEX); + else if (cv.equals(SyncTaskItem.SYNC_FOLDER_SMB_PROTOCOL_SMB23)) spinner.setSelection(SyncTaskItem.SYNC_FOLDER_SMB_PROTOCOL_SMB23_INDEX); + else spinner.setSelection(SyncTaskItem.SYNC_FOLDER_SMB_PROTOCOL_DEFAULT_INDEX); } private void setSpinnerSyncTaskErrorOption(SyncTaskItem sti, Spinner spinner, String cv) { @@ -2870,8 +2914,8 @@ private void setSpinnerSyncTaskErrorOption(SyncTaskItem sti, Spinner spinner, St } private void setSpinnerSyncFolderType(SyncTaskItem sti, Spinner spinner, String cv, boolean source) { - final Spinner spinnerSyncType = (Spinner) mDialog.findViewById(R.id.edit_sync_task_sync_type); - String sync_type=spinnerSyncType.getSelectedItem().toString(); + //final Spinner spinnerSyncType = (Spinner) mDialog.findViewById(R.id.edit_sync_task_sync_type); + //String sync_type=spinnerSyncType.getSelectedItem().toString(); CommonUtilities.setSpinnerBackground(mActivity, spinner, mGp.isScreenThemeIsLight()); final CustomSpinnerAdapter adapter = new CustomSpinnerAdapter(mActivity, android.R.layout.simple_spinner_item); // adapter.setDropDownTextWordwrapEnabled(true); @@ -2923,7 +2967,7 @@ else if (cv.equals(SyncTaskItem.SYNC_FOLDER_TYPE_ZIP)) { adapter.notifyDataSetChanged(); } - private void setSpinnerSyncTaskType(Spinner spinnerSyncOption, String prof_syncopt, String destination_folder_type) { + private void setSpinnerSyncTaskType(Spinner spinnerSyncOption, String prof_syncopt) { CommonUtilities.setSpinnerBackground(mActivity, spinnerSyncOption, mGp.isScreenThemeIsLight()); final CustomSpinnerAdapter adapterSyncOption = new CustomSpinnerAdapter(mActivity, android.R.layout.simple_spinner_item); // adapterSyncOption.setDropDownTextWordwrapEnabled(true); @@ -2949,6 +2993,7 @@ private void setSpinnerSyncTaskType(Spinner spinnerSyncOption, String prof_synco adapterSyncOption.notifyDataSetChanged(); } + // not used private void setSpinnerTwoWaySyncConflictRule(Spinner spinner, String cv) { CommonUtilities.setSpinnerBackground(mActivity, spinner, mGp.isScreenThemeIsLight()); final CustomSpinnerAdapter adapter = new CustomSpinnerAdapter(mActivity, android.R.layout.simple_spinner_item); @@ -3127,15 +3172,16 @@ private String buildFilterInfo(ArrayList filte String exc_char = "\u2296"; //(-) ASCII if (filter_list != null && filter_list.size() > 0) { - String t_info = "", cn = ""; + StringBuilder t_info = new StringBuilder(); + String cn = ""; for (int i = 0; i < filter_list.size(); i++) { if (!filter_list.get(i).isDeleted() && filter_list.get(i).isEnabled()) { - if (filter_list.get(i).isInclude()) t_info += cn+inc_char+ filter_list.get(i).getFilter()+";"; - else t_info +=cn+ exc_char+ filter_list.get(i).getFilter()+";"; + if (filter_list.get(i).isInclude()) t_info.append(cn).append(inc_char).append(filter_list.get(i).getFilter()).append(";"); + else t_info.append(cn).append(exc_char).append(filter_list.get(i).getFilter()).append(";"); cn=" "; } } - if (!t_info.equals("")) info = t_info; + if (!t_info.toString().equals("")) info = t_info.toString(); } return info; } @@ -3161,7 +3207,7 @@ private String checkTaskNameValidity(String type, String t_name, TextView tv, Bu public static final String TASK_EDIT_METHOD_EDIT="EDIT"; public static final String TASK_EDIT_METHOD_COPY="COPY"; private void editSyncTask(final String type, final SyncTaskItem pfli) { - final SyncTaskItem n_sti = pfli.clone(); + final SyncTaskItem n_sti = pfli.cloneSerial(); mUtil.addDebugMsg(1,"I","editSyncTask entered, type="+type+", task="+pfli.getSyncTaskName()); mGp.safMgr.refreshSafList(); @@ -3169,69 +3215,71 @@ private void editSyncTask(final String type, final SyncTaskItem pfli) { // カスタムダイアログの生成 mDialog.setContentView(R.layout.edit_sync_task_dlg); - LinearLayout ll_dlg_view = (LinearLayout) mDialog.findViewById(R.id.edit_sync_task_dlg_view); + LinearLayout ll_dlg_view = mDialog.findViewById(R.id.edit_sync_task_dlg_view); // ll_dlg_view.setBackgroundColor(mGp.themeColorList.title_background_color); - final LinearLayout title_view = (LinearLayout) mDialog.findViewById(R.id.edit_profile_sync_title_view); + final LinearLayout title_view = mDialog.findViewById(R.id.edit_profile_sync_title_view); title_view.setBackgroundColor(mGp.themeColorList.title_background_color); - final TextView dlg_title = (TextView) mDialog.findViewById(R.id.edit_profile_sync_title); + final TextView dlg_title = mDialog.findViewById(R.id.edit_profile_sync_title); dlg_title.setTextColor(mGp.themeColorList.title_text_color); // dlg_title.setBackgroundColor(mGp.themeColorList.title_background_color); - final TextView dlg_title_sub = (TextView) mDialog.findViewById(R.id.edit_profile_sync_title_sub); + final TextView dlg_title_sub = mDialog.findViewById(R.id.edit_profile_sync_title_sub); dlg_title_sub.setTextColor(mGp.themeColorList.title_text_color); // dlg_title_sub.setBackgroundColor(mGp.themeColorList.title_background_color); - final TextView dlg_msg = (TextView) mDialog.findViewById(R.id.edit_sync_task_msg); + final TextView dlg_msg = mDialog.findViewById(R.id.edit_sync_task_msg); dlg_msg.setTextColor(mGp.themeColorList.text_color_error); dlg_msg.setVisibility(TextView.GONE); - final Button destination_folder_info = (Button) mDialog.findViewById(R.id.edit_sync_task_destination_folder_info_btn); - final ImageView destination_folder_icon=(ImageView)mDialog.findViewById(R.id.edit_sync_task_destination_folder_info_icon); - final Button swap_source_destination = (Button) mDialog.findViewById(R.id.edit_sync_task_swap_source_and_destination_btn); - final Button source_folder_info = (Button) mDialog.findViewById(R.id.edit_sync_task_source_folder_info_btn); - final ImageView source_folder_icon=(ImageView)mDialog.findViewById(R.id.edit_sync_task_source_folder_info_icon); + final Button destination_folder_info = mDialog.findViewById(R.id.edit_sync_task_destination_folder_info_btn); + final ImageView destination_folder_icon= mDialog.findViewById(R.id.edit_sync_task_destination_folder_info_icon); + final Button swap_source_destination = mDialog.findViewById(R.id.edit_sync_task_swap_source_and_destination_btn); + final Button source_folder_info = mDialog.findViewById(R.id.edit_sync_task_source_folder_info_btn); + final ImageView source_folder_icon= mDialog.findViewById(R.id.edit_sync_task_source_folder_info_icon); - final LinearLayout ll_sync_task_name_view = (LinearLayout) mDialog.findViewById(R.id.edit_sync_task_task_name_view); - final EditText et_sync_main_task_name = (EditText) mDialog.findViewById(R.id.edit_sync_task_task_name); + final LinearLayout ll_sync_task_name_view = mDialog.findViewById(R.id.edit_sync_task_task_name_view); + final EditText et_sync_main_task_name = mDialog.findViewById(R.id.edit_sync_task_task_name); if (type.equals(TASK_EDIT_METHOD_EDIT)) { et_sync_main_task_name.setText(n_sti.getSyncTaskName()); ll_sync_task_name_view.setVisibility(EditText.GONE); dlg_title.setText(mActivity.getString(R.string.msgs_edit_sync_profile)); - dlg_title_sub.setText(" (" + n_sti.getSyncTaskName() + ")"); + String str = String.format(" (%s)", n_sti.getSyncTaskName()); + dlg_title_sub.setText(str); } else if (type.equals(TASK_EDIT_METHOD_COPY)) { et_sync_main_task_name.setText(n_sti.getSyncTaskName()); dlg_title.setText(mActivity.getString(R.string.msgs_copy_sync_profile)); - dlg_title_sub.setText(" (" + n_sti.getSyncTaskName() + ")"); + String str = String.format(" (%s)", n_sti.getSyncTaskName()); + dlg_title_sub.setText(str); } else if (type.equals(TASK_EDIT_METHOD_ADD)) { dlg_title.setText(mActivity.getString(R.string.msgs_add_sync_profile)); dlg_title_sub.setVisibility(TextView.GONE); n_sti.setSyncOptionWifiStatusOption(SyncTaskItem.WIFI_STATUS_WIFI_OFF); } - final LinearLayout ll_advanced_network_option_view = (LinearLayout) mDialog.findViewById(R.id.edit_sync_task_option_ll_advanced_network_option_view); + final LinearLayout ll_advanced_network_option_view = mDialog.findViewById(R.id.edit_sync_task_option_ll_advanced_network_option_view); if (n_sti.getSourceFolderType().equals(SyncTaskItem.SYNC_FOLDER_TYPE_SMB) || n_sti.getDestinationFolderType().equals(SyncTaskItem.SYNC_FOLDER_TYPE_SMB)) { ll_advanced_network_option_view.setVisibility(LinearLayout.VISIBLE); } else { ll_advanced_network_option_view.setVisibility(LinearLayout.GONE); } - final CheckedTextView ctv_auto = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_ctv_auto); + final CheckedTextView ctv_auto = mDialog.findViewById(R.id.edit_sync_task_ctv_auto); CommonUtilities.setCheckedTextViewListener(ctv_auto); ctv_auto.setChecked(n_sti.isSyncTaskAuto()); setCtvListenerForEditSyncTask(ctv_auto, type, n_sti, dlg_msg); - final CheckedTextView ctv_confirm_exif_date = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_confirm_exif_date); + final CheckedTextView ctv_confirm_exif_date = mDialog.findViewById(R.id.edit_sync_task_option_confirm_exif_date); CommonUtilities.setCheckedTextViewListener(ctv_confirm_exif_date); ctv_confirm_exif_date.setChecked(n_sti.isSyncOptionConfirmNotExistsExifDate()); setCtvListenerForEditSyncTask(ctv_confirm_exif_date, type, n_sti, dlg_msg); - final CheckedTextView ctv_ignore_file_size_gt_4gb = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ignore_source_file_that_file_size_gt_4gb); + final CheckedTextView ctv_ignore_file_size_gt_4gb = mDialog.findViewById(R.id.edit_sync_task_option_ignore_source_file_that_file_size_gt_4gb); CommonUtilities.setCheckedTextViewListener(ctv_ignore_file_size_gt_4gb); ctv_ignore_file_size_gt_4gb.setChecked(n_sti.isSyncOptionIgnoreDestinationFileWhenSourceFileSizeGreaterThan4Gb()); setCtvListenerForEditSyncTask(ctv_ignore_file_size_gt_4gb, type, n_sti, dlg_msg); - final EditText et_max_dest_file_name_length = (EditText) mDialog.findViewById(R.id.edit_sync_task_option_max_destination_file_name_length); + final EditText et_max_dest_file_name_length = mDialog.findViewById(R.id.edit_sync_task_option_max_destination_file_name_length); et_max_dest_file_name_length.setText(String.valueOf(n_sti.getSyncOptionMaxDestinationFileNameLength())); et_max_dest_file_name_length.addTextChangedListener(new TextWatcher() { @Override @@ -3246,14 +3294,14 @@ public void afterTextChanged(Editable s) { } }); - final CheckedTextView ctvIgnoreFilterRemoveDirFileDesNotExistsInSource = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_remove_dir_file_excluded_by_filter); - final LinearLayout ctvIgnoreFilterRemoveDirFileDesNotExistsInSourceView = (LinearLayout) mDialog.findViewById(R.id.edit_sync_task_option_ll_sync_remove_dir_file_excluded_by_filter); - final CheckedTextView ctvDeleteFirst = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_delete_first_when_mirror); - final LinearLayout ctvDeleteFirstView = (LinearLayout) mDialog.findViewById(R.id.edit_sync_task_option_ll_sync_delete_first_when_mirror); + final CheckedTextView ctvIgnoreFilterRemoveDirFileDesNotExistsInSource = mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_remove_dir_file_excluded_by_filter); + final LinearLayout ctvIgnoreFilterRemoveDirFileDesNotExistsInSourceView = mDialog.findViewById(R.id.edit_sync_task_option_ll_sync_remove_dir_file_excluded_by_filter); + final CheckedTextView ctvDeleteFirst = mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_delete_first_when_mirror); + final LinearLayout ctvDeleteFirstView = mDialog.findViewById(R.id.edit_sync_task_option_ll_sync_delete_first_when_mirror); - final Spinner spinnerSyncType = (Spinner) mDialog.findViewById(R.id.edit_sync_task_sync_type); + final Spinner spinnerSyncType = mDialog.findViewById(R.id.edit_sync_task_sync_type); spinnerSyncType.setOnItemSelectedListener(null); - setSpinnerSyncTaskType(spinnerSyncType, n_sti.getSyncTaskType(), n_sti.getDestinationFolderType()); + setSpinnerSyncTaskType(spinnerSyncType, n_sti.getSyncTaskType()); spinnerSyncType.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { @@ -3274,21 +3322,21 @@ public void onItemSelected(AdapterView parent, View view, int position, long public void onNothingSelected(AdapterView parent) { } }); - final LinearLayout ll_wifi_condition_view = (LinearLayout) mDialog.findViewById(R.id.edit_sync_task_option_wifi_condition_view); - final LinearLayout ll_wifi_wl_view = (LinearLayout) mDialog.findViewById(R.id.edit_sync_task_option_wl_view); - final LinearLayout ll_wifi_wl_address_view = (LinearLayout) mDialog.findViewById(R.id.edit_sync_task_option_address_list_view); - final Button edit_wifi_addr_list = (Button) mDialog.findViewById(R.id.edit_sync_task_option_btn_edit_address_white_list); + final LinearLayout ll_wifi_condition_view = mDialog.findViewById(R.id.edit_sync_task_option_wifi_condition_view); + final LinearLayout ll_wifi_wl_view = mDialog.findViewById(R.id.edit_sync_task_option_wl_view); + final LinearLayout ll_wifi_wl_address_view = mDialog.findViewById(R.id.edit_sync_task_option_address_list_view); + final Button edit_wifi_addr_list = mDialog.findViewById(R.id.edit_sync_task_option_btn_edit_address_white_list); setWifiApWhiteListInfo(n_sti.getSyncOptionWifiIPAddressGrantList(), edit_wifi_addr_list); - final CheckedTextView ctv_sync_allow_global_ip_addr = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_sync_allow_all_ip_address); + final CheckedTextView ctv_sync_allow_global_ip_addr = mDialog.findViewById(R.id.edit_sync_task_option_sync_allow_all_ip_address); ctv_sync_allow_global_ip_addr.setChecked(n_sti.isSyncOptionSyncAllowAllIpAddress()); setCtvListenerForEditSyncTask(ctv_sync_allow_global_ip_addr, type, n_sti, dlg_msg); - final CheckedTextView ctv_task_sync_when_cahrging = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_start_when_charging); + final CheckedTextView ctv_task_sync_when_cahrging = mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_start_when_charging); // CommonUtilities.setCheckedTextViewListener(ctv_task_sync_when_cahrging); ctv_task_sync_when_cahrging.setChecked(n_sti.isSyncOptionSyncWhenCharging()); setCtvListenerForEditSyncTask(ctv_task_sync_when_cahrging, type, n_sti, dlg_msg); - final CheckedTextView ctv_never_overwrite_destination_file_newer_than_the_source_file = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_never_overwrite_destination_file_if_it_is_newer_than_the_source_file); + final CheckedTextView ctv_never_overwrite_destination_file_newer_than_the_source_file = mDialog.findViewById(R.id.edit_sync_task_option_never_overwrite_destination_file_if_it_is_newer_than_the_source_file); ctv_never_overwrite_destination_file_newer_than_the_source_file.setChecked(n_sti.isSyncOptionDoNotOverwriteDestinationFileIfItIsNewerThanTheSourceFile()); ctv_never_overwrite_destination_file_newer_than_the_source_file.setOnClickListener(new OnClickListener() { @Override @@ -3319,18 +3367,18 @@ public void negativeResponse(Context context, Object[] objects) {} }); ctv_never_overwrite_destination_file_newer_than_the_source_file.setChecked(n_sti.isSyncOptionDoNotOverwriteDestinationFileIfItIsNewerThanTheSourceFile()); - final CheckedTextView ctv_ignore_dst_difference = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_diff_ignore_dst_difference); + final CheckedTextView ctv_ignore_dst_difference = mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_diff_ignore_dst_difference); ctv_ignore_dst_difference.setChecked(n_sti.isSyncOptionIgnoreDstDifference()); - final CheckedTextView ctv_edit_sync_task_option_ignore_unusable_character_used_directory_file_name = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ignore_unusable_character_used_directory_file_name); + final CheckedTextView ctv_edit_sync_task_option_ignore_unusable_character_used_directory_file_name = mDialog.findViewById(R.id.edit_sync_task_option_ignore_unusable_character_used_directory_file_name); ctv_edit_sync_task_option_ignore_unusable_character_used_directory_file_name.setChecked(n_sti.isSyncOptionIgnoreDirectoriesOrFilesThatContainUnusableCharacters()); setCtvListenerForEditSyncTask(ctv_edit_sync_task_option_ignore_unusable_character_used_directory_file_name, type, n_sti, dlg_msg); - final CheckedTextView ctv_sync_remove_source_if_empty = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_remove_directory_if_empty_when_move); + final CheckedTextView ctv_sync_remove_source_if_empty = mDialog.findViewById(R.id.edit_sync_task_option_ctv_remove_directory_if_empty_when_move); ctv_sync_remove_source_if_empty.setChecked(n_sti.isSyncOptionMoveOnlyRemoveSourceDirectoryIfEmpty()); setCtvListenerForEditSyncTask(ctv_sync_remove_source_if_empty, type, n_sti, dlg_msg); - final Spinner sp_sync_task_option_error_option=(Spinner)mDialog.findViewById(R.id.edit_sync_task_option_error_option_value); + final Spinner sp_sync_task_option_error_option= mDialog.findViewById(R.id.edit_sync_task_option_error_option_value); sp_sync_task_option_error_option.setOnItemSelectedListener(null); setSpinnerSyncTaskErrorOption(n_sti, sp_sync_task_option_error_option, n_sti.getSyncTaskErrorOption()); Handler hndl=new Handler(); @@ -3365,7 +3413,7 @@ public void onNothingSelected(AdapterView parent) {} } }, 100); - final Spinner spinnerSyncWifiStatus = (Spinner) mDialog.findViewById(R.id.edit_sync_task_option_spinner_wifi_status); + final Spinner spinnerSyncWifiStatus = mDialog.findViewById(R.id.edit_sync_task_option_spinner_wifi_status); spinnerSyncWifiStatus.setOnItemSelectedListener(null); setSpinnerSyncTaskWifiOption(spinnerSyncWifiStatus, n_sti.getSyncOptionWifiStatusOption()); if (n_sti.getSourceFolderType().equals(SyncTaskItem.SYNC_FOLDER_TYPE_SMB) || n_sti.getDestinationFolderType().equals(SyncTaskItem.SYNC_FOLDER_TYPE_SMB)) { @@ -3392,31 +3440,31 @@ public void onNothingSelected(AdapterView parent) { destination_folder_info.setText(buildDestinationSyncFolderInfo(n_sti, destination_folder_info, destination_folder_icon)); destination_folder_info.requestLayout(); - final Spinner sp_file_size_type=(Spinner)mDialog.findViewById(R.id.sync_filter_file_size_type_spinner); - final EditText et_file_size_value=(EditText)mDialog.findViewById(R.id.sync_filter_file_size_value); - final TextInputLayout et_file_size_value_view=(TextInputLayout)mDialog.findViewById(R.id.sync_filter_file_size_value_view); + final Spinner sp_file_size_type= mDialog.findViewById(R.id.sync_filter_file_size_type_spinner); + final EditText et_file_size_value= mDialog.findViewById(R.id.sync_filter_file_size_value); + final TextInputLayout et_file_size_value_view= mDialog.findViewById(R.id.sync_filter_file_size_value_view); et_file_size_value.setText(n_sti.getSyncFilterFileSizeValue()); - final Spinner sp_file_size_unit=(Spinner)mDialog.findViewById(R.id.sync_filter_file_size_unit_spinner); + final Spinner sp_file_size_unit= mDialog.findViewById(R.id.sync_filter_file_size_unit_spinner); setSpinnerSyncTaskFileSizeTypeFilter(sp_file_size_type, n_sti.getSyncFilterFileSizeType()); setSpinnerSyncTaskFileSizeUnitFilter(sp_file_size_unit, n_sti.getSyncFilterFileSizeUnit()); - final Spinner sp_file_date_type=(Spinner)mDialog.findViewById(R.id.sync_filter_file_date_type_spinner); - final EditText et_file_date_value=(EditText)mDialog.findViewById(R.id.sync_filter_file_date_value); - final TextInputLayout et_file_date_value_view=(TextInputLayout)mDialog.findViewById(R.id.sync_filter_file_date_value_view); + final Spinner sp_file_date_type= mDialog.findViewById(R.id.sync_filter_file_date_type_spinner); + final EditText et_file_date_value= mDialog.findViewById(R.id.sync_filter_file_date_value); + final TextInputLayout et_file_date_value_view= mDialog.findViewById(R.id.sync_filter_file_date_value_view); et_file_date_value.setText(n_sti.getSyncFilterFileDateValue()); setSpinnerSyncTaskFileDateTypeFilter(sp_file_date_type, n_sti.getSyncFilterFileDateType()); - final CheckedTextView ctvIgnore_0_byte_file=(CheckedTextView)mDialog.findViewById(R.id.edit_sync_task_option_ignore_file_size_0_bytes_file); + final CheckedTextView ctvIgnore_0_byte_file= mDialog.findViewById(R.id.edit_sync_task_option_ignore_file_size_0_bytes_file); - final Button dir_filter_btn = (Button) mDialog.findViewById(R.id.sync_filter_edit_dir_filter_btn); - final Button file_filter_btn = (Button) mDialog.findViewById(R.id.sync_filter_edit_file_filter_btn); + final Button dir_filter_btn = mDialog.findViewById(R.id.sync_filter_edit_dir_filter_btn); + final Button file_filter_btn = mDialog.findViewById(R.id.sync_filter_edit_file_filter_btn); // final TextView dlg_file_filter=(TextView) mDialog.findViewById(R.id.sync_filter_summary_file_filter); file_filter_btn.setText(buildFileFilterInfo(n_sti.getFileNameFilter())); // final TextView dlg_dir_filter=(TextView) mDialog.findViewById(R.id.sync_filter_summary_dir_filter); dir_filter_btn.setText(buildDirectoryFilterInfo(n_sti.getDirectoryFilter())); - final LinearLayout ll_file_filter_detail = (LinearLayout) mDialog.findViewById(R.id.sync_filter_file_type_detail_view); - final LinearLayout ll_archive_filter_detail = (LinearLayout) mDialog.findViewById(R.id.edit_sync_filter_archive_file_type_view); - final LinearLayout ll_dir_filter_detail = (LinearLayout) mDialog.findViewById(R.id.sync_filter_sub_directory_detail_view); + final LinearLayout ll_file_filter_detail = mDialog.findViewById(R.id.sync_filter_file_type_detail_view); + final LinearLayout ll_archive_filter_detail = mDialog.findViewById(R.id.edit_sync_filter_archive_file_type_view); + final LinearLayout ll_dir_filter_detail = mDialog.findViewById(R.id.sync_filter_sub_directory_detail_view); sp_file_size_type.setOnItemSelectedListener(new OnItemSelectedListener() { @Override @@ -3496,15 +3544,16 @@ public void afterTextChanged(Editable s) { } }); - final TextView tv_archive_type=(TextView)mDialog.findViewById(R.id.edit_sync_filter_archive_file_type_list); - String arch_type="", arch_sep=""; + final TextView tv_archive_type= mDialog.findViewById(R.id.edit_sync_filter_archive_file_type_list); + StringBuilder arch_type= new StringBuilder(); + String arch_sep=""; for(String arch_item:ARCHIVE_FILE_TYPE) { - arch_type+=arch_sep+arch_item; + arch_type.append(arch_sep).append(arch_item); arch_sep=", "; } - tv_archive_type.setText(arch_type); + tv_archive_type.setText(arch_type.toString()); - final Spinner sp_sync_retain_period = (Spinner) mDialog.findViewById(R.id.edit_sync_filter_archive_retention_period); + final Spinner sp_sync_retain_period = mDialog.findViewById(R.id.edit_sync_filter_archive_retention_period); sp_sync_retain_period.setOnItemSelectedListener(null); setSpinnerSyncTaskArchiveRetainPeriod(sp_sync_retain_period, n_sti.getSyncFilterArchiveRetentionPeriod()); @@ -3517,11 +3566,11 @@ public void onItemSelected(AdapterView adapterView, View view, int i, long l) public void onNothingSelected(AdapterView adapterView) {} }); - final CheckedTextView ctvProcessRootDirFile = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_source_root_dir_file); + final CheckedTextView ctvProcessRootDirFile = mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_source_root_dir_file); CommonUtilities.setCheckedTextViewListener(ctvProcessRootDirFile); ctvProcessRootDirFile.setChecked(n_sti.isSyncProcessRootDirFile()); - final CheckedTextView ctvSyncSubDir = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_sub_dir); + final CheckedTextView ctvSyncSubDir = mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_sub_dir); CommonUtilities.setCheckedTextViewListener(ctvSyncSubDir); ctvSyncSubDir.setChecked(n_sti.isSyncOptionSyncSubDirectory()); @@ -3551,26 +3600,26 @@ public void onClick(View v) { setCtvListenerForEditSyncTask(ctvSyncSubDir, type, n_sti, dlg_msg); - final CheckedTextView ctvSyncEmptyDir = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_empty_directory); + final CheckedTextView ctvSyncEmptyDir = mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_empty_directory); CommonUtilities.setCheckedTextViewListener(ctvSyncEmptyDir); ctvSyncEmptyDir.setChecked(n_sti.isSyncOptionSyncEmptyDirectory()); setCtvListenerForEditSyncTask(ctvSyncEmptyDir, type, n_sti, dlg_msg); - final CheckedTextView ctvSyncHiddenDir = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_hidden_directory); + final CheckedTextView ctvSyncHiddenDir = mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_hidden_directory); CommonUtilities.setCheckedTextViewListener(ctvSyncHiddenDir); ctvSyncHiddenDir.setChecked(n_sti.isSyncOptionSyncHiddenDirectory()); setCtvListenerForEditSyncTask(ctvSyncHiddenDir, type, n_sti, dlg_msg); - final CheckedTextView ctvSyncHiddenFile = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_hidden_file); + final CheckedTextView ctvSyncHiddenFile = mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_hidden_file); CommonUtilities.setCheckedTextViewListener(ctvSyncHiddenFile); ctvSyncHiddenFile.setChecked(n_sti.isSyncOptionSyncHiddenFile()); setCtvListenerForEditSyncTask(ctvSyncHiddenFile, type, n_sti, dlg_msg); - final CheckedTextView ctvProcessOverride = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_process_override_delete_file); + final CheckedTextView ctvProcessOverride = mDialog.findViewById(R.id.edit_sync_task_option_ctv_process_override_delete_file); ctvProcessOverride.setChecked(n_sti.isSyncOverrideCopyMoveFile()); setCtvListenerForEditSyncTask(ctvProcessOverride, type, n_sti, dlg_msg); - final CheckedTextView ctvConfirmOverride = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_confirm_override_delete_file); + final CheckedTextView ctvConfirmOverride = mDialog.findViewById(R.id.edit_sync_task_option_ctv_confirm_override_delete_file); CommonUtilities.setCheckedTextViewListener(ctvConfirmOverride); ctvConfirmOverride.setChecked(n_sti.isSyncConfirmOverrideOrDelete()); setCtvListenerForEditSyncTask(ctvConfirmOverride, type, n_sti, dlg_msg); @@ -3611,8 +3660,8 @@ public void negativeResponse(Context context, Object[] objects) { } }); - final LinearLayout ll_special_option_view = (LinearLayout) mDialog.findViewById(R.id.edit_sync_task_option_special_option_view); - final CheckedTextView ctvShowSpecialOption = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_show_special_option); + final LinearLayout ll_special_option_view = mDialog.findViewById(R.id.edit_sync_task_option_special_option_view); + final CheckedTextView ctvShowSpecialOption = mDialog.findViewById(R.id.edit_sync_task_option_ctv_show_special_option); ll_special_option_view.setVisibility(LinearLayout.GONE); ctvShowSpecialOption.setChecked(false); ctvShowSpecialOption.setOnClickListener(new OnClickListener() { @@ -3625,7 +3674,7 @@ public void onClick(View v) { } }); - final CheckedTextView ctvDoNotResetFileLastMod = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_do_mot_reset_file_last_mod_time); + final CheckedTextView ctvDoNotResetFileLastMod = mDialog.findViewById(R.id.edit_sync_task_option_ctv_do_mot_reset_file_last_mod_time); CommonUtilities.setCheckedTextViewListener(ctvDoNotResetFileLastMod); ctvDoNotResetFileLastMod.setChecked(n_sti.isSyncDoNotResetFileLastModified()); ctvDoNotResetFileLastMod.setOnClickListener(new OnClickListener() { @@ -3657,18 +3706,17 @@ public void negativeResponse(Context context, Object[] objects) {} } }); - final CheckedTextView ctvRetry = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_retry_if_error_occured); + final CheckedTextView ctvRetry = mDialog.findViewById(R.id.edit_sync_task_option_ctv_retry_if_error_occured); CommonUtilities.setCheckedTextViewListener(ctvRetry); - if (n_sti.getSyncOptionRetryCount()==0) ctvRetry.setChecked(false); - else ctvRetry.setChecked(true); + ctvRetry.setChecked(n_sti.getSyncOptionRetryCount() != 0); setCtvListenerForEditSyncTask(ctvRetry, type, n_sti, dlg_msg); - final CheckedTextView ctvSyncUseRemoteSmallIoArea = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_use_remote_small_io_area); + final CheckedTextView ctvSyncUseRemoteSmallIoArea = mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_use_remote_small_io_area); CommonUtilities.setCheckedTextViewListener(ctvSyncUseRemoteSmallIoArea); ctvSyncUseRemoteSmallIoArea.setChecked(n_sti.isSyncOptionUseSmallIoBuffer()); setCtvListenerForEditSyncTask(ctvSyncUseRemoteSmallIoArea, type, n_sti, dlg_msg); - final CheckedTextView ctvTestMode = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_test_mode); + final CheckedTextView ctvTestMode = mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_test_mode); ctvTestMode.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { @@ -3681,12 +3729,11 @@ public void onClick(View v) { ctvTestMode.setChecked(n_sti.isSyncTestMode()); CommonUtilities.setViewEnabled(mActivity, ctv_auto, !ctvTestMode.isChecked()); - final LinearLayout ll_use_file_last_mod = (LinearLayout) mDialog.findViewById(R.id.edit_sync_task_option_sync_diff_use_last_mod_time_view); - final LinearLayout ll_last_mod_allowed_time = (LinearLayout) mDialog.findViewById(R.id.edit_sync_task_option_diff_file_determin_time_value_view); - final CheckedTextView ctvDeterminChangedFileSizeGtDestination = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_diff_file_size_greater_than_destination); + final LinearLayout ll_use_file_last_mod = mDialog.findViewById(R.id.edit_sync_task_option_sync_diff_use_last_mod_time_view); + final CheckedTextView ctvDeterminChangedFileSizeGtDestination = mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_diff_file_size_greater_than_destination); ctvDeterminChangedFileSizeGtDestination.setChecked(n_sti.isSyncDifferentFileSizeGreaterThanDestinationFile()); - final CheckedTextView ctvDiffUseFileSize = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_diff_use_file_size); - final CheckedTextView ctDeterminChangedFileByTime = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_diff_use_last_mod_time); + final CheckedTextView ctvDiffUseFileSize = mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_diff_use_file_size); + final CheckedTextView ctDeterminChangedFileByTime = mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_diff_use_last_mod_time); CommonUtilities.setCheckedTextViewListener(ctvDiffUseFileSize); ctvDiffUseFileSize.setChecked(n_sti.isSyncOptionDifferentFileBySize()); @@ -3729,16 +3776,16 @@ public void negativeResponse(Context context, Object[] objects) {} CommonUtilities.setViewEnabled(mActivity, ctvDeterminChangedFileSizeGtDestination, ctvDiffUseFileSize.isChecked()); - final LinearLayout ll_DeterminChangedFileByTimeDependantView=(LinearLayout)mDialog.findViewById(R.id.edit_sync_task_option_sync_diff_use_last_mod_time_dependant_view); - final LinearLayout ll_syncDiffTimeView=(LinearLayout)mDialog.findViewById(R.id.edit_sync_task_option_diff_file_determin_time_value_view); - final Spinner spinnerSyncDiffTimeValue = (Spinner) mDialog.findViewById(R.id.edit_sync_task_option_spinner_diff_file_determin_time_value); + final LinearLayout ll_DeterminChangedFileByTimeDependantView= mDialog.findViewById(R.id.edit_sync_task_option_sync_diff_use_last_mod_time_dependant_view); + final LinearLayout ll_syncDiffTimeView= mDialog.findViewById(R.id.edit_sync_task_option_diff_file_determin_time_value_view); + final Spinner spinnerSyncDiffTimeValue = mDialog.findViewById(R.id.edit_sync_task_option_spinner_diff_file_determin_time_value); spinnerSyncDiffTimeValue.setOnItemSelectedListener(null); setSpinnerSyncTaskDiffTimeValue(spinnerSyncDiffTimeValue, n_sti.getSyncOptionDifferentFileAllowableTime()); - final Spinner spinnerSyncDstOffsetValue = (Spinner) mDialog.findViewById(R.id.edit_sync_task_option_spinner_offset_daylight_saving_time_value); + final Spinner spinnerSyncDstOffsetValue = mDialog.findViewById(R.id.edit_sync_task_option_spinner_offset_daylight_saving_time_value); spinnerSyncDstOffsetValue.setOnItemSelectedListener(null); setSpinnerSyncDstOffsetValue(spinnerSyncDstOffsetValue, n_sti.getSyncOptionOffsetOfDst()); - final LinearLayout ll_offset_dst_view=(LinearLayout)mDialog.findViewById(R.id.edit_sync_task_option_spinner_offset_daylight_saving_time_value_view); + final LinearLayout ll_offset_dst_view= mDialog.findViewById(R.id.edit_sync_task_option_spinner_offset_daylight_saving_time_value_view); if (n_sti.isSyncOptionIgnoreDstDifference()) { ll_offset_dst_view.setVisibility(LinearLayout.VISIBLE); } else { @@ -3832,7 +3879,7 @@ public void onNothingSelected(AdapterView parent) {} CommonDialog.setDlgBoxSizeLimit(mDialog, true); - final Button btn_ok = (Button) mDialog.findViewById(R.id.edit_profile_sync_dlg_btn_ok); + final Button btn_ok = mDialog.findViewById(R.id.edit_profile_sync_dlg_btn_ok); et_sync_main_task_name.addTextChangedListener(new TextWatcher() { @Override @@ -3849,8 +3896,7 @@ public void afterTextChanged(Editable s) { checkSyncTaskOkButtonEnabled(mDialog, type, n_sti, dlg_msg); } }); - if (n_sti.getDestinationFolderType().equals(SyncTaskItem.SYNC_FOLDER_TYPE_ZIP)) CommonUtilities.setViewEnabled(mActivity, swap_source_destination,false); - else CommonUtilities.setViewEnabled(mActivity, swap_source_destination, true); + CommonUtilities.setViewEnabled(mActivity, swap_source_destination, !n_sti.getDestinationFolderType().equals(SyncTaskItem.SYNC_FOLDER_TYPE_ZIP)); source_folder_info.setOnClickListener(new OnClickListener() { @Override @@ -3879,7 +3925,7 @@ public void positiveResponse(Context c, Object[] o) { destination_folder_info.setText(buildDestinationSyncFolderInfo(n_sti, destination_folder_info, destination_folder_icon)); destination_folder_info.requestLayout(); - setSpinnerSyncTaskType(spinnerSyncType, n_sti.getSyncTaskType(), n_sti.getDestinationFolderType()); + setSpinnerSyncTaskType(spinnerSyncType, n_sti.getSyncTaskType()); checkSyncTaskOkButtonEnabled(mDialog, type, n_sti, dlg_msg); if (!prev_source_folder_type.equals(n_sti.getSourceFolderType())) { ll_wifi_condition_view.setVisibility(LinearLayout.GONE); @@ -3952,11 +3998,10 @@ public void negativeResponse(Context c, Object[] o) { sfev.folder_smb_share = n_sti.getSourceSmbShareName(); sfev.folder_smb_protocol=n_sti.getSourceSmbProtocol(); sfev.folder_type = n_sti.getSourceFolderType(); - if (!n_sti.getSourceSmbAccountName().equals("") || !n_sti.getSourceSmbAccountPassword().equals("")) { - sfev.folder_smb_use_pswd =true; - } else { - sfev.folder_smb_use_pswd =false; - } + sfev.folder_smb_use_pswd = !sfev.folder_smb_account.equals("") || !sfev.folder_smb_password.equals(""); + + sfev.folder_smb_use_port = !sfev.folder_smb_port.equals(""); + sfev.folder_error_code=n_sti.getSourceFolderStatusError(); editSyncFolder(false, n_sti, sfev, ntfy); } @@ -3969,7 +4014,7 @@ public void onClick(View arg0) { ntfy_swap.setListener(new NotifyEvent.NotifyEventListener() { @Override public void positiveResponse(Context context, Object[] objects) { - SyncTaskItem t_sti = n_sti.clone(); + SyncTaskItem t_sti = n_sti.cloneSerial(); String new_dir=t_sti.getDestinationDirectoryName(); if (SyncThread.isTakenDateConvertRequired(new_dir)) { @@ -4006,7 +4051,7 @@ public void positiveResponse(Context context, Object[] objects) { destination_folder_info.setText(buildDestinationSyncFolderInfo(n_sti, destination_folder_info, destination_folder_icon)); destination_folder_info.requestLayout(); - setSpinnerSyncTaskType(spinnerSyncType, n_sti.getSyncTaskType(), n_sti.getDestinationFolderType()); + setSpinnerSyncTaskType(spinnerSyncType, n_sti.getSyncTaskType()); checkSyncTaskOkButtonEnabled(mDialog, type, n_sti, dlg_msg); } @@ -4060,10 +4105,9 @@ public void positiveResponse(Context c, Object[] o) { n_sti.setDestinationArchiveSuffixOption(nsfev.archive_file_append_suffix_digit); n_sti.setDestinationArchiveIgnoreSourceDirectory(nsfev.archive_ignore_source_directory_hiearachy); - if (n_sti.getDestinationFolderType().equals(SyncTaskItem.SYNC_FOLDER_TYPE_ZIP)) CommonUtilities.setViewEnabled(mActivity, swap_source_destination, false); - else CommonUtilities.setViewEnabled(mActivity, swap_source_destination, true); + CommonUtilities.setViewEnabled(mActivity, swap_source_destination, !n_sti.getDestinationFolderType().equals(SyncTaskItem.SYNC_FOLDER_TYPE_ZIP)); - setSpinnerSyncTaskType(spinnerSyncType, n_sti.getSyncTaskType(), n_sti.getDestinationFolderType()); + setSpinnerSyncTaskType(spinnerSyncType, n_sti.getSyncTaskType()); checkSyncTaskOkButtonEnabled(mDialog, type, n_sti, dlg_msg); if (!prev_destination_folder_type.equals(n_sti.getDestinationFolderType())) { @@ -4126,18 +4170,16 @@ public void negativeResponse(Context c, Object[] o) { sfev.folder_smb_password = ""; sfev.folder_smb_account = ""; } else { - sfev.folder_smb_password = n_sti.getSourceSmbAccountPassword(); - sfev.folder_smb_account = n_sti.getSourceSmbAccountName(); + sfev.folder_smb_password = n_sti.getDestinationSmbPassword(); + sfev.folder_smb_account = n_sti.getDestinationSmbAccountName(); } sfev.folder_smb_share = n_sti.getDestinationSmbShareName(); sfev.folder_type = n_sti.getDestinationFolderType(); sfev.folder_smb_protocol = n_sti.getDestinationSmbProtocol(); - if (!n_sti.getSourceSmbAccountName().equals("") || !n_sti.getSourceSmbAccountPassword().equals("")) { - sfev.folder_smb_use_pswd =true; - } else { - sfev.folder_smb_use_pswd =false; - } + sfev.folder_smb_use_pswd = !sfev.folder_smb_account.equals("") || !sfev.folder_smb_password.equals(""); + + sfev.folder_smb_use_port = !sfev.folder_smb_port.equals(""); sfev.zip_comp_level = n_sti.getDestinationZipCompressionLevel(); sfev.zip_enc_method = n_sti.getDestinationZipEncryptMethod(); @@ -4195,7 +4237,7 @@ public void onClick(View v) { } }); - final Button btn_cancel = (Button) mDialog.findViewById(R.id.edit_profile_sync_dlg_btn_cancel); + final Button btn_cancel = mDialog.findViewById(R.id.edit_profile_sync_dlg_btn_cancel); btn_cancel.setOnClickListener(new OnClickListener() { public void onClick(View v) { mGp.syncTaskListAdapter.notifyDataSetChanged(); @@ -4274,7 +4316,7 @@ public void positiveResponse(Context c, Object[] o) { mTaskUtil.saveConfigListWithAutosave(mActivity, mGp, mUtil); mFragment.dismissAllowingStateLoss(); mUtil.addDebugMsg(1,"I","editSyncTask edit saved, type="+type+", task="+new_stli.getSyncTaskName()); - ((ActivityMain)mActivity).refreshOptionMenu(); + mActivity.refreshOptionMenu(); } @Override public void negativeResponse(Context c, Object[] o) {} @@ -4292,6 +4334,7 @@ public void negativeResponse(Context c, Object[] o) {} checkSyncTaskOkButtonEnabled(mDialog, type, n_sti, dlg_msg); } + // unused private String removeKeyword(String input_string) { String new_val=input_string; if (input_string.contains("%")) { @@ -4323,21 +4366,21 @@ public void onClick(View v) { } private void checkArchiveOkButtonEnabled(SyncFolderEditValue current_sfev, SyncTaskItem n_sti, Dialog dialog) { - final Button btn_sync_folder_ok = (Button) dialog.findViewById(R.id.edit_profile_remote_btn_ok); + final Button btn_sync_folder_ok = dialog.findViewById(R.id.edit_profile_remote_btn_ok); // final Spinner sp_sync_retain_period = (Spinner) dialog.findViewById(R.id.edit_sync_folder_dlg_archive_retention_period); - final EditText et_file_template = (EditText) dialog.findViewById(R.id.edit_sync_folder_dlg_archive_file_name_template); + final EditText et_file_template = dialog.findViewById(R.id.edit_sync_folder_dlg_archive_file_name_template); boolean changed=false; - SyncFolderEditValue nsfev=buildSyncFolderEditValue(dialog, current_sfev); - changed=!current_sfev.isSame(nsfev); + SyncFolderEditValue nsfev=buildSyncFolderEditValue(dialog, current_sfev, false); + changed=!current_sfev.isSame(nsfev, mUtil); if (!changed) { if (!et_file_template.getText().toString().equals(n_sti.getDestinationArchiveRenameFileTemplate())) changed=true; // else if (n_sti.getDestinationArchiveRetentionPeriod()!=sp_sync_retain_period.getSelectedItemPosition()) changed=true; } - if (changed) setSyncFolderOkButtonEnabled(btn_sync_folder_ok, true);//CommonUtilities.setViewEnabled(mActivity, btn_sync_folder_ok, true); - else setSyncFolderOkButtonEnabled(btn_sync_folder_ok, false);//CommonUtilities.setViewEnabled(mActivity, btn_sync_folder_ok, false); + //CommonUtilities.setViewEnabled(mActivity, btn_sync_folder_ok, changed); + setSyncFolderOkButtonEnabled(btn_sync_folder_ok, changed); } @@ -4357,9 +4400,24 @@ private String getArchiveSuffixOptionFromSpinner(Spinner spinner) { private String getConvertedDirectoryFileName(String template, long time, String org_name) { String result=""; - - Date c_date = new Date("2000/01/02 01:20:30"); + //for Current Date: date = new Date(); + //for default Date: date = new Date(0); + Date c_date = null; Date e_date = new Date(); + try { + String date_c_format = "2000/01/02 01:20:30"; + DateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.getDefault()); //Locale.getDefault() is lang set in app, not system wide, as we alter locale in mGp.setLocaleConfigForApi24() + c_date = format.parse(date_c_format); + } catch (ParseException pe) { + mUtil.addDebugMsg(1, "E", "getConvertedDirectoryFileName: parse data format exception"); + } + + if (c_date == null) { + Calendar cal = Calendar.getInstance(); + cal.set(2000, 1, 2, 1, 20, 30); + c_date = cal.getTime(); + } + String taken_converted=SyncThread.replaceKeywordTakenDateValue(template, c_date.getTime()); String exec_converted=SyncThread.replaceKeywordExecutionDateValue(taken_converted, e_date.getTime()); result=exec_converted.replaceAll(SyncTaskItem.TEMPLATE_ORIGINAL_NAME, org_name); @@ -4430,70 +4488,70 @@ private void setSpinnerSyncTaskArchiveRetainPeriod(Spinner spinner, int cv) { } private SyncTaskItem buildSyncTaskListItem(Dialog dialog, SyncTaskItem base_stli) { - final EditText et_sync_main_task_name = (EditText) dialog.findViewById(R.id.edit_sync_task_task_name); - final CheckedTextView ctv_auto = (CheckedTextView) dialog.findViewById(R.id.edit_sync_task_ctv_auto); + final EditText et_sync_main_task_name = dialog.findViewById(R.id.edit_sync_task_task_name); + final CheckedTextView ctv_auto = dialog.findViewById(R.id.edit_sync_task_ctv_auto); - final Spinner spinnerSyncType = (Spinner) dialog.findViewById(R.id.edit_sync_task_sync_type); - final Spinner spinnerSyncWifiStatus = (Spinner) dialog.findViewById(R.id.edit_sync_task_option_spinner_wifi_status); + final Spinner spinnerSyncType = dialog.findViewById(R.id.edit_sync_task_sync_type); + final Spinner spinnerSyncWifiStatus = dialog.findViewById(R.id.edit_sync_task_option_spinner_wifi_status); - final CheckedTextView ctv_task_sync_when_cahrging = (CheckedTextView) dialog.findViewById(R.id.edit_sync_task_option_ctv_sync_start_when_charging); - final CheckedTextView ctv_never_overwrite_destination_file_newer_than_the_source_file = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_never_overwrite_destination_file_if_it_is_newer_than_the_source_file); - final CheckedTextView ctv_ignore_unusable_character_used_directory_file_name = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ignore_unusable_character_used_directory_file_name); + final CheckedTextView ctv_task_sync_when_cahrging = dialog.findViewById(R.id.edit_sync_task_option_ctv_sync_start_when_charging); + final CheckedTextView ctv_never_overwrite_destination_file_newer_than_the_source_file = mDialog.findViewById(R.id.edit_sync_task_option_never_overwrite_destination_file_if_it_is_newer_than_the_source_file); + final CheckedTextView ctv_ignore_unusable_character_used_directory_file_name = mDialog.findViewById(R.id.edit_sync_task_option_ignore_unusable_character_used_directory_file_name); - final CheckedTextView ctv_ignore_dst_difference = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_diff_ignore_dst_difference); - final Spinner spinnerSyncDstOffsetValue = (Spinner) mDialog.findViewById(R.id.edit_sync_task_option_spinner_offset_daylight_saving_time_value); + final CheckedTextView ctv_ignore_dst_difference = mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_diff_ignore_dst_difference); + final Spinner spinnerSyncDstOffsetValue = mDialog.findViewById(R.id.edit_sync_task_option_spinner_offset_daylight_saving_time_value); - final Button swap_source_destination = (Button) dialog.findViewById(R.id.edit_sync_task_swap_source_and_destination_btn); - final Button source_folder_info = (Button) dialog.findViewById(R.id.edit_sync_task_source_folder_info_btn); - final Button destination_folder_info = (Button) dialog.findViewById(R.id.edit_sync_task_destination_folder_info_btn); + final Button swap_source_destination = dialog.findViewById(R.id.edit_sync_task_swap_source_and_destination_btn); + final Button source_folder_info = dialog.findViewById(R.id.edit_sync_task_source_folder_info_btn); + final Button destination_folder_info = dialog.findViewById(R.id.edit_sync_task_destination_folder_info_btn); - final Button dir_filter_btn = (Button) dialog.findViewById(R.id.sync_filter_edit_dir_filter_btn); - final Button file_filter_btn = (Button) dialog.findViewById(R.id.sync_filter_edit_file_filter_btn); + final Button dir_filter_btn = dialog.findViewById(R.id.sync_filter_edit_dir_filter_btn); + final Button file_filter_btn = dialog.findViewById(R.id.sync_filter_edit_file_filter_btn); - final CheckedTextView ctvProcessRootDirFile = (CheckedTextView) dialog.findViewById(R.id.edit_sync_task_option_ctv_sync_source_root_dir_file); - final CheckedTextView ctvSyncSubDir = (CheckedTextView) dialog.findViewById(R.id.edit_sync_task_option_ctv_sync_sub_dir); - final CheckedTextView ctvSyncEmptyDir = (CheckedTextView) dialog.findViewById(R.id.edit_sync_task_option_ctv_sync_empty_directory); - final CheckedTextView ctvSyncHiddenDir = (CheckedTextView) dialog.findViewById(R.id.edit_sync_task_option_ctv_sync_hidden_directory); - final CheckedTextView ctvSyncHiddenFile = (CheckedTextView) dialog.findViewById(R.id.edit_sync_task_option_ctv_sync_hidden_file); - final CheckedTextView ctvProcessOverride = (CheckedTextView) dialog.findViewById(R.id.edit_sync_task_option_ctv_process_override_delete_file); - final CheckedTextView ctvConfirmOverride = (CheckedTextView) dialog.findViewById(R.id.edit_sync_task_option_ctv_confirm_override_delete_file); - final CheckedTextView ctvDeleteFirst = (CheckedTextView) dialog.findViewById(R.id.edit_sync_task_option_ctv_sync_delete_first_when_mirror); + final CheckedTextView ctvProcessRootDirFile = dialog.findViewById(R.id.edit_sync_task_option_ctv_sync_source_root_dir_file); + final CheckedTextView ctvSyncSubDir = dialog.findViewById(R.id.edit_sync_task_option_ctv_sync_sub_dir); + final CheckedTextView ctvSyncEmptyDir = dialog.findViewById(R.id.edit_sync_task_option_ctv_sync_empty_directory); + final CheckedTextView ctvSyncHiddenDir = dialog.findViewById(R.id.edit_sync_task_option_ctv_sync_hidden_directory); + final CheckedTextView ctvSyncHiddenFile = dialog.findViewById(R.id.edit_sync_task_option_ctv_sync_hidden_file); + final CheckedTextView ctvProcessOverride = dialog.findViewById(R.id.edit_sync_task_option_ctv_process_override_delete_file); + final CheckedTextView ctvConfirmOverride = dialog.findViewById(R.id.edit_sync_task_option_ctv_confirm_override_delete_file); + final CheckedTextView ctvDeleteFirst = dialog.findViewById(R.id.edit_sync_task_option_ctv_sync_delete_first_when_mirror); - final CheckedTextView ctvIgnoreFilterRemoveDirFileDesNotExistsInSource = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_remove_dir_file_excluded_by_filter); + final CheckedTextView ctvIgnoreFilterRemoveDirFileDesNotExistsInSource = mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_remove_dir_file_excluded_by_filter); - final CheckedTextView ctvShowSpecialOption = (CheckedTextView) dialog.findViewById(R.id.edit_sync_task_option_ctv_show_special_option); - final CheckedTextView ctvDoNotResetFileLastMod = (CheckedTextView) dialog.findViewById(R.id.edit_sync_task_option_ctv_do_mot_reset_file_last_mod_time); - final CheckedTextView ctvDeterminChangedFileSizeGtDestination = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_diff_file_size_greater_than_destination); - final CheckedTextView ctvRetry = (CheckedTextView) dialog.findViewById(R.id.edit_sync_task_option_ctv_retry_if_error_occured); - final CheckedTextView ctvSyncUseRemoteSmallIoArea = (CheckedTextView) dialog.findViewById(R.id.edit_sync_task_option_ctv_sync_use_remote_small_io_area); - final CheckedTextView ctvTestMode = (CheckedTextView) dialog.findViewById(R.id.edit_sync_task_option_ctv_sync_test_mode); - final CheckedTextView ctvDiffUseFileSize = (CheckedTextView) dialog.findViewById(R.id.edit_sync_task_option_ctv_sync_diff_use_file_size); - final CheckedTextView ctDeterminChangedFileByTime = (CheckedTextView) dialog.findViewById(R.id.edit_sync_task_option_ctv_sync_diff_use_last_mod_time); + final CheckedTextView ctvShowSpecialOption = dialog.findViewById(R.id.edit_sync_task_option_ctv_show_special_option); + final CheckedTextView ctvDoNotResetFileLastMod = dialog.findViewById(R.id.edit_sync_task_option_ctv_do_mot_reset_file_last_mod_time); + final CheckedTextView ctvDeterminChangedFileSizeGtDestination = mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_diff_file_size_greater_than_destination); + final CheckedTextView ctvRetry = dialog.findViewById(R.id.edit_sync_task_option_ctv_retry_if_error_occured); + final CheckedTextView ctvSyncUseRemoteSmallIoArea = dialog.findViewById(R.id.edit_sync_task_option_ctv_sync_use_remote_small_io_area); + final CheckedTextView ctvTestMode = dialog.findViewById(R.id.edit_sync_task_option_ctv_sync_test_mode); + final CheckedTextView ctvDiffUseFileSize = dialog.findViewById(R.id.edit_sync_task_option_ctv_sync_diff_use_file_size); + final CheckedTextView ctDeterminChangedFileByTime = dialog.findViewById(R.id.edit_sync_task_option_ctv_sync_diff_use_last_mod_time); - final CheckedTextView ctv_sync_allow_global_ip_addr = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_sync_allow_all_ip_address); + final CheckedTextView ctv_sync_allow_global_ip_addr = mDialog.findViewById(R.id.edit_sync_task_option_sync_allow_all_ip_address); - final CheckedTextView ctv_sync_remove_source_if_empty = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_remove_directory_if_empty_when_move); - final Spinner sp_sync_task_option_error_option=(Spinner)mDialog.findViewById(R.id.edit_sync_task_option_error_option_value); + final CheckedTextView ctv_sync_remove_source_if_empty = mDialog.findViewById(R.id.edit_sync_task_option_ctv_remove_directory_if_empty_when_move); + final Spinner sp_sync_task_option_error_option= mDialog.findViewById(R.id.edit_sync_task_option_error_option_value); - final CheckedTextView ctv_confirm_exif_date = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_confirm_exif_date); - final CheckedTextView ctv_ignore_file_size_gt_4gb = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ignore_source_file_that_file_size_gt_4gb); - final EditText et_max_dest_file_name_length = (EditText) mDialog.findViewById(R.id.edit_sync_task_option_max_destination_file_name_length); + final CheckedTextView ctv_confirm_exif_date = mDialog.findViewById(R.id.edit_sync_task_option_confirm_exif_date); + final CheckedTextView ctv_ignore_file_size_gt_4gb = mDialog.findViewById(R.id.edit_sync_task_option_ignore_source_file_that_file_size_gt_4gb); + final EditText et_max_dest_file_name_length = mDialog.findViewById(R.id.edit_sync_task_option_max_destination_file_name_length); - final Spinner spinnerSyncDiffTimeValue = (Spinner) dialog.findViewById(R.id.edit_sync_task_option_spinner_diff_file_determin_time_value); - final Button btn_ok = (Button) dialog.findViewById(R.id.edit_profile_sync_dlg_btn_ok); + final Spinner spinnerSyncDiffTimeValue = dialog.findViewById(R.id.edit_sync_task_option_spinner_diff_file_determin_time_value); + final Button btn_ok = dialog.findViewById(R.id.edit_profile_sync_dlg_btn_ok); - final Spinner sp_file_size_type=(Spinner)dialog.findViewById(R.id.sync_filter_file_size_type_spinner); - final EditText et_file_size_value=(EditText)dialog.findViewById(R.id.sync_filter_file_size_value); - final Spinner sp_file_size_unit=(Spinner)dialog.findViewById(R.id.sync_filter_file_size_unit_spinner); + final Spinner sp_file_size_type= dialog.findViewById(R.id.sync_filter_file_size_type_spinner); + final EditText et_file_size_value= dialog.findViewById(R.id.sync_filter_file_size_value); + final Spinner sp_file_size_unit= dialog.findViewById(R.id.sync_filter_file_size_unit_spinner); - final CheckedTextView ctvIgnore_0_byte_file=(CheckedTextView)dialog.findViewById(R.id.edit_sync_task_option_ignore_file_size_0_bytes_file); + final CheckedTextView ctvIgnore_0_byte_file= dialog.findViewById(R.id.edit_sync_task_option_ignore_file_size_0_bytes_file); - final Spinner sp_file_date_type=(Spinner)dialog.findViewById(R.id.sync_filter_file_date_type_spinner); - final EditText et_file_date_value=(EditText)dialog.findViewById(R.id.sync_filter_file_date_value); + final Spinner sp_file_date_type= dialog.findViewById(R.id.sync_filter_file_date_type_spinner); + final EditText et_file_date_value= dialog.findViewById(R.id.sync_filter_file_date_value); - final Spinner sp_sync_retain_period = (Spinner) dialog.findViewById(R.id.edit_sync_filter_archive_retention_period); + final Spinner sp_sync_retain_period = dialog.findViewById(R.id.edit_sync_filter_archive_retention_period); - SyncTaskItem nstli = base_stli.clone(); + SyncTaskItem nstli = base_stli.cloneSerial(); nstli.setSyncTaskAuto(ctv_auto.isChecked()); nstli.setSyncTaskName(et_sync_main_task_name.getText().toString()); @@ -4513,7 +4571,7 @@ private SyncTaskItem buildSyncTaskListItem(Dialog dialog, SyncTaskItem base_stli nstli.setSyncOptionDeleteFirstWhenMirror(ctvDeleteFirst.isChecked()); - nstli.setSyncTaskErrorOption(nstli.getSyncTaskErrorOptionValueByIndex(sp_sync_task_option_error_option.getSelectedItemPosition())); + nstli.setSyncTaskErrorOption(SyncTaskItem.getSyncTaskErrorOptionValueByIndex(sp_sync_task_option_error_option.getSelectedItemPosition())); String wifi_sel = getSpinnerSyncTaskWifiOptionValue(spinnerSyncWifiStatus); nstli.setSyncOptionWifiStatusOption(wifi_sel); @@ -4534,23 +4592,25 @@ private SyncTaskItem buildSyncTaskListItem(Dialog dialog, SyncTaskItem base_stli nstli.setSyncOptionIgnoreDstDifference(ctv_ignore_dst_difference.isChecked()); try { String dst_offset=(String)spinnerSyncDstOffsetValue.getSelectedItem(); - nstli.setSyncOptionOffsetOfDst(Integer.valueOf(dst_offset)); - } catch(Exception e) {} + nstli.setSyncOptionOffsetOfDst(Integer.parseInt(dst_offset)); + } catch(Exception e) { + mUtil.addDebugMsg(1, "E", "buildSyncTaskListItem: Error parseInt for Exception="+e); + } nstli.setSyncOptionDoNotOverwriteDestinationFileIfItIsNewerThanTheSourceFile(ctv_never_overwrite_destination_file_newer_than_the_source_file.isChecked()); nstli.setSyncOptionIgnoreDirectoriesOrFilesThatContainUnusableCharacters(ctv_ignore_unusable_character_used_directory_file_name.isChecked()); String diff_val = spinnerSyncDiffTimeValue.getSelectedItem().toString(); - nstli.setSyncOptionDifferentFileAllowableTime(Integer.valueOf(diff_val)); - String size_type=nstli.getSyncFilterFileSizeTypeByIndex(sp_file_size_type.getSelectedItemPosition()); + nstli.setSyncOptionDifferentFileAllowableTime(Integer.parseInt(diff_val)); + String size_type= SyncTaskItem.getSyncFilterFileSizeTypeByIndex(sp_file_size_type.getSelectedItemPosition()); nstli.setSyncFilterFileSizeType(size_type); - String size_unit=nstli.getSyncFilterFileSizeUnitByIndex(sp_file_size_unit.getSelectedItemPosition()); + String size_unit= SyncTaskItem.getSyncFilterFileSizeUnitByIndex(sp_file_size_unit.getSelectedItemPosition()); nstli.setSyncFilterFileSizeUnit(size_unit); nstli.setSyncFilterFileSizeValue(et_file_size_value.getText().toString()); - String date_type=nstli.getSyncFilterFileDateTypeByIndex(sp_file_date_type.getSelectedItemPosition()); + String date_type= SyncTaskItem.getSyncFilterFileDateTypeByIndex(sp_file_date_type.getSelectedItemPosition()); nstli.setSyncFilterFileDateType(date_type); nstli.setSyncFilterFileDateValue(et_file_date_value.getText().toString()); @@ -4563,7 +4623,7 @@ private SyncTaskItem buildSyncTaskListItem(Dialog dialog, SyncTaskItem base_stli nstli.setSyncOptionRemoveDirectoryFileThatExcludedByFilter(ctvIgnoreFilterRemoveDirFileDesNotExistsInSource.isChecked()); - nstli.setSyncOptionMaxDestinationFileNameLength(Integer.valueOf(et_max_dest_file_name_length.getText().toString())); + nstli.setSyncOptionMaxDestinationFileNameLength(Integer.parseInt(et_max_dest_file_name_length.getText().toString())); nstli.setSyncOptionIgnoreFileSize0ByteFile(ctvIgnore_0_byte_file.isChecked()); @@ -4576,15 +4636,15 @@ static public void showFieldHelp(Activity a, GlobalParameters mGp, String title, Dialog dialog = new Dialog(a, mGp.applicationTheme); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(R.layout.help_dlg); - LinearLayout ll_title_view = (LinearLayout) dialog.findViewById(R.id.help_view_title_view); + LinearLayout ll_title_view = dialog.findViewById(R.id.help_view_title_view); ll_title_view.setBackgroundColor(mGp.themeColorList.title_background_color); - TextView dlg_tv = (TextView) dialog.findViewById(R.id.help_view_title_text); + TextView dlg_tv = dialog.findViewById(R.id.help_view_title_text); dlg_tv.setTextColor(mGp.themeColorList.title_text_color); int zf=(int)((float)100* GlobalParameters.getFontScaleFactorValue(a)); - WebView wv = (WebView) dialog.findViewById(R.id.help_view_help); + WebView wv = dialog.findViewById(R.id.help_view_help); String html=CommonUtilities.convertMakdownToHtml(a, help_msg); // dlg_wb.loadData(html, "text/html", "UTF-8"); @@ -4593,7 +4653,7 @@ static public void showFieldHelp(Activity a, GlobalParameters mGp, String title, wv.setScrollbarFadingEnabled(false); CommonUtilities.setWebViewListener(mGp, wv, zf); - LinearLayout ll_help=(LinearLayout)dialog.findViewById(R.id.help_view); + LinearLayout ll_help= dialog.findViewById(R.id.help_view); CommonUtilities.setAboutFindListener(a, ll_help, wv); wv.setOnKeyListener(new View.OnKeyListener() { @@ -4635,7 +4695,7 @@ else if (so.equals(mActivity.getString(R.string.msgs_main_sync_profile_dlg_archi } private void setSyncTaskFieldHelpListener(Dialog dialog, SyncTaskItem sti) { - final ImageButton help_sync_option = (ImageButton) dialog.findViewById(R.id.edit_profile_sync_help); + final ImageButton help_sync_option = dialog.findViewById(R.id.edit_profile_sync_help); help_sync_option.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { @@ -4646,7 +4706,7 @@ public void onClick(View v) { } private void setSyncFolderFieldHelpListener(Dialog dialog, final String f_type) { - final ImageButton help_sync_folder = (ImageButton) dialog.findViewById(R.id.edit_sync_folder_dlg_help); + final ImageButton help_sync_folder = dialog.findViewById(R.id.edit_sync_folder_dlg_help); help_sync_folder.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { @@ -4665,7 +4725,7 @@ public void onClick(View v) { } private void setSyncFolderKeywordHelpListener(Dialog dialog, final boolean exec_only) { - ImageButton ib_help=(ImageButton)dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_help); + ImageButton ib_help= dialog.findViewById(R.id.edit_sync_folder_edit_keywor_dlg_help); ib_help.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { @@ -4680,66 +4740,66 @@ private void checkSyncTaskOkButtonEnabled(Dialog dialog, String type, SyncTaskIt // final CheckedTextView ctvSyncHiddenDir = (CheckedTextView) dialog.findViewById(R.id.edit_sync_task_option_ctv_sync_hidden_directory); // final CheckedTextView ctvSyncHiddenFile = (CheckedTextView) dialog.findViewById(R.id.edit_sync_task_option_ctv_sync_hidden_file); - final LinearLayout ll_ctvProcessOverride = (LinearLayout) mDialog.findViewById(R.id.edit_sync_task_option_ll_process_override_delete_file); - final LinearLayout ll_ctvConfirmOverride = (LinearLayout) mDialog.findViewById(R.id.edit_sync_task_option_ll_confirm_override_delete_file); + final LinearLayout ll_ctvProcessOverride = mDialog.findViewById(R.id.edit_sync_task_option_ll_process_override_delete_file); + final LinearLayout ll_ctvConfirmOverride = mDialog.findViewById(R.id.edit_sync_task_option_ll_confirm_override_delete_file); // final CheckedTextView ctUseExtendedDirectoryFilter1 = (CheckedTextView) dialog.findViewById(R.id.edit_sync_task_option_ctv_sync_use_extended_filter1); // final CheckedTextView ctvShowSpecialOption = (CheckedTextView) dialog.findViewById(R.id.edit_sync_task_option_ctv_show_special_option); - final LinearLayout ll_ctvDoNotResetFileLastMod = (LinearLayout) mDialog.findViewById(R.id.edit_sync_task_option_ll_do_mot_reset_file_last_mod_time); + final LinearLayout ll_ctvDoNotResetFileLastMod = mDialog.findViewById(R.id.edit_sync_task_option_ll_do_mot_reset_file_last_mod_time); // final CheckedTextView ctvRetry = (CheckedTextView) dialog.findViewById(R.id.edit_sync_task_option_ctv_retry_if_error_occured); // final CheckedTextView ctvSyncUseRemoteSmallIoArea = (CheckedTextView) dialog.findViewById(R.id.edit_sync_task_option_ctv_sync_use_remote_small_io_area); // final CheckedTextView ctvTestMode = (CheckedTextView) dialog.findViewById(R.id.edit_sync_task_option_ctv_sync_test_mode); - final LinearLayout ll_wifi_condition_view = (LinearLayout) mDialog.findViewById(R.id.edit_sync_task_option_wifi_condition_view); - final LinearLayout ll_wifi_wl_view = (LinearLayout) mDialog.findViewById(R.id.edit_sync_task_option_wl_view); - final LinearLayout ll_wifi_wl_address_view = (LinearLayout) mDialog.findViewById(R.id.edit_sync_task_option_address_list_view); - final CheckedTextView ctv_sync_allow_global_ip_addr = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_sync_allow_all_ip_address); - final Spinner spinnerSyncWifiStatus = (Spinner) mDialog.findViewById(R.id.edit_sync_task_option_spinner_wifi_status); + final LinearLayout ll_wifi_condition_view = mDialog.findViewById(R.id.edit_sync_task_option_wifi_condition_view); + final LinearLayout ll_wifi_wl_view = mDialog.findViewById(R.id.edit_sync_task_option_wl_view); + final LinearLayout ll_wifi_wl_address_view = mDialog.findViewById(R.id.edit_sync_task_option_address_list_view); + final CheckedTextView ctv_sync_allow_global_ip_addr = mDialog.findViewById(R.id.edit_sync_task_option_sync_allow_all_ip_address); + final Spinner spinnerSyncWifiStatus = mDialog.findViewById(R.id.edit_sync_task_option_spinner_wifi_status); - final LinearLayout ll_ctvDiffUseFileSize = (LinearLayout) mDialog.findViewById(R.id.edit_sync_task_option_ll_sync_diff_use_file_size); - final LinearLayout ll_ctDeterminChangedFileByTime = (LinearLayout) mDialog.findViewById(R.id.edit_sync_task_option_sync_diff_use_last_mod_time_view); + final LinearLayout ll_ctvDiffUseFileSize = mDialog.findViewById(R.id.edit_sync_task_option_ll_sync_diff_use_file_size); + final LinearLayout ll_ctDeterminChangedFileByTime = mDialog.findViewById(R.id.edit_sync_task_option_sync_diff_use_last_mod_time_view); - final CheckedTextView ctvDoNotResetRemoteFile = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_do_mot_reset_file_last_mod_time); + final CheckedTextView ctvDoNotResetRemoteFile = mDialog.findViewById(R.id.edit_sync_task_option_ctv_do_mot_reset_file_last_mod_time); - final LinearLayout ll_diff_time_allowed_time = (LinearLayout) mDialog.findViewById(R.id.edit_sync_task_option_diff_file_determin_time_value_view); + final LinearLayout ll_diff_time_allowed_time = mDialog.findViewById(R.id.edit_sync_task_option_diff_file_determin_time_value_view); - final LinearLayout ll_sync_remove_source_if_empty = (LinearLayout) mDialog.findViewById(R.id.edit_sync_task_option_ll_remove_directory_if_empty_when_move_view); + final LinearLayout ll_sync_remove_source_if_empty = mDialog.findViewById(R.id.edit_sync_task_option_ll_remove_directory_if_empty_when_move_view); - final CheckedTextView ctv_ignore_dst_difference = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_diff_ignore_dst_difference); + final CheckedTextView ctv_ignore_dst_difference = mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_diff_ignore_dst_difference); - final CheckedTextView ctvDeterminChangedFileSizeGtDestination = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_diff_file_size_greater_than_destination); - final CheckedTextView ctvDiffUseFileSize = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_diff_use_file_size); + final CheckedTextView ctvDeterminChangedFileSizeGtDestination = mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_diff_file_size_greater_than_destination); + final CheckedTextView ctvDiffUseFileSize = mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_diff_use_file_size); - final CheckedTextView ctDeterminChangedFileByTime = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_diff_use_last_mod_time); - final LinearLayout ll_DeterminChangedFileByTime_dependant_view=(LinearLayout)mDialog.findViewById(R.id.edit_sync_task_option_sync_diff_use_last_mod_time_dependant_view); + final CheckedTextView ctDeterminChangedFileByTime = mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_diff_use_last_mod_time); + final LinearLayout ll_DeterminChangedFileByTime_dependant_view= mDialog.findViewById(R.id.edit_sync_task_option_sync_diff_use_last_mod_time_dependant_view); - final CheckedTextView ctv_sync_remove_source_if_empty = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_remove_directory_if_empty_when_move); - final Spinner sp_sync_task_option_error_option=(Spinner)mDialog.findViewById(R.id.edit_sync_task_option_error_option_value); + final CheckedTextView ctv_sync_remove_source_if_empty = mDialog.findViewById(R.id.edit_sync_task_option_ctv_remove_directory_if_empty_when_move); + final Spinner sp_sync_task_option_error_option= mDialog.findViewById(R.id.edit_sync_task_option_error_option_value); - final CheckedTextView ctvIgnoreFilterRemoveDirFileDesNotExistsInSource = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_remove_dir_file_excluded_by_filter); - final LinearLayout ctvIgnoreFilterRemoveDirFileDesNotExistsInSourceView = (LinearLayout) mDialog.findViewById(R.id.edit_sync_task_option_ll_sync_remove_dir_file_excluded_by_filter); - final CheckedTextView ctvDeleteFirst = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_delete_first_when_mirror); - final LinearLayout ctvDeleteFirstView = (LinearLayout) mDialog.findViewById(R.id.edit_sync_task_option_ll_sync_delete_first_when_mirror); + final CheckedTextView ctvIgnoreFilterRemoveDirFileDesNotExistsInSource = mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_remove_dir_file_excluded_by_filter); + final LinearLayout ctvIgnoreFilterRemoveDirFileDesNotExistsInSourceView = mDialog.findViewById(R.id.edit_sync_task_option_ll_sync_remove_dir_file_excluded_by_filter); + final CheckedTextView ctvDeleteFirst = mDialog.findViewById(R.id.edit_sync_task_option_ctv_sync_delete_first_when_mirror); + final LinearLayout ctvDeleteFirstView = mDialog.findViewById(R.id.edit_sync_task_option_ll_sync_delete_first_when_mirror); - final LinearLayout ll_ignore_file_size_gt_4gb = (LinearLayout) mDialog.findViewById(R.id.edit_sync_task_option_ignore_source_file_that_file_size_gt_4gb_view); - final CheckedTextView ctv_ignore_file_size_gt_4gb = (CheckedTextView) mDialog.findViewById(R.id.edit_sync_task_option_ignore_source_file_that_file_size_gt_4gb); + final LinearLayout ll_ignore_file_size_gt_4gb = mDialog.findViewById(R.id.edit_sync_task_option_ignore_source_file_that_file_size_gt_4gb_view); + final CheckedTextView ctv_ignore_file_size_gt_4gb = mDialog.findViewById(R.id.edit_sync_task_option_ignore_source_file_that_file_size_gt_4gb); - final Button destination_folder_info = (Button) mDialog.findViewById(R.id.edit_sync_task_destination_folder_info_btn); - final ImageView destination_folder_icon=(ImageView)mDialog.findViewById(R.id.edit_sync_task_destination_folder_info_icon); - final Button swap_source_destination = (Button) mDialog.findViewById(R.id.edit_sync_task_swap_source_and_destination_btn); - final Button source_folder_info = (Button) mDialog.findViewById(R.id.edit_sync_task_source_folder_info_btn); - final ImageView source_folder_icon=(ImageView)mDialog.findViewById(R.id.edit_sync_task_source_folder_info_icon); + final Button destination_folder_info = mDialog.findViewById(R.id.edit_sync_task_destination_folder_info_btn); + final ImageView destination_folder_icon= mDialog.findViewById(R.id.edit_sync_task_destination_folder_info_icon); + final Button swap_source_destination = mDialog.findViewById(R.id.edit_sync_task_swap_source_and_destination_btn); + final Button source_folder_info = mDialog.findViewById(R.id.edit_sync_task_source_folder_info_btn); + final ImageView source_folder_icon= mDialog.findViewById(R.id.edit_sync_task_source_folder_info_icon); - final LinearLayout ll_sync_task_name_view = (LinearLayout) mDialog.findViewById(R.id.edit_sync_task_task_name_view); - final EditText et_sync_main_task_name = (EditText) mDialog.findViewById(R.id.edit_sync_task_task_name); + final LinearLayout ll_sync_task_name_view = mDialog.findViewById(R.id.edit_sync_task_task_name_view); + final EditText et_sync_main_task_name = mDialog.findViewById(R.id.edit_sync_task_task_name); - final LinearLayout ll_file_filter_detail_view = (LinearLayout) mDialog.findViewById(R.id.sync_filter_file_type_detail_view); - final LinearLayout ll_archive_detail_view = (LinearLayout) mDialog.findViewById(R.id.edit_sync_filter_archive_file_type_view); + final LinearLayout ll_file_filter_detail_view = mDialog.findViewById(R.id.sync_filter_file_type_detail_view); + final LinearLayout ll_archive_detail_view = mDialog.findViewById(R.id.edit_sync_filter_archive_file_type_view); - final EditText et_max_dest_file_name_length = (EditText) mDialog.findViewById(R.id.edit_sync_task_option_max_destination_file_name_length); + final EditText et_max_dest_file_name_length = mDialog.findViewById(R.id.edit_sync_task_option_max_destination_file_name_length); - final Button btn_ok = (Button) dialog.findViewById(R.id.edit_profile_sync_dlg_btn_ok); + final Button btn_ok = dialog.findViewById(R.id.edit_profile_sync_dlg_btn_ok); String t_name_msg = checkTaskNameValidity(type, n_sti.getSyncTaskName(), dlg_msg, btn_ok); boolean error_detected = false; swap_source_destination.setVisibility(Button.VISIBLE); @@ -4827,7 +4887,7 @@ private void checkSyncTaskOkButtonEnabled(Dialog dialog, String type, SyncTaskIt t_name_msg= TaskListUtils.hasSyncTaskNameUnusableCharacter(mActivity, et_sync_main_task_name.getText().toString()); } if (t_name_msg.equals("")) { - if (et_sync_main_task_name.getText().length()>SyncTaskItem.SYNC_TASK_NAME_MAX_LENGTH) t_name_msg=mActivity.getString(R.string.msgs_sync_task_name_length_invalid, SyncTaskItem.SYNC_TASK_NAME_MAX_LENGTH); + if (et_sync_main_task_name.getText().length() > SyncTaskItem.SYNC_TASK_NAME_MAX_LENGTH) t_name_msg = String.format(mActivity.getString(R.string.msgs_sync_task_name_length_invalid), SyncTaskItem.SYNC_TASK_NAME_MAX_LENGTH); } if (t_name_msg.equals("")) { @@ -4866,7 +4926,7 @@ private void checkSyncTaskOkButtonEnabled(Dialog dialog, String type, SyncTaskIt } else { String ev=et_max_dest_file_name_length.getText().toString(); if (ev.length()>0) { - int val=Integer.parseInt(ev.toString()); + int val=Integer.parseInt(ev); if (val==0) { s_msg=mActivity.getString(R.string.msgs_task_sync_task_sync_ignore_file_name_length_gt_specified_value_gt_0); } else if (val>255) { @@ -4877,17 +4937,15 @@ private void checkSyncTaskOkButtonEnabled(Dialog dialog, String type, SyncTaskIt } if (s_msg.equals("")) { setDialogMsg(dlg_msg, s_msg); - if (isSyncTaskChanged(n_sti, mCurrentSyncTaskItem)) CommonUtilities.setViewEnabled(mActivity, btn_ok, true); - else CommonUtilities.setViewEnabled(mActivity, btn_ok, false); + CommonUtilities.setViewEnabled(mActivity, btn_ok, isSyncTaskChanged(n_sti, mCurrentSyncTaskItem)); } else { setDialogMsg(dlg_msg, s_msg); - CommonDialog.setViewEnabled(getActivity(), btn_ok, false); + CommonDialog.setViewEnabled(mActivity, btn_ok, false); } } } else { setDialogMsg(dlg_msg, s_msg); - if (isSyncTaskChanged(n_sti, mCurrentSyncTaskItem)) CommonUtilities.setViewEnabled(mActivity, btn_ok, true); - else CommonUtilities.setViewEnabled(mActivity, btn_ok, false); + CommonUtilities.setViewEnabled(mActivity, btn_ok, isSyncTaskChanged(n_sti, mCurrentSyncTaskItem)); } } else { setDialogMsg(dlg_msg, filter_msg); @@ -4906,21 +4964,20 @@ private boolean isSyncTaskChanged(SyncTaskItem curr_stli, SyncTaskItem org_stli) String n_type = new_stli.getSyncTaskType(); String c_type = mCurrentSyncTaskItem.getSyncTaskType(); - boolean result = !new_stli.isSame(org_stli); - return result; + return !new_stli.isSame(org_stli); } private String checkFilter(Dialog dialog, String type, SyncTaskItem n_sti) { String result = ""; - final Spinner sp_file_size_type=(Spinner)mDialog.findViewById(R.id.sync_filter_file_size_type_spinner); - final EditText et_file_size_value=(EditText)mDialog.findViewById(R.id.sync_filter_file_size_value); - final Spinner sp_file_size_unit=(Spinner)mDialog.findViewById(R.id.sync_filter_file_size_unit_spinner); + final Spinner sp_file_size_type= mDialog.findViewById(R.id.sync_filter_file_size_type_spinner); + final EditText et_file_size_value= mDialog.findViewById(R.id.sync_filter_file_size_value); + final Spinner sp_file_size_unit= mDialog.findViewById(R.id.sync_filter_file_size_unit_spinner); - final CheckedTextView ctvIgnore_0_byte_file=(CheckedTextView)mDialog.findViewById(R.id.edit_sync_task_option_ignore_file_size_0_bytes_file); + final CheckedTextView ctvIgnore_0_byte_file= mDialog.findViewById(R.id.edit_sync_task_option_ignore_file_size_0_bytes_file); - final Spinner sp_file_date_type=(Spinner)mDialog.findViewById(R.id.sync_filter_file_date_type_spinner); - final EditText et_file_date_value=(EditText)mDialog.findViewById(R.id.sync_filter_file_date_value); + final Spinner sp_file_date_type= mDialog.findViewById(R.id.sync_filter_file_date_type_spinner); + final EditText et_file_date_value= mDialog.findViewById(R.id.sync_filter_file_date_value); boolean error_detected = false; @@ -4991,12 +5048,13 @@ private String checkStorageStatus(Dialog dialog, String type, SyncTaskItem n_sti private void setWifiApWhiteListInfo(ArrayList wpal, Button edit_wifi_ap_list) { if (wpal.size() > 0) { - String ap_list = "", sep = ""; + StringBuilder ap_list = new StringBuilder(); + String sep = ""; for (FilterListAdapter.FilterListItem wapl : wpal) { - ap_list += sep + wapl.getFilter(); + ap_list.append(sep).append(wapl.getFilter()); sep = ","; } - edit_wifi_ap_list.setText(ap_list); + edit_wifi_ap_list.setText(ap_list.toString()); } else { edit_wifi_ap_list.setText(mActivity.getString(R.string.msgs_filter_list_dlg_not_specified)); } @@ -5058,7 +5116,7 @@ private String isSameDirectoryAccess(Dialog dialog, SyncTaskItem sti) { if (sti.getDestinationDirectoryName().equals("")) { //Valid combination } else { - if (sti.getSourceDirectoryName().toLowerCase().equals(sti.getDestinationDirectoryName().toLowerCase())) { + if (sti.getSourceDirectoryName().equalsIgnoreCase(sti.getDestinationDirectoryName())) { msg=mActivity.getString(R.string.msgs_main_sync_profile_dlg_invalid_source_destination_combination_external); } else { if (!sti.getDestinationDirectoryName().toLowerCase().equals(sti.getSourceDirectoryName().toLowerCase())) { @@ -5091,26 +5149,26 @@ private String checkSourceDestinationCombination(Dialog dialog, SyncTaskItem sti return result; } + //static class SyncFolderEditValue implements Serializable { //optional way and remove the overrided clone() method static class SyncFolderEditValue implements Serializable, Cloneable { public boolean isChanged=false; public String task_type=""; public String folder_title = ""; public boolean is_source_folder = false; - public boolean folder_smb_use_pswd =false; public String folder_type = ""; public String folder_directory = ""; public String folder_storage_uuid = ""; + public boolean folder_smb_use_pswd =false; public String folder_smb_account = ""; public String folder_smb_password = ""; public String folder_smb_domain = ""; public String folder_smb_host = ""; public String folder_smb_share = ""; + public boolean folder_smb_use_port =false; public String folder_smb_port = ""; public String folder_smb_protocol = "1"; public boolean folder_smb_ipc_enforced=true; public boolean folder_smb_use_smb2_negotiation=false; - public boolean folder_smb_use_port_number =false; - public boolean folder_smb_use_account_name_password =false; public boolean show_smb_detail_settings=false; public boolean show_smb_passowrd=false; @@ -5129,10 +5187,26 @@ static class SyncFolderEditValue implements Serializable, Cloneable { public int folder_error_code= SyncTaskItem.SYNC_FOLDER_STATUS_ERROR_NO_ERROR; - public SyncFolderEditValue(){}; + public SyncFolderEditValue(){} + + // Clone using java Cloneable clone() + // not used + @NonNull @Override public SyncFolderEditValue clone() { + SyncFolderEditValue npfli = null; + try { + npfli = (SyncFolderEditValue) super.clone(); + } catch (CloneNotSupportedException e) { + e.printStackTrace(); + } + assert npfli != null; + return npfli; + } + + // Custom clone using Serialization/Deserialization + public SyncFolderEditValue cloneSerial() { SyncFolderEditValue npfli = null; try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); @@ -5152,24 +5226,32 @@ public SyncFolderEditValue clone() { npfli = (SyncFolderEditValue) ois.readObject(); ois.close(); bais.close(); - } catch (IOException e) { - e.printStackTrace(); - } catch (ClassNotFoundException e) { + } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } return npfli; } - public boolean isSame(SyncFolderEditValue comp) { + public boolean isSame(SyncFolderEditValue comp, CommonUtilities cu) { boolean result = false; if (folder_type.equals(SyncTaskItem.SYNC_FOLDER_TYPE_LOCAL)) { + //log.debug("SyncFolderEditValue.isSame : {}={}", folder_directory, comp.folder_directory); + cu.addDebugMsg(3, "W", "SyncFolderEditValue.isSame folder_type: "+folder_type + "=" + comp.folder_type); + cu.addDebugMsg(3, "W", "SyncFolderEditValue.isSame isChanged: "+isChanged + "=" + comp.isChanged); + cu.addDebugMsg(3, "W", "SyncFolderEditValue.isSame folder_directory: "+folder_directory + "=" + comp.folder_directory); + cu.addDebugMsg(3, "W", "SyncFolderEditValue.isSame folder_storage_uuid: "+folder_storage_uuid + "=" + comp.folder_storage_uuid); + if (folder_type.equals(comp.folder_type) && isChanged==comp.isChanged && folder_directory.equals(comp.folder_directory) && folder_storage_uuid.equals(comp.folder_storage_uuid) ) { if (task_type.equals(SyncTaskItem.SYNC_TASK_TYPE_ARCHIVE)) { + cu.addDebugMsg(3, "W", "SyncFolderEditValue.isSame archive_file_append_suffix_digit: "+archive_file_append_suffix_digit + "=" + comp.archive_file_append_suffix_digit); + cu.addDebugMsg(3, "W", "SyncFolderEditValue.isSame archive_file_rename_template: "+archive_file_rename_template + "=" + comp.archive_file_rename_template); + cu.addDebugMsg(3, "W", "SyncFolderEditValue.isSame archive_ignore_source_directory_hiearachy: "+archive_ignore_source_directory_hiearachy + "=" + comp.archive_ignore_source_directory_hiearachy); + if (archive_file_append_suffix_digit.equals(comp.archive_file_append_suffix_digit) && // archive_retention_period.equals(comp.archive_retention_period) && archive_file_rename_template.equals(comp.archive_file_rename_template) && @@ -5180,6 +5262,21 @@ public boolean isSame(SyncFolderEditValue comp) { } } } else if (folder_type.equals(SyncTaskItem.SYNC_FOLDER_TYPE_SMB)) { + cu.addDebugMsg(3, "W", "SyncFolderEditValue.isSame folder_type: "+folder_type + "=" + comp.folder_type); + cu.addDebugMsg(3, "W", "SyncFolderEditValue.isSame isChanged: "+isChanged + "=" + comp.isChanged); + cu.addDebugMsg(3, "W", "SyncFolderEditValue.isSame folder_directory: "+folder_directory + "=" + comp.folder_directory); + cu.addDebugMsg(3, "W", "SyncFolderEditValue.isSame folder_smb_account: "+folder_smb_account + "=" + comp.folder_smb_account); + cu.addDebugMsg(3, "W", "SyncFolderEditValue.isSame folder_smb_password: "+folder_smb_password + "=" + comp.folder_smb_password); + cu.addDebugMsg(3, "W", "SyncFolderEditValue.isSame folder_smb_domain: "+folder_smb_domain + "=" + comp.folder_smb_domain); + cu.addDebugMsg(3, "W", "SyncFolderEditValue.isSame folder_smb_host: "+folder_smb_host + "=" + comp.folder_smb_host); + cu.addDebugMsg(3, "W", "SyncFolderEditValue.isSame folder_smb_share: "+folder_smb_share + "=" + comp.folder_smb_share); + cu.addDebugMsg(3, "W", "SyncFolderEditValue.isSame folder_smb_port: "+folder_smb_port + "=" + comp.folder_smb_port); + cu.addDebugMsg(3, "W", "SyncFolderEditValue.isSame folder_smb_protocol: "+folder_smb_protocol + "=" + comp.folder_smb_protocol); + cu.addDebugMsg(3, "W", "SyncFolderEditValue.isSame folder_smb_use_pswd: "+folder_smb_use_pswd + "=" + comp.folder_smb_use_pswd); + cu.addDebugMsg(3, "W", "SyncFolderEditValue.isSame folder_smb_use_port: "+folder_smb_use_port + "=" + comp.folder_smb_use_port); + cu.addDebugMsg(3, "W", "SyncFolderEditValue.isSame folder_smb_ipc_enforced: "+folder_smb_ipc_enforced + "=" + comp.folder_smb_ipc_enforced); + cu.addDebugMsg(3, "W", "SyncFolderEditValue.isSame folder_smb_use_smb2_negotiation: "+folder_smb_use_smb2_negotiation + "=" + comp.folder_smb_use_smb2_negotiation); + if (folder_type.equals(comp.folder_type) && isChanged==comp.isChanged && folder_directory.equals(comp.folder_directory) && @@ -5191,10 +5288,15 @@ public boolean isSame(SyncFolderEditValue comp) { folder_smb_port.equals(comp.folder_smb_port) && folder_smb_protocol.equals(comp.folder_smb_protocol) && (folder_smb_use_pswd == comp.folder_smb_use_pswd) && + (folder_smb_use_port == comp.folder_smb_use_port) && (folder_smb_ipc_enforced==comp.folder_smb_ipc_enforced) && (folder_smb_use_smb2_negotiation==comp.folder_smb_use_smb2_negotiation) ) { if (task_type.equals(SyncTaskItem.SYNC_TASK_TYPE_ARCHIVE)) { + cu.addDebugMsg(3, "W", "SyncFolderEditValue.isSame archive_file_append_suffix_digit: "+archive_file_append_suffix_digit + "=" + comp.archive_file_append_suffix_digit); + cu.addDebugMsg(3, "W", "SyncFolderEditValue.isSame archive_file_rename_template: "+archive_file_rename_template + "=" + comp.archive_file_rename_template); + cu.addDebugMsg(3, "W", "SyncFolderEditValue.isSame archive_ignore_source_directory_hiearachy: "+archive_ignore_source_directory_hiearachy + "=" + comp.archive_ignore_source_directory_hiearachy); + if (archive_file_append_suffix_digit.equals(comp.archive_file_append_suffix_digit) && // archive_retention_period.equals(comp.archive_retention_period) && archive_file_rename_template.equals(comp.archive_file_rename_template) && @@ -5206,6 +5308,15 @@ public boolean isSame(SyncFolderEditValue comp) { } } } else if (folder_type.equals(SyncTaskItem.SYNC_FOLDER_TYPE_ZIP)) { + cu.addDebugMsg(3, "W", "SyncFolderEditValue.isSame folder_type: "+folder_type + "=" + comp.folder_type); + cu.addDebugMsg(3, "W", "SyncFolderEditValue.isSame isChanged: "+isChanged + "=" + comp.isChanged); + cu.addDebugMsg(3, "W", "SyncFolderEditValue.isSame folder_directory: "+folder_directory + "=" + comp.folder_directory); + cu.addDebugMsg(3, "W", "SyncFolderEditValue.isSame folder_storage_uuid: "+folder_storage_uuid + "=" + comp.folder_storage_uuid); + cu.addDebugMsg(3, "W", "SyncFolderEditValue.isSame zip_comp_level: "+zip_comp_level + "=" + comp.zip_comp_level); + cu.addDebugMsg(3, "W", "SyncFolderEditValue.isSame zip_enc_method: "+zip_enc_method + "=" + comp.zip_enc_method); + cu.addDebugMsg(3, "W", "SyncFolderEditValue.isSame zip_file_name: "+zip_file_name + "=" + comp.zip_file_name); + cu.addDebugMsg(3, "W", "SyncFolderEditValue.isSame zip_file_password: "+zip_file_password + "=" + comp.zip_file_password); + if (folder_type.equals(comp.folder_type) && isChanged==comp.isChanged && folder_directory.equals(comp.folder_directory) && diff --git a/app/src/main/java/com/sentaroh/android/SMBSync3/TaskListAdapter.java b/app/src/main/java/com/sentaroh/android/SMBSync3/TaskListAdapter.java index 31e58625..15a7ce1d 100644 --- a/app/src/main/java/com/sentaroh/android/SMBSync3/TaskListAdapter.java +++ b/app/src/main/java/com/sentaroh/android/SMBSync3/TaskListAdapter.java @@ -217,7 +217,7 @@ final public View getView(int position, View convertView, ViewGroup parent) { if (o != null) { boolean sync_btn_disable=false; - holder.ll_view.setBackgroundDrawable(mDefaultBackground); + holder.ll_view.setBackground(mDefaultBackground); // holder.ib_row_sync.setBackgroundDrawable(ib_default); String act = ""; diff --git a/app/src/main/java/com/sentaroh/android/SMBSync3/TaskListImportExport.java b/app/src/main/java/com/sentaroh/android/SMBSync3/TaskListImportExport.java index 3b485cab..c277878a 100644 --- a/app/src/main/java/com/sentaroh/android/SMBSync3/TaskListImportExport.java +++ b/app/src/main/java/com/sentaroh/android/SMBSync3/TaskListImportExport.java @@ -590,7 +590,7 @@ public void promptPasswordForImport(SafFile3 sf, String enc_data, final NotifyEv final CheckedTextView ctv_protect = (CheckedTextView) dialog.findViewById(R.id.password_input_ctv_protect); final Button btn_ok = (Button) dialog.findViewById(R.id.password_input_ok_btn); final Button btn_cancel = (Button) dialog.findViewById(R.id.password_input_cancel_btn); - final TextInputLayout ll_password_view=(TextInputLayout)dialog.findViewById(R.id.password_input_password_view); +// final TextInputLayout ll_password_view=(TextInputLayout)dialog.findViewById(R.id.password_input_password_view); final TextInputEditText et_password = (TextInputEditText) dialog.findViewById(R.id.password_input_password); final TextInputLayout ll_confirm_view=(TextInputLayout)dialog.findViewById(R.id.password_input_password_confirm_view); final TextInputEditText et_confirm = (TextInputEditText) dialog.findViewById(R.id.password_input_password_confirm); @@ -603,6 +603,9 @@ public void promptPasswordForImport(SafFile3 sf, String enc_data, final NotifyEv CommonDialog.setDlgBoxSizeCompactWithInput(dialog); ll_confirm_view.setVisibility(TextInputLayout.GONE); + +/* + // Mod: allow copy/paste on password field for import encryped app settings ll_password_view.setEndIconOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { @@ -632,7 +635,7 @@ public void onDestroyActionMode(ActionMode mode) {} } } }); - +*/ CommonUtilities.setViewEnabled(mActivity, btn_ok, false); et_password.addTextChangedListener(new TextWatcher() { @Override @@ -731,44 +734,48 @@ public void onClick(View v) { } }); + //settingExportedTaskEncryptRequired: Setting to remember last user choice (encrypt or not exported config) + // only valid for current app session, until app is exited ctv_protect.setChecked(mGp.settingExportedTaskEncryptRequired); ThreadCtrl disable_text_watcher=new ThreadCtrl(); - ll_password_view.setPasswordVisibilityToggleEnabled(false); -// ll_password_view.setEndIconOnClickListener(new View.OnClickListener() { -// @Override -// public void onClick(View v) { -// disable_text_watcher.setDisabled(); -// if (et_password.getTransformationMethod()!=null) { -// et_password.setTransformationMethod(null); -// ll_confirm_view.setVisibility(TextInputLayout.GONE); -// et_password.setCustomSelectionActionModeCallback(new ActionMode.Callback() { -// @Override -// public boolean onCreateActionMode(ActionMode mode, Menu menu) { -// return true; -// } -// @Override -// public boolean onPrepareActionMode(ActionMode mode, Menu menu) { -// menu.removeItem(android.R.id.cut); -// menu.removeItem(android.R.id.copy); -// menu.removeItem(android.R.id.shareText); -// return true; -// } -// @Override -// public boolean onActionItemClicked(ActionMode mode, MenuItem item) { -// return false; -// } -// @Override -// public void onDestroyActionMode(ActionMode mode) {} -// }); -// } else { -// et_password.setTransformationMethod(new PasswordTransformationMethod()); -// ll_confirm_view.setVisibility(TextInputLayout.VISIBLE); -// } -// disable_text_watcher.setEnabled(); -// setPasswordPromptOkButton(dialog); -// } -// }); + // Mod: enable password confirmation field toggle and copy/paste when exporting settings with password + ll_password_view.setEndIconOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + disable_text_watcher.setDisabled(); + if (et_password.getTransformationMethod()!=null) { + et_password.setTransformationMethod(null); + ll_confirm_view.setVisibility(TextInputLayout.GONE); +/* + et_password.setCustomSelectionActionModeCallback(new ActionMode.Callback() { + @Override + public boolean onCreateActionMode(ActionMode mode, Menu menu) { + return true; + } + @Override + public boolean onPrepareActionMode(ActionMode mode, Menu menu) { + menu.removeItem(android.R.id.cut); + menu.removeItem(android.R.id.copy); + menu.removeItem(android.R.id.shareText); + return true; + } + @Override + public boolean onActionItemClicked(ActionMode mode, MenuItem item) { + return false; + } + @Override + public void onDestroyActionMode(ActionMode mode) {} + }); +*/ + } else { + et_password.setTransformationMethod(new PasswordTransformationMethod()); + ll_confirm_view.setVisibility(TextInputLayout.VISIBLE); + } + disable_text_watcher.setEnabled(); + setPasswordPromptOkButton(dialog); + } + }); setPasswordFieldVisibility(dialog, mGp.settingExportedTaskEncryptRequired); @@ -873,7 +880,7 @@ private void setPasswordFieldVisibility(Dialog dialog, boolean isChecked) { private void setPasswordPromptOkButton(Dialog dialog) { final TextView dlg_msg = (TextView) dialog.findViewById(R.id.password_input_msg); final Button btn_ok = (Button) dialog.findViewById(R.id.password_input_ok_btn); - final TextInputLayout ll_password_view=(TextInputLayout)dialog.findViewById(R.id.password_input_password_view); +// final TextInputLayout ll_password_view=(TextInputLayout)dialog.findViewById(R.id.password_input_password_view); final TextInputEditText et_password = (TextInputEditText) dialog.findViewById(R.id.password_input_password); final TextInputLayout ll_confirm_view=(TextInputLayout)dialog.findViewById(R.id.password_input_password_confirm_view); final TextInputEditText et_confirm = (TextInputEditText) dialog.findViewById(R.id.password_input_password_confirm); @@ -1201,7 +1208,6 @@ public void negativeResponse(Context c, Object[] o) { } else { ntfy.notifyToListener(true, null); } - } final static private String CONFIG_FILE_NAME = "config.xml"; diff --git a/app/src/main/java/com/sentaroh/android/SMBSync3/TaskListUtils.java b/app/src/main/java/com/sentaroh/android/SMBSync3/TaskListUtils.java index 7fb62aa8..841ff80f 100644 --- a/app/src/main/java/com/sentaroh/android/SMBSync3/TaskListUtils.java +++ b/app/src/main/java/com/sentaroh/android/SMBSync3/TaskListUtils.java @@ -76,6 +76,7 @@ this software and associated documentation files (the "Software"), to deal import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; +import java.util.List; import static android.view.KeyEvent.KEYCODE_BACK; import static com.sentaroh.android.SMBSync3.Constants.DIRECTORY_FILTER_MATCH_ANY_WHERE_PREFIX; @@ -311,48 +312,56 @@ public void onCancel(DialogInterface arg0) { } }); dialog.show(); - } - public void invokeSelectSmbShareDlg(Dialog dialog) { -// final TextView dlg_msg=(TextView) dialog.findViewById(R.id.edit_sync_folder_dlg_msg); - - final Spinner sp_sync_folder_smb_proto = (Spinner) dialog.findViewById(R.id.edit_sync_folder_dlg_smb_protocol); - final EditText edituser = (EditText) dialog.findViewById(R.id.edit_sync_folder_dlg_remote_user); - final EditText editpass = (EditText) dialog.findViewById(R.id.edit_sync_folder_dlg_remote_pass); - final EditText editshare = (EditText) dialog.findViewById(R.id.edit_sync_folder_dlg_share_name); - final EditText edithost = (EditText) dialog.findViewById(R.id.edit_sync_folder_dlg_remote_server); - final CheckedTextView ctv_use_userpass = (CheckedTextView) dialog.findViewById(R.id.edit_sync_folder_dlg_ctv_use_user_pass); - final EditText editport = (EditText) dialog.findViewById(R.id.edit_sync_folder_dlg_remote_port); - final CheckedTextView ctv_use_port_number = (CheckedTextView) dialog.findViewById(R.id.edit_sync_folder_dlg_ctv_use_remote_port_number); -// final CheckedTextView ctv_sync_folder_smb_ipc_enforced = (CheckedTextView) dialog.findViewById(R.id.edit_sync_folder_dlg_ctv_smb_ipc_signing_enforced); -// final CheckedTextView ctv_sync_folder_smb_use_smb2_negotiation = (CheckedTextView) dialog.findViewById(R.id.edit_sync_folder_dlg_ctv_smb_use_smb2_negotiation); - String remote_addr="", remote_user = "", remote_pass = "", remote_host=""; - - if (ctv_use_userpass.isChecked()) { - remote_user = edituser.getText().toString().trim(); - remote_pass = editpass.getText().toString(); - } - - final String smb_proto=(String)sp_sync_folder_smb_proto.getSelectedItem(); -// final boolean ipc_enforced=ctv_sync_folder_smb_ipc_enforced.isChecked(); -// final boolean smb2_negotiation=ctv_sync_folder_smb_use_smb2_negotiation.isChecked(); - String host=edithost.getText().toString().trim(); + //public void invokeSelectSmbShareDlg(Dialog dialog, final NotifyEvent p_ntfy) { + public void invokeSelectSmbShareDlg(final String remote_host, final String smb_proto, final String remote_port, final String remote_user, final String remote_pass, final String share_name, final NotifyEvent p_ntfy) { + //final TextView dlg_msg=(TextView) dialog.findViewById(R.id.edit_sync_folder_dlg_msg); + + //final Spinner sp_sync_folder_smb_proto = (Spinner) dialog.findViewById(R.id.edit_sync_folder_dlg_smb_protocol); + //final EditText edituser = (EditText) dialog.findViewById(R.id.edit_sync_folder_dlg_remote_user); + //final EditText editpass = (EditText) dialog.findViewById(R.id.edit_sync_folder_dlg_remote_pass); + //final EditText editshare = (EditText) dialog.findViewById(R.id.edit_sync_folder_dlg_share_name); + //final EditText edithost = (EditText) dialog.findViewById(R.id.edit_sync_folder_dlg_remote_server); + //final CheckedTextView ctv_use_userpass = (CheckedTextView) dialog.findViewById(R.id.edit_sync_folder_dlg_ctv_use_user_pass); + //final EditText editport = (EditText) dialog.findViewById(R.id.edit_sync_folder_dlg_remote_port); + //final CheckedTextView ctv_use_port_number = (CheckedTextView) dialog.findViewById(R.id.edit_sync_folder_dlg_ctv_use_remote_port_number); + ////final CheckedTextView ctv_sync_folder_smb_ipc_enforced = (CheckedTextView) dialog.findViewById(R.id.edit_sync_folder_dlg_ctv_smb_ipc_signing_enforced); + //final CheckedTextView ctv_sync_folder_smb_use_smb2_negotiation = (CheckedTextView) dialog.findViewById(R.id.edit_sync_folder_dlg_ctv_smb_use_smb2_negotiation); + + //final String smb_proto=(String)sp_sync_folder_smb_proto.getSelectedItem(); + //final boolean ipc_enforced=ctv_sync_folder_smb_ipc_enforced.isChecked(); + //final boolean smb2_negotiation=ctv_sync_folder_smb_use_smb2_negotiation.isChecked(); + + SmbServerInfo ssi = new SmbServerInfo(); + ssi.serverHostName = remote_host; + ssi.serverProtocol = smb_proto; + ssi.serverPort = remote_port; + ssi.serverAccountName = remote_user; + ssi.serverAccountPassword = remote_pass; + ssi.serverShareName = share_name; - SmbServerInfo ssi=new SmbServerInfo(); - ssi.serverHostName= edithost.getText().toString(); - ssi.serverShareName=editshare.getText().toString();; - if (ctv_use_port_number.isChecked() && editport.getText().length() > 0) ssi.serverPort = editport.getText().toString(); - ssi.serverProtocol=smb_proto; - ssi.serverAccountName=remote_user; - ssi.serverAccountPassword=remote_pass; - - NotifyEvent ntfy = new NotifyEvent(mActivity); //Listen setRemoteShare response + NotifyEvent ntfy = new NotifyEvent(mActivity); ntfy.setListener(new NotifyEvent.NotifyEventListener() { @Override public void positiveResponse(Context arg0, Object[] arg1) { - editshare.setText((String) arg1[0]); + //editshare.setText((String) arg1[0]); + //String selected_share_name = (String) arg1[0]; + List> index_and_shares_lists = (List>) arg1[0]; + List selected_index_list = index_and_shares_lists.get(0); + List shares_list = index_and_shares_lists.get(1); + + int selected_index = 0; + try { + selected_index = Integer.parseInt(selected_index_list.get(0)); + } catch (NumberFormatException e) { + mUtil.addDebugMsg(1, "E", "invokeSelectSmbShareDlg: Integer Expected. selected_index="+selected_index_list.get(0)); + selected_index = 0; + } + + String selected_share_name = shares_list.get(selected_index); + p_ntfy.notifyToListener(true, new Object[]{new String[]{selected_share_name}}); } @Override @@ -846,45 +855,45 @@ private void isRemoteItemExists(SmbServerInfo ssi, final String new_dir, final N final Dialog dialog=CommonDialog.showProgressSpinIndicator(mActivity); dialog.show(); Thread th=new Thread(){ - @Override - public void run() { - try { - JcifsAuth auth=null; - if (ssi.serverProtocol.equals(SyncTaskItem.SYNC_FOLDER_SMB_PROTOCOL_SMB1)) { - auth=new JcifsAuth(JcifsAuth.JCIFS_FILE_SMB1, ssi.serverDomainName, ssi.serverAccountName, ssi.serverAccountPassword); - } else { - auth=new JcifsAuth(SyncTaskItem.SYNC_FOLDER_SMB_PROTOCOL_SMB23, ssi.serverDomainName, ssi.serverAccountName, ssi.serverAccountPassword); - } - JcifsFile jf=new JcifsFile(new_dir, auth); - if (jf.exists()) p_ntfy.notifyToListener(true, new Object[] {true}); - else p_ntfy.notifyToListener(true, new Object[] {false}); - } catch (MalformedURLException e) { - e.printStackTrace(); - mUtil.addDebugMsg(1, "E", e.toString()); - p_ntfy.notifyToListener(false, new Object[]{e.toString()}); - } catch (JcifsException e) { - e.printStackTrace(); - String suggest_msg=getJcifsErrorSugestionMessage(mActivity, MiscUtil.getStackTraceString(e)); - String cause=""; - String un=""; - if (mGp.settingSecurityReinitSmbAccountPasswordValue && !mGp.settingSecurityApplicationPasswordHashValue.equals("")) { - if (ssi.serverAccountName!=null) un=(ssi.serverAccountName.equals(""))?"":"????????"; - else un=null; - } else { - un=ssi.serverAccountName; - } - String[] e_msg= JcifsUtil.analyzeNtStatusCode(e, new_dir, un); - if (e.getCause()!=null) { - String tc=e.getCause().toString(); - cause=tc.substring(tc.indexOf(":")+1); - e_msg[0]=cause+"\n"+e_msg[0]; - } - String error_msg=suggest_msg.equals("")?e_msg[0]:suggest_msg+"\n"+e_msg[0]; - mUtil.addDebugMsg(1, "E", error_msg); - p_ntfy.notifyToListener(false, new Object[]{error_msg}); - } - dialog.dismiss(); - } + @Override + public void run() { + try { + JcifsAuth auth=null; + if (ssi.serverProtocol.equals(SyncTaskItem.SYNC_FOLDER_SMB_PROTOCOL_SMB1)) { + auth=new JcifsAuth(JcifsAuth.JCIFS_FILE_SMB1, ssi.serverDomainName, ssi.serverAccountName, ssi.serverAccountPassword); + } else { + auth=new JcifsAuth(SyncTaskItem.SYNC_FOLDER_SMB_PROTOCOL_SMB23, ssi.serverDomainName, ssi.serverAccountName, ssi.serverAccountPassword); + } + JcifsFile jf=new JcifsFile(new_dir, auth); + if (jf.exists()) p_ntfy.notifyToListener(true, new Object[] {true}); + else p_ntfy.notifyToListener(true, new Object[] {false}); + } catch (MalformedURLException e) { + e.printStackTrace(); + mUtil.addDebugMsg(1, "E", e.toString()); + p_ntfy.notifyToListener(false, new Object[]{e.toString()}); + } catch (JcifsException e) { + e.printStackTrace(); + String suggest_msg=getJcifsErrorSugestionMessage(mActivity, MiscUtil.getStackTraceString(e)); + String cause=""; + String un=""; + if (mGp.settingSecurityReinitSmbAccountPasswordValue && !mGp.settingSecurityApplicationPasswordHashValue.equals("")) { + if (ssi.serverAccountName!=null) un=(ssi.serverAccountName.equals(""))?"":"????????"; + else un=null; + } else { + un=ssi.serverAccountName; + } + String[] e_msg= JcifsUtil.analyzeNtStatusCode(e, new_dir, un); + if (e.getCause()!=null) { + String tc=e.getCause().toString(); + cause=tc.substring(tc.indexOf(":")+1); + e_msg[0]=cause+"\n"+e_msg[0]; + } + String error_msg=suggest_msg.equals("")?e_msg[0]:suggest_msg+"\n"+e_msg[0]; + mUtil.addDebugMsg(1, "E", error_msg); + p_ntfy.notifyToListener(false, new Object[]{error_msg}); + } + dialog.dismiss(); + } }; th.start(); } @@ -1116,7 +1125,7 @@ public void afterTextChanged(Editable s) { if (!add_exclude_btn.isChecked()) { add_exclude_btn.setChecked(true); mUtil.showCommonDialog(false, "W", - mActivity.getString(R.string.msgs_filter_list_match_any_where_change_to_exclude, filter), "", null); + String.format(mActivity.getString(R.string.msgs_filter_list_match_any_where_change_to_exclude), filter), "", null); } } else { CommonUtilities.setViewEnabled(mActivity, add_include_btn, true); @@ -1898,7 +1907,7 @@ public void afterTextChanged(Editable s) { if (!rb_exclude.isChecked()) { rb_exclude.setChecked(true); mUtil.showCommonDialog(false, "W", - mActivity.getString(R.string.msgs_filter_list_match_any_where_change_to_exclude, newfilter), "", null); + String.format(mActivity.getString(R.string.msgs_filter_list_match_any_where_change_to_exclude), newfilter), "", null); } } else { CommonUtilities.setViewEnabled(mActivity, rb_include, true); @@ -1998,7 +2007,7 @@ public void onClick(View v) { if (org_inc) { CommonDialog.showCommonDialog(mActivity.getSupportFragmentManager(), false, "W", mActivity.getString(R.string.msgs_filter_edit_dlg_title), - mActivity.getString(R.string.msgs_filter_list_match_any_where_change_to_exclude, fli.getFilter()), null); + String.format(mActivity.getString(R.string.msgs_filter_list_match_any_where_change_to_exclude), fli.getFilter()), null); } } @@ -2745,15 +2754,15 @@ public void selectRemoteShareDlg(SmbServerInfo ssi, final NotifyEvent p_ntfy) { @SuppressWarnings("unchecked") @Override public void positiveResponse(Context c, Object[] o) { - final ArrayList rows = new ArrayList(); + final ArrayList shares_list = new ArrayList(); ArrayList rfl = (ArrayList) o[0]; - for (TreeFilelistItem item:rfl) rows.add(item.getName()); - if (rows.size() < 1) { + for (TreeFilelistItem item:rfl) shares_list.add(item.getName()); + if (shares_list.size() < 1) { mUtil.showCommonDialog(false, "W", mActivity.getString(R.string.msgs_share_list_not_obtained), "", null); return; } - Collections.sort(rows, String.CASE_INSENSITIVE_ORDER); + Collections.sort(shares_list, String.CASE_INSENSITIVE_ORDER); //カスタムダイアログの生成 final Dialog dialog = new Dialog(mActivity, mGp.applicationTheme); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); @@ -2782,7 +2791,7 @@ public void positiveResponse(Context c, Object[] o) { final ListView lv = (ListView) dialog.findViewById(R.id.list_view); lv.setAdapter(new ArrayAdapter(mActivity, - android.R.layout.simple_list_item_single_choice, rows)); + android.R.layout.simple_list_item_single_choice, shares_list)); lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE); lv.setScrollingCacheEnabled(false); lv.setScrollbarFadingEnabled(false); @@ -2805,9 +2814,23 @@ public void onClick(View v) { public void onClick(View v) { dialog.dismiss(); SparseBooleanArray checked = lv.getCheckedItemPositions(); - for (int i = 0; i <= rows.size(); i++) { + + final List> index_and_shares_lists = new ArrayList>(); + final ArrayList selected_index_list = new ArrayList(); + for (int i = 0; i <= shares_list.size(); i++) { if (checked.get(i) == true) { - p_ntfy.notifyToListener(true, new Object[]{rows.get(i)}); + selected_index_list.add(String.valueOf(i)); + index_and_shares_lists.add(selected_index_list); + index_and_shares_lists.add(shares_list); + if (mUtil.getLogLevel() >= 3) { + for (List list:index_and_shares_lists) { + for (String item:list) { + mUtil.addDebugMsg(3, "I", "selectRemoteShareDlg p_notify: " + item); + } + } + } + p_ntfy.notifyToListener(true, new Object[]{index_and_shares_lists}); + //p_ntfy.notifyToListener(true, new Object[]{shares_list.get(i)}); break; } } diff --git a/app/src/main/res/drawable/ic_android.xml b/app/src/main/res/drawable/ic_android.xml new file mode 100644 index 00000000..7fcda2e0 --- /dev/null +++ b/app/src/main/res/drawable/ic_android.xml @@ -0,0 +1,24 @@ + + + + diff --git a/app/src/main/res/layout-large/edit_sync_folder_edit_keywor_dlg.xml b/app/src/main/res/layout-large/edit_sync_folder_edit_keywor_dlg.xml index 02bc6642..45072828 100644 --- a/app/src/main/res/layout-large/edit_sync_folder_edit_keywor_dlg.xml +++ b/app/src/main/res/layout-large/edit_sync_folder_edit_keywor_dlg.xml @@ -427,7 +427,7 @@ android:layout_height="wrap_content" android:layout_marginLeft="20dp" android:layout_marginRight="5dp" - android:text="/storage/emulated/0/DCIM" + android:text="DSC-001" android:textAppearance="?android:attr/textAppearanceMedium"/> + app:endIconMode="password_toggle"> + android:orientation="horizontal" + app:endIconMode="password_toggle"> + android:inputType="textPassword" > @@ -81,7 +81,7 @@ android:longClickable="false" android:ems="10" android:hint="@string/msgs_export_import_pswd_hint_confirm" - android:inputType="text|textPassword" /> + android:inputType="textPassword" /> - - - - - \ No newline at end of file diff --git a/app/src/main/res/layout/scan_address_result_list_item.xml b/app/src/main/res/layout/scan_address_result_list_item.xml index f90d0323..ef035167 100644 --- a/app/src/main/res/layout/scan_address_result_list_item.xml +++ b/app/src/main/res/layout/scan_address_result_list_item.xml @@ -2,7 +2,7 @@ @@ -22,9 +24,10 @@ android:id="@+id/scan_result_list_item_server_name" android:layout_width="0dp" android:layout_height="wrap_content" + android:layout_marginRight="10dp" android:layout_gravity="center_vertical" - android:layout_weight="1" android:gravity="center_vertical|left" + android:layout_weight="1" android:lines="2" android:text="ABCDEFGHIJKLMN" android:textAppearance="?android:attr/textAppearanceMedium" /> diff --git a/app/src/main/res/layout/scan_smb_server_parm_dlg.xml b/app/src/main/res/layout/scan_smb_server_parm_dlg.xml index c111a466..6b1f7771 100644 --- a/app/src/main/res/layout/scan_smb_server_parm_dlg.xml +++ b/app/src/main/res/layout/scan_smb_server_parm_dlg.xml @@ -16,7 +16,7 @@ - - - - - + + + + + android:layout_marginLeft="20dp" + android:orientation="horizontal"> + + + + + + + + + android:gravity="left" + android:text="@string/msgs_task_edit_sync_folder_dlg_smb_protocol_hdr" + android:textAppearance="?android:attr/textAppearanceLarge" + tools:ignore="HardcodedText,RtlHardcoded" /> + + android:id="@+id/scan_smb_server_parm_dlg_smb_server_smb_protocol_smb_rg" + android:layout_width="match_parent" + android:layout_height="match_parent" + android:layout_marginLeft="20dp" + android:orientation="horizontal"> + android:text="SMBv1" /> + android:text="SMBv2/3" /> - - + - - - - - - - - + + + + + + + - + - + + android:hint="@string/msgs_task_edit_sync_folder_dlg_remote_smb_password" + android:inputType="textPassword" + android:textAppearance="?android:attr/textAppearanceMedium" /> + + - - - - - +