commit 548759c61ea948d2ed9a5ca3be879b5e77c0f787 Author: Erik C. Thauvin Date: Wed Aug 24 19:05:38 2016 -0700 Initial commit. diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..57041ce --- /dev/null +++ b/.gitignore @@ -0,0 +1,10 @@ +*.iml +.gradle +/local.properties +/.idea/workspace.xml +/.idea/libraries +.DS_Store +/build +/captures +Thumbs.db +ehthumbs.db \ No newline at end of file diff --git a/.idea/.name b/.idea/.name new file mode 100644 index 0000000..8d09339 --- /dev/null +++ b/.idea/.name @@ -0,0 +1 @@ +TESRemoteProgrammer \ No newline at end of file diff --git a/.idea/compiler.xml b/.idea/compiler.xml new file mode 100644 index 0000000..9a8b7e5 --- /dev/null +++ b/.idea/compiler.xml @@ -0,0 +1,22 @@ + + + + + \ No newline at end of file diff --git a/.idea/copyright/Erik_s_Copyright_Notice.xml b/.idea/copyright/Erik_s_Copyright_Notice.xml new file mode 100644 index 0000000..5f24d5a --- /dev/null +++ b/.idea/copyright/Erik_s_Copyright_Notice.xml @@ -0,0 +1,6 @@ + + + + \ No newline at end of file diff --git a/.idea/copyright/profiles_settings.xml b/.idea/copyright/profiles_settings.xml new file mode 100644 index 0000000..3807500 --- /dev/null +++ b/.idea/copyright/profiles_settings.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/encodings.xml b/.idea/encodings.xml new file mode 100644 index 0000000..97626ba --- /dev/null +++ b/.idea/encodings.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.idea/gradle.xml b/.idea/gradle.xml new file mode 100644 index 0000000..508b3d9 --- /dev/null +++ b/.idea/gradle.xml @@ -0,0 +1,23 @@ + + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..95f0f03 --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,46 @@ + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000..d5cbd39 --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/.idea/runConfigurations.xml b/.idea/runConfigurations.xml new file mode 100644 index 0000000..7f68460 --- /dev/null +++ b/.idea/runConfigurations.xml @@ -0,0 +1,12 @@ + + + + + + \ No newline at end of file diff --git a/.idea/scopes/Source.xml b/.idea/scopes/Source.xml new file mode 100644 index 0000000..dabb296 --- /dev/null +++ b/.idea/scopes/Source.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md new file mode 100644 index 0000000..8a2f361 --- /dev/null +++ b/README.md @@ -0,0 +1,5 @@ +# Telephone Entry System Remote Programmer for Android + +![License](http://img.shields.io/:license-apache-blue.svg?style=flat-square)](http://www.apache.org/licenses/LICENSE-2.0.html) + +[![VersionEye Logo](/images/feature_graphic.png | width=800)] \ No newline at end of file diff --git a/app/.gitignore b/app/.gitignore new file mode 100644 index 0000000..796b96d --- /dev/null +++ b/app/.gitignore @@ -0,0 +1 @@ +/build diff --git a/app/build.gradle b/app/build.gradle new file mode 100644 index 0000000..4ccf0d1 --- /dev/null +++ b/app/build.gradle @@ -0,0 +1,56 @@ +apply plugin: 'com.android.application' +apply plugin: 'kotlin-android' + +android { + compileSdkVersion 24 + buildToolsVersion "24.0.1" + + defaultConfig { + applicationId "net.thauvin.erik.android.tesremoteprogrammer" + minSdkVersion 23 + targetSdkVersion 24 + versionCode 1 + versionName "1.0" + } + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + } + } + sourceSets { + main.java.srcDirs += 'src/main/kotlin' + } +} + +dependencies { + compile fileTree(dir: 'libs', include: ['*.jar']) + + testCompile 'junit:junit:4.12' + + compile 'com.android.support:support-v13:24.1.1' + compile 'com.android.support:appcompat-v7:24.1.1' + compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" + compile 'org.jetbrains.anko:anko-sdk23:0.9' + compile 'org.jetbrains.anko:anko-appcompat-v7:0.9' + compile 'org.jetbrains.anko:anko-support-v4:0.9' + compile 'org.jetbrains.anko:anko-design:0.9' + compile 'com.android.support:design:24.1.1' + compile group: 'com.google.code.gson', name: 'gson', version: '2.7' + + + // https://github.com/JakeWharton/ViewPagerIndicator + compile 'fr.avianey.com.viewpagerindicator:library:2.4.1.1@aar' + + // https://github.com/hotchemi/PermissionsDispatcher + compile 'com.github.hotchemi:permissionsdispatcher:2.1.3' + kapt 'com.github.hotchemi:permissionsdispatcher-processor:2.1.3' +} + +repositories { + mavenCentral() +} + +kapt { + generateStubs = true +} \ No newline at end of file diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro new file mode 100644 index 0000000..668f307 --- /dev/null +++ b/app/proguard-rules.pro @@ -0,0 +1,17 @@ +# Add project specific ProGuard rules here. +# By default, the flags in this file are appended to flags specified +# in C:\Users\erik\AppData\Local\Android\android-sdk/tools/proguard/proguard-android.txt +# You can edit the include path and order by changing the proguardFiles +# directive in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# Add any project specific keep options here: + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..4a032d0 --- /dev/null +++ b/app/src/main/AndroidManifest.xml @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/java/net/thauvin/erik/android/tesremoteprogrammer/MainActivity.kt b/app/src/main/java/net/thauvin/erik/android/tesremoteprogrammer/MainActivity.kt new file mode 100644 index 0000000..5e815d8 --- /dev/null +++ b/app/src/main/java/net/thauvin/erik/android/tesremoteprogrammer/MainActivity.kt @@ -0,0 +1,385 @@ +/* + * MainActivity.kt + * + * Copyright 2016 Erik C. Thauvin (erik@thauvin.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.thauvin.erik.android.tesremoteprogrammer + +import android.Manifest +import android.app.Activity +import android.app.AlertDialog +import android.content.Context +import android.content.Intent +import android.graphics.Typeface +import android.os.Bundle +import android.support.v7.app.AppCompatActivity +import android.text.Html +import android.text.InputFilter +import android.text.InputType +import android.text.TextUtils +import android.text.method.LinkMovementMethod +import android.util.TypedValue +import android.view.Menu +import android.view.MenuItem +import android.view.inputmethod.EditorInfo +import android.view.inputmethod.InputMethodManager +import android.widget.AdapterView +import android.widget.ArrayAdapter +import android.widget.EditText +import android.widget.TextView +import com.google.gson.Gson +import com.google.gson.JsonSyntaxException +import net.thauvin.erik.android.tesremoteprogrammer.models.Config +import net.thauvin.erik.android.tesremoteprogrammer.models.Configurations +import net.thauvin.erik.android.tesremoteprogrammer.util.Dtmf +import net.thauvin.erik.android.tesremoteprogrammer.util.plural +import org.jetbrains.anko.* +import org.jetbrains.anko.design.textInputLayout +import permissions.dispatcher.NeedsPermission +import permissions.dispatcher.RuntimePermissions +import java.io.FileNotFoundException +import java.io.InputStreamReader +import java.io.ObjectInputStream +import java.io.ObjectOutputStream +import java.util.* + +@RuntimePermissions +class MainActivity : AppCompatActivity(), AnkoLogger { + lateinit var config: Config + val configurations_data = "configurations.dat" + val current_config_data = "config.dat" + val read_request_code = 42 + + companion object { + val PAUSE = ',' + } + + override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { + if (requestCode == read_request_code && resultCode == Activity.RESULT_OK) { + if (data != null) { + MainActivityPermissionsDispatcher.validateConfigWithCheck(this, data) + } + } + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + + val fields = arrayListOf() + + loadConfig() + + verticalLayout { + padding = dip(20) + + textView { + text = config.params.name.toUpperCase() + bottomPadding = dip(5) + typeface = Typeface.DEFAULT_BOLD + setTextSize(TypedValue.COMPLEX_UNIT_DIP, 24f) + isFocusableInTouchMode = true + singleLine = true + ellipsize = TextUtils.TruncateAt.END + } + + textInputLayout { + horizontalPadding = dip(40) + val phone = editText() { + lparams(width = matchParent) + inputType = InputType.TYPE_CLASS_PHONE + hint = getString(R.string.hint_phone_number) + + if (config.params.phone.isNotBlank()) { + setText(config.params.phone) + } + + setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_call_black_24dp, 0) + setOnFocusChangeListener { view, hasFocus -> + if (!hasFocus) { + config.params.phone = (view as EditText).text.toString() + saveConfig() + } + } + } + fields.add(phone) + } + + textInputLayout { + horizontalPadding = dip(40) + val masterCode = editText() { + lparams(width = matchParent) + inputType = InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_VARIATION_PASSWORD + hint = getString(R.string.hint_master_code) + filters = arrayOf(InputFilter.LengthFilter(config.params.size)) + setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_verified_user_black_24dp, 0) + imeOptions = EditorInfo.IME_ACTION_DONE + + if (config.params.master.isNotBlank()) { + setText(config.params.master) + } + + setOnFocusChangeListener { view, hasFocus -> + if (!hasFocus) { + config.params.master = (view as EditText).text.toString() + saveConfig() + } + } + + setOnEditorActionListener { v, id, event -> + if (id == EditorInfo.IME_ACTION_DONE) { + clearFocus() + val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager + imm.hideSoftInputFromWindow(windowToken, 0) + true + } else { + false + } + } + } + fields.add(masterCode) + } + + textView { + topPadding = dip(10) + text = getString(R.string.programming_heading) + setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18f) + typeface = Typeface.DEFAULT_BOLD + }.lparams(width = matchParent) + + val opts = config.opts.sorted() + val titles = arrayListOf() + opts.all { + titles.add(it.title) + } + + listView { + adapter = ArrayAdapter(this@MainActivity, android.R.layout.simple_list_item_1, titles) + isTextFilterEnabled = true + isScrollbarFadingEnabled = false + onItemClickListener = AdapterView.OnItemClickListener { parent, v, position, id -> + if (validateFields(fields, config.params.size)) { + startActivity( + "net.thauvin.erik.android.tesremoteprogrammer.models.Params" to config.params, + "net.thauvin.erik.android.tesremoteprogrammer.models.Option" to opts[position]) + } + } + }.lparams(width = matchParent) + } + } + + override fun onCreateOptionsMenu(menu: Menu?): Boolean { + menuInflater.inflate(R.menu.menu_main, menu) + return true + } + + override fun onOptionsItemSelected(item: MenuItem?): Boolean { + when (item?.itemId) { + R.id.action_about -> { + val alert = alert { + title(R.string.app_name) + message(Html.fromHtml( + getString(R.string.about_message, BuildConfig.VERSION_NAME))) + icon(R.mipmap.ic_launcher) + okButton {} + }.show() + (alert.dialog?.findViewById(android.R.id.message) as TextView) + .movementMethod = LinkMovementMethod.getInstance() + } + R.id.action_config -> { + val configs = loadConfigurations().configs + val keys = configs.keys + val checked = keys.indexOf(config.params.name) + val alert = AlertDialog.Builder(this) + + alert.setTitle(R.string.action_config) + + alert.setSingleChoiceItems(keys.toTypedArray(), checked, + { dialogInterface, i -> + if (i != checked) { + config = configs.getOrElse(keys.elementAt(i), defaultValue = { config }) + saveConfig() + this.recreate() + } + dialogInterface.dismiss() + }) + + alert.setNegativeButton(android.R.string.cancel, + { dialogInterface, i -> + dialogInterface.dismiss() + }) + + alert.setNeutralButton(R.string.dialog_import, + { dialogInterface, i -> + dialogInterface.dismiss() + val intent = Intent(Intent.ACTION_GET_CONTENT) + intent.addCategory(Intent.CATEGORY_OPENABLE) + intent.type = "application/json" + startActivityForResult(intent, read_request_code) + }) + + + alert.show() + + } + } + return super.onOptionsItemSelected(item) + } + + override fun onRequestPermissionsResult(requestCode: Int, + permissions: Array, + grantResults: IntArray) { + super.onRequestPermissionsResult(requestCode, permissions, grantResults) + MainActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults) + } + + fun loadConfigurations(): Configurations { + try { + ObjectInputStream(openFileInput(configurations_data)).use { + return it.readObject() as Configurations + } + } catch (ex: FileNotFoundException) { + return Configurations() + } + } + + fun loadConfig() { + try { + ObjectInputStream(openFileInput(current_config_data)).use { + config = it.readObject() as Config + } + } catch (ex: FileNotFoundException) { + config = Gson().fromJson(InputStreamReader(resources.openRawResource(R.raw.dks_1802_epd)), + Config::class.java) + + saveConfig() + } + } + + fun saveConfigurations(confs: Configurations) { + ObjectOutputStream(openFileOutput(configurations_data, Context.MODE_PRIVATE)).use { + it.writeObject(confs) + } + } + fun saveConfig() { + val confs = loadConfigurations() + confs.configs.put(config.params.name, config) + saveConfigurations(confs) + + ObjectOutputStream(openFileOutput(current_config_data, Context.MODE_PRIVATE)).use { + it.writeObject(config) + } + } + + @NeedsPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) + fun validateConfig(intent: Intent) { + val errors = StringBuilder() + + val tmp: Config? = try { + Gson().fromJson(InputStreamReader(contentResolver.openInputStream(intent.data)), + Config::class.java) + } catch (jse: JsonSyntaxException) { + val cause = jse.cause + if (cause != null) { + errors.append(cause.message) + } else { + errors.append(jse.message) + } + null + } + + if (tmp != null) { + with(tmp) { + if (params.name.isBlank()) { + errors.append(getString(R.string.validate_missing_param, "name")) + } + + if (params.size < 1) { + errors.append(getString(R.string.validate_invalid_param, "size")) + } + + if (params.star.isBlank()) { + errors.append(getString(R.string.validate_missing_param, "star")) + } + + if (opts.size == 0) { + errors.append(getString(R.string.validate_missing_ops)) + } + + opts.forEachIndexed { i, option -> + if (option.fields.size == 0) { + errors.append(getString(R.string.validate_missing_fields, i + 1)) + } + + option.fields.forEachIndexed { j, field -> + if (field.size <= 0) { + errors.append(getString(R.string.validate_invalid_attr, i + 1, j + 1, "size")) + } + + if (!field.alpha) { + if (field.min >= 0 || field.max >= 0) { + if (field.max < 1) { + errors.append(getString(R.string.validate_invalid_attr, i + 1, j + 1, "max")) + } else if (field.min < 0) { + errors.append(getString(R.string.validate_invalid_attr, i + 1, j + 1, "min")) + } else if (field.min > field.max) { + errors.append(getString(R.string.validate_invalid_attr, i + 1, j + 1, "max/min")) + } + } + } + } + + val blank = "\\0" + val dtmf = Dtmf.mock(option, blank) + if (!Dtmf.validate(dtmf, "${MainActivity.PAUSE}${params.star}${params.hash}$blank")) { + errors.append(getString(R.string.validate_invalid_dtmf, i + 1, dtmf.replace(blank, "✓"))) + + } + } + } + + if (errors.length == 0) { + config = tmp + saveConfig() + recreate() + } + } + + if (errors.length > 0) { + alert { + title(R.string.alert_config_error) + message(Html.fromHtml("$errors")) + cancelButton { } + }.show() + } + } + + fun validateFields(fields: ArrayList, size: Int): Boolean { + var isValid = true + + fields.forEach { + if (it.text.isNullOrBlank()) { + it.error = getString(R.string.error_required) + isValid = false + } + } + if (size > 0 && (fields[1].text.length != size)) { + isValid = false + fields[1].error = getString(R.string.error_invalid_size, size, + getString(R.string.error_digit).plural(size)) + } + + return isValid + } +} diff --git a/app/src/main/java/net/thauvin/erik/android/tesremoteprogrammer/ProgrammingActivity.kt b/app/src/main/java/net/thauvin/erik/android/tesremoteprogrammer/ProgrammingActivity.kt new file mode 100644 index 0000000..434243a --- /dev/null +++ b/app/src/main/java/net/thauvin/erik/android/tesremoteprogrammer/ProgrammingActivity.kt @@ -0,0 +1,232 @@ +/* + * ProgrammingActivity.kt + * + * Copyright 2016 Erik C. Thauvin (erik@thauvin.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.thauvin.erik.android.tesremoteprogrammer + +import android.Manifest +import android.content.Context +import android.content.res.ColorStateList +import android.graphics.Color +import android.graphics.Typeface +import android.os.Bundle +import android.support.design.widget.Snackbar +import android.support.v7.app.AppCompatActivity +import android.text.InputFilter +import android.text.InputType +import android.text.TextUtils +import android.text.method.DigitsKeyListener +import android.util.TypedValue +import android.view.Gravity.* +import android.view.inputmethod.EditorInfo +import android.view.inputmethod.InputMethodManager +import android.widget.EditText +import net.thauvin.erik.android.tesremoteprogrammer.filters.AlphaFilter +import net.thauvin.erik.android.tesremoteprogrammer.filters.MinMaxFilter +import net.thauvin.erik.android.tesremoteprogrammer.models.Option +import net.thauvin.erik.android.tesremoteprogrammer.models.Params +import net.thauvin.erik.android.tesremoteprogrammer.util.Dtmf +import net.thauvin.erik.android.tesremoteprogrammer.util.plural +import net.thauvin.erik.android.tesremoteprogrammer.widget.ScrollAwareFABBehavior +import org.jetbrains.anko.* +import org.jetbrains.anko.design.coordinatorLayout +import org.jetbrains.anko.design.floatingActionButton +import org.jetbrains.anko.design.textInputLayout +import org.jetbrains.anko.support.v4.nestedScrollView +import permissions.dispatcher.NeedsPermission +import permissions.dispatcher.RuntimePermissions +import java.util.* + +@RuntimePermissions +class ProgrammingActivity : AppCompatActivity(), AnkoLogger { + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + + val params: Params = intent.extras.getParcelable("net.thauvin.erik.android.tesremoteprogrammer.models.Params") + val option: Option = intent.extras.getParcelable("net.thauvin.erik.android.tesremoteprogrammer.models.Option") + val fields = arrayListOf() + + coordinatorLayout { + + textView { + padding = dip(20) + text = option.title + setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20f) + typeface = Typeface.DEFAULT_BOLD + isFocusableInTouchMode = true + singleLine = true + ellipsize = TextUtils.TruncateAt.END + } + + nestedScrollView { + topPadding = dip(55) + horizontalPadding = dip(20) + + verticalLayout { + lparams(width = matchParent, height = wrapContent) + + + val it = option.fields.iterator() + while (it.hasNext()) { + val field = it.next() + + textInputLayout { + horizontalPadding = dip(40) + lparams(width = matchParent) + + val inputFilters: ArrayList = ArrayList() + + val editText = editText() { + hint = field.hint + + if (field.alpha) { + inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS + inputFilters.add(AlphaFilter()) + } else { + inputType = InputType.TYPE_CLASS_NUMBER + keyListener = DigitsKeyListener.getInstance("0,1,2,3,4,5,6,7,8,9" + + if (field.hash) ",${params.hash}" else "") + if (field.max != -1 && field.min != -1) { + inputFilters.add(MinMaxFilter(field.min, field.max, field.size)) + } + } + + if (field.size != -1) { + inputFilters.add(InputFilter.LengthFilter(field.size)) + } + + if (inputFilters.isNotEmpty()) { + filters = inputFilters.toTypedArray() + } + + if (!it.hasNext()) { + imeOptions = EditorInfo.IME_ACTION_DONE + setOnEditorActionListener { v, id, event -> + if (id == EditorInfo.IME_ACTION_DONE) { + clearFocus() + val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager + imm.hideSoftInputFromWindow(windowToken, 0) + true + } else { + false + } + } + } + } + fields.add(editText) + } + } + } + }.lparams(width = matchParent, height = matchParent) + + floatingActionButton { + imageResource = R.drawable.ic_menu_dialpad_lt + + if (!option.nodial) { + backgroundTintList = ColorStateList.valueOf(Color.GRAY) + } + + onClick { + if (validateFields(fields, option)) { + val dtmf = Dtmf.build(params.master, params.star, option, fields) + if (Dtmf.validate(dtmf, "${MainActivity.PAUSE}${params.star}${params.hash}")) { + startActivity( + StepsActivity.EXTRA_STEPS to "$dtmf${MainActivity.PAUSE}${params.end}".split(',')) + } else { + Snackbar.make(this@coordinatorLayout, getString(R.string.error_invalid_dtmf, dtmf), + Snackbar.LENGTH_LONG).show() + } + } else { + Snackbar.make(this@coordinatorLayout, R.string.error_invalid_field, + Snackbar.LENGTH_LONG).show() + } + } + }.lparams(width = wrapContent, height = wrapContent) { + if (option.nodial) { + gravity = BOTTOM or END + rightMargin = dip(16) + } else { + gravity = BOTTOM or START + leftMargin = dip(16) + } + + bottomMargin = dip(16) + elevation = dip(6).toFloat() + behavior = ScrollAwareFABBehavior() + } + + if (!option.nodial) { + floatingActionButton { + imageResource = R.drawable.fab_ic_call + onClick { + if (validateFields(fields, option)) { + val dtmf = Dtmf.build(params.master, params.star, option, fields) + if (Dtmf.validate(dtmf, "${MainActivity.PAUSE}${params.star}${params.hash}")) { + ProgrammingActivityPermissionsDispatcher.callWithCheck( + this@ProgrammingActivity, params.phone, dtmf) + } else { + Snackbar.make(this@coordinatorLayout, getString(R.string.error_invalid_dtmf, dtmf), + Snackbar.LENGTH_LONG).show() + } + } else { + Snackbar.make(this@coordinatorLayout, R.string.error_invalid_field, + Snackbar.LENGTH_LONG).show() + } + } + }.lparams(width = wrapContent, height = wrapContent) { + gravity = BOTTOM or END + bottomMargin = dip(16) + rightMargin = dip(16) + elevation = dip(6).toFloat() + behavior = ScrollAwareFABBehavior() + } + } + } + } + + override fun onRequestPermissionsResult(requestCode: Int, + permissions: Array, + grantResults: IntArray) { + super.onRequestPermissionsResult(requestCode, permissions, grantResults) + ProgrammingActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults) + } + + @NeedsPermission(Manifest.permission.CALL_PHONE) + fun call(phone: String, dtmf: String) { + info("$phone${MainActivity.PAUSE}${MainActivity.PAUSE}$dtmf") + makeCall("$phone${MainActivity.PAUSE}${MainActivity.PAUSE}$dtmf") + } + + fun validateFields(fields: ArrayList, option: Option): Boolean { + var isValid = true + + fields.forEachIndexed { i, v -> + if (v.text.isNullOrBlank()) { + v.error = getString(R.string.error_required) + isValid = false + } else { + val size = option.fields[i].size + if (!option.fields[i].alpha && size > 0 && (v.length() != size)) { + v.error = getString(R.string.error_invalid_size, size, + getString(R.string.error_digit).plural(size)) + isValid = false + } + } + } + + return isValid + } +} diff --git a/app/src/main/java/net/thauvin/erik/android/tesremoteprogrammer/StepsActivity.java b/app/src/main/java/net/thauvin/erik/android/tesremoteprogrammer/StepsActivity.java new file mode 100644 index 0000000..034df6f --- /dev/null +++ b/app/src/main/java/net/thauvin/erik/android/tesremoteprogrammer/StepsActivity.java @@ -0,0 +1,74 @@ +/* + * StepsActivity.java + * + * Copyright 2016 Erik C. Thauvin (erik@thauvin.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.thauvin.erik.android.tesremoteprogrammer; + +import android.app.Fragment; +import android.app.FragmentManager; +import android.os.Bundle; +import android.support.v13.app.FragmentStatePagerAdapter; +import android.support.v4.app.FragmentActivity; +import android.support.v4.view.PagerAdapter; +import android.support.v4.view.ViewPager; + +import com.viewpagerindicator.UnderlinePageIndicator; + +import java.util.ArrayList; + +public class StepsActivity extends FragmentActivity { + + public static final String EXTRA_STEPS = "steps"; + + private final ArrayList steps = new ArrayList<>(); + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_steps); + + steps.clear(); + steps.addAll(getIntent().getExtras().getStringArrayList(EXTRA_STEPS)); + + final ViewPager pager = (ViewPager) findViewById(R.id.pager); + final PagerAdapter pagerAdapter = new StepsAdapter(getFragmentManager(), steps); + pager.setAdapter(pagerAdapter); + final UnderlinePageIndicator pageIndicator = (UnderlinePageIndicator) findViewById(R.id.indicator); + pageIndicator.setViewPager(pager, pager.getCurrentItem() - 1); + pageIndicator.setFades(false); + } + + private class StepsAdapter extends FragmentStatePagerAdapter { + private final ArrayList stepsArray = new ArrayList<>(); + + public StepsAdapter(FragmentManager fm, ArrayList steps) { + super(fm); + + stepsArray.clear(); + stepsArray.addAll(steps); + } + + @Override + public Fragment getItem(int position) { + return StepsFragment.create(position, stepsArray); + } + + @Override + public int getCount() { + return stepsArray.size(); + } + } +} diff --git a/app/src/main/java/net/thauvin/erik/android/tesremoteprogrammer/StepsFragment.java b/app/src/main/java/net/thauvin/erik/android/tesremoteprogrammer/StepsFragment.java new file mode 100644 index 0000000..27149ce --- /dev/null +++ b/app/src/main/java/net/thauvin/erik/android/tesremoteprogrammer/StepsFragment.java @@ -0,0 +1,67 @@ +/* + * StepsFragment.java + * + * Copyright 2016 Erik C. Thauvin (erik@thauvin.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.thauvin.erik.android.tesremoteprogrammer; + +import android.app.Fragment; +import android.os.Bundle; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.TextView; + +import java.util.ArrayList; + +public class StepsFragment extends Fragment { + public static final String ARG_PAGE = "page"; + private static final ArrayList stepsArray = new ArrayList<>(); + private int pageNumber; + + public StepsFragment() { + } + + public static StepsFragment create(int pageNumber, ArrayList steps) { + final StepsFragment fragment = new StepsFragment(); + Bundle args = new Bundle(); + + args.putInt(ARG_PAGE, pageNumber); + fragment.setArguments(args); + + stepsArray.clear(); + stepsArray.addAll(steps); + + return fragment; + } + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + pageNumber = getArguments().getInt(ARG_PAGE); + } + + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, + Bundle savedInstanceState) { + final ViewGroup rootView = (ViewGroup) inflater + .inflate(R.layout.fragment_steps, container, false); + + ((TextView) rootView.findViewById(R.id.frag_steps_title)).setText( + getString(R.string.title_template_step, pageNumber + 1, stepsArray.size())); + ((TextView) rootView.findViewById(R.id.frag_steps)).setText(stepsArray.get(pageNumber)); + return rootView; + } +} diff --git a/app/src/main/java/net/thauvin/erik/android/tesremoteprogrammer/filters/AlphaFilter.kt b/app/src/main/java/net/thauvin/erik/android/tesremoteprogrammer/filters/AlphaFilter.kt new file mode 100644 index 0000000..ae6a2d3 --- /dev/null +++ b/app/src/main/java/net/thauvin/erik/android/tesremoteprogrammer/filters/AlphaFilter.kt @@ -0,0 +1,51 @@ +/* + * AlphaFilter.kt + * + * Copyright 2016 Erik C. Thauvin (erik@thauvin.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.thauvin.erik.android.tesremoteprogrammer.filters + +import android.text.InputFilter +import android.text.SpannableStringBuilder +import android.text.Spanned + +class AlphaFilter : InputFilter { + override fun filter(source: CharSequence, + start: Int, + end: Int, + dest: Spanned, + dstart: Int, + dend: Int): CharSequence? { + + if (source is SpannableStringBuilder) { + for (i in end - 1 downTo start) { + val c = source[i] + if (!c.isLetterOrDigit() && !Character.isSpaceChar(c)) { + source.delete(i, i + 1) + } + } + return source + } else { + val sb = StringBuilder() + for (i in start..end - 1) { + val c = source[i] + if (c.isLetterOrDigit() || Character.isSpaceChar(c)) { + sb.append(c.toUpperCase()) + } + } + return sb.toString() + } + } +} \ No newline at end of file diff --git a/app/src/main/java/net/thauvin/erik/android/tesremoteprogrammer/filters/MinMaxFilter.kt b/app/src/main/java/net/thauvin/erik/android/tesremoteprogrammer/filters/MinMaxFilter.kt new file mode 100644 index 0000000..9328e7f --- /dev/null +++ b/app/src/main/java/net/thauvin/erik/android/tesremoteprogrammer/filters/MinMaxFilter.kt @@ -0,0 +1,42 @@ +/* + * MinMaxFilter.kt + * + * Copyright 2016 Erik C. Thauvin (erik@thauvin.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.thauvin.erik.android.tesremoteprogrammer.filters + +import android.text.InputFilter +import android.text.Spanned + +class MinMaxFilter : InputFilter { + private var min: Int = 0 + private var max: Int = 0 + private var size: Int = 0 + + constructor(min: Int, max: Int, size: Int) { + this.min = min + this.max = max + this.size = size + } + + override fun filter(source: CharSequence, start: Int, end: Int, dest: Spanned, dstart: Int, dend: Int): CharSequence? { + val input = (dest.toString() + source.toString()).toInt() + val len = dest.length + source.length + if ((min > 0 && size > 1 && len < size && input == 0) || input in IntRange(min, max)) { + return null + } + return "" + } +} \ No newline at end of file diff --git a/app/src/main/java/net/thauvin/erik/android/tesremoteprogrammer/models/Config.kt b/app/src/main/java/net/thauvin/erik/android/tesremoteprogrammer/models/Config.kt new file mode 100644 index 0000000..b9e4cc8 --- /dev/null +++ b/app/src/main/java/net/thauvin/erik/android/tesremoteprogrammer/models/Config.kt @@ -0,0 +1,46 @@ +/* + * Config.kt + * + * Copyright 2016 Erik C. Thauvin (erik@thauvin.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.thauvin.erik.android.tesremoteprogrammer.models + +import android.os.Parcel +import android.os.Parcelable +import java.io.Serializable + +data class Config(var params: Params, var opts: List