initial commit - chats working

This commit is contained in:
2025-07-03 17:52:05 -04:00
commit ed5ee56848
35 changed files with 1827 additions and 0 deletions

142
.gitignore vendored Normal file
View File

@@ -0,0 +1,142 @@
# Built application files
*.apk
*.aar
*.ap_
*.aab
# Files for the ART/Dalvik VM
*.dex
# Java class files
*.class
# Generated files
bin/
gen/
out/
# Uncomment the following line in case you need and you don't have the release build type files in your app
# release/
# Gradle files
.gradle/
build/
# Local configuration file (sdk path, etc)
local.properties
# Proguard folder generated by Eclipse
proguard/
# Log Files
*.log
# Android Studio Navigation editor temp files
.navigation/
# Android Studio captures folder
captures/
# IntelliJ
*.iml
.idea/workspace.xml
.idea/tasks.xml
.idea/gradle.xml
.idea/assetWizardSettings.xml
.idea/dictionaries
.idea/libraries
.idea/jarRepositories.xml
# Android Studio 3 in .gitignore file.
.idea/caches
.idea/modules.xml
# Comment next line if keeping position of elements in Navigation Editor is relevant for you
.idea/navEditor.xml
# Keystore files
# Uncomment the following lines if you do not want to check your keystore files in.
#*.jks
#*.keystore
# External native build folder generated in Android Studio 2.2 and later
.externalNativeBuild
.cxx/
# Google Services (e.g. APIs or Firebase)
# google-services.json
# Freeline
freeline.py
freeline/
freeline_project_description.json
# fastlane
fastlane/report.xml
fastlane/Preview.html
fastlane/screenshots
fastlane/test_output
fastlane/readme.md
# Version control
vcs.xml
# lint
lint/intermediates/
lint/generated/
lint/outputs/
lint/tmp/
# lint/reports/
# Android Profiling
*.hprof
# Cordova plugins for Cordova-based hybrid apps
# Uncomment the following line if you're using Cordova
# plugins/
# platforms/
# macOS
.DS_Store
# Windows
Thumbs.db
# Gradle Wrapper
!gradle/wrapper/gradle-wrapper.jar
# IDE-specific files
.idea/
*.iws
*.ipr
# VS Code
.vscode/
# Eclipse
.classpath
.project
.settings/
# NDK
obj/
# Backup files
*.bak
*~
*.swp
*.swo
# Temporary files
*.tmp
*.temp
# Private/sensitive files
secrets.properties
apikeys.properties
# Kotlin
.kotlin/
# Build reports
build/reports/
# Claude Code
.claude/

126
README.md Normal file
View File

@@ -0,0 +1,126 @@
# LocalChat (lchat)
A peer-to-peer chat application for Android using Wi-Fi Aware (NAN - Neighbor Awareness Networking) technology. Chat with nearby users without internet or traditional Wi-Fi access points.
## Overview
**Package Name:** `com.mattintech.lchat`
**Min SDK:** API 26 (Android 8.0)
**Technology:** Wi-Fi Aware (NAN)
## Features
### Core Functionality
- **Dual Mode Operation:** Single APK that can function as both host and client
- **Direct P2P Communication:** No internet or router required
- **Real-time Messaging:** Instant message delivery to nearby devices
- **Auto-discovery:** Automatically find and connect to nearby chat rooms
- **Session Management:** Maintain chat sessions while devices are in range
### User Features
- Create or join chat rooms
- Set custom nicknames
- View active users in range
- Message history (session-based)
- Material Design 3 interface
- Background service for persistent connections
## Technical Requirements
### Android Permissions
```xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.NEARBY_WIFI_DEVICES" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
```
### Architecture
#### Single APK Design
The app operates in two modes within a single application:
1. **Host Mode** - Publishes a chat service for others to discover
2. **Client Mode** - Subscribes to discover available chat services
#### Key Components
- `WifiAwareManager` - Core Wi-Fi Aware functionality
- `PublishConfig` - Configuration for hosting chat rooms
- `SubscribeConfig` - Configuration for discovering chat rooms
- `WifiAwareSession` - Manages aware connections
- `NetworkSpecifier` - Establishes data paths between devices
### Data Flow
1. **Discovery Phase**
- Host publishes service with room name
- Clients subscribe to discover services
- Service discovery triggers connection UI
2. **Connection Phase**
- Client requests connection to host
- Host accepts/manages connections
- Bidirectional data path established
3. **Communication Phase**
- Messages sent over established data path
- All connected clients receive messages
- Host manages client list and broadcasting
## Project Structure
```
lchat/
├── app/
│ ├── src/main/java/com/mattintech/lchat/
│ │ ├── MainActivity.kt
│ │ ├── network/
│ │ │ ├── WifiAwareManager.kt
│ │ │ ├── ChatService.kt
│ │ │ └── MessageHandler.kt
│ │ ├── ui/
│ │ │ ├── ChatFragment.kt
│ │ │ ├── LobbyFragment.kt
│ │ │ └── adapters/
│ │ ├── data/
│ │ │ ├── Message.kt
│ │ │ ├── User.kt
│ │ │ └── ChatRepository.kt
│ │ └── utils/
│ └── src/main/res/
├── gradle/
└── build.gradle.kts
```
## Development Roadmap
### Phase 1: Foundation
- [ ] Basic Android project setup
- [ ] Wi-Fi Aware permission handling
- [ ] Simple host/client mode switching
### Phase 2: Core Messaging
- [ ] Message sending/receiving
- [ ] User management
- [ ] Basic UI implementation
### Phase 3: Enhanced Features
- [ ] Message persistence
- [ ] Reconnection handling
- [ ] Advanced UI features
### Phase 4: Polish
- [ ] Error handling
- [ ] Performance optimization
- [ ] UI/UX refinements
## Building
```bash
./gradlew assembleDebug
```
## Testing
Wi-Fi Aware requires physical devices for testing (API 26+). Emulator support is limited.
## License
[To be determined]

