Compare commits

...
27 Commits
Author SHA1 Message Date
omni 8fe59df6f9 refactor + feat: updated UI and added cards search logic 2026-06-23 15:11:33 +03:00
omni d3c194ce9c fix: fixed top bar and added back handler for floating action button 2026-06-23 12:03:13 +03:00
omni 13d6ba0b52 refactor: replaced bottom actions list with floating action button 2026-06-23 11:53:30 +03:00
omni 3cf6b876f9 feat: added icons support for WearOS 2026-06-23 11:09:55 +03:00
omni bb57ab007c feat: added icons for cards 2026-06-22 22:33:11 +03:00
omni d3ef728007 fix: fixed backup buttons 2026-06-22 16:09:54 +03:00
omni 1fa90ff0b7 redesign: updated card buttons style on WearOS 2026-06-22 16:00:24 +03:00
omni 25c38418a3 redesign: updated card buttons style 2026-06-22 08:24:23 +03:00
omni 0a383573e2 fix: enabled minify 2026-06-21 21:53:54 +03:00
omni e6ebd574fd feat: added templates search 2026-06-21 21:35:36 +03:00
omni d7ff167e32 fix: setted UTF-8 charset for codes 2026-06-21 21:15:54 +03:00
omni 9d9b90deb1 feat: added localization for templates by language 2026-06-21 21:11:56 +03:00
omni 24927ba7ef fix 2026-06-21 20:44:34 +03:00
omni aea6607c29 fix: fixed wear database 2026-06-21 20:43:46 +03:00
omni 12b64766ef fix: fixed UI 2026-06-21 20:40:44 +03:00
omni 576642a920 refactor: updated UI 2026-06-21 20:14:41 +03:00
omni 2cc7a3a2c3 feat: added templates 2026-06-21 19:09:08 +03:00
omni 464094e6cb fix: fixed color picker 2026-06-21 15:25:05 +03:00
omni df95702247 feat: moved card color choosing to new screen 2026-06-21 14:07:12 +03:00
omni 1272e87ccd restore: restored older version 2026-06-21 12:27:54 +03:00
omni 123af530ed update: updated versions 2026-06-15 22:20:46 +03:00
omni 564245aa08 update: changed code size 2026-06-15 22:19:58 +03:00
omni 2277ae340c fix: fixed translations 2026-06-15 21:26:06 +03:00
omni edcaf6e02c fix: fixed closing action bar 2026-06-15 18:50:47 +03:00
omni da33a6813b feat: added animations 2026-06-15 18:43:03 +03:00
omni ca355f4135 update: updated versions 2026-06-15 17:34:59 +03:00
omni 4a5355e633 Merge pull request 'Added translations' (#1) from translations into main
Reviewed-on: #1
2026-06-15 14:33:00 +00:00
30 changed files with 1514 additions and 246 deletions
+8 -2
View File
@@ -23,14 +23,17 @@ android {
minSdk = 30 minSdk = 30
targetSdk = 36 targetSdk = 36
versionCode = generateVersionCode() versionCode = generateVersionCode()
versionName = "2.3.1" versionName = "4.0.0"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
} }
buildTypes { buildTypes {
debug {
applicationIdSuffix = ".debug"
}
release { release {
isMinifyEnabled = false isMinifyEnabled = true
proguardFiles( proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"), getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro" "proguard-rules.pro"
@@ -74,4 +77,7 @@ dependencies {
implementation("com.google.android.gms:play-services-wearable:18.1.0") implementation("com.google.android.gms:play-services-wearable:18.1.0")
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.9.0") implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.9.0")
implementation(libs.compose.colorpicker) implementation(libs.compose.colorpicker)
implementation("io.ktor:ktor-client-core:3.5.0")
implementation("io.ktor:ktor-client-cio:3.5.0")
implementation("androidx.compose.material:material-icons-extended")
} }
Binary file not shown.
Binary file not shown.
+19
View File
@@ -1,6 +1,8 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"> <manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<application <application
android:allowBackup="true" android:allowBackup="true"
android:icon="@mipmap/ic_launcher" android:icon="@mipmap/ic_launcher"
@@ -8,6 +10,23 @@
android:roundIcon="@mipmap/ic_launcher_round" android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true" android:supportsRtl="true"
android:theme="@style/Theme.OmniCards"> android:theme="@style/Theme.OmniCards">
<activity
android:name=".SelectIconActivity"
android:exported="false"
android:label="@string/title_activity_select_icon"
android:theme="@style/Theme.OmniCards" />
<activity
android:name=".FillTemplateActivity"
android:exported="false"
android:theme="@style/Theme.OmniCards" />
<activity
android:name=".SelectTemplateActivity"
android:exported="false"
android:theme="@style/Theme.OmniCards" />
<activity
android:name=".ChooseColorActivity"
android:exported="false"
android:theme="@style/Theme.OmniCards" />
<activity <activity
android:name=".BackupActivity" android:name=".BackupActivity"
android:exported="false" android:exported="false"
@@ -11,6 +11,10 @@ import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Save
import androidx.compose.material.icons.outlined.Restore
import androidx.compose.material3.AlertDialog import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Scaffold import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text import androidx.compose.material3.Text
@@ -131,15 +135,19 @@ fun BackupPage(innerPadding: PaddingValues, getDbFun: () -> DbHelper) {
) )
} }
Page("Backup", innerPadding) { Page(stringResource(R.string.backup), innerPadding) {
FullWidthButton( AdaptiveButton(
modifier = Modifier.fillMaxWidth(),
icon = Icons.Outlined.Save,
onClick = { onClick = {
createBackupLauncher.launch("omnicards-backup.json") createBackupLauncher.launch("omnicards-backup.json")
} }
) { ) {
Text(stringResource(R.string.do_backup)) Text(stringResource(R.string.do_backup))
} }
FullWidthButton( AdaptiveButton(
modifier = Modifier.fillMaxWidth(),
icon = Icons.Outlined.Restore,
onClick = { onClick = {
restoreFromBackupLauncher.launch("application/json") restoreFromBackupLauncher.launch("application/json")
} }
@@ -0,0 +1,28 @@
package ru.omni_devel.cards
import kotlinx.serialization.Serializable
import org.json.JSONArray
@Serializable
class CardIcon(
val names: LinkedHashMap<String, String>,
val iconId: String? = null
) {
companion object {
fun parseIconsDataFromJson(json: String): List<CardIcon> {
val array = JSONArray(json)
val icons = mutableListOf<CardIcon>()
for (i in 0 until array.length()) {
val obj = array.getJSONObject(i)
icons.add(CardIcon(
names = jsonObjectToMap(obj.getJSONObject("names")),
iconId = if (obj.has("iconId")) obj.getString("iconId") else null
))
}
return icons
}
}
}
@@ -15,4 +15,5 @@ class CardInfo (
val codeType: BarcodeFormat, val codeType: BarcodeFormat,
val codeValue: String, val codeValue: String,
val color: String?, val color: String?,
val icon: String?
) {} ) {}
@@ -0,0 +1,118 @@
package ru.omni_devel.cards
import android.app.Activity
import android.content.Intent
import android.content.res.Configuration
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.LocalActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.core.graphics.toColorInt
import com.github.skydoves.colorpicker.compose.ColorEnvelope
import com.github.skydoves.colorpicker.compose.HsvColorPicker
import com.github.skydoves.colorpicker.compose.rememberColorPickerController
import ru.omni_devel.cards.ui.theme.OmniCardsTheme
class ChooseColorActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
val currentColor = intent.getStringExtra("currentColor")
setContent {
OmniCardsTheme {
Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
EditColorPage(innerPadding, currentColor)
}
}
}
}
}
@Composable
fun EditColorPage(innerPadding: PaddingValues, currentColor: String?) {
val activityContext = LocalActivity.current
val configuration = LocalConfiguration.current
val screenHeight = configuration.screenHeightDp.dp
val isPortrait = configuration.orientation == Configuration.ORIENTATION_PORTRAIT
var color by rememberSaveable { mutableStateOf(currentColor) }
val colorPickerController = rememberColorPickerController()
Page(
stringResource(R.string.choosing_color),
innerPadding
) {
Column(
modifier = Modifier.verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.spacedBy(8.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
var colorPickerModifier = Modifier
.padding(10.dp)
if (isPortrait) {
colorPickerModifier = colorPickerModifier
.fillMaxWidth()
.height(450.dp)
} else {
val size = screenHeight * 0.5f
colorPickerModifier = colorPickerModifier
.height(size)
.width(size)
}
HsvColorPicker(
modifier = colorPickerModifier,
initialColor = color?.let { Color(it.toColorInt()) },
controller = colorPickerController,
onColorChanged = { colorEnvelope: ColorEnvelope ->
color = "#${colorEnvelope.hexCode.substring(2)}"
}
)
AdaptiveButton(
modifier = Modifier.fillMaxWidth(),
onClick = {
val resultIntent = Intent()
resultIntent.putExtra("color", color)
activityContext!!.setResult(Activity.RESULT_OK, resultIntent)
activityContext.finish()
}
) {
Text(stringResource(R.string.do_save))
}
}
}
}
@@ -0,0 +1,15 @@
package ru.omni_devel.cards
const val REPO_BASE_URL = "https://gitea.omni-devel.ru/omni/OmniCardsRepo/raw/branch/main"
const val TEMPLATES_REPO_FILE = "templates.json"
const val ICONS_REPO_FILE = "icons.json"
const val ICONS_REPO_FOLDER = "icons"
val SEARCH_REPLACE_SYMBOLS = mapOf(
" " to "",
"-" to "",
"_" to "",
"ё" to "е"
)
@@ -4,11 +4,14 @@ import android.content.ContentValues
import android.content.Context import android.content.Context
import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper import android.database.sqlite.SQLiteOpenHelper
import androidx.core.database.getStringOrNull
import com.google.zxing.BarcodeFormat import com.google.zxing.BarcodeFormat
class DbHelper(val context: Context, val factory: SQLiteDatabase.CursorFactory?) : SQLiteOpenHelper(context, "omni_cards", factory, 2) { class DbHelper(val context: Context, val factory: SQLiteDatabase.CursorFactory?) : SQLiteOpenHelper(context, "omni_cards", factory, 6) {
override fun onCreate(db: SQLiteDatabase?) { override fun onCreate(db: SQLiteDatabase?) {
db!!.execSQL("CREATE TABLE IF NOT EXISTS cards (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, codeType TEXT, codeValue TEXT, color TEXT)") db!!.execSQL(
"CREATE TABLE IF NOT EXISTS cards (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, codeType TEXT, codeValue TEXT, color TEXT, icon TEXT)"
)
} }
override fun onUpgrade( override fun onUpgrade(
@@ -19,30 +22,52 @@ class DbHelper(val context: Context, val factory: SQLiteDatabase.CursorFactory?)
if (oldVersion < 2) { if (oldVersion < 2) {
db!!.execSQL("ALTER TABLE cards ADD COLUMN color TEXT") db!!.execSQL("ALTER TABLE cards ADD COLUMN color TEXT")
} }
if (oldVersion < 3) {
db!!.execSQL("ALTER TABLE cards ADD COLUMN position INTEGER DEFAULT 0")
db.execSQL("ALTER TABLE cards ADD COLUMN iconPath TEXT")
db.execSQL("UPDATE cards SET position = id")
} }
fun addCard(name: String, codeValue: String, codeType: BarcodeFormat, color: String?) { if (oldVersion < 4) {
db!!.execSQL("ALTER TABLE cards ADD COLUMN monochrome INTEGER DEFAULT 0")
}
if (oldVersion < 5) {
db!!.execSQL("ALTER TABLE cards DROP COLUMN iconPath")
db.execSQL("ALTER TABLE cards DROP COLUMN monochrome")
db.execSQL("ALTER TABLE cards DROP COLUMN position")
}
if (oldVersion < 6) {
db!!.execSQL("ALTER TABLE cards ADD COLUMN icon TEXT")
}
}
fun addCard(name: String, codeValue: String, codeType: BarcodeFormat, color: String?, icon: String?) {
val db = this.writableDatabase
val values = ContentValues() val values = ContentValues()
values.put("name", name) values.put("name", name)
values.put("codeValue", codeValue) values.put("codeValue", codeValue)
values.put("codeType", codeType.name) values.put("codeType", codeType.name)
values.put("color", color) values.put("color", color)
values.put("icon", icon)
val db = this.writableDatabase
db.insert("cards", null, values) db.insert("cards", null, values)
db.close() db.close()
} }
fun editCard(id: Int, name: String, codeValue: String, codeType: BarcodeFormat, color: String?) { fun editCard(id: Int, name: String, codeValue: String, codeType: BarcodeFormat, color: String?, icon: String?) {
val values = ContentValues() val values = ContentValues()
values.put("name", name) values.put("name", name)
values.put("codeValue", codeValue) values.put("codeValue", codeValue)
values.put("codeType", codeType.name) values.put("codeType", codeType.name)
values.put("color", color) values.put("color", color)
values.put("icon", icon)
val db = this.writableDatabase val db = this.writableDatabase
@@ -54,7 +79,7 @@ class DbHelper(val context: Context, val factory: SQLiteDatabase.CursorFactory?)
fun getCards(): List<CardInfo> { fun getCards(): List<CardInfo> {
val db = this.readableDatabase val db = this.readableDatabase
val cursor = db.rawQuery("SELECT * FROM cards", null) val cursor = db.rawQuery("SELECT * FROM cards ORDER BY id ASC", null)
val cards = mutableListOf<CardInfo>() val cards = mutableListOf<CardInfo>()
while (cursor.moveToNext()) { while (cursor.moveToNext()) {
@@ -63,7 +88,8 @@ class DbHelper(val context: Context, val factory: SQLiteDatabase.CursorFactory?)
name = cursor.getString(cursor.getColumnIndexOrThrow("name")), name = cursor.getString(cursor.getColumnIndexOrThrow("name")),
codeType = BarcodeFormat.valueOf(cursor.getString(cursor.getColumnIndexOrThrow("codeType"))), codeType = BarcodeFormat.valueOf(cursor.getString(cursor.getColumnIndexOrThrow("codeType"))),
codeValue = cursor.getString(cursor.getColumnIndexOrThrow("codeValue")), codeValue = cursor.getString(cursor.getColumnIndexOrThrow("codeValue")),
color = cursor.getString(cursor.getColumnIndexOrThrow("color")) color = cursor.getString(cursor.getColumnIndexOrThrow("color")),
icon = cursor.getStringOrNull(cursor.getColumnIndexOrThrow("icon"))
)) ))
} }
@@ -90,7 +116,8 @@ class DbHelper(val context: Context, val factory: SQLiteDatabase.CursorFactory?)
name = cursor.getString(cursor.getColumnIndexOrThrow("name")), name = cursor.getString(cursor.getColumnIndexOrThrow("name")),
codeType = BarcodeFormat.valueOf(cursor.getString(cursor.getColumnIndexOrThrow("codeType"))), codeType = BarcodeFormat.valueOf(cursor.getString(cursor.getColumnIndexOrThrow("codeType"))),
codeValue = cursor.getString(cursor.getColumnIndexOrThrow("codeValue")), codeValue = cursor.getString(cursor.getColumnIndexOrThrow("codeValue")),
color = cursor.getString(cursor.getColumnIndexOrThrow("color")) color = cursor.getString(cursor.getColumnIndexOrThrow("color")),
icon = cursor.getStringOrNull(cursor.getColumnIndexOrThrow("icon"))
) )
cursor.close() cursor.close()
@@ -124,6 +151,7 @@ class DbHelper(val context: Context, val factory: SQLiteDatabase.CursorFactory?)
values.put("codeValue", card.codeValue) values.put("codeValue", card.codeValue)
values.put("codeType", card.codeType.name) values.put("codeType", card.codeType.name)
values.put("color", card.color) values.put("color", card.color)
values.put("icon", card.icon)
db.insert("cards", null, values) db.insert("cards", null, values)
} }
@@ -1,5 +1,7 @@
package ru.omni_devel.cards package ru.omni_devel.cards
import android.app.Activity
import android.content.Intent
import android.os.Bundle import android.os.Bundle
import android.widget.Toast import android.widget.Toast
import androidx.activity.ComponentActivity import androidx.activity.ComponentActivity
@@ -7,6 +9,8 @@ import androidx.activity.compose.LocalActivity
import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.compose.setContent import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Box
@@ -19,13 +23,18 @@ import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button
import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold import androidx.compose.material3.Scaffold
import androidx.compose.material3.Switch import androidx.compose.material3.Switch
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Palette
import androidx.compose.material.icons.outlined.QrCodeScanner
import androidx.compose.material.icons.outlined.TextFields
import androidx.compose.material.icons.outlined.Save
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
@@ -37,10 +46,6 @@ import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.core.graphics.toColorInt
import com.github.skydoves.colorpicker.compose.ColorEnvelope
import com.github.skydoves.colorpicker.compose.HsvColorPicker
import com.github.skydoves.colorpicker.compose.rememberColorPickerController
import com.google.zxing.BarcodeFormat import com.google.zxing.BarcodeFormat
import com.journeyapps.barcodescanner.ScanContract import com.journeyapps.barcodescanner.ScanContract
import com.journeyapps.barcodescanner.ScanOptions import com.journeyapps.barcodescanner.ScanOptions
@@ -79,15 +84,15 @@ fun CardEditable(
codeType: BarcodeFormat, codeType: BarcodeFormat,
onCodeTypeChange: (BarcodeFormat) -> Unit, onCodeTypeChange: (BarcodeFormat) -> Unit,
color: String?, color: String?,
onColorChange: (String?) -> Unit onColorChange: (String?) -> Unit,
icon: String?,
onIconChange: (String?) -> Unit
) { ) {
val context = LocalContext.current val context = LocalContext.current
var isCodeTypeDropdownExpanded by rememberSaveable { mutableStateOf(false) } var isCodeTypeDropdownExpanded by rememberSaveable { mutableStateOf(false) }
var isColorPickerExpanded by rememberSaveable { mutableStateOf(false) }
var isColorEnabled by rememberSaveable { mutableStateOf(color != null) } var isColorEnabled by rememberSaveable { mutableStateOf(color != null) }
var currentColor by rememberSaveable { mutableStateOf(color) }
val colorPickerController = rememberColorPickerController()
val fieldModifier = Modifier.fillMaxWidth() val fieldModifier = Modifier.fillMaxWidth()
@@ -100,41 +105,55 @@ fun CardEditable(
result.formatName?.let { formatName -> result.formatName?.let { formatName ->
try { try {
onCodeTypeChange(BarcodeFormat.valueOf(formatName)) onCodeTypeChange(BarcodeFormat.valueOf(formatName))
} catch (e: IllegalArgumentException) {} } catch (_: IllegalArgumentException) {}
} }
} }
} }
val editColorLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.StartActivityForResult()
) { result ->
if (result.resultCode == Activity.RESULT_OK) {
val color = result.data?.getStringExtra("color")
currentColor = color
onColorChange(color)
}
}
val selectTemplateLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.StartActivityForResult()
) { result ->
if (result.resultCode == Activity.RESULT_OK) {
val codeValue = result.data?.getStringExtra("codeValue") ?: ""
onCodeValueChange(codeValue)
}
}
val selectIconLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.StartActivityForResult()
) { result ->
if (result.resultCode == Activity.RESULT_OK) {
val icon = result.data?.getStringExtra("icon")
onIconChange(icon)
}
}
OutlinedTextField( OutlinedTextField(
value = cardName, value = cardName,
onValueChange = onCardNameChange, onValueChange = onCardNameChange,
modifier = fieldModifier, modifier = fieldModifier,
label = { Text(stringResource(R.string.card_name)) } label = { Text(stringResource(R.string.card_name)) }
) )
Row(
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
OutlinedTextField( OutlinedTextField(
value = codeValue, value = codeValue,
onValueChange = onCodeValueChange, onValueChange = onCodeValueChange,
modifier = Modifier.weight(1f), modifier = fieldModifier,
label = { Text(stringResource(R.string.card_value)) } label = { Text(stringResource(R.string.card_value)) }
) )
Button(
modifier = Modifier.align(Alignment.CenterVertically),
onClick = {
scanLauncher.launch(
ScanOptions().apply {
setPrompt(context.getString(R.string.scan_your_card))
setBeepEnabled(true)
setOrientationLocked(false)
}
)
}
) {
Text(stringResource(R.string.do_scan_card))
}
}
Box( Box(
modifier = fieldModifier, modifier = fieldModifier,
@@ -170,18 +189,53 @@ fun CardEditable(
} }
} }
AdaptiveButton(
modifier = Modifier.fillMaxWidth(),
icon = Icons.Outlined.QrCodeScanner,
onClick = {
scanLauncher.launch(
ScanOptions().apply {
setPrompt(context.getString(R.string.scan_your_card))
setBeepEnabled(true)
setOrientationLocked(true)
}
)
}
) {
Text(stringResource(R.string.do_scan_card))
}
AdaptiveButton(
modifier = Modifier.fillMaxWidth(),
icon = Icons.Outlined.TextFields,
onClick = {
val intent = Intent(context, SelectTemplateActivity::class.java)
selectTemplateLauncher.launch(intent)
}
) {
Text(stringResource(R.string.card_from_template))
}
Row( Row(
modifier = fieldModifier, modifier = fieldModifier,
horizontalArrangement = Arrangement.SpaceBetween horizontalArrangement = Arrangement.spacedBy(8.dp)
) { ) {
Button( AdaptiveButton(
modifier = Modifier.fillMaxWidth().weight(1.0f),
icon = Icons.Outlined.Palette,
enabled = isColorEnabled, enabled = isColorEnabled,
onClick = { onClick = {
isColorPickerExpanded = !isColorPickerExpanded val intent = Intent(context, ChooseColorActivity::class.java)
intent.putExtra("currentColor", currentColor)
editColorLauncher.launch(intent)
} }
) { ) {
Text(stringResource(R.string.do_choose_color)) Text(stringResource(R.string.do_choose_color))
} }
Switch( Switch(
checked = isColorEnabled, checked = isColorEnabled,
onCheckedChange = { onCheckedChange = {
@@ -194,18 +248,27 @@ fun CardEditable(
) )
} }
if (isColorPickerExpanded && isColorEnabled) { AdaptiveButton(
HsvColorPicker( modifier = Modifier.fillMaxWidth().height(64.dp),
contentPadding = PaddingValues(horizontal = 0.dp),
onClick = {
val intent = Intent(context, SelectIconActivity::class.java)
selectIconLauncher.launch(intent)
}
) {
Row(
modifier = Modifier modifier = Modifier
.fillMaxWidth() .fillMaxSize()
.height(450.dp) .background(Color.Transparent)
.padding(10.dp), .padding(horizontal = 8.dp),
initialColor = color?.let { Color(it.toColorInt()) }, verticalAlignment = Alignment.CenterVertically,
controller = colorPickerController, horizontalArrangement = Arrangement.spacedBy(8.dp)
onColorChanged = { colorEnvelope: ColorEnvelope -> ) {
onColorChange("#${colorEnvelope.hexCode.substring(2)}") CardIcon(if (icon == null) null else base64ToImageBitmap(icon), MaterialTheme.colorScheme.primary)
Text(stringResource(R.string.do_select_icon))
} }
)
} }
} }
@@ -215,6 +278,7 @@ fun AddCard(innerPadding: PaddingValues, getDbFun: () -> DbHelper) {
var codeValue by rememberSaveable { mutableStateOf("") } var codeValue by rememberSaveable { mutableStateOf("") }
var codeType by rememberSaveable { mutableStateOf(BarcodeFormat.QR_CODE) } var codeType by rememberSaveable { mutableStateOf(BarcodeFormat.QR_CODE) }
var color by rememberSaveable { mutableStateOf<String?>(null) } var color by rememberSaveable { mutableStateOf<String?>(null) }
var icon by rememberSaveable { mutableStateOf<String?>(null) }
val context = LocalActivity.current val context = LocalActivity.current
@@ -234,18 +298,21 @@ fun AddCard(innerPadding: PaddingValues, getDbFun: () -> DbHelper) {
codeType = codeType, codeType = codeType,
onCodeTypeChange = { codeType = it }, onCodeTypeChange = { codeType = it },
color = color, color = color,
onColorChange = { color = it } onColorChange = { color = it },
icon = icon,
onIconChange = { icon = it }
) )
Button( AdaptiveButton(
modifier = Modifier.fillMaxWidth(), modifier = Modifier.fillMaxWidth(),
icon = Icons.Outlined.Save,
onClick = { onClick = {
cardName = cardName.trim() cardName = cardName.trim()
val err = checkCardData(cardName, codeValue) val err = checkCardData(cardName, codeValue)
if (err == null) { if (err == null) {
getDbFun().addCard(cardName, codeValue, codeType, color) getDbFun().addCard(cardName, codeValue, codeType, color, icon)
context!!.finish() context!!.finish()
} else { } else {
Toast.makeText(context, context!!.getString(err), Toast.LENGTH_SHORT).show() Toast.makeText(context, context!!.getString(err), Toast.LENGTH_SHORT).show()
@@ -264,6 +331,7 @@ fun EditCard(cardInfo: CardInfo, innerPadding: PaddingValues, getDbFun: () -> Db
var codeValue by rememberSaveable { mutableStateOf(cardInfo.codeValue) } var codeValue by rememberSaveable { mutableStateOf(cardInfo.codeValue) }
var codeType by rememberSaveable { mutableStateOf(cardInfo.codeType) } var codeType by rememberSaveable { mutableStateOf(cardInfo.codeType) }
var color by rememberSaveable { mutableStateOf(cardInfo.color) } var color by rememberSaveable { mutableStateOf(cardInfo.color) }
var icon by rememberSaveable { mutableStateOf(cardInfo.icon) }
val context = LocalActivity.current val context = LocalActivity.current
@@ -283,18 +351,21 @@ fun EditCard(cardInfo: CardInfo, innerPadding: PaddingValues, getDbFun: () -> Db
codeType = codeType, codeType = codeType,
onCodeTypeChange = { codeType = it }, onCodeTypeChange = { codeType = it },
color = color, color = color,
onColorChange = { color = it } onColorChange = { color = it },
icon = icon,
onIconChange = { icon = it }
) )
Button( AdaptiveButton(
modifier = Modifier.fillMaxWidth(), modifier = Modifier.fillMaxWidth(),
icon = Icons.Outlined.Save,
onClick = { onClick = {
cardName = cardName.trim() cardName = cardName.trim()
val err = checkCardData(cardName, codeValue) val err = checkCardData(cardName, codeValue)
if (err == null) { if (err == null) {
getDbFun().editCard(cardInfo.id, cardName, codeValue, codeType, color) getDbFun().editCard(cardInfo.id, cardName, codeValue, codeType, color, icon)
context!!.finish() context!!.finish()
} else { } else {
Toast.makeText(context, context!!.getString(err), Toast.LENGTH_SHORT).show() Toast.makeText(context, context!!.getString(err), Toast.LENGTH_SHORT).show()
@@ -1,34 +1,68 @@
package ru.omni_devel.cards package ru.omni_devel.cards
import android.content.Intent import android.content.Intent
import androidx.activity.compose.BackHandler
import androidx.activity.compose.LocalActivity
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.scaleIn
import androidx.compose.animation.scaleOut
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.background import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectTapGestures import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material3.Button import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.ButtonElevation
import androidx.compose.material3.DrawerValue
import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.Icon
import androidx.compose.material.icons.outlined.Add
import androidx.compose.material.icons.outlined.QrCode
import androidx.compose.material.icons.outlined.DensityMedium
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExtendedFloatingActionButton
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalDrawerSheet
import androidx.compose.material3.ModalNavigationDrawer
import androidx.compose.material3.NavigationDrawerItem
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface import androidx.compose.material3.Surface
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.material3.rememberDrawerState
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.stringResource
@@ -36,51 +70,135 @@ import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp import androidx.compose.ui.unit.sp
import androidx.core.graphics.toColorInt import androidx.core.graphics.toColorInt
import kotlinx.coroutines.launch
@Composable @Composable
fun Page(name: String, innerPadding: PaddingValues, content: @Composable () -> Unit) { fun Page(
Column() { name: String,
TopBar(name, innerPadding) innerPadding: PaddingValues,
topBarAdditionalElements: @Composable () -> Unit = {},
Column( floatingActionButton: @Composable (() -> Unit) = {},
content: @Composable () -> Unit
) {
Scaffold(
topBar = {
TopBar(name, innerPadding, topBarAdditionalElements)
},
floatingActionButton = floatingActionButton
) { padding ->
Box(
modifier = Modifier modifier = Modifier
.padding(padding)
.fillMaxSize() .fillMaxSize()
.padding(horizontal = 16.dp)
.background(MaterialTheme.colorScheme.background) .background(MaterialTheme.colorScheme.background)
.padding(horizontal = 16.dp)
.padding(top = 16.dp)
) {
Column(
verticalArrangement = Arrangement.spacedBy(8.dp)
) { ) {
content() content()
} }
} }
}
} }
@Composable @Composable
fun TopBar(text: String, innerPadding: PaddingValues) { fun ExpandableFab(
items: List<NavigationPageData>
) {
val activityContext = LocalActivity.current
var isExpanded by remember { mutableStateOf(false) }
val rotation by animateFloatAsState(if (isExpanded) 45f else 0f)
BackHandler(
enabled = isExpanded
) {
isExpanded = false
}
Column(
horizontalAlignment = Alignment.End,
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
items.forEach { page ->
AnimatedVisibility(
visible = isExpanded,
enter = fadeIn() + scaleIn(),
exit = fadeOut() + scaleOut()
) {
ExtendedFloatingActionButton(
text = { Text(page.name) },
icon = { Icon(page.icon, contentDescription = null) },
onClick = {
isExpanded = false
if (page.pageClass != null) {
val intent = Intent(activityContext, page.pageClass)
activityContext!!.startActivity(intent)
} else if (page.onClick != null) {
page.onClick()
}
}
)
}
}
FloatingActionButton(
onClick = { isExpanded = !isExpanded }
) {
Icon(
modifier = Modifier.graphicsLayer { rotationZ = rotation },
imageVector = Icons.Outlined.Add,
contentDescription = null
)
}
}
}
@Composable
fun TopBar(
text: String,
innerPadding: PaddingValues,
topBarAdditionalElements: @Composable () -> Unit = {}
) {
Row( Row(
modifier = Modifier modifier = Modifier
.fillMaxWidth() .fillMaxWidth()
.background(MaterialTheme.colorScheme.primaryContainer) .background(MaterialTheme.colorScheme.primaryContainer)
.padding(top = innerPadding.calculateTopPadding()) .padding(top = innerPadding.calculateTopPadding())
.padding(horizontal = 8.dp) .padding(vertical = 12.dp, horizontal = 12.dp),
.padding(bottom = 8.dp) verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
) { ) {
Text( Text(
text, text,
modifier = Modifier.padding(vertical = 4.dp, horizontal = 12.dp), modifier = Modifier,
fontSize = 24.sp, fontSize = 24.sp,
color = MaterialTheme.colorScheme.onPrimaryContainer color = MaterialTheme.colorScheme.onPrimaryContainer
) )
topBarAdditionalElements()
} }
} }
@Composable @Composable
fun CardButton(cardInfo: CardInfo, onDeleteCard: (Int) -> Unit) { fun CardButton(cardInfo: CardInfo, onDeleteCard: (Int) -> Unit) {
val context = LocalContext.current val context = LocalContext.current
var menuExpanded by remember { mutableStateOf(false) } var menuExpanded by remember { mutableStateOf(false) }
val cardColor = if (cardInfo.color == null)
MaterialTheme.colorScheme.primaryContainer
else
Color(cardInfo.color.toColorInt())
Box(modifier = Modifier.fillMaxWidth()) { Box(modifier = Modifier.fillMaxWidth()) {
Surface( Surface(
modifier = Modifier modifier = Modifier
.fillMaxWidth() .fillMaxWidth()
.height(64.dp)
.pointerInput(Unit) { .pointerInput(Unit) {
detectTapGestures( detectTapGestures(
onTap = { onTap = {
@@ -93,32 +211,28 @@ fun CardButton(cardInfo: CardInfo, onDeleteCard: (Int) -> Unit) {
} }
) )
}, },
shape = ButtonDefaults.shape, shape = RoundedCornerShape(12.dp),
color = MaterialTheme.colorScheme.primaryContainer, color = MaterialTheme.colorScheme.primaryContainer.copy(0.625f),
tonalElevation = 2.dp tonalElevation = 2.dp,
) { ) {
Row( Row(
modifier = Modifier.fillMaxWidth().height(IntrinsicSize.Min),
horizontalArrangement = Arrangement.SpaceBetween
) {
Box(
modifier = Modifier modifier = Modifier
.fillMaxHeight() .fillMaxSize()
.width(32.dp) .background(Color.Transparent)
.background( .padding(horizontal = 8.dp),
if (cardInfo.color == null) MaterialTheme.colorScheme.secondaryContainer.copy(alpha = 0.625f) verticalAlignment = Alignment.CenterVertically,
else Color(cardInfo.color.toColorInt()).copy(alpha = 0.625f) horizontalArrangement = Arrangement.spacedBy(8.dp)
) ) {
CardIcon(
if (cardInfo.icon == null) null else base64ToImageBitmap(cardInfo.icon),
cardColor = cardColor
) )
Text( Text(
cardInfo.name, cardInfo.name,
fontSize = 16.sp, fontSize = 16.sp,
color = MaterialTheme.colorScheme.onPrimaryContainer, color = MaterialTheme.colorScheme.onPrimaryContainer,
modifier = Modifier modifier = Modifier.fillMaxWidth(),
.padding(16.dp)
.fillMaxWidth()
.weight(1f),
textAlign = TextAlign.Start textAlign = TextAlign.Start
) )
} }
@@ -153,11 +267,85 @@ fun CardButton(cardInfo: CardInfo, onDeleteCard: (Int) -> Unit) {
} }
@Composable @Composable
fun FullWidthButton(onClick: () -> Unit, content: @Composable () -> Unit) { fun CardIcon(icon: ImageBitmap?, cardColor: Color, isLoading: Boolean = false) {
Button( Row(
modifier = Modifier.fillMaxWidth(), modifier = Modifier
onClick = onClick .background(
cardColor.copy(0.525f),
RoundedCornerShape(12.dp)
)
.padding(8.dp)
.size(32.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Center
) { ) {
content() if (isLoading) {
CircularProgressIndicator(
modifier = Modifier.size(24.dp),
color = MaterialTheme.colorScheme.primary
)
} else if (icon == null) {
Icon(
modifier = Modifier.size(24.dp),
imageVector = Icons.Outlined.QrCode,
tint = MaterialTheme.colorScheme.onPrimaryContainer,
contentDescription = null
)
} else {
Image(
bitmap = icon,
contentDescription = null,
modifier = Modifier.size(32.dp)
)
}
} }
} }
@Composable
fun AdaptiveButton(
onClick: () -> Unit,
modifier: Modifier = Modifier,
enabled: Boolean = true,
icon: ImageVector? = null,
elevation: ButtonElevation? = ButtonDefaults.buttonElevation(),
border: BorderStroke? = null,
contentPadding: PaddingValues = ButtonDefaults.ContentPadding,
interactionSource: MutableInteractionSource? = null,
isSecondary: Boolean = false,
content: @Composable RowScope.() -> Unit
) {
val colors = if (isSecondary)
ButtonDefaults.buttonColors(
containerColor = MaterialTheme.colorScheme.secondaryContainer,
contentColor = MaterialTheme.colorScheme.onSecondaryContainer
)
else
ButtonDefaults.buttonColors(
containerColor = MaterialTheme.colorScheme.primaryContainer,
contentColor = MaterialTheme.colorScheme.onPrimaryContainer
)
Button(
onClick = onClick,
modifier = modifier,
enabled = enabled,
shape = RoundedCornerShape(12.dp),
colors = colors,
elevation = elevation,
border = border,
contentPadding = contentPadding,
interactionSource = interactionSource,
content = {
if (icon != null) {
Icon(
imageVector = icon,
contentDescription = null,
modifier = Modifier.size(18.dp)
)
Spacer(modifier = Modifier.width(8.dp))
}
content()
}
)
}
@@ -0,0 +1,107 @@
package ru.omni_devel.cards
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.LocalActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import ru.omni_devel.cards.ui.theme.OmniCardsTheme
class FillTemplateActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
val templateJson = intent.getStringExtra("templateJson") ?: ""
val template = Template.parseTemplateFromJson(templateJson)
setContent {
OmniCardsTheme {
Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
FillTemplatePage(template, innerPadding)
}
}
}
}
}
@Composable
fun FillTemplatePage(template: Template, innerPadding: PaddingValues) {
val activityContext = LocalActivity.current
val context = LocalContext.current
val language = getLanguage(context)
var filledFields by rememberSaveable { mutableStateOf(template.fields.associate { field ->
field.id to (field.default ?: "")
}) }
Page(
selectItemNameViaLanguage(template.names, language),
innerPadding
) {
for (field in template.fields) {
OutlinedTextField(
value = filledFields[field.id]!!,
onValueChange = { newValue ->
filledFields = filledFields.toMutableMap().apply {
this[field.id] = newValue
}
},
modifier = Modifier.fillMaxWidth(),
label = { Text((if (field.maybeEmpty) "" else "*") + selectItemNameViaLanguage(field.names, language)) }
)
}
AdaptiveButton(
modifier = Modifier.fillMaxWidth(),
onClick = {
var isSuccess = true
for (field in template.fields) {
if (filledFields[field.id]!!.isEmpty() && !field.maybeEmpty) {
isSuccess = false
}
}
if (!isSuccess) {
Toast.makeText(context, context.getString(R.string.error_in_data), Toast.LENGTH_LONG).show()
return@AdaptiveButton
}
var result = template.template
for ((id, value) in filledFields) {
result = result.replace("$$id$", value)
}
val resultIntent = Intent()
resultIntent.putExtra("codeValue", result)
activityContext!!.setResult(Activity.RESULT_OK, resultIntent)
activityContext.finish()
}
) {
Text(stringResource(R.string.do_save))
}
}
}
@@ -1,36 +1,43 @@
package ru.omni_devel.cards package ru.omni_devel.cards
import android.content.Intent
import android.os.Bundle import android.os.Bundle
import android.widget.Toast import android.widget.Toast
import androidx.activity.ComponentActivity import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.background import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.expandVertically
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.scaleIn
import androidx.compose.animation.scaleOut
import androidx.compose.animation.shrinkVertically
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.rememberScrollState import androidx.compose.material.icons.Icons
import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.outlined.Add
import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.outlined.Sync
import androidx.compose.material3.Button import androidx.compose.material.icons.outlined.Backup
import androidx.compose.material3.MaterialTheme import androidx.compose.material.icons.outlined.Code
import androidx.compose.material.icons.outlined.Search
import androidx.compose.material3.Icon
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalUriHandler import androidx.compose.ui.platform.LocalUriHandler
import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.stringResource
@@ -82,59 +89,31 @@ fun MainPage(
val context = LocalContext.current val context = LocalContext.current
val uriHandler = LocalUriHandler.current val uriHandler = LocalUriHandler.current
var isActionBarShowed by remember { mutableStateOf(false) } var searchQuery by rememberSaveable { mutableStateOf("") }
var isSearchFieldShowed by rememberSaveable { mutableStateOf(false) }
Box( Box(
modifier = Modifier.fillMaxSize() modifier = Modifier.fillMaxSize()
) { ) {
Page( Page(
stringResource(R.string.app_name), stringResource(R.string.app_name),
innerPadding innerPadding,
) { topBarAdditionalElements = {
Column( Icon(
modifier = Modifier.verticalScroll(rememberScrollState()).padding(bottom = 64.dp).background(Color.Transparent).padding(top = 16.dp), Icons.Outlined.Search,
verticalArrangement = Arrangement.spacedBy(8.dp) contentDescription = null,
) { modifier = Modifier.clickable {
if (cards.isEmpty()) { isSearchFieldShowed = !isSearchFieldShowed
Text( searchQuery = ""
stringResource(R.string.add_card_to_get_started) }
) )
} else { },
for (card in cards) { floatingActionButton = {
CardButton(card, onDeleteCard) ExpandableFab(
} items = listOf(
} NavigationPageData(stringResource(R.string.do_add_card), Icons.Outlined.Add, EditCardActivity::class.java),
} NavigationPageData(stringResource(R.string.do_sync), Icons.Outlined.Sync) {
}
if (isActionBarShowed) {
Column(
modifier = Modifier
.align(Alignment.BottomEnd)
.padding(innerPadding)
.padding(16.dp)
.background(
MaterialTheme.colorScheme.inversePrimary,
RoundedCornerShape(24.dp)
)
.padding(16.dp)
.fillMaxWidth()
) {
FullWidthButton(
onClick = {
isActionBarShowed = false
val intent = Intent(context, EditCardActivity::class.java)
context.startActivity(intent)
}
) {
Text(stringResource(R.string.do_add_card))
}
FullWidthButton(
onClick = {
Toast.makeText(context, context.getString(R.string.sync_in_progress), Toast.LENGTH_SHORT).show() Toast.makeText(context, context.getString(R.string.sync_in_progress), Toast.LENGTH_SHORT).show()
sendToWatch(context, "/updateCards", Json.encodeToString(getDbFun().getCards())) { isSuccess -> sendToWatch(context, "/updateCards", Json.encodeToString(getDbFun().getCards())) { isSuccess ->
if (isSuccess) { if (isSuccess) {
Toast.makeText(context, context.getString(R.string.sync_is_successful), Toast.LENGTH_SHORT).show() Toast.makeText(context, context.getString(R.string.sync_is_successful), Toast.LENGTH_SHORT).show()
@@ -142,50 +121,78 @@ fun MainPage(
Toast.makeText(context, context.getString(R.string.sync_is_fail), Toast.LENGTH_LONG).show() Toast.makeText(context, context.getString(R.string.sync_is_fail), Toast.LENGTH_LONG).show()
} }
} }
},
isActionBarShowed = false NavigationPageData(stringResource(R.string.open_backup_menu), Icons.Outlined.Backup, BackupActivity::class.java),
} NavigationPageData(stringResource(R.string.source_code), Icons.Outlined.Code) {
) {
Text(stringResource(R.string.do_sync))
}
FullWidthButton(
onClick = {
val intent = Intent(context, BackupActivity::class.java)
context.startActivity(intent)
isActionBarShowed = false
}
) {
Text(stringResource(R.string.open_backup_menu))
}
FullWidthButton(
onClick = {
uriHandler.openUri("https://github.com/omni-devel/OmniCards") uriHandler.openUri("https://github.com/omni-devel/OmniCards")
},
)
)
}
) {
var queryCleaned = searchQuery.lowercase()
isActionBarShowed = false for ((from, to) in SEARCH_REPLACE_SYMBOLS) {
queryCleaned = queryCleaned.replace(from, to)
} }
val searchResults = cards.filter { cardInfo ->
if (queryCleaned.isEmpty()) {
return@filter true
}
var cardNameCleaned = cardInfo.name.lowercase()
for ((from, to) in SEARCH_REPLACE_SYMBOLS) {
cardNameCleaned = cardNameCleaned.replace(from, to)
}
if (cardNameCleaned.contains(queryCleaned)) {
return@filter true
}
return@filter false
}
LazyColumn(
verticalArrangement = Arrangement.spacedBy(8.dp)
) { ) {
Text(stringResource(R.string.source_code)) item {
} AnimatedVisibility(
FullWidthButton( visible = isSearchFieldShowed,
onClick = { enter = fadeIn() + expandVertically(),
isActionBarShowed = false exit = fadeOut() + shrinkVertically()
}
) { ) {
Text(">") OutlinedTextField(
value = searchQuery,
onValueChange = {
searchQuery = it
},
modifier = Modifier.fillMaxWidth(),
label = { Text(stringResource(R.string.search)) }
)
} }
} }
if (cards.isEmpty()) {
item {
Text(
stringResource(R.string.add_card_to_get_started)
)
}
} else if (searchResults.isEmpty()) {
item {
Text(
stringResource(R.string.cards_not_found)
)
}
} else { } else {
Button( for (card in searchResults) {
modifier = Modifier item {
.align(Alignment.BottomEnd) CardButton(card, onDeleteCard)
.padding(innerPadding).padding(32.dp), }
onClick = { }
isActionBarShowed = true
} }
) {
Text("<")
} }
} }
} }
@@ -0,0 +1,11 @@
package ru.omni_devel.cards
import android.app.Activity
import androidx.compose.ui.graphics.vector.ImageVector
data class NavigationPageData(
val name: String,
val icon: ImageVector,
val pageClass: Class<out Activity>? = null,
val onClick: (() -> Unit)? = null
)
@@ -0,0 +1,238 @@
package ru.omni_devel.cards
import android.app.Activity
import android.content.Intent
import android.graphics.BitmapFactory
import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.LocalActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.ActivityResult
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.QrCode
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.setValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.engine.cio.CIO
import io.ktor.client.request.get
import io.ktor.client.statement.HttpResponse
import io.ktor.client.statement.bodyAsText
import ru.omni_devel.cards.ui.theme.OmniCardsTheme
class SelectIconActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContent {
OmniCardsTheme {
Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
SelectIconPage(innerPadding)
}
}
}
}
}
@Composable
fun SelectIconPage(innerPadding: PaddingValues) {
val context = LocalContext.current
val activityContext = LocalActivity.current
val language = getLanguage(context)
var searchQuery by rememberSaveable { mutableStateOf("") }
var iconsData by remember { mutableStateOf<List<CardIcon>?>(null) }
val loadedIcons = remember { mutableStateMapOf<String, ImageBitmap?>() }
var loadingError by remember { mutableStateOf<String?>(null) }
LaunchedEffect(Unit) {
try {
val client = HttpClient(CIO)
val response: HttpResponse = client.get("$REPO_BASE_URL/$ICONS_REPO_FILE")
val loadedIconsData = CardIcon.parseIconsDataFromJson(response.bodyAsText())
iconsData = loadedIconsData
for (iconData in loadedIconsData) {
if (iconData.iconId != null) {
val response = client.get("$REPO_BASE_URL/icons/${iconData.iconId}.png")
val bytes: ByteArray = response.body()
BitmapFactory.decodeByteArray(bytes, 0, bytes.size)?.let { bitmap ->
loadedIcons[iconData.iconId] = bitmap.asImageBitmap()
}
}
}
} catch (e: Exception) {
loadingError = e.toString()
}
}
var queryCleaned = searchQuery.lowercase()
for ((from, to) in SEARCH_REPLACE_SYMBOLS) {
queryCleaned = queryCleaned.replace(from, to)
}
val searchResults = iconsData!!.filter { iconData ->
if (queryCleaned.isEmpty()) {
return@filter true
}
for (name in iconData.names.values) {
var nameCleaned = name.lowercase()
for ((from, to) in SEARCH_REPLACE_SYMBOLS) {
nameCleaned = nameCleaned.replace(from, to)
}
if (nameCleaned.contains(queryCleaned)) {
return@filter true
}
}
return@filter false
}
Page(context.getString(R.string.choosing_icon), innerPadding) {
OutlinedTextField(
value = searchQuery,
onValueChange = { newValue ->
searchQuery = newValue
},
modifier = Modifier.fillMaxWidth(),
label = { Text(stringResource(R.string.search)) }
)
LazyColumn(
verticalArrangement = Arrangement.spacedBy(8.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
if (loadingError != null) {
item {
Text(loadingError!!)
}
} else if (iconsData == null) {
item {
Column(
modifier = Modifier.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally
) {
CircularProgressIndicator(
modifier = Modifier.size(48.dp),
color = MaterialTheme.colorScheme.primary
)
}
}
} else {
if (searchResults.isEmpty()) {
item {
Text(stringResource(R.string.icons_not_found))
}
} else {
for (chunk in searchResults.chunked(2)) {
item {
Row(
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
for (iconData in chunk) {
val loadedIcon = loadedIcons[iconData.iconId]
AdaptiveButton(
modifier = Modifier.weight(1f).height(64.dp),
contentPadding = PaddingValues(0.dp),
onClick = {
if (loadedIcon == null && iconData.iconId != null) {
Toast.makeText(
context,
context.getString(R.string.wait_for_icon_load),
Toast.LENGTH_SHORT
).show()
} else {
val intent = Intent()
if (loadedIcon != null) {
intent.putExtra(
"icon",
imageBitmapToBase64(loadedIcon)
)
}
activityContext!!.setResult(
Activity.RESULT_OK,
intent
)
activityContext.finish()
}
}
) {
Row(
modifier = Modifier
.fillMaxSize()
.background(Color.Transparent)
.padding(horizontal = 8.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
CardIcon(
loadedIcon,
MaterialTheme.colorScheme.primary,
loadedIcon == null && iconData.iconId != null
)
Text(
selectItemNameViaLanguage(
iconData.names,
language
)
)
}
}
}
}
}
}
}
}
}
}
}
@@ -0,0 +1,183 @@
package ru.omni_devel.cards
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.LocalActivity
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import io.ktor.client.HttpClient
import io.ktor.client.engine.cio.CIO
import io.ktor.client.request.get
import io.ktor.client.statement.HttpResponse
import io.ktor.client.statement.bodyAsText
import kotlinx.serialization.json.Json
import ru.omni_devel.cards.ui.theme.OmniCardsTheme
class SelectTemplateActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContent {
OmniCardsTheme {
Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
SelectTemplatePage(innerPadding)
}
}
}
}
}
@Composable
fun SelectTemplatePage(innerPadding: PaddingValues) {
val activityContext = LocalActivity.current
val context = LocalContext.current
val language = getLanguage(context)
var searchQuery by rememberSaveable { mutableStateOf("") }
var templates by remember { mutableStateOf<List<Template>?>(null) }
var loadingError by remember { mutableStateOf<String?>(null) }
LaunchedEffect(Unit) {
try {
val client = HttpClient(CIO)
val response: HttpResponse = client.get("$REPO_BASE_URL/$TEMPLATES_REPO_FILE")
templates = Template.parseTemplatesFromJson(response.bodyAsText())
} catch (e: Exception) {
loadingError = e.toString()
}
}
val fillTemplateLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.StartActivityForResult()
) { result ->
if (result.resultCode == Activity.RESULT_OK) {
val codeValue = result.data?.getStringExtra("codeValue")
val resultIntent = Intent()
resultIntent.putExtra("codeValue", codeValue)
activityContext!!.setResult(Activity.RESULT_OK, resultIntent)
activityContext.finish()
}
}
Page(
stringResource(R.string.choosing_template),
innerPadding
) {
OutlinedTextField(
value = searchQuery,
onValueChange = { newValue ->
searchQuery = newValue
},
modifier = Modifier.fillMaxWidth(),
label = { Text(stringResource(R.string.search)) }
)
LazyColumn(
horizontalAlignment = Alignment.CenterHorizontally
) {
val currentTemplates = templates
if (loadingError != null) {
item {
Text(loadingError!!)
}
} else if (currentTemplates == null) {
item {
Column(
modifier = Modifier.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally
) {
CircularProgressIndicator(
modifier = Modifier.size(48.dp),
color = MaterialTheme.colorScheme.primary
)
}
}
} else {
var queryCleaned = searchQuery.lowercase()
for ((from, to) in SEARCH_REPLACE_SYMBOLS) {
queryCleaned = queryCleaned.replace(from, to)
}
val searchResults = currentTemplates.filter { template ->
if (queryCleaned.isEmpty()) {
return@filter true
}
for (name in template.names.values) {
var nameCleaned = name.lowercase()
for ((from, to) in SEARCH_REPLACE_SYMBOLS) {
nameCleaned = nameCleaned.replace(from, to)
}
if (nameCleaned.contains(queryCleaned)) {
return@filter true
}
}
return@filter false
}
if (searchResults.isEmpty()) {
item {
Text(stringResource(R.string.templates_not_found))
}
} else {
for (template in searchResults) {
item {
AdaptiveButton(
modifier = Modifier.fillMaxWidth(),
onClick = {
val intent = Intent(context, FillTemplateActivity::class.java)
intent.putExtra("templateJson", Json.encodeToString(template))
fillTemplateLauncher.launch(intent)
}
) {
Text(selectItemNameViaLanguage(template.names, language))
}
}
}
}
}
}
}
}
@@ -7,12 +7,14 @@ import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.Image import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text import androidx.compose.material3.Text
@@ -20,6 +22,8 @@ import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.stringResource
@@ -95,10 +99,10 @@ fun ShowCardPage(innerPadding: PaddingValues, cardInfo: CardInfo) {
contentDescription = cardInfo.codeValue, contentDescription = cardInfo.codeValue,
modifier = Modifier modifier = Modifier
.padding(bottom = 8.dp) .padding(bottom = 8.dp)
.fillMaxWidth() .clip(RoundedCornerShape(12.dp)),
.weight(1f, fill = false),
contentScale = ContentScale.Fit contentScale = ContentScale.Fit
) )
Text( Text(
cardInfo.codeValue, cardInfo.codeValue,
modifier = Modifier.fillMaxWidth(), modifier = Modifier.fillMaxWidth(),
@@ -0,0 +1,77 @@
package ru.omni_devel.cards
import kotlinx.serialization.Serializable
import org.json.JSONArray
import org.json.JSONObject
@Serializable
class Field(
val id: String,
val names: LinkedHashMap<String, String>,
val default: String? = null,
val maybeEmpty: Boolean = false
)
@Serializable
class Template(
val names: LinkedHashMap<String, String>,
val fields: List<Field>,
val template: String
) {
companion object {
fun parseTemplateFromJson(json: String): Template {
val obj = JSONObject(json)
val fieldsArray = obj.getJSONArray("fields")
val fields = mutableListOf<Field>()
for (fi in 0 until fieldsArray.length()) {
val fieldObj = fieldsArray.getJSONObject(fi)
fields.add(Field(
id = fieldObj.getString("id"),
names = jsonObjectToMap(fieldObj.getJSONObject("names")),
default = fieldObj.optString("default"),
maybeEmpty = fieldObj.optBoolean("maybeEmpty")
))
}
return Template(
names = jsonObjectToMap(obj.getJSONObject("names")),
fields = fields,
template = obj.getString("template")
)
}
fun parseTemplatesFromJson(json: String): List<Template> {
val array = JSONArray(json)
val templates = mutableListOf<Template>()
for (i in 0 until array.length()) {
val obj = array.getJSONObject(i)
val fieldsArray = obj.getJSONArray("fields")
val fields = mutableListOf<Field>()
for (fi in 0 until fieldsArray.length()) {
val fieldObj = fieldsArray.getJSONObject(fi)
fields.add(Field(
id = fieldObj.getString("id"),
names = jsonObjectToMap(fieldObj.getJSONObject("names")),
default = fieldObj.optString("default"),
maybeEmpty = fieldObj.optBoolean("maybeEmpty")
))
}
templates.add(Template(
names = jsonObjectToMap(obj.getJSONObject("names")),
fields = fields,
template = obj.getString("template")
))
}
return templates
}
}
}
@@ -2,15 +2,33 @@ package ru.omni_devel.cards
import android.content.Context import android.content.Context
import android.graphics.Bitmap import android.graphics.Bitmap
import androidx.compose.ui.platform.LocalContext import android.graphics.BitmapFactory
import android.os.LocaleList
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.asAndroidBitmap
import com.google.android.gms.wearable.Wearable import com.google.android.gms.wearable.Wearable
import com.google.zxing.BarcodeFormat import com.google.zxing.BarcodeFormat
import com.google.zxing.EncodeHintType
import com.google.zxing.MultiFormatWriter import com.google.zxing.MultiFormatWriter
import com.journeyapps.barcodescanner.BarcodeEncoder import com.journeyapps.barcodescanner.BarcodeEncoder
import org.json.JSONObject
import java.io.ByteArrayOutputStream
import android.util.Base64
import androidx.compose.ui.graphics.asImageBitmap
fun generateCode(value: String, format: BarcodeFormat): Bitmap { fun generateCode(value: String, format: BarcodeFormat): Bitmap {
val writer = MultiFormatWriter() val writer = MultiFormatWriter()
val matrix = writer.encode(value, format, 800, 400)
val (width, height) = when (format) {
BarcodeFormat.QR_CODE, BarcodeFormat.DATA_MATRIX, BarcodeFormat.AZTEC -> 800 to 800
else -> 800 to 400
}
val hints = mapOf(
EncodeHintType.CHARACTER_SET to "UTF-8"
)
val matrix = writer.encode(value, format, width, height, hints)
return BarcodeEncoder().createBitmap(matrix) return BarcodeEncoder().createBitmap(matrix)
} }
@@ -61,3 +79,45 @@ fun checkCardData(name: String, value: String): Int? {
return null return null
} }
fun getLanguage(context: Context): String {
val locales: LocaleList = context.resources.configuration.locales
val primaryLocale = locales[0]
val languageCode = primaryLocale.language
return languageCode
}
fun selectItemNameViaLanguage(names: LinkedHashMap<String, String>, language: String): String {
return names[language] ?: names.values.firstOrNull() ?: "???"
}
fun jsonObjectToMap(obj: JSONObject): LinkedHashMap<String, String> {
val map = LinkedHashMap<String, String>()
val keys = obj.keys()
while (keys.hasNext()) {
val key = keys.next()
map[key] = obj.getString(key)
}
return map
}
fun imageBitmapToBase64(imageBitmap: ImageBitmap): String {
val bitmap = imageBitmap.asAndroidBitmap()
val outputStream = ByteArrayOutputStream()
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream)
val byteArray = outputStream.toByteArray()
return Base64.encodeToString(byteArray, Base64.DEFAULT)
}
fun base64ToImageBitmap(base64String: String): ImageBitmap {
val decodedBytes = Base64.decode(base64String, Base64.DEFAULT)
val bitmap = BitmapFactory.decodeByteArray(decodedBytes, 0, decodedBytes.size)
return bitmap.asImageBitmap()
}
+13 -1
View File
@@ -11,7 +11,8 @@
<string name="sync_is_successful">Успешная синхронизация</string> <string name="sync_is_successful">Успешная синхронизация</string>
<string name="sync_is_fail">Ошибка синхронизации. Проверьте подключение к часам</string> <string name="sync_is_fail">Ошибка синхронизации. Проверьте подключение к часам</string>
<string name="open_backup_menu">Бэкап/восстановление</string> <string name="backup">Резервное копирование</string>
<string name="open_backup_menu">Резервное копирование</string>
<string name="do_backup">Сохранить данные</string> <string name="do_backup">Сохранить данные</string>
<string name="do_restore">Восстановить данные</string> <string name="do_restore">Восстановить данные</string>
<string name="ask_do_restore">Восстановить данные?</string> <string name="ask_do_restore">Восстановить данные?</string>
@@ -30,9 +31,20 @@
<string name="card_name">Название карты</string> <string name="card_name">Название карты</string>
<string name="card_value">Значение карты</string> <string name="card_value">Значение карты</string>
<string name="do_scan_card">Сканировать карту</string> <string name="do_scan_card">Сканировать карту</string>
<string name="card_from_template">Из шаблона</string>
<string name="scan_your_card">Отсканируйте вашу карту</string> <string name="scan_your_card">Отсканируйте вашу карту</string>
<string name="card_code_type">Тип кода карты</string> <string name="card_code_type">Тип кода карты</string>
<string name="do_choose_color">Выбрать цвет</string> <string name="do_choose_color">Выбрать цвет</string>
<string name="choosing_color">Выбор цвета</string>
<string name="choosing_template">Выбор шаблона</string>
<string name="error_in_data">Ошибка в данных. Пожалуйста, заполните все необходимые (*) поля</string>
<string name="templates_not_found">Шаблоны не найдены</string>
<string name="search">Поиск</string>
<string name="cards_not_found">Карты не найдены</string>
<string name="choosing_icon">Выбор иконки</string>
<string name="icons_not_found">Иконки не найдены</string>
<string name="do_select_icon">Выбрать иконку</string>
<string name="wait_for_icon_load">Дождитесь загрузки иконки</string>
<string name="card_name_should_not_be_empty">Имя карты не должно быть пустым</string> <string name="card_name_should_not_be_empty">Имя карты не должно быть пустым</string>
<string name="card_value_should_not_be_empty">Значение карты не должно быть пустым</string> <string name="card_value_should_not_be_empty">Значение карты не должно быть пустым</string>
<string name="name_must_be_shorter_than_32_symbols">Имя карты должно быть короче 32 символов</string> <string name="name_must_be_shorter_than_32_symbols">Имя карты должно быть короче 32 символов</string>
+14 -1
View File
@@ -16,7 +16,8 @@
<string name="sync_is_successful">Sync successful</string> <string name="sync_is_successful">Sync successful</string>
<string name="sync_is_fail">Sync failed. Check your watch connection</string> <string name="sync_is_fail">Sync failed. Check your watch connection</string>
<string name="open_backup_menu">Backup / Restore</string> <string name="backup">Backup</string>
<string name="open_backup_menu">Backup</string>
<string name="do_backup">Save data</string> <string name="do_backup">Save data</string>
<string name="do_restore">Restore data</string> <string name="do_restore">Restore data</string>
<string name="ask_do_restore">Restore data?</string> <string name="ask_do_restore">Restore data?</string>
@@ -35,12 +36,24 @@
<string name="card_name">Card name</string> <string name="card_name">Card name</string>
<string name="card_value">Card value</string> <string name="card_value">Card value</string>
<string name="do_scan_card">Scan card</string> <string name="do_scan_card">Scan card</string>
<string name="card_from_template">From template</string>
<string name="scan_your_card">Scan your card</string> <string name="scan_your_card">Scan your card</string>
<string name="card_code_type">Card code type</string> <string name="card_code_type">Card code type</string>
<string name="do_choose_color">Choose color</string> <string name="do_choose_color">Choose color</string>
<string name="choosing_color">Choosing color</string>
<string name="choosing_template">Choosing template</string>
<string name="error_in_data">Error in data. Please, fill all required (*) fields</string>
<string name="templates_not_found">Templates not found</string>
<string name="search">Search</string>
<string name="cards_not_found">Cards not found</string>
<string name="choosing_icon">Choosing icon</string>
<string name="icons_not_found">Icons not found</string>
<string name="do_select_icon">Select icon</string>
<string name="wait_for_icon_load">Wait for icon load</string>
<string name="card_name_should_not_be_empty">Card name must not be empty</string> <string name="card_name_should_not_be_empty">Card name must not be empty</string>
<string name="card_value_should_not_be_empty">Card value must not be empty</string> <string name="card_value_should_not_be_empty">Card value must not be empty</string>
<string name="name_must_be_shorter_than_32_symbols">Card name must be shorter than 32 characters</string> <string name="name_must_be_shorter_than_32_symbols">Card name must be shorter than 32 characters</string>
<string name="failed_to_generate_card_code">Failed to generate card code. Check the card data</string> <string name="failed_to_generate_card_code">Failed to generate card code. Check the card data</string>
<string name="title_activity_select_icon">SelectIconActivity</string>
</resources> </resources>
+6 -2
View File
@@ -23,17 +23,20 @@ android {
minSdk = 30 minSdk = 30
targetSdk = 36 targetSdk = 36
versionCode = generateVersionCode() versionCode = generateVersionCode()
versionName = "1.3.0" versionName = "3.0.0"
} }
buildTypes { buildTypes {
release { release {
isMinifyEnabled = false isMinifyEnabled = true
proguardFiles( proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"), getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro" "proguard-rules.pro"
) )
} }
debug {
applicationIdSuffix = ".debug"
}
} }
compileOptions { compileOptions {
sourceCompatibility = JavaVersion.VERSION_11 sourceCompatibility = JavaVersion.VERSION_11
@@ -68,4 +71,5 @@ dependencies {
implementation(libs.zxing.android) implementation(libs.zxing.android)
implementation(libs.material) implementation(libs.material)
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.9.0") implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.9.0")
implementation("androidx.compose.material:material-icons-extended")
} }
Binary file not shown.
Binary file not shown.
@@ -9,5 +9,6 @@ class CardInfo (
val name: String, val name: String,
val codeType: BarcodeFormat, val codeType: BarcodeFormat,
val codeValue: String, val codeValue: String,
val color: String? val color: String?,
val icon: String?
) )
@@ -4,11 +4,14 @@ import android.content.ContentValues
import android.content.Context import android.content.Context
import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper import android.database.sqlite.SQLiteOpenHelper
import androidx.core.database.getStringOrNull
import com.google.zxing.BarcodeFormat import com.google.zxing.BarcodeFormat
class DbHelper(val context: Context, val factory: SQLiteDatabase.CursorFactory?) : SQLiteOpenHelper(context, "omni_cards", factory, 2) { class DbHelper(val context: Context, val factory: SQLiteDatabase.CursorFactory?) : SQLiteOpenHelper(context, "omni_cards", factory, 5) {
override fun onCreate(db: SQLiteDatabase?) { override fun onCreate(db: SQLiteDatabase?) {
db!!.execSQL("CREATE TABLE IF NOT EXISTS cards (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, codeType TEXT, codeValue TEXT, color TEXT)") db!!.execSQL(
"CREATE TABLE IF NOT EXISTS cards (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, codeType TEXT, codeValue TEXT, color TEXT, icon TEXT)"
)
} }
override fun onUpgrade( override fun onUpgrade(
@@ -19,6 +22,21 @@ class DbHelper(val context: Context, val factory: SQLiteDatabase.CursorFactory?)
if (oldVersion < 2) { if (oldVersion < 2) {
db!!.execSQL("ALTER TABLE cards ADD COLUMN color TEXT") db!!.execSQL("ALTER TABLE cards ADD COLUMN color TEXT")
} }
if (oldVersion < 3) {
db!!.execSQL("ALTER TABLE cards ADD COLUMN position INTEGER DEFAULT 0")
db.execSQL("ALTER TABLE cards ADD COLUMN iconPath TEXT")
db.execSQL("UPDATE cards SET position = id")
}
if (oldVersion < 4) {
db!!.execSQL("ALTER TABLE cards DROP COLUMN position")
db.execSQL("ALTER TABLE cards DROP COLUMN iconPath")
}
if (oldVersion < 5) {
db!!.execSQL("ALTER TABLE cards ADD COLUMN icon TEXT")
}
} }
fun clearDatabase() { fun clearDatabase() {
@@ -40,6 +58,7 @@ class DbHelper(val context: Context, val factory: SQLiteDatabase.CursorFactory?)
values.put("codeValue", card.codeValue) values.put("codeValue", card.codeValue)
values.put("codeType", card.codeType.name) values.put("codeType", card.codeType.name)
values.put("color", card.color) values.put("color", card.color)
values.put("icon", card.icon)
db.insert("cards", null, values) db.insert("cards", null, values)
} }
@@ -59,7 +78,8 @@ class DbHelper(val context: Context, val factory: SQLiteDatabase.CursorFactory?)
name = cursor.getString(cursor.getColumnIndexOrThrow("name")), name = cursor.getString(cursor.getColumnIndexOrThrow("name")),
codeType = BarcodeFormat.valueOf(cursor.getString(cursor.getColumnIndexOrThrow("codeType"))), codeType = BarcodeFormat.valueOf(cursor.getString(cursor.getColumnIndexOrThrow("codeType"))),
codeValue = cursor.getString(cursor.getColumnIndexOrThrow("codeValue")), codeValue = cursor.getString(cursor.getColumnIndexOrThrow("codeValue")),
color = cursor.getString(cursor.getColumnIndexOrThrow("color")) color = cursor.getString(cursor.getColumnIndexOrThrow("color")),
icon = cursor.getStringOrNull(cursor.getColumnIndexOrThrow("icon"))
)) ))
} }
@@ -86,7 +106,8 @@ class DbHelper(val context: Context, val factory: SQLiteDatabase.CursorFactory?)
name = cursor.getString(cursor.getColumnIndexOrThrow("name")), name = cursor.getString(cursor.getColumnIndexOrThrow("name")),
codeType = BarcodeFormat.valueOf(cursor.getString(cursor.getColumnIndexOrThrow("codeType"))), codeType = BarcodeFormat.valueOf(cursor.getString(cursor.getColumnIndexOrThrow("codeType"))),
codeValue = cursor.getString(cursor.getColumnIndexOrThrow("codeValue")), codeValue = cursor.getString(cursor.getColumnIndexOrThrow("codeValue")),
color = cursor.getString(cursor.getColumnIndexOrThrow("color")) color = cursor.getString(cursor.getColumnIndexOrThrow("color")),
icon = cursor.getStringOrNull(cursor.getColumnIndexOrThrow("icon"))
) )
cursor.close() cursor.close()
@@ -1,20 +1,25 @@
package ru.omni_devel.cards.presentation package ru.omni_devel.cards.presentation
import android.content.Intent import android.content.Intent
import androidx.compose.foundation.Image
import androidx.compose.foundation.background import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.QrCode
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
@@ -22,6 +27,7 @@ import androidx.compose.ui.unit.sp
import androidx.core.graphics.toColorInt import androidx.core.graphics.toColorInt
import androidx.wear.compose.material3.Button import androidx.wear.compose.material3.Button
import androidx.wear.compose.material3.ButtonDefaults import androidx.wear.compose.material3.ButtonDefaults
import androidx.wear.compose.material3.Icon
import androidx.wear.compose.material3.MaterialTheme import androidx.wear.compose.material3.MaterialTheme
import androidx.wear.compose.material3.Text import androidx.wear.compose.material3.Text
@@ -29,12 +35,18 @@ import androidx.wear.compose.material3.Text
fun CardButton(cardInfo: CardInfo) { fun CardButton(cardInfo: CardInfo) {
val context = LocalContext.current val context = LocalContext.current
val cardColor = if (cardInfo.color == null)
MaterialTheme.colorScheme.primaryContainer
else
Color(cardInfo.color.toColorInt())
Box(modifier = Modifier.fillMaxWidth()) { Box(modifier = Modifier.fillMaxWidth()) {
Button( Button(
modifier = Modifier.fillMaxWidth(), modifier = Modifier.fillMaxWidth().height(64.dp),
colors = ButtonDefaults.buttonColors( colors = ButtonDefaults.buttonColors(
containerColor = MaterialTheme.colorScheme.primaryContainer containerColor = MaterialTheme.colorScheme.primaryContainer.copy(0.625f)
), ),
shape = RoundedCornerShape(12.dp),
contentPadding = PaddingValues(0.dp), contentPadding = PaddingValues(0.dp),
onClick = { onClick = {
val intent = Intent(context, ShowCardActivity::class.java) val intent = Intent(context, ShowCardActivity::class.java)
@@ -46,32 +58,55 @@ fun CardButton(cardInfo: CardInfo) {
) { ) {
Row( Row(
modifier = Modifier modifier = Modifier
.fillMaxWidth() .fillMaxSize()
.height(IntrinsicSize.Min) .background(Color.Transparent)
.clip(ButtonDefaults.shape) .padding(horizontal = 8.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp)
) { ) {
Box( CardIcon(
modifier = Modifier if (cardInfo.icon == null) null else base64ToImageBitmap(cardInfo.icon),
.fillMaxHeight() cardColor = cardColor
.width(32.dp)
.background(
if (cardInfo.color == null)
MaterialTheme.colorScheme.secondaryContainer.copy(alpha = 0.625f)
else
Color(cardInfo.color.toColorInt()).copy(alpha = 0.625f)
)
) )
Text( Text(
cardInfo.name, cardInfo.name,
fontSize = 16.sp, fontSize = 16.sp,
color = MaterialTheme.colorScheme.onPrimaryContainer, color = MaterialTheme.colorScheme.onPrimaryContainer,
modifier = Modifier modifier = Modifier.fillMaxWidth(),
.padding(16.dp)
.fillMaxWidth()
.weight(1f),
textAlign = TextAlign.Start textAlign = TextAlign.Start
) )
} }
} }
} }
} }
@Composable
fun CardIcon(icon: ImageBitmap?, cardColor: Color) {
Row(
modifier = Modifier
.background(
cardColor.copy(0.525f),
RoundedCornerShape(12.dp)
)
.padding(8.dp)
.size(32.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Center
) {
if (icon == null) {
Icon(
modifier = Modifier.size(24.dp),
imageVector = Icons.Outlined.QrCode,
tint = MaterialTheme.colorScheme.onPrimaryContainer,
contentDescription = null
)
} else {
Image(
bitmap = icon,
contentDescription = null,
modifier = Modifier.size(32.dp)
)
}
}
}
@@ -4,6 +4,7 @@ import android.annotation.SuppressLint
import android.os.Bundle import android.os.Bundle
import androidx.activity.ComponentActivity import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.BoxWithConstraints
@@ -15,6 +16,7 @@ import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.wear.compose.foundation.lazy.TransformingLazyColumn import androidx.wear.compose.foundation.lazy.TransformingLazyColumn
import androidx.wear.compose.material3.MaterialTheme
import androidx.wear.compose.material3.Text import androidx.wear.compose.material3.Text
import ru.omni_devel.cards.R import ru.omni_devel.cards.R
@@ -35,7 +37,7 @@ class MainActivity : ComponentActivity() {
@SuppressLint("UnusedBoxWithConstraintsScope") @SuppressLint("UnusedBoxWithConstraintsScope")
@Composable @Composable
fun App(cards: List<CardInfo>) { fun App(cards: List<CardInfo>) {
BoxWithConstraints(modifier = Modifier.fillMaxSize()) { BoxWithConstraints(modifier = Modifier.fillMaxSize().background(MaterialTheme.colorScheme.background)) {
val topBottomPadding = maxHeight * 0.4f val topBottomPadding = maxHeight * 0.4f
if (cards.isEmpty()) { if (cards.isEmpty()) {
@@ -1,6 +1,10 @@
package ru.omni_devel.cards.presentation package ru.omni_devel.cards.presentation
import android.graphics.Bitmap import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.util.Base64
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.asImageBitmap
import com.google.zxing.BarcodeFormat import com.google.zxing.BarcodeFormat
import com.google.zxing.MultiFormatWriter import com.google.zxing.MultiFormatWriter
import com.journeyapps.barcodescanner.BarcodeEncoder import com.journeyapps.barcodescanner.BarcodeEncoder
@@ -11,3 +15,10 @@ fun generateCode(value: String, format: BarcodeFormat, width: Int, height: Int):
return BarcodeEncoder().createBitmap(matrix) return BarcodeEncoder().createBitmap(matrix)
} }
fun base64ToImageBitmap(base64String: String): ImageBitmap {
val decodedBytes = Base64.decode(base64String, Base64.DEFAULT)
val bitmap = BitmapFactory.decodeByteArray(decodedBytes, 0, decodedBytes.size)
return bitmap.asImageBitmap()
}