Port forwarding related code refactoring

Bug: 383243644
Test: check port forwarding behavior
Change-Id: I7c43a2015c97ffa0cd976c7c92ddbf982aa347c1
diff --git a/android/TerminalApp/java/com/android/virtualization/terminal/PortNotifier.kt b/android/TerminalApp/java/com/android/virtualization/terminal/PortNotifier.kt
index ed6e02e..dd58e0a 100644
--- a/android/TerminalApp/java/com/android/virtualization/terminal/PortNotifier.kt
+++ b/android/TerminalApp/java/com/android/virtualization/terminal/PortNotifier.kt
@@ -23,7 +23,7 @@
 import android.content.Intent
 import android.content.IntentFilter
 import android.graphics.drawable.Icon
-import java.util.HashSet
+import com.android.virtualization.terminal.MainActivity.TAG
 import java.util.Locale
 
 /**
@@ -32,7 +32,7 @@
  */
 internal class PortNotifier(val context: Context) {
     private val notificationManager: NotificationManager =
-        context.getSystemService<NotificationManager?>(NotificationManager::class.java)
+        context.getSystemService<NotificationManager>(NotificationManager::class.java)
     private val receiver: BroadcastReceiver =
         PortForwardingRequestReceiver().also {
             val intentFilter = IntentFilter(ACTION_PORT_FORWARDING)
@@ -41,15 +41,10 @@
     private val portsStateListener: PortsStateManager.Listener =
         object : PortsStateManager.Listener {
             override fun onPortsStateUpdated(oldActivePorts: Set<Int>, newActivePorts: Set<Int>) {
-                val union: MutableSet<Int> = HashSet<Int>(oldActivePorts)
-                union.addAll(newActivePorts)
-                for (port in union) {
-                    if (!oldActivePorts.contains(port)) {
-                        showNotificationFor(port)
-                    } else if (!newActivePorts.contains(port)) {
-                        discardNotificationFor(port)
-                    }
-                }
+                // added active ports
+                (newActivePorts - oldActivePorts).forEach { showNotificationFor(it) }
+                // removed active ports
+                (oldActivePorts - newActivePorts).forEach { discardNotificationFor(it) }
             }
         }
     private val portsStateManager: PortsStateManager =
@@ -64,7 +59,7 @@
         return context.getString(resId)
     }
 
-    private fun getPendingIntentFor(port: Int, enabled: Boolean): PendingIntent? {
+    private fun getPendingIntentFor(port: Int, enabled: Boolean): PendingIntent {
         val intent = Intent(ACTION_PORT_FORWARDING)
         intent.setPackage(context.getPackageName())
         intent.setIdentifier(String.format(Locale.ROOT, "%d_%b", port, enabled))
@@ -109,11 +104,11 @@
                 .addAction(acceptAction)
                 .addAction(denyAction)
                 .build()
-        notificationManager.notify(MainActivity.TAG, port, notification)
+        notificationManager.notify(TAG, port, notification)
     }
 
     private fun discardNotificationFor(port: Int) {
-        notificationManager.cancel(MainActivity.TAG, port)
+        notificationManager.cancel(TAG, port)
     }
 
     private inner class PortForwardingRequestReceiver : BroadcastReceiver() {
diff --git a/android/TerminalApp/java/com/android/virtualization/terminal/PortsStateManager.kt b/android/TerminalApp/java/com/android/virtualization/terminal/PortsStateManager.kt
index 736176a..7e53cce 100644
--- a/android/TerminalApp/java/com/android/virtualization/terminal/PortsStateManager.kt
+++ b/android/TerminalApp/java/com/android/virtualization/terminal/PortsStateManager.kt
@@ -27,7 +27,7 @@
 class PortsStateManager private constructor(private val sharedPref: SharedPreferences) {
     private val lock = Any()
 
-    @GuardedBy("lock") private var activePorts: MutableSet<Int> = hashSetOf()
+    @GuardedBy("lock") private val activePorts: MutableSet<Int> = hashSetOf()
 
     @GuardedBy("lock")
     private val enabledPorts: MutableSet<Int> =
@@ -42,29 +42,28 @@
 
     @GuardedBy("lock") private val listeners: MutableSet<Listener> = hashSetOf()
 
-    fun getActivePorts(): MutableSet<Int> {
+    fun getActivePorts(): Set<Int> {
         synchronized(lock) {
             return HashSet<Int>(activePorts)
         }
     }
 
-    fun getEnabledPorts(): MutableSet<Int> {
+    fun getEnabledPorts(): Set<Int> {
         synchronized(lock) {
             return HashSet<Int>(enabledPorts)
         }
     }
 
-    fun updateActivePorts(ports: MutableSet<Int>) {
-        var oldPorts: MutableSet<Int>
+    fun updateActivePorts(ports: Set<Int>) {
         synchronized(lock) {
-            oldPorts = activePorts
-            activePorts = ports
+            val oldPorts = getActivePorts()
+            activePorts.clear()
+            activePorts.addAll(ports)
+            notifyPortsStateUpdated(oldPorts, getActivePorts())
         }
-        notifyPortsStateUpdated(oldPorts, ports)
     }
 
     fun updateEnabledPort(port: Int, enabled: Boolean) {
-        var activePorts: MutableSet<Int>
         synchronized(lock) {
             val editor = sharedPref.edit()
             editor.putInt(port.toString(), if (enabled) FLAG_ENABLED else 0)
@@ -74,21 +73,18 @@
             } else {
                 enabledPorts.remove(port)
             }
-            activePorts = this@PortsStateManager.activePorts
         }
-        notifyPortsStateUpdated(activePorts, activePorts)
+        notifyPortsStateUpdated(getActivePorts(), getActivePorts())
     }
 
     fun clearEnabledPorts() {
-        var activePorts: MutableSet<Int>
         synchronized(lock) {
             val editor = sharedPref.edit()
             editor.clear()
             editor.apply()
             enabledPorts.clear()
-            activePorts = this@PortsStateManager.activePorts
         }
-        notifyPortsStateUpdated(activePorts, activePorts)
+        notifyPortsStateUpdated(getActivePorts(), getActivePorts())
     }
 
     fun registerListener(listener: Listener) {
@@ -99,15 +95,13 @@
         synchronized(lock) { listeners.remove(listener) }
     }
 
-    private fun notifyPortsStateUpdated(
-        oldActivePorts: MutableSet<Int>,
-        newActivePorts: MutableSet<Int>,
-    ) {
-        var listeners: MutableSet<Listener>
-        synchronized(lock) { listeners = HashSet<Listener>(this@PortsStateManager.listeners) }
-        for (listener in listeners) {
-            listener.onPortsStateUpdated(HashSet<Int>(oldActivePorts), HashSet<Int>(newActivePorts))
-        }
+    // TODO: it notifies when both enabledPort and activePort are changed, but doesn't provide
+    // enabledPort's value change. Make this callback provide that information as well.
+    private fun notifyPortsStateUpdated(oldActivePorts: Set<Int>, newActivePorts: Set<Int>) {
+        synchronized(lock) { HashSet<Listener>(this@PortsStateManager.listeners) }
+            .forEach {
+                it.onPortsStateUpdated(HashSet<Int>(oldActivePorts), HashSet<Int>(newActivePorts))
+            }
     }
 
     interface Listener {