62
app/build.gradle.kts Normal file
View File

@@ -0,0 +1,62 @@
plugins {
id("com.android.application")
id("org.jetbrains.kotlin.android")
id("androidx.navigation.safeargs.kotlin")
}
android {
namespace = "com.mattintech.lchat"
compileSdk = 34
lint {
abortOnError = false
}
defaultConfig {
applicationId = "com.mattintech.lchat"
minSdk = 29
targetSdk = 34
versionCode = 1
versionName = "1.0"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
isMinifyEnabled = false
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
kotlinOptions {
jvmTarget = "17"
}
buildFeatures {
viewBinding = true
}
}
dependencies {
implementation("androidx.core:core-ktx:1.12.0")
implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.7.0")
implementation("androidx.activity:activity-compose:1.8.2")
implementation("androidx.appcompat:appcompat:1.6.1")
implementation("com.google.android.material:material:1.11.0")
implementation("androidx.constraintlayout:constraintlayout:2.1.4")
implementation("androidx.lifecycle:lifecycle-viewmodel-ktx:2.7.0")
implementation("androidx.lifecycle:lifecycle-livedata-ktx:2.7.0")
implementation("androidx.fragment:fragment-ktx:1.6.2")
implementation("androidx.navigation:navigation-fragment-ktx:2.7.6")
implementation("androidx.navigation:navigation-ui-ktx:2.7.6")
testImplementation("junit:junit:4.13.2")
androidTestImplementation("androidx.test.ext:junit:1.1.5")
androidTestImplementation("androidx.test.espresso:espresso-core:3.5.1")
}

14
app/proguard-rules.pro vendored Normal file
View File

@@ -0,0 +1,14 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Uncomment this to preserve the line number information for
# debugging stack traces.
-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile

View File

@@ -0,0 +1,43 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<!-- Wi-Fi Aware permissions -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.NEARBY_WIFI_DEVICES"
android:usesPermissionFlags="neverForLocation"
tools:targetApi="s" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<!-- Wi-Fi Aware feature requirement -->
<uses-feature android:name="android.hardware.wifi.aware" android:required="true" />
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/Theme.LChat"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".network.ChatService"
android:exported="false" />
</application>
</manifest>

View File

@@ -0,0 +1,78 @@
package com.mattintech.lchat
import android.Manifest
import android.util.Log
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import com.google.android.material.snackbar.Snackbar
import com.mattintech.lchat.databinding.ActivityMainBinding
import com.mattintech.lchat.utils.LOG_PREFIX
class MainActivity : AppCompatActivity() {
companion object {
private const val TAG = LOG_PREFIX + "MainActivity:"
}
private lateinit var binding: ActivityMainBinding
private val locationPermissionRequest = registerForActivityResult(
ActivityResultContracts.RequestMultiplePermissions()
) { permissions ->
when {
permissions.getOrDefault(Manifest.permission.ACCESS_FINE_LOCATION, false) -> {
Log.d(TAG, "Location permission granted")
}
else -> {
Snackbar.make(
binding.root,
getString(R.string.permission_required),
Snackbar.LENGTH_LONG
).show()
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Log.d(TAG, "onCreate")
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
setSupportActionBar(binding.toolbar)
checkPermissions()
}
private fun checkPermissions() {
val permissionsToRequest = mutableListOf<String>()
if (ContextCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_FINE_LOCATION
) != PackageManager.PERMISSION_GRANTED
) {
permissionsToRequest.add(Manifest.permission.ACCESS_FINE_LOCATION)
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
if (ContextCompat.checkSelfPermission(
this,
Manifest.permission.NEARBY_WIFI_DEVICES
) != PackageManager.PERMISSION_GRANTED
) {
permissionsToRequest.add(Manifest.permission.NEARBY_WIFI_DEVICES)
}
}
if (permissionsToRequest.isNotEmpty()) {
Log.d(TAG, "Requesting permissions: $permissionsToRequest")
locationPermissionRequest.launch(permissionsToRequest.toTypedArray())
} else {
Log.d(TAG, "All permissions already granted")
}
}
}

View File

@@ -0,0 +1,10 @@
package com.mattintech.lchat.data
data class Message(
val id: String,
val senderId: String,
val senderName: String,
val content: String,
val timestamp: Long,
val isLocal: Boolean = false
)

View File

@@ -0,0 +1,8 @@
package com.mattintech.lchat.data
data class User(
val id: String,
val name: String,
val isHost: Boolean = false,
val lastSeen: Long = System.currentTimeMillis()
)

View File

@@ -0,0 +1,20 @@
package com.mattintech.lchat.network
import android.app.Service
import android.content.Intent
import android.os.IBinder
class ChatService : Service() {
override fun onBind(intent: Intent?): IBinder? {
return null
}
override fun onCreate() {
super.onCreate()
}
override fun onDestroy() {
super.onDestroy()
}
}

View File

@@ -0,0 +1,230 @@
package com.mattintech.lchat.network
import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.net.NetworkRequest
import android.net.wifi.aware.*
import android.os.Build
import android.util.Log
import androidx.annotation.RequiresApi
import com.mattintech.lchat.utils.LOG_PREFIX
import java.util.concurrent.ConcurrentHashMap
@RequiresApi(Build.VERSION_CODES.O)
class WifiAwareManager(private val context: Context) {
companion object {
private const val TAG = LOG_PREFIX + "WifiAwareManager:"
private const val SERVICE_NAME = "lchat"
private const val PORT = 8888
}
private var wifiAwareManager: android.net.wifi.aware.WifiAwareManager? = null
private var wifiAwareSession: WifiAwareSession? = null
private var publishDiscoverySession: PublishDiscoverySession? = null
private var subscribeDiscoverySession: SubscribeDiscoverySession? = null
private val peerHandles = ConcurrentHashMap<String, PeerHandle>()
private var messageCallback: ((String, String, String) -> Unit)? = null
private var connectionCallback: ((String, Boolean) -> Unit)? = null
private val attachCallback = object : AttachCallback() {
override fun onAttached(session: WifiAwareSession) {
Log.d(TAG, "Wi-Fi Aware attached")
wifiAwareSession = session
}
override fun onAttachFailed() {
Log.e(TAG, "Wi-Fi Aware attach failed")
}
}
fun initialize() {
wifiAwareManager = context.getSystemService(Context.WIFI_AWARE_SERVICE) as? android.net.wifi.aware.WifiAwareManager
if (wifiAwareManager?.isAvailable == true) {
wifiAwareManager?.attach(attachCallback, null)
} else {
Log.e(TAG, "Wi-Fi Aware is not available")
}
}
fun startHostMode(roomName: String) {
val config = PublishConfig.Builder()
.setServiceName(SERVICE_NAME)
.setServiceSpecificInfo(roomName.toByteArray())
.build()
wifiAwareSession?.publish(config, object : DiscoverySessionCallback() {
override fun onPublishStarted(session: PublishDiscoverySession) {
Log.d(TAG, "Publish started for room: $roomName")
publishDiscoverySession = session
}
override fun onMessageReceived(peerHandle: PeerHandle, message: ByteArray) {
val messageStr = String(message)
Log.d(TAG, "Host: Received message: $messageStr")
if (messageStr == "CONNECT_REQUEST") {
Log.d(TAG, "Host: Received connection request")
acceptConnection(peerHandle)
} else {
handleIncomingMessage(peerHandle, message)
}
}
}, null)
}
fun startClientMode() {
val config = SubscribeConfig.Builder()
.setServiceName(SERVICE_NAME)
.build()
wifiAwareSession?.subscribe(config, object : DiscoverySessionCallback() {
override fun onSubscribeStarted(session: SubscribeDiscoverySession) {
Log.d(TAG, "Subscribe started")
subscribeDiscoverySession = session
}
override fun onServiceDiscovered(
peerHandle: PeerHandle,
serviceSpecificInfo: ByteArray?,
matchFilter: List<ByteArray>?
) {
val roomName = serviceSpecificInfo?.let { String(it) } ?: "Unknown"
Log.d(TAG, "Discovered room: $roomName")
// Store peer handle for this room
peerHandles[roomName] = peerHandle
// Send connection request to host
Log.d(TAG, "Sending connection request to room: $roomName")
subscribeDiscoverySession?.sendMessage(peerHandle, 0, "CONNECT_REQUEST".toByteArray())
// Wait a bit for host to prepare, then connect
android.os.Handler(android.os.Looper.getMainLooper()).postDelayed({
connectToPeer(peerHandle, roomName)
}, 500)
}
override fun onMessageReceived(peerHandle: PeerHandle, message: ByteArray) {
handleIncomingMessage(peerHandle, message)
}
}, null)
}
private fun connectToPeer(peerHandle: PeerHandle, roomName: String) {
Log.d(TAG, "connectToPeer: Starting connection to room: $roomName")
val networkSpecifier = WifiAwareNetworkSpecifier.Builder(subscribeDiscoverySession!!, peerHandle)
.setPskPassphrase("lchat-secure-key")
.build()
val networkRequest = NetworkRequest.Builder()
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI_AWARE)
.setNetworkSpecifier(networkSpecifier)
.build()
Log.d(TAG, "connectToPeer: Network request created for room: $roomName")
val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
try {
connectivityManager.requestNetwork(networkRequest, object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: android.net.Network) {
Log.d(TAG, "onAvailable: Network connected for room: $roomName")
connectionCallback?.invoke(roomName, true)
}
override fun onLost(network: android.net.Network) {
Log.d(TAG, "onLost: Network lost for room: $roomName")
connectionCallback?.invoke(roomName, false)
}
override fun onUnavailable() {
Log.e(TAG, "onUnavailable: Network request failed for room: $roomName")
connectionCallback?.invoke(roomName, false)
}
override fun onCapabilitiesChanged(network: android.net.Network, networkCapabilities: NetworkCapabilities) {
Log.d(TAG, "onCapabilitiesChanged: Capabilities changed for room: $roomName")
}
override fun onLinkPropertiesChanged(network: android.net.Network, linkProperties: android.net.LinkProperties) {
Log.d(TAG, "onLinkPropertiesChanged: Link properties changed for room: $roomName")
}
}, android.os.Handler(android.os.Looper.getMainLooper()), 30000) // 30 second timeout
Log.d(TAG, "connectToPeer: Network request submitted for room: $roomName")
} catch (e: Exception) {
Log.e(TAG, "connectToPeer: Failed to request network", e)
connectionCallback?.invoke(roomName, false)
}
}
private fun acceptConnection(peerHandle: PeerHandle) {
Log.d(TAG, "acceptConnection: Accepting connection from client")
val networkSpecifier = WifiAwareNetworkSpecifier.Builder(publishDiscoverySession!!, peerHandle)
.setPskPassphrase("lchat-secure-key")
.setPort(PORT)
.build()
val networkRequest = NetworkRequest.Builder()
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI_AWARE)
.setNetworkSpecifier(networkSpecifier)
.build()
val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
connectivityManager.requestNetwork(networkRequest, object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: android.net.Network) {
Log.d(TAG, "Client connected")
peerHandles[peerHandle.toString()] = peerHandle
}
override fun onUnavailable() {
Log.e(TAG, "Failed to accept client connection - Check if Wi-Fi is enabled")
}
})
}
private fun handleIncomingMessage(peerHandle: PeerHandle, message: ByteArray) {
try {
val messageStr = String(message)
val parts = messageStr.split("|", limit = 3)
if (parts.size == 3) {
messageCallback?.invoke(parts[0], parts[1], parts[2])
}
} catch (e: Exception) {
Log.e(TAG, "Error parsing message", e)
}
}
fun sendMessage(userId: String, userName: String, content: String) {
val message = "$userId|$userName|$content".toByteArray()
if (publishDiscoverySession != null) {
peerHandles.values.forEach { peerHandle ->
publishDiscoverySession?.sendMessage(peerHandle, 0, message)
}
} else if (subscribeDiscoverySession != null) {
peerHandles.values.forEach { peerHandle ->
subscribeDiscoverySession?.sendMessage(peerHandle, 0, message)
}
}
}
fun setMessageCallback(callback: (String, String, String) -> Unit) {
messageCallback = callback
}
fun setConnectionCallback(callback: (String, Boolean) -> Unit) {
connectionCallback = callback
}
fun stop() {
publishDiscoverySession?.close()
subscribeDiscoverySession?.close()
wifiAwareSession?.close()
peerHandles.clear()
}
}

