Quellcode durchsuchen

network widget progress

Johan Rong vor 3 Monaten
Ursprung
Commit
0aae0afa65

+ 6 - 6
flake.lock

@@ -7,11 +7,11 @@
         ]
       },
       "locked": {
-        "lastModified": 1777851538,
-        "narHash": "sha256-Gp8qwTEYNoy2yvmErVGlvLOQvrtEECCAKbonW7VJef8=",
+        "lastModified": 1778401693,
+        "narHash": "sha256-OVHdCqXXUF5UdGkH+FF2ZL06OLZjj2kvP2dIUmzVWoo=",
         "owner": "nix-community",
         "repo": "home-manager",
-        "rev": "cc09c0f9b7eaa95c2d9827338a5eb03d32505ca5",
+        "rev": "389b83002efc26f1145e89a6a8e6edc5a6435948",
         "type": "github"
       },
       "original": {
@@ -39,11 +39,11 @@
     },
     "nixpkgs": {
       "locked": {
-        "lastModified": 1777673416,
-        "narHash": "sha256-5c2POKPOjU40Kh0MirOdScBLG0bu9TAuPYAtPRNZMBs=",
+        "lastModified": 1778003029,
+        "narHash": "sha256-q/nkKLDtHIyLjZpKhWk3cSK5IYsFqtMd6UtXF3ddjgA=",
         "owner": "NixOS",
         "repo": "nixpkgs",
-        "rev": "26ef669cffa904b6f6832ab57b77892a37c1a671",
+        "rev": "0c88e1f2bdb93d5999019e99cb0e61e1fe2af4c5",
         "type": "github"
       },
       "original": {

+ 0 - 91
home/features/desktop/sway/scripts.nix

@@ -2,83 +2,6 @@
 {
   home = {
     file = {
-      clock = {
-        target = ".config/waybar/clock.sh";
-        text = ''
-        # Generate the formatted date string
-        formatted_date=$(LC_TIME=nb_NO.UTF-8 date +"%H:%M %A, %d %b" | tr '[:upper:]' '[:lower:]' | sed 's/\.//g')
-
-        # Output as JSON for Waybar
-        printf '{"text": "%s"}\n' "$formatted_date"
-        '';
-        executable = true;
-      };
-      memory = {
-        target = ".config/waybar/memory.sh";
-        text = ''
-          free -m | awk '
-          /^Mem:/ {
-              current_gb = $3 / 1024;
-              total_gb = $2 / 1024;
-              printf "{\"text\": \"%.1fG/%.1fG\"}\n", current_gb, total_gb
-          }'
-        '';
-        executable = true;
-      };
-      volume = {
-        target = ".config/waybar/volume.sh";
-        text = ''
-          VOLUME_INFO=$(wpctl get-volume @DEFAULT_AUDIO_SINK@)
-          VOL_NUM=$(echo "$VOLUME_INFO" | awk '{print $2}')
-          VOL_PERC=$(awk -v n="$VOL_NUM" 'BEGIN {print int(n * 100)}')
-
-          if [[ "$VOLUME_INFO" == *"[MUTED]"* ]]; then
-              RESULT="M($VOL_PERC%)"
-          else
-              RESULT="$VOL_PERC%"
-          fi
-
-          echo "{\"text\": \"$RESULT\"}"
-        '';
-        executable = true;
-      };
-      mic = {
-        target = ".config/waybar/mic.sh";
-        text = ''
-          VOLUME_INFO=$(wpctl get-volume @DEFAULT_AUDIO_SOURCE@)
-          VOL_NUM=$(echo "$VOLUME_INFO" | awk '{print $2}')
-          VOL_PERC=$(awk -v n="$VOL_NUM" 'BEGIN {print int(n * 100)}')
-
-          if [[ "$VOLUME_INFO" == *"[MUTED]"* ]]; then
-              RESULT="M($VOL_PERC%)"
-          else
-              RESULT="$VOL_PERC%"
-          fi
-
-          echo "{\"text\": \"$RESULT\"}"
-        '';
-        executable = true;
-      };
-      net = {
-        target = ".config/waybar/net.sh";
-        executable = true;
-        text = ''
-          #!/usr/bin/env bash
-
-          # Get default network interface
-          DEVICE=$(ip route | awk '/default/ {print $5; exit}')
-
-          if [[ -n "$DEVICE" ]]; then
-              IP=$(ip -4 addr show "$DEVICE" | awk '/inet / {print $2}' | cut -d/ -f1 | head -n1)
-
-              RESULT="$DEVICE"
-          else
-              RESULT="Disconnected"
-          fi
-
-          echo "{\"text\": \"$RESULT\"}"
-        '';
-      };
       mic-mute = {
         target = ".config/waybar/mic-mute.sh";
         text = ''
@@ -123,20 +46,6 @@
         '';
         executable = true;
       };
-      #futhark-xkb = {
-      #  target = ".config/xkb/symbols/futhark";
-      #  text = ''
-      #    default partial alphanumeric_keys
-      #    xkb_symbols "basic" {
-#
-      #        name[Group1]= "Futhark";
-#
-      #        key <AD04> { [ U16A0 ] }; // f -> ᚠ
-#
-      #        include "no(basic)"
-      #    };
-      #  '';
-      #};
     };
   };
 }

+ 8 - 1
home/features/desktop/sway/ui/eww/default.nix

@@ -19,7 +19,14 @@
       eww_scss = {
         target = ".config/eww/eww.scss";
         text = ''
-          
+          @import "widgets/network/network.scss";
+
+          * {
+            border: none;
+            font-family: "JetBrainsMono Nerd Font", "Material Symbols Outlined";
+            font-size: 12px;
+            font-weight: 700;
+          }
         '';
       };
     };

+ 12 - 136
home/features/desktop/sway/ui/eww/network/default.nix

@@ -8,151 +8,27 @@ in
   home = {
     file = {
       "${folder}/network.yuck".source = ./network.yuck;
-      network_scss = {
-        target = "${folder}/network.scss";
-        text = ''
-          .network-menu {
-            background: #1e1e2e;
-            border-radius: 14px;
-            padding: 16px;
-            min-width: 320px;
-          }
-
-          .title {
-            font-size: 22px;
-            margin-bottom: 12px;
-          }
+      "${folder}/network.scss".source = ./network.scss;
 
-          button {
-            background: #313244;
-            border-radius: 10px;
-            padding: 10px;
-            margin: 4px 0;
-          }
-
-          button:hover {
-            background: #45475a;
-          }
-        '';
-      };
-      network_connections_sh = {
-        target = "${scripts}/connections.sh";
+      "${scripts}/available_wifi.py" = {
+        source = ./scripts/available_wifi.py;
         executable = true;
-        text = ''
-          #!/usr/bin/env bash
-
-          echo '(box :orientation "v" :spacing 12'
-
-          #
-          # ACTIVE CONNECTIONS
-          #
-
-          echo '(label :text "Connected")'
-
-          nmcli -t -f NAME,TYPE,DEVICE connection show --active | \
-          while IFS=: read -r name type device
-          do
-              icon="󰈀"
-
-              case "$type" in
-                  802-11-wireless)
-                      icon="󰤨"
-                      ;;
-                  802-3-ethernet)
-                      icon="󰈁"
-                      ;;
-                  vpn)
-                      icon="󰖂"
-                      ;;
-              esac
-
-              safe_name=$(printf '%s\n' "$name" | sed 's/"/\\"/g')
-
-              echo "(button
-                  :onclick \"~/.config/eww/widgets/network/scripts/disconnect.sh '$safe_name'\"
-                  (box :orientation \"h\" :spacing 12
-                      (label :text \"$icon\")
-                      (label :text \"$safe_name\")
-                      (label :text \"Connected\")
-                  )
-              )"
-          done
-
-          #
-          # WIFI NETWORKS
-          #
-
-          echo '(label :text "Wi-Fi")'
-
-          nmcli -t -f SSID,SIGNAL device wifi list | \
-          awk -F: '
-          {
-              ssid=$1
-              signal=$2
-
-              if (ssid == "")
-                  next
-
-              if (!(ssid in best) || signal > best[ssid]) {
-                  best[ssid]=signal
-              }
-          }
-          END {
-              for (ssid in best)
-                  print ssid ":" best[ssid]
-          }
-          ' | sort -t: -k2 -nr | \
-          while IFS=: read -r ssid signal
-          do
-              safe_ssid=$(printf '%s\n' "$ssid" | sed 's/"/\\"/g')
-
-              if [ "$signal" -ge 80 ]; then
-                  icon="󰤨"
-              elif [ "$signal" -ge 60 ]; then
-                  icon="󰤥"
-              elif [ "$signal" -ge 40 ]; then
-                  icon="󰤢"
-              else
-                  icon="󰤟"
-              fi
-
-              echo "(button
-                  :onclick \"~/.config/eww/widgets/network/scripts/connect.sh '$safe_ssid'\"
-                  (box :orientation \"h\" :spacing 12
-                      (label :text \"$icon\")
-                      (label :text \"$safe_ssid\")
-                      (label :text \"$signal%\")
-                  )
-              )"
-          done
-
-          echo ")"
-        '';
       };
-      network_connect_sh = {
-        target = "${scripts}/connect.sh";
+      "${scripts}/connected.py" = {
+        source = ./scripts/connected.py;
         executable = true;
-        text = ''
-          #!/usr/bin/env bash
-
-          TARGET="$1"
-
-          if nmcli connection show "$TARGET" >/dev/null 2>&1; then
-              nmcli connection up "$TARGET"
-          else
-              PASSWORD=$(wofi --dmenu --password --prompt "Wi-Fi Password")
-              nmcli device wifi connect "$TARGET" password "$PASSWORD"
-          fi
-        '';
       };
-      network_disconnect_sh = {
-        target = "${scripts}/disconnect.sh";
+
+      "${scripts}/connect_wifi.sh" = {
+        source = ./scripts/connect_wifi.sh;
         executable = true;
+      };
+      "${scripts}/disconnect_wifi.sh" = {
         text = ''
           #!/usr/bin/env bash
-
-          nmcli connection down "$1"
+          nmcli connection down id "$1"
         '';
+        executable = true;
       };
     };
   };

+ 38 - 0
home/features/desktop/sway/ui/eww/network/network.scss

@@ -0,0 +1,38 @@
+.network-menu {
+    background: #0A0101;
+    padding: 16px;
+    min-width: 320px;
+    transition: all 0.3s ease-in;
+}
+
+.title {
+    font-size: 22px;
+    margin-bottom: 12px;
+}
+
+button {
+    background: #0A0101;
+    border-radius: 14px;
+    padding: 10px;
+    margin: 4px 0;
+}
+
+button:hover {
+    background: #190202;
+}   
+
+button.active-wifi {
+    background: #140202;
+}
+
+button.active-wifi:hover {
+    background: #190202;
+}
+
+button.inactive-wifi {
+    background: #0A0101;
+}
+
+button.inactive-wifi:hover {
+    background: #261616;
+}

+ 22 - 15
home/features/desktop/sway/ui/eww/network/network.yuck

@@ -1,27 +1,34 @@
-(defpoll network_connections
+(defpoll available_networks
     :interval "5s"
-    "~/.config/eww/widgets/network/scripts/connections.sh")
+    "~/.config/eww/widgets/network/scripts/available_wifi.py"
+)
 
 (defwindow network
-    :monitor 0
+    :monitor 0 ; fiks slik at den kommer på riktig skjerm
     :geometry (geometry
-        :x "70%"
-        :y "40px"
-        :width "360px"
-        :height "600px")
-    :anchor "top left"
+        :width "300px"
+        :height "500px"
+        :anchor "bottom right"
+    )
     :stacking "fg"
-    (network-menu))
+    (network-menu)
+)
 
 (defwidget network-menu []
     (box
         :orientation "v"
         :class "network-menu"
 
-    (label
-        :class "title"
-        :text "Internet")
+        (label
+            :class "title"
+            :text "Internet"
+            :xalign 0.5
+            :yalign 0.2
+        )
 
-    (scroll
-        :vexpand true
-        (literal :content network_connections))))
+        (scroll
+            :vexpand false
+            (literal :content available_networks)
+        )
+    )
+)

+ 38 - 0
home/features/desktop/sway/ui/eww/network/scripts/available_other.py

@@ -0,0 +1,38 @@
+def get_wired() -> list:
+    ret = []
+    cmd = r"""
+    nmcli -t -f DEVICE,TYPE,STATE,CONNECTION device status | grep ethernet
+    """
+    eth = subprocess.run(
+        cmd,
+        shell = True,
+        text = True,
+        capture_output = True,
+        check = True,
+    )
+    if eth.check_returncode():
+        return
+    
+    for line in eth.stdout.strip().split("\n"):
+        parts = line.split(":")
+
+        device = parts[0]
+        if device == "":
+            continue
+        typ = parts[1]
+        if typ == "":
+            continue
+        state = parts[2]
+        if state == "" or state == "unavailable":
+            continue
+        connection = parts[3]
+        if connection == "":
+            continue
+        
+        ret.append({
+            "device": device,
+            "type": typ,
+            "state": state,
+            "name": connection,
+        })
+    return ret

+ 105 - 0
home/features/desktop/sway/ui/eww/network/scripts/available_wifi.py

@@ -0,0 +1,105 @@
+#!/usr/bin/env python3
+
+import subprocess
+import sys
+from pathlib import Path
+
+script_dir = Path(__file__).parent
+sys.path.insert(0, str(script_dir))
+
+from connected import get_connected
+
+def get_networks() -> list:
+    ret = []
+    cmd = r"""
+    nmcli -t -f SSID,SIGNAL,SECURITY,DEVICE,ACTIVE dev wifi list \
+    | sort -t: -k1,1 -k2,2nr \
+    | awk -F: '!seen[$1]++'
+    """
+    wifi = subprocess.run(
+        cmd,
+        shell = True,
+        text = True,
+        capture_output = True,
+        check = True,
+    )
+    if wifi.check_returncode():
+        return
+
+    for line in wifi.stdout.strip().split("\n"):
+        parts = line.split(":")
+
+        ssid = parts[0]
+        if ssid == "":
+            continue
+        signal = parts[1]
+        if signal == "" or not int(signal):
+            continue
+        security = parts[2]
+        if security == "":
+            continue
+        device = parts[3]
+        if device == "":
+            continue
+        active = parts[4]
+        if active == "":
+            continue
+
+        ret.append({
+            "name": ssid,
+            "type": "802-11-wireless",
+            "signal": int(signal),
+            "security": security,
+            "device": device,
+            "active": True if active == "yes" else False
+        })
+    return ret
+
+def get_available() -> list:
+    available_networks = get_networks()
+
+    available_networks = sorted(available_networks, key=lambda x: (0 if x["active"] else 1, -x["signal"]))
+
+    return available_networks
+
+def yuck() -> str:
+    available = get_available()
+    ret = r"""(box :orientation "v" :spacing 2"""
+
+    for connection in available:
+        icon = ""
+        if connection["type"] == "802-11-wireless":
+            icon = "w" # legg inn ikon etter signal strength
+        elif connection["type"] == "802-3-ethernet":
+            icon = "e"
+        elif connection["type"] == "vpn":
+            icon = "v"
+        else:
+            icon = "?"
+        
+        safe_name = connection["name"].replace('"', r'\"')
+
+        if connection["active"] == True:
+            ret += rf"""
+            (button
+                :class "active-wifi"
+                :onclick "~/.config/eww/widgets/network/scripts/disconnect_wifi.sh"
+            """
+        else:
+            ret += rf"""
+            (button
+                :class "inactive-wifi"
+                :onclick "~/.config/eww/widgets/network/scripts/connect_wifi.sh"
+            """
+        ret += rf"""
+                (box :orientation "h" :height 32 :spacing 2
+                    (label :text "{icon}")
+                    (label :text "{safe_name}")
+                )
+            )
+        """
+    return ret + ")"
+
+if __name__ == "__main__":
+    print(yuck())
+

+ 9 - 0
home/features/desktop/sway/ui/eww/network/scripts/connect_wifi.sh

@@ -0,0 +1,9 @@
+#!/usr/bin/env bash
+TARGET="$1"
+
+if nmcli connection show "$TARGET" >/dev/null 2>&1; then
+    nmcli connection up "$TARGET"
+else
+    PASSWORD=$(wofi --dmenu --password --prompt "Wi-Fi Password")
+    nmcli device wifi connect "$TARGET" password "$PASSWORD"
+fi

+ 50 - 0
home/features/desktop/sway/ui/eww/network/scripts/connected.py

@@ -0,0 +1,50 @@
+#!/usr/bin/env python3
+
+import subprocess
+
+def get_connected() -> list:
+    ret = []
+
+    IGNORED_PREFIXES = ("lo", "docker", "br-", "veth", "virbr")
+    IGNORED_TYPES = {"loopback", "bridge"}
+
+    cmd = r"""
+    nmcli -t -f DEVICE,TYPE,STATE,NAME connection show --active
+    """
+    connected = subprocess.run(
+        cmd,
+        shell = True,
+        text = True,
+        capture_output = True,
+        check = True,
+    )
+    if connected.check_returncode():
+        return
+
+    for line in connected.stdout.strip().split("\n"):
+        parts = line.split(":")
+
+        device = parts[0]
+        conn_type = parts[1]
+        state = parts[2]
+        name = parts[3]
+
+        if conn_type in IGNORED_TYPES:
+            continue
+
+        if any(device.startswith(prefix) for prefix in IGNORED_PREFIXES):
+            continue
+
+        ret.append({
+            "device": device,
+            "type": conn_type,
+            "state": state,
+            "name": name,
+        })
+    return ret
+
+def yuck() -> str:
+    return get_connected()
+
+if __name__ == "__main__":
+    print(yuck())

+ 4 - 1
home/features/desktop/sway/ui/waybar/default.nix

@@ -37,7 +37,10 @@
 
         "custom/clock" = {
           format = "{}";
-          exec = "~/.config/waybar/clock.sh";
+          exec = ''
+            formatted_date=$(LC_TIME=nb_NO.UTF-8 date +"%H:%M %A, %d %b" | tr '[:upper:]' '[:lower:]' | sed 's/\.//g')
+            printf '{"text": "%s"}\n' "$formatted_date"
+          '';
           return-type = "json";
           restart-interval = 1;
         };