View File

@@ -0,0 +1,20 @@
package com.mattintech.lchat.network
import android.content.Context
object WifiAwareManagerSingleton {
private var instance: WifiAwareManager? = null
fun getInstance(context: Context): WifiAwareManager {
if (instance == null) {
instance = WifiAwareManager(context.applicationContext)
instance!!.initialize()
}
return instance!!
}
fun reset() {
instance?.stop()
instance = null
}
}

View File

@@ -0,0 +1,125 @@
package com.mattintech.lchat.ui
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.navArgs
import androidx.recyclerview.widget.LinearLayoutManager
import com.mattintech.lchat.data.Message
import com.mattintech.lchat.databinding.FragmentChatBinding
import com.mattintech.lchat.network.WifiAwareManager
import com.mattintech.lchat.network.WifiAwareManagerSingleton
import com.mattintech.lchat.ui.adapters.MessageAdapter
import com.mattintech.lchat.utils.LOG_PREFIX
import java.util.UUID
class ChatFragment : Fragment() {
companion object {
private const val TAG = LOG_PREFIX + "ChatFragment:"
}
private var _binding: FragmentChatBinding? = null
private val binding get() = _binding!!
private val args: ChatFragmentArgs by navArgs()
private lateinit var wifiAwareManager: WifiAwareManager
private lateinit var messageAdapter: MessageAdapter
private val messages = mutableListOf<Message>()
private val userId = UUID.randomUUID().toString()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
Log.d(TAG, "onCreateView")
_binding = FragmentChatBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
Log.d(TAG, "onViewCreated - room: ${args.roomName}, user: ${args.userName}, isHost: ${args.isHost}")
setupUI()
setupWifiAware()
}
private fun setupUI() {
messageAdapter = MessageAdapter()
binding.messagesRecyclerView.apply {
adapter = messageAdapter
layoutManager = LinearLayoutManager(context).apply {
stackFromEnd = true
}
}
binding.sendButton.setOnClickListener {
sendMessage()
}
binding.messageInput.setOnEditorActionListener { _, _, _ ->
sendMessage()
true
}
}
private fun setupWifiAware() {
wifiAwareManager = WifiAwareManagerSingleton.getInstance(requireContext())
wifiAwareManager.setMessageCallback { senderId, senderName, content ->
Log.d(TAG, "Message received - from: $senderName, content: $content")
val message = Message(
id = UUID.randomUUID().toString(),
senderId = senderId,
senderName = senderName,
content = content,
timestamp = System.currentTimeMillis(),
isLocal = senderId == userId
)
activity?.runOnUiThread {
messages.add(message)
messageAdapter.submitList(messages.toList())
binding.messagesRecyclerView.smoothScrollToPosition(messages.size - 1)
}
}
// No need to start host mode here - already started in LobbyFragment
Log.d(TAG, "Chat setup complete - isHost: ${args.isHost}, room: ${args.roomName}")
}
private fun sendMessage() {
val content = binding.messageInput.text?.toString()?.trim()
if (content.isNullOrEmpty()) return
val message = Message(
id = UUID.randomUUID().toString(),
senderId = userId,
senderName = args.userName,
content = content,
timestamp = System.currentTimeMillis(),
isLocal = true
)
messages.add(message)
messageAdapter.submitList(messages.toList())
binding.messagesRecyclerView.smoothScrollToPosition(messages.size - 1)
Log.d(TAG, "Sending message: $content")
wifiAwareManager.sendMessage(userId, args.userName, content)
binding.messageInput.text?.clear()
}
override fun onDestroyView() {
super.onDestroyView()
Log.d(TAG, "onDestroyView")
// Don't stop WifiAwareManager here - it's shared across fragments
_binding = null
}
}

View File

@@ -0,0 +1,130 @@
package com.mattintech.lchat.ui
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import com.mattintech.lchat.R
import com.mattintech.lchat.databinding.FragmentLobbyBinding
import com.mattintech.lchat.network.WifiAwareManager
import com.mattintech.lchat.network.WifiAwareManagerSingleton
import com.mattintech.lchat.utils.LOG_PREFIX
class LobbyFragment : Fragment() {
companion object {
private const val TAG = LOG_PREFIX + "LobbyFragment:"
}
private var _binding: FragmentLobbyBinding? = null
private val binding get() = _binding!!
private lateinit var wifiAwareManager: WifiAwareManager
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
Log.d(TAG, "onCreateView")
_binding = FragmentLobbyBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
Log.d(TAG, "onViewCreated")
Log.d(TAG, "Getting WifiAwareManager singleton")
wifiAwareManager = WifiAwareManagerSingleton.getInstance(requireContext())
setupUI()
}
private fun setupUI() {
binding.modeRadioGroup.setOnCheckedChangeListener { _, checkedId ->
when (checkedId) {
R.id.hostRadio -> {
binding.roomLayout.visibility = View.VISIBLE
binding.actionButton.text = getString(R.string.start_hosting)
binding.roomsRecyclerView.visibility = View.GONE
binding.noRoomsText.visibility = View.GONE
}
R.id.clientRadio -> {
binding.roomLayout.visibility = View.GONE
binding.actionButton.text = getString(R.string.search_rooms)
binding.roomsRecyclerView.visibility = View.VISIBLE
}
}
}
binding.actionButton.setOnClickListener {
val userName = binding.nameInput.text?.toString()?.trim()
if (userName.isNullOrEmpty()) {
Toast.makeText(context, "Please enter your name", Toast.LENGTH_SHORT).show()
return@setOnClickListener
}
when (binding.modeRadioGroup.checkedRadioButtonId) {
R.id.hostRadio -> {
val roomName = binding.roomInput.text?.toString()?.trim()
if (roomName.isNullOrEmpty()) {
Toast.makeText(context, "Please enter a room name", Toast.LENGTH_SHORT).show()
return@setOnClickListener
}
startHostMode(roomName, userName)
}
R.id.clientRadio -> {
startClientMode(userName)
}
}
}
wifiAwareManager.setConnectionCallback { roomName, isConnected ->
Log.d(TAG, "Connection callback - room: $roomName, connected: $isConnected")
activity?.runOnUiThread {
if (isConnected && binding.modeRadioGroup.checkedRadioButtonId == R.id.clientRadio) {
val userName = binding.nameInput.text?.toString()?.trim() ?: ""
navigateToChat(roomName, userName, false)
} else if (!isConnected && binding.modeRadioGroup.checkedRadioButtonId == R.id.clientRadio) {
binding.noRoomsText.text = "Failed to connect to $roomName. Ensure Wi-Fi is enabled on both devices."
Toast.makeText(context, "Connection failed. Check Wi-Fi is enabled.", Toast.LENGTH_LONG).show()
}
}
}
}
private fun startHostMode(roomName: String, userName: String) {
Log.d(TAG, "Starting host mode - room: $roomName, user: $userName")
wifiAwareManager.startHostMode(roomName)
navigateToChat(roomName, userName, true)
}
private fun startClientMode(userName: String) {
Log.d(TAG, "Starting client mode - user: $userName")
binding.noRoomsText.visibility = View.VISIBLE
binding.noRoomsText.text = getString(R.string.connecting)
wifiAwareManager.startClientMode()
}
private fun navigateToChat(roomName: String, userName: String, isHost: Boolean) {
Log.d(TAG, "Navigating to chat - room: $roomName, user: $userName, isHost: $isHost")
val action = LobbyFragmentDirections.actionLobbyToChat(
roomName = roomName,
userName = userName,
isHost = isHost
)
findNavController().navigate(action)
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}

View File

@@ -0,0 +1,69 @@
package com.mattintech.lchat.ui.adapters
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.mattintech.lchat.R
import com.mattintech.lchat.data.Message
import com.mattintech.lchat.databinding.ItemMessageBinding
import java.text.SimpleDateFormat
import java.util.*
class MessageAdapter : ListAdapter<Message, MessageAdapter.MessageViewHolder>(MessageDiffCallback()) {
private val timeFormat = SimpleDateFormat("HH:mm", Locale.getDefault())
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MessageViewHolder {
val binding = ItemMessageBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
return MessageViewHolder(binding)
}
override fun onBindViewHolder(holder: MessageViewHolder, position: Int) {
holder.bind(getItem(position))
}
inner class MessageViewHolder(
private val binding: ItemMessageBinding
) : RecyclerView.ViewHolder(binding.root) {
fun bind(message: Message) {
binding.senderName.text = message.senderName
binding.messageContent.text = message.content
binding.timestamp.text = timeFormat.format(Date(message.timestamp))
val layoutParams = binding.messageCard.layoutParams as ConstraintLayout.LayoutParams
if (message.isLocal) {
layoutParams.startToStart = ConstraintLayout.LayoutParams.UNSET
layoutParams.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID
binding.messageCard.setCardBackgroundColor(
ContextCompat.getColor(binding.root.context, R.color.purple_200)
)
} else {
layoutParams.startToStart = ConstraintLayout.LayoutParams.PARENT_ID
layoutParams.endToEnd = ConstraintLayout.LayoutParams.UNSET
binding.messageCard.setCardBackgroundColor(
ContextCompat.getColor(binding.root.context, R.color.teal_200)
)
}
binding.messageCard.layoutParams = layoutParams
}
}
class MessageDiffCallback : DiffUtil.ItemCallback<Message>() {
override fun areItemsTheSame(oldItem: Message, newItem: Message): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: Message, newItem: Message): Boolean {
return oldItem == newItem
}
}
}

View File

@@ -0,0 +1,3 @@
package com.mattintech.lchat.utils
const val LOG_PREFIX = "LChat::"

View File

@@ -0,0 +1,12 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp"
android:height="108dp"
android:viewportWidth="108"
android:viewportHeight="108">
<path
android:fillColor="#FF000000"
android:pathData="M54,34 C43,34 34,43 34,54 C34,65 43,74 54,74 C65,74 74,65 74,54 C74,43 65,34 54,34 Z M54,40 C62,40 68,46 68,54 C68,62 62,68 54,68 C46,68 40,62 40,54 C40,46 46,40 54,40 Z"/>
<path
android:fillColor="#FF000000"
android:pathData="M48,50 L60,50 L60,52 L48,52 Z M48,56 L60,56 L60,58 L48,58 Z"/>
</vector>

View File

@@ -0,0 +1,31 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.google.android.material.appbar.MaterialToolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
app:title="@string/app_name"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
<androidx.fragment.app.FragmentContainerView
android:id="@+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="0dp"
android:layout_height="0dp"
app:defaultNavHost="true"
app:navGraph="@navigation/nav_graph"
app:layout_constraintTop_toBottomOf="@id/toolbar"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

View File

@@ -0,0 +1,57 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/messagesRecyclerView"
android:layout_width="0dp"
android:layout_height="0dp"
android:padding="8dp"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toTopOf="@id/messageInputLayout"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
<com.google.android.material.card.MaterialCardView
android:id="@+id/messageInputLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
app:cardElevation="4dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="8dp"
android:gravity="center_vertical">
<EditText
android:id="@+id/messageInput"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="@string/type_message"
android:inputType="textMultiLine"
android:maxLines="4"
android:padding="12dp"
android:background="@null" />
<ImageButton
android:id="@+id/sendButton"
android:layout_width="48dp"
android:layout_height="48dp"
android:src="@android:drawable/ic_menu_send"
android:contentDescription="@string/send"
android:background="?attr/selectableItemBackgroundBorderless" />
</LinearLayout>
</com.google.android.material.card.MaterialCardView>
</androidx.constraintlayout.widget.ConstraintLayout>

View File

@@ -0,0 +1,115 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp">
<com.google.android.material.card.MaterialCardView
android:id="@+id/modeCard"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardElevation="4dp"
app:layout_constraintTop_toTopOf="parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Choose Mode"
android:textAppearance="?attr/textAppearanceHeadline6"
android:layout_marginBottom="16dp" />
<RadioGroup
android:id="@+id/modeRadioGroup"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RadioButton
android:id="@+id/hostRadio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/host_mode"
android:checked="true" />
<RadioButton
android:id="@+id/clientRadio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/client_mode" />
</RadioGroup>
</LinearLayout>
</com.google.android.material.card.MaterialCardView>
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/nameLayout"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
app:layout_constraintTop_toBottomOf="@id/modeCard"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/nameInput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/your_name"
android:inputType="textPersonName" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/roomLayout"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
app:layout_constraintTop_toBottomOf="@id/nameLayout"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/roomInput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/room_name"
android:inputType="text" />
</com.google.android.material.textfield.TextInputLayout>
<Button
android:id="@+id/actionButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="@string/start_hosting"
app:layout_constraintTop_toBottomOf="@id/roomLayout" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/roomsRecyclerView"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginTop="16dp"
android:visibility="gone"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
app:layout_constraintTop_toBottomOf="@id/actionButton"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
<TextView
android:id="@+id/noRoomsText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/no_rooms_found"
android:textAppearance="?attr/textAppearanceBody1"
android:visibility="gone"
app:layout_constraintTop_toBottomOf="@id/actionButton"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

View File

@@ -0,0 +1,50 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp">
<com.google.android.material.card.MaterialCardView
android:id="@+id/messageCard"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="4dp"
app:cardCornerRadius="12dp"
app:cardElevation="0dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="12dp"
android:maxWidth="280dp">
<TextView
android:id="@+id/senderName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textSize="14sp"
android:layout_marginBottom="4dp" />
<TextView
android:id="@+id/messageContent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16sp" />
<TextView
android:id="@+id/timestamp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="12sp"
android:layout_marginTop="4dp"
android:alpha="0.6" />
</LinearLayout>
</com.google.android.material.card.MaterialCardView>
</androidx.constraintlayout.widget.ConstraintLayout>

View File

@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@android:color/white"/>
<foreground android:drawable="@drawable/ic_launcher_foreground"/>
</adaptive-icon>

View File

@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@android:color/white"/>
<foreground android:drawable="@drawable/ic_launcher_foreground"/>
</adaptive-icon>

View File

@@ -0,0 +1,34 @@
<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/nav_graph"
app:startDestination="@id/lobbyFragment">
<fragment
android:id="@+id/lobbyFragment"
android:name="com.mattintech.lchat.ui.LobbyFragment"
android:label="Lobby"
tools:layout="@layout/fragment_lobby">
<action
android:id="@+id/action_lobby_to_chat"
app:destination="@id/chatFragment" />
</fragment>
<fragment
android:id="@+id/chatFragment"
android:name="com.mattintech.lchat.ui.ChatFragment"
android:label="Chat"
tools:layout="@layout/fragment_chat">
<argument
android:name="roomName"
app:argType="string" />
<argument
android:name="userName"
app:argType="string" />
<argument
android:name="isHost"
app:argType="boolean" />
</fragment>
</navigation>

View File

@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="purple_200">#FFBB86FC</color>
<color name="purple_500">#FF6200EE</color>
<color name="purple_700">#FF3700B3</color>
<color name="teal_200">#FF03DAC5</color>
<color name="teal_700">#FF018786</color>
<color name="black">#FF000000</color>
<color name="white">#FFFFFFFF</color>
</resources>

View File

@@ -0,0 +1,15 @@
<resources>
<string name="app_name">LocalChat</string>
<string name="host_mode">Host Mode</string>
<string name="client_mode">Join Mode</string>
<string name="room_name">Room Name</string>
<string name="your_name">Your Name</string>
<string name="start_hosting">Start Hosting</string>
<string name="search_rooms">Search Rooms</string>
<string name="send">Send</string>
<string name="type_message">Type a message...</string>
<string name="connected_users">Connected Users</string>
<string name="no_rooms_found">No rooms found nearby</string>
<string name="connecting">Connecting...</string>
<string name="permission_required">Location permission is required for Wi-Fi Aware</string>
</resources>

View File

@@ -0,0 +1,11 @@
<resources xmlns:tools="http://schemas.android.com/tools">
<style name="Theme.LChat" parent="Theme.Material3.DayNight.NoActionBar">
<item name="colorPrimary">@color/purple_500</item>
<item name="colorPrimaryVariant">@color/purple_700</item>
<item name="colorOnPrimary">@color/white</item>
<item name="colorSecondary">@color/teal_200</item>
<item name="colorSecondaryVariant">@color/teal_700</item>
<item name="colorOnSecondary">@color/black</item>
<item name="android:statusBarColor">?attr/colorPrimaryVariant</item>
</style>
</resources>

View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<full-backup-content>
<exclude domain="sharedpref" path="."/>
<exclude domain="database" path="."/>
<exclude domain="file" path="."/>
<exclude domain="external" path="."/>
<exclude domain="root" path="."/>
</full-backup-content>

View File

@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<data-extraction-rules>
<cloud-backup>
<exclude domain="sharedpref" path="."/>
<exclude domain="database" path="."/>
<exclude domain="file" path="."/>
<exclude domain="root" path="."/>
</cloud-backup>
</data-extraction-rules>

15
build.gradle.kts Normal file
View File

@@ -0,0 +1,15 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
mavenCentral()
}
dependencies {
classpath("androidx.navigation:navigation-safe-args-gradle-plugin:2.7.6")
}
}
plugins {
id("com.android.application") version "8.9.1" apply false
id("org.jetbrains.kotlin.android") version "1.9.0" apply false
}

6
gradle.properties Normal file
View File

@@ -0,0 +1,6 @@
# Project-wide Gradle settings.
org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
android.useAndroidX=true
android.nonTransitiveRClass=true
android.defaults.buildfeatures.buildconfig=true
android.nonFinalResIds=false

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View File

@@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.11.1-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

249
gradlew vendored Executable file
View File

@@ -0,0 +1,249 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# 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
#
# https://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.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

92
gradlew.bat vendored Normal file
View File

@@ -0,0 +1,92 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

16
settings.gradle.kts Normal file
View File

@@ -0,0 +1,16 @@
pluginManagement {
repositories {
google()
mavenCentral()
gradlePluginPortal()
}
}
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google()
mavenCentral()
}
}
rootProject.name = "lchat"
include(":